file_name
stringlengths
71
779k
comments
stringlengths
20
182k
code_string
stringlengths
20
36.9M
__index_level_0__
int64
0
17.2M
input_ids
sequence
attention_mask
sequence
labels
sequence
/* AMP Copyright 2017-2020 AMP Development 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. This code does not constitute an offer or a means to sell or a solicitation of an offer to buy a security in any jurisdiction in which it is unlawful to make such an offer or solicitation. This technology is not built to enable securitization, but accounting transparency in asset-backed and non-asset-backed transactions. All notices regarding the AMP market include notices of restrictions for the participation by US-citizens and residents of the US, South Korea, United Kingdom and the EU. */ pragma experimental ABIEncoderV2; pragma solidity 0.6.6; // Uniswap import '@uniswap/v2-periphery/contracts/UniswapV2Router02.sol'; interface OrFeedInterface { function getExchangeRate ( string calldata fromSymbol, string calldata toSymbol, string calldata venue, uint256 amount ) external view returns ( uint256 ); function getTokenDecimalCount ( address tokenAddress ) external view returns ( uint256 ); function getTokenAddress ( string calldata symbol ) external view returns ( address ); function getSynthBytes32 ( string calldata symbol ) external view returns ( bytes32 ); function getForexAddress ( string calldata symbol ) external view returns ( address ); function requestAsyncEvent(string calldata eventName, string calldata source) external view returns(string memory); function arb(address fundsReturnToAddress, address liquidityProviderContractAddress, string[] calldata tokens, uint256 amount, string[] calldata exchanges) external payable returns (bool); } contract Amp { using SafeMath for uint256; // orfeed interface OrFeedInterface orfeed; // dai tokenAddress IERC20 daiToken; // the uniswap v2 router UniswapV2Router02 uniswap; // the owner of the contract address owner; // the address of the uniswap v2 router to use address payable uniswapAddress; // Represents a single asset struct Asset { address tokenAddress; string title; string description; string entityName; uint256 proposedMarketCapUSD; string fileHash1; string fileHash2; string photo1URL; string photo2URL; string photo3URL; uint256 assetSaleRewards; uint256 assetRegularRewards; } // Represents a single prediction struct Prediction { address userAddress; bool predictFor; uint256 amountStableCoinStaked; } // Represents a token issuer i.e. the person who adds the asset to the assurance market struct TokenIssuer { address issuerAddress; uint256 dateIssued; // date the token was added to the market } // a mapping of assets in the contract mapping (address => Asset) assets; // a mapping of assets in the contract mapping (address => TokenIssuer) tokenIssuers; // a mapping of predictions for each asset mapping (address => Prediction[]) predictions; // a mapping of each tokens resolution date mapping (address => uint256) assetResolutionDates; constructor(address _daiTokenAddress, address payable _uniswapAddress) public { // set the owner of the contract owner = msg.sender; // init the dai token address daiToken = IERC20(_daiTokenAddress); //init the uniswap router uniswapAddress = _uniswapAddress; uniswap = UniswapV2Router02(_uniswapAddress); } // check that the user is the owner of the contract modifier onlyOwner() { if (msg.sender != owner) { revert(); } _; } // contract events event AssetAdded(address _tokenAddress, uint256 _resolutionDate); event AssetInactivated(address _tokenAddress, string _reasonGivenByAdminOrCreator); /// @notice allow the owner to set the address of the orfeed contract /// @param _orfeedAddress the new address of the orfeed contract /// @return true function setOrfeedAddress(address _orfeedAddress) onlyOwner external returns(bool) { orfeed = OrFeedInterface(_orfeedAddress); return true; } function getCreditScore(address entityAddress) public view returns (uint256 score){ // placeholder for now (score) = 200; } function getPrice(string memory fromTokenSymbol, uint256 amount, string memory venue) public view returns (uint256 price){ (price) = orfeed.getExchangeRate(fromTokenSymbol, "USD", venue, amount); } function getSwapPrice(string memory fromTokenSymbol, string memory toTokenSymbol, uint256 amount, string memory venue) public view returns (uint256 price) { (price) = orfeed.getExchangeRate(fromTokenSymbol, toTokenSymbol, venue, amount); } function getProposedYield(address tokenAddress) public view returns (uint256 percentage){ // placeholder for now (percentage) = 200; } function getHistoricYield(address tokenAddress, uint256 numOfYears) public view returns (uint256 percentage){ // placeholder for now (percentage) = 200; } function getProposedMarketCap(address tokenAddress) external view returns (uint256 marketCap){ // placeholder for now (marketCap) = assets[tokenAddress].proposedMarketCapUSD; } function getAssetPredictionScoreAndSize(address tokenAddress) external view returns (uint256 score, uint256 totalPredictionMarketSize){ uint256 assetScore = getCreditScore(tokenAddress); (score, totalPredictionMarketSize) = (assetScore, 200); } function getPredictionMarketAssetExpirationDate(address tokenAddress) external view returns (uint256 timestamp) { (timestamp) = assetResolutionDates[tokenAddress]; } function getPredictionBalance(address predictorAddress, address tokenAddress) public view returns (uint256 currentBalance, uint256 side){ // placeholder for now (currentBalance, side) = (200, 200); } function isAssetOnAMP(address tokenAddress) public view returns (bool isOn){ address assetAddress = assets[tokenAddress].tokenAddress; if (assetAddress != address(0)){ (isOn) = true; } else{ (isOn) = false; } } function isPredictionMarketResolved(address tokenAddress) public view returns (bool isOn){ uint256 resolutionDate = assetResolutionDates[tokenAddress]; if (now > resolutionDate){ (isOn) = true; } else{ (isOn) = false; } } function rateEntityForCreditScore(address entityAddress, uint256 proposedScore) public returns(bool){ // placeholder for now return true; } function swapAsset( address fromAsset, address toAsset, string calldata fromTokenSymbol, string calldata toTokenSymbol, uint256 amountInput, uint256 minimumOutput) external returns(uint256 outputAmount){ // check if the contract is allowed to spend the the swap amount require(IERC20(fromAsset).allowance(msg.sender, address(this)) >= amountInput, 'Please approve this contract to spend the swap amount'); // check if the contract is able to transfer the swap amount from the user to itself if the allowance is given require(IERC20(fromAsset).transferFrom(msg.sender, address(this), amountInput), 'Failed to transfer the from asset to the contract'); // check if the contract is able to approve the asset for swapping in uniswap require(IERC20(fromAsset).approve(address(uniswapAddress), amountInput), 'Token approve failed for the token swap via uniswap.'); uint256 finalOutputAmount = 0; // get the asset swap price via orfeed uint256 swapPrice = getSwapPrice(fromTokenSymbol, toTokenSymbol, amountInput, "UNISWAPBYSYMBOLV2"); if (swapPrice < minimumOutput) { revert("The final output amount for this swap will be less than the minimum amount set!"); } else { // start the token to token swap address[] memory path = new address[](2); path[0] = fromAsset; path[1] = toAsset; uint[] memory swapAmounts = uniswap.swapExactTokensForTokens(amountInput, minimumOutput, path, msg.sender, block.timestamp); for (uint i= 0; i < swapAmounts.length; i++) { // skip the first index amount because it will be the input amount if (i > 0) { // add up the rest of the amounts in the array and return them finalOutputAmount += swapAmounts[i]; } } } (outputAmount) = finalOutputAmount; } function predictForOrAgainst(address tokenAddress, bool predictFor, uint256 amountStableCoinStaked) payable external returns(bool) { bool predicitionSuccessful = false; // first of all check if the contract is allow spend the dai amount set by the sender if(IERC20(daiToken).allowance(msg.sender, address(this)) >= amountStableCoinStaked) { // check if the contract is able to transfer the dai amount from the user to itself if the allowance is given require(IERC20(daiToken).transferFrom(msg.sender, address(this), amountStableCoinStaked), 'Failed to transfer the dai from your address to the contract for prediction'); // if transfer is sucessful, then update the predicitions for the token for this user predictions[tokenAddress].push(Prediction(msg.sender, predictFor, amountStableCoinStaked)); // mark the prediction as successful predicitionSuccessful = true; } else{ require(msg.value > 0, "Please send some ETH that'll be swapped for dai and sused for the prediction"); uint256 swapPrice = orfeed.getExchangeRate("ETH", "DAI", "UNISWAPBYSYMBOLV2", amountStableCoinStaked); if (swapPrice < amountStableCoinStaked) { revert("The final output amount for the ETH/DAI swap will be less than the amount of stable coins to be staked!"); } else { // start the eth to token swap uint256 finalOutputAmount = 0; address[] memory path = new address[](2); path[0] = uniswap.WETH(); path[1] = address(daiToken); // sent uniswap the eth uniswapAddress.transfer(msg.value); // do the swap via uniswap v2 and get the array out the outputs uint[] memory swapAmounts = uniswap.swapETHForExactTokens(amountStableCoinStaked, path, address(this), block.timestamp); for (uint i = 0; i < swapAmounts.length; i++) { // skip the first index amount because it will be the input amount if (i > 0) { // add up the rest of the amounts in the array and return them finalOutputAmount += swapAmounts[i]; } } // update the users predicitions predictions[tokenAddress].push(Prediction(msg.sender, predictFor, amountStableCoinStaked)); // mark the prediction as successful predicitionSuccessful = true; } } return predicitionSuccessful; } function resolvePredictionMarketAsset(address tokenAddress) public returns(bool resolved) { uint256 resolutionDate = assetResolutionDates[tokenAddress]; if (now > resolutionDate){ (resolved) = true; } else{ (resolved) = false; } } function addAssetToMarket(address tokenAddress, string memory title, string memory description, string memory entityName, uint256 proposedMarketCapUSD, string memory fileHash1, string memory fileHash2, string memory photo1URL, string memory photo2URL, string memory photo3URL ) public { // add the asset assets[tokenAddress] = Asset(tokenAddress, title, description, entityName, proposedMarketCapUSD, fileHash1, fileHash2, photo1URL, photo2URL, photo3URL, 0, 0); // set the token issuer tokenIssuers[tokenAddress] = TokenIssuer(msg.sender, now); // calculate and set its resolution date uint256 resolutionDate = now + 365 days; assetResolutionDates[tokenAddress] = resolutionDate; // then emit the appropriate event emit AssetAdded(tokenAddress, resolutionDate); } function inactivateAsset(address tokenAddress, string memory reasonGivenByAdminOrCreator ) public { // remove the asset from the assets mapping delete assets[tokenAddress]; // remove the issuer of the token delete tokenIssuers[tokenAddress]; // delete its resolution date delete assetResolutionDates[tokenAddress]; // then emit an event explaining why the asset was inactivated emit AssetInactivated(tokenAddress, reasonGivenByAdminOrCreator); } function claimPredictionRewards(address tokenAddress) public returns(uint256 amountReturned) { // placeholder for now (amountReturned) = 200; } function claimAssetRewards(address tokenAddress) public returns(uint256 amountReturned) { // placeholder for now (amountReturned) = 200; } function claimAssetSaleRewards(address tokenAddress) public returns(uint256 amountReturned){ // placeholder for now (amountReturned) = 200; } function contributeAssetRegularRewards(address tokenAddress, uint256 amountUSD) public returns(bool){ bool contributionSuccessful = false; // make sure the asset is listed on amp if(isAssetOnAMP(tokenAddress)) { // check if the contract is allowed to spend require(IERC20(daiToken).allowance(msg.sender, address(this)) >= amountUSD, 'Please approve this contract to spend the contribution dai amount'); // check if the contract is able to transfer the dai amount from the user to itself if the allowance is given require(IERC20(daiToken).transferFrom(msg.sender, address(this), amountUSD), 'Failed to transfer the dai from your address to the contract'); // if the transfer is successful, then updaate the regular rewards balance for the asset/token assets[tokenAddress].assetRegularRewards += amountUSD; // then mark the contribution as successful contributionSuccessful = true; } return contributionSuccessful; } function contributeAssetSaleRewards(address tokenAddress, uint256 amountUSD) public returns(bool){ bool contributionSuccessful = false; // make sure the asset is listed on amp if(isAssetOnAMP(tokenAddress)) { // check if the contract is allowed to spend the dai require(IERC20(daiToken).allowance(msg.sender, address(this)) >= amountUSD, 'Please approve this contract to spend the contribution dai amount'); // check if the contract is able to transfer the dai amount from the user to itself if the allowance is given require(IERC20(daiToken).transferFrom(msg.sender, address(this), amountUSD), 'Failed to transfer the dai from your address to the contract'); // if the transfer is successful, then updaate the regular rewards balance for the asset/token assets[tokenAddress].assetSaleRewards += amountUSD; // then mark the contribution as successful contributionSuccessful = true; } return contributionSuccessful; } }
make sure the asset is listed on amp check if the contract is allowed to spend check if the contract is able to transfer the dai amount from the user to itself if the allowance is given if the transfer is successful, then updaate the regular rewards balance for the asset/token then mark the contribution as successful
function contributeAssetRegularRewards(address tokenAddress, uint256 amountUSD) public returns(bool){ bool contributionSuccessful = false; if(isAssetOnAMP(tokenAddress)) { require(IERC20(daiToken).allowance(msg.sender, address(this)) >= amountUSD, 'Please approve this contract to spend the contribution dai amount'); require(IERC20(daiToken).transferFrom(msg.sender, address(this), amountUSD), 'Failed to transfer the dai from your address to the contract'); assets[tokenAddress].assetRegularRewards += amountUSD; contributionSuccessful = true; } return contributionSuccessful; }
12,562,696
[ 1, 6540, 3071, 326, 3310, 353, 12889, 603, 16946, 866, 309, 326, 6835, 353, 2935, 358, 17571, 866, 309, 326, 6835, 353, 7752, 358, 7412, 326, 5248, 77, 3844, 628, 326, 729, 358, 6174, 309, 326, 1699, 1359, 353, 864, 309, 326, 7412, 353, 6873, 16, 1508, 2166, 69, 340, 326, 6736, 283, 6397, 11013, 364, 326, 3310, 19, 2316, 1508, 2267, 326, 24880, 487, 6873, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 356, 887, 6672, 17974, 17631, 14727, 12, 2867, 1147, 1887, 16, 2254, 5034, 3844, 3378, 40, 13, 1071, 1135, 12, 6430, 15329, 203, 203, 3639, 1426, 24880, 14277, 273, 629, 31, 203, 203, 3639, 309, 12, 291, 6672, 1398, 8900, 12, 2316, 1887, 3719, 288, 203, 5411, 2583, 12, 45, 654, 39, 3462, 12, 2414, 77, 1345, 2934, 5965, 1359, 12, 3576, 18, 15330, 16, 1758, 12, 2211, 3719, 1545, 3844, 3378, 40, 16, 296, 8496, 6617, 537, 333, 6835, 358, 17571, 326, 24880, 5248, 77, 3844, 8284, 203, 203, 5411, 2583, 12, 45, 654, 39, 3462, 12, 2414, 77, 1345, 2934, 13866, 1265, 12, 3576, 18, 15330, 16, 1758, 12, 2211, 3631, 3844, 3378, 40, 3631, 296, 2925, 358, 7412, 326, 5248, 77, 628, 3433, 1758, 358, 326, 6835, 8284, 203, 203, 5411, 7176, 63, 2316, 1887, 8009, 9406, 17974, 17631, 14727, 1011, 3844, 3378, 40, 31, 203, 203, 5411, 24880, 14277, 273, 638, 31, 203, 3639, 289, 203, 203, 3639, 327, 24880, 14277, 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 ]
./partial_match/1/0x63E9E16421a2b1Ea14AE8592C0810A9E47809399/sources/pacman.sol
Buy FeeSell FeeOriginal Fee
contract pacman is Context, IERC20, Ownable { using SafeMath for uint256; string private constant _name = "pacman"; string private constant _symbol = "pacman"; uint8 private constant _decimals = 9; mapping(address => uint256) private _rOwned; mapping(address => uint256) private _tOwned; mapping(address => mapping(address => uint256)) private _allowances; mapping(address => bool) private _isExcludedFromFee; uint256 private constant MAX = ~uint256(0); uint256 private constant _tTotal = 1000000000 * 10**9; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; uint256 private _redisFeeOnBuy = 0; uint256 private _taxFeeOnBuy = 10; uint256 private _redisFeeOnSell = 0; uint256 private _taxFeeOnSell = 66; uint256 public totalFees; uint256 private _redisFee = _redisFeeOnSell; uint256 private _taxFee = _taxFeeOnSell; uint256 private _previousredisFee = _redisFee; uint256 private _previoustaxFee = _taxFee; mapping(address => uint256) private cooldown; address payable private _developmentAddress = payable(0xcC2e2Cf958aAe551D956f1F820a0508122dE5AEB); address payable private _marketingAddress = payable(0xcC2e2Cf958aAe551D956f1F820a0508122dE5AEB); IUniswapV2Router02 public uniswapV2Router; address public uniswapV2Pair; bool private tradingOpen; bool private inSwap = false; bool private swapEnabled = true; uint256 public _maxTxAmount = 20000000 * 10**9; uint256 public _maxWalletSize = 20000000 * 10**9; uint256 public _swapTokensAtAmount = 200000 * 10**9; event MaxTxAmountUpdated(uint256 _maxTxAmount); modifier lockTheSwap { inSwap = true; _; inSwap = false; } constructor() { _rOwned[_msgSender()] = _rTotal; uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; _isExcludedFromFee[_developmentAddress] = true; _isExcludedFromFee[_marketingAddress] = true; emit Transfer(address(0), _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 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 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 removeAllFee() private { if (_redisFee == 0 && _taxFee == 0) return; _previousredisFee = _redisFee; _previoustaxFee = _taxFee; _redisFee = 0; _taxFee = 0; } function restoreAllFee() private { _redisFee = _previousredisFee; _taxFee = _previoustaxFee; } 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 (from != owner() && to != owner()) { if (!tradingOpen) { require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled"); } require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit"); if(to != uniswapV2Pair) { require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!"); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= _swapTokensAtAmount; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } bool takeFee = true; if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) { takeFee = false; if(from == uniswapV2Pair && to != address(uniswapV2Router)) { _redisFee = _redisFeeOnBuy; _taxFee = _taxFeeOnBuy; } if (to == uniswapV2Pair && from != address(uniswapV2Router)) { _redisFee = _redisFeeOnSell; _taxFee = _taxFeeOnSell; } } _tokenTransfer(from, to, amount, takeFee); } 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 (from != owner() && to != owner()) { if (!tradingOpen) { require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled"); } require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit"); if(to != uniswapV2Pair) { require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!"); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= _swapTokensAtAmount; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } bool takeFee = true; if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) { takeFee = false; if(from == uniswapV2Pair && to != address(uniswapV2Router)) { _redisFee = _redisFeeOnBuy; _taxFee = _taxFeeOnBuy; } if (to == uniswapV2Pair && from != address(uniswapV2Router)) { _redisFee = _redisFeeOnSell; _taxFee = _taxFeeOnSell; } } _tokenTransfer(from, to, amount, takeFee); } 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 (from != owner() && to != owner()) { if (!tradingOpen) { require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled"); } require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit"); if(to != uniswapV2Pair) { require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!"); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= _swapTokensAtAmount; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } bool takeFee = true; if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) { takeFee = false; if(from == uniswapV2Pair && to != address(uniswapV2Router)) { _redisFee = _redisFeeOnBuy; _taxFee = _taxFeeOnBuy; } if (to == uniswapV2Pair && from != address(uniswapV2Router)) { _redisFee = _redisFeeOnSell; _taxFee = _taxFeeOnSell; } } _tokenTransfer(from, to, amount, takeFee); } 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 (from != owner() && to != owner()) { if (!tradingOpen) { require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled"); } require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit"); if(to != uniswapV2Pair) { require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!"); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= _swapTokensAtAmount; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } bool takeFee = true; if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) { takeFee = false; if(from == uniswapV2Pair && to != address(uniswapV2Router)) { _redisFee = _redisFeeOnBuy; _taxFee = _taxFeeOnBuy; } if (to == uniswapV2Pair && from != address(uniswapV2Router)) { _redisFee = _redisFeeOnSell; _taxFee = _taxFeeOnSell; } } _tokenTransfer(from, to, amount, takeFee); } 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 (from != owner() && to != owner()) { if (!tradingOpen) { require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled"); } require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit"); if(to != uniswapV2Pair) { require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!"); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= _swapTokensAtAmount; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } bool takeFee = true; if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) { takeFee = false; if(from == uniswapV2Pair && to != address(uniswapV2Router)) { _redisFee = _redisFeeOnBuy; _taxFee = _taxFeeOnBuy; } if (to == uniswapV2Pair && from != address(uniswapV2Router)) { _redisFee = _redisFeeOnSell; _taxFee = _taxFeeOnSell; } } _tokenTransfer(from, to, amount, takeFee); } 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 (from != owner() && to != owner()) { if (!tradingOpen) { require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled"); } require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit"); if(to != uniswapV2Pair) { require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!"); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= _swapTokensAtAmount; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } bool takeFee = true; if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) { takeFee = false; if(from == uniswapV2Pair && to != address(uniswapV2Router)) { _redisFee = _redisFeeOnBuy; _taxFee = _taxFeeOnBuy; } if (to == uniswapV2Pair && from != address(uniswapV2Router)) { _redisFee = _redisFeeOnSell; _taxFee = _taxFeeOnSell; } } _tokenTransfer(from, to, amount, takeFee); } 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 (from != owner() && to != owner()) { if (!tradingOpen) { require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled"); } require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit"); if(to != uniswapV2Pair) { require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!"); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= _swapTokensAtAmount; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } bool takeFee = true; if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) { takeFee = false; if(from == uniswapV2Pair && to != address(uniswapV2Router)) { _redisFee = _redisFeeOnBuy; _taxFee = _taxFeeOnBuy; } if (to == uniswapV2Pair && from != address(uniswapV2Router)) { _redisFee = _redisFeeOnSell; _taxFee = _taxFeeOnSell; } } _tokenTransfer(from, to, amount, takeFee); } 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 (from != owner() && to != owner()) { if (!tradingOpen) { require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled"); } require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit"); if(to != uniswapV2Pair) { require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!"); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= _swapTokensAtAmount; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } bool takeFee = true; if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) { takeFee = false; if(from == uniswapV2Pair && to != address(uniswapV2Router)) { _redisFee = _redisFeeOnBuy; _taxFee = _taxFeeOnBuy; } if (to == uniswapV2Pair && from != address(uniswapV2Router)) { _redisFee = _redisFeeOnSell; _taxFee = _taxFeeOnSell; } } _tokenTransfer(from, to, amount, takeFee); } } else { 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 (from != owner() && to != owner()) { if (!tradingOpen) { require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled"); } require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit"); if(to != uniswapV2Pair) { require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!"); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= _swapTokensAtAmount; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } bool takeFee = true; if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) { takeFee = false; if(from == uniswapV2Pair && to != address(uniswapV2Router)) { _redisFee = _redisFeeOnBuy; _taxFee = _taxFeeOnBuy; } if (to == uniswapV2Pair && from != address(uniswapV2Router)) { _redisFee = _redisFeeOnSell; _taxFee = _taxFeeOnSell; } } _tokenTransfer(from, to, amount, takeFee); } 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 (from != owner() && to != owner()) { if (!tradingOpen) { require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled"); } require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit"); if(to != uniswapV2Pair) { require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!"); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= _swapTokensAtAmount; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } bool takeFee = true; if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) { takeFee = false; if(from == uniswapV2Pair && to != address(uniswapV2Router)) { _redisFee = _redisFeeOnBuy; _taxFee = _taxFeeOnBuy; } if (to == uniswapV2Pair && from != address(uniswapV2Router)) { _redisFee = _redisFeeOnSell; _taxFee = _taxFeeOnSell; } } _tokenTransfer(from, to, amount, takeFee); } function swapTokensForEth(uint256 tokenAmount) private lockTheSwap { address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, path, address(this), block.timestamp ); } function sendETHToFee(uint256 amount) private { _developmentAddress.transfer(amount.div(2)); _marketingAddress.transfer(amount.div(2)); } function setTrading(bool _tradingOpen) public onlyOwner { tradingOpen = _tradingOpen; } function manualswap() external { require(_msgSender() == _developmentAddress || _msgSender() == _marketingAddress); uint256 contractBalance = balanceOf(address(this)); swapTokensForEth(contractBalance); } function manualsend() external { require(_msgSender() == _developmentAddress || _msgSender() == _marketingAddress); uint256 contractETHBalance = address(this).balance; sendETHToFee(contractETHBalance); } function _tokenTransfer( address sender, address recipient, uint256 amount, bool takeFee ) private { if (!takeFee) removeAllFee(); _transferStandard(sender, recipient, amount); if (!takeFee) restoreAllFee(); } function _transferStandard( address sender, address recipient, uint256 tAmount ) private { ( uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tTeam ) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeTeam(tTeam); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _takeTeam(uint256 tTeam) private { uint256 currentRate = _getRate(); uint256 rTeam = tTeam.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rTeam); } function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } receive() external payable {} function _getValues(uint256 tAmount) private view returns ( uint256, uint256, uint256, uint256, uint256, uint256 ) { (uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getTValues(tAmount, _redisFee, _taxFee); 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 redisFee, uint256 taxFee ) private pure returns ( uint256, uint256, uint256 ) { uint256 tFee = tAmount.mul(redisFee).div(100); uint256 tTeam = tAmount.mul(taxFee).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 _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); } function setFee(uint256 redisFeeOnBuy, uint256 redisFeeOnSell, uint256 taxFeeOnBuy, uint256 taxFeeOnSell) public onlyOwner { _redisFeeOnBuy = redisFeeOnBuy; _redisFeeOnSell = redisFeeOnSell; _taxFeeOnBuy = taxFeeOnBuy; _taxFeeOnSell = taxFeeOnSell; totalFees = _redisFeeOnBuy + _redisFeeOnSell + _taxFeeOnBuy + _taxFeeOnSell; require(totalFees <= 100, "Must keep fees at 100% or less"); } function setMinSwapTokensThreshold(uint256 swapTokensAtAmount) public onlyOwner { _swapTokensAtAmount = swapTokensAtAmount; } function toggleSwap(bool _swapEnabled) public onlyOwner { swapEnabled = _swapEnabled; } function setMaxTxnAmount(uint256 maxTxAmount) public onlyOwner { _maxTxAmount = maxTxAmount; } function setMaxWalletSize(uint256 maxWalletSize) public onlyOwner { _maxWalletSize = maxWalletSize; } function excludeMultipleAccountsFromFees(address[] calldata accounts, bool excluded) public onlyOwner { for(uint256 i = 0; i < accounts.length; i++) { _isExcludedFromFee[accounts[i]] = excluded; } } function excludeMultipleAccountsFromFees(address[] calldata accounts, bool excluded) public onlyOwner { for(uint256 i = 0; i < accounts.length; i++) { _isExcludedFromFee[accounts[i]] = excluded; } } }
9,173,247
[ 1, 38, 9835, 30174, 55, 1165, 30174, 8176, 30174, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 293, 1077, 4728, 353, 1772, 16, 467, 654, 39, 3462, 16, 14223, 6914, 288, 203, 7010, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 7010, 565, 533, 3238, 5381, 389, 529, 273, 315, 84, 1077, 4728, 14432, 7010, 565, 533, 3238, 5381, 389, 7175, 273, 315, 84, 1077, 4728, 14432, 7010, 565, 2254, 28, 3238, 5381, 389, 31734, 273, 2468, 31, 203, 7010, 565, 2874, 12, 2867, 516, 2254, 5034, 13, 3238, 389, 86, 5460, 329, 31, 203, 565, 2874, 12, 2867, 516, 2254, 5034, 13, 3238, 389, 88, 5460, 329, 31, 203, 565, 2874, 12, 2867, 516, 2874, 12, 2867, 516, 2254, 5034, 3719, 3238, 389, 5965, 6872, 31, 203, 565, 2874, 12, 2867, 516, 1426, 13, 3238, 389, 291, 16461, 1265, 14667, 31, 203, 565, 2254, 5034, 3238, 5381, 4552, 273, 4871, 11890, 5034, 12, 20, 1769, 203, 203, 565, 2254, 5034, 3238, 5381, 389, 88, 5269, 273, 15088, 3784, 380, 1728, 636, 29, 31, 7010, 565, 2254, 5034, 3238, 389, 86, 5269, 273, 261, 6694, 300, 261, 6694, 738, 389, 88, 5269, 10019, 203, 565, 2254, 5034, 3238, 389, 88, 14667, 5269, 31, 203, 7010, 565, 2254, 5034, 3238, 389, 12311, 14667, 1398, 38, 9835, 273, 374, 31, 21281, 565, 2254, 5034, 3238, 389, 8066, 14667, 1398, 38, 9835, 273, 1728, 31, 27699, 7010, 565, 2254, 5034, 3238, 389, 12311, 14667, 1398, 55, 1165, 273, 374, 31, 7010, 565, 2254, 5034, 3238, 389, 8066, 14667, 1398, 55, 1165, 273, 22342, 31, 21281, 203, 565, 2254, 5034, 1071, 2078, 2954, 2 ]
pragma solidity ^0.5.9; // File: openzeppelin-solidity/contracts/token/ERC20/IERC20.sol /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see `ERC20Detailed`. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a `Transfer` event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through `transferFrom`. This is * zero by default. * * This value changes when `approve` or `transferFrom` are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * > Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an `Approval` event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a `Transfer` event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to `approve`. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: openzeppelin-solidity/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) { require(b <= a, "SafeMath: subtraction overflow"); 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-solidity/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) { // Solidity only automatically asserts when dividing by 0 require(b > 0, "SafeMath: division by zero"); 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) { require(b != 0, "SafeMath: modulo by zero"); return a % b; } } // File: openzeppelin-solidity/contracts/utils/Address.sol /** * @dev Collection of functions related to the address type, */ library Address { /** * @dev Returns true if `account` is a contract. * * This test is non-exhaustive, and there may be false-negatives: during the * execution of a contract's constructor, its address will be reported as * not containing a contract. * * > It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. */ function isContract(address account) internal view returns (bool) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } } // File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File: openzeppelin-solidity/contracts/ownership/Ownable.sol /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be aplied to your functions to restrict their use to * the owner. */ contract Ownable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return msg.sender == _owner; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * > Note: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: contracts/openzeppelin/TokenVesting.sol /** * @title TokenVesting * @dev A token holder contract that can release its token balance gradually like a * typical vesting scheme, with a cliff and vesting period. Optionally revocable by the * owner. */ contract TokenVesting is Ownable { // The vesting schedule is time-based (i.e. using block timestamps as opposed to e.g. block numbers), and is // therefore sensitive to timestamp manipulation (which is something miners can do, to a certain degree). Therefore, // it is recommended to avoid using short time durations (less than a minute). Typical vesting schemes, with a // cliff period of a year and a duration of four years, are safe to use. // solhint-disable not-rely-on-time using SafeMath for uint256; using SafeERC20 for IERC20; event TokensReleased(address token, uint256 amount); event TokenVestingRevoked(address token); // beneficiary of tokens after they are released address private _beneficiary; // Durations and timestamps are expressed in UNIX time, the same units as block.timestamp. uint256 private _cliff; uint256 private _start; uint256 private _duration; bool private _revocable; mapping (address => uint256) private _released; mapping (address => bool) private _revoked; /** * @dev Creates a vesting contract that vests its balance of any ERC20 token to the * beneficiary, gradually in a linear fashion until start + duration. By then all * of the balance will have vested. * @param beneficiary address of the beneficiary to whom vested tokens are transferred * @param cliffDuration duration in seconds of the cliff in which tokens will begin to vest * @param start the time (as Unix time) at which point vesting starts * @param duration duration in seconds of the period in which the tokens will vest * @param revocable whether the vesting is revocable or not */ constructor (address beneficiary, uint256 start, uint256 cliffDuration, uint256 duration, bool revocable) public { require(beneficiary != address(0), "TokenVesting: beneficiary is the zero address"); // solhint-disable-next-line max-line-length require(cliffDuration <= duration, "TokenVesting: cliff is longer than duration"); require(duration > 0, "TokenVesting: duration is 0"); // solhint-disable-next-line max-line-length require(start.add(duration) > block.timestamp, "TokenVesting: final time is before current time"); _beneficiary = beneficiary; _revocable = revocable; _duration = duration; _cliff = start.add(cliffDuration); _start = start; } /** * @return the beneficiary of the tokens. */ function beneficiary() public view returns (address) { return _beneficiary; } /** * @return the cliff time of the token vesting. */ function cliff() public view returns (uint256) { return _cliff; } /** * @return the start time of the token vesting. */ function start() public view returns (uint256) { return _start; } /** * @return the duration of the token vesting. */ function duration() public view returns (uint256) { return _duration; } /** * @return true if the vesting is revocable. */ function revocable() public view returns (bool) { return _revocable; } /** * @return the amount of the token released. */ function released(address token) public view returns (uint256) { return _released[token]; } /** * @return true if the token is revoked. */ function revoked(address token) public view returns (bool) { return _revoked[token]; } /** * @notice Transfers vested tokens to beneficiary. * @param token ERC20 token which is being vested */ function release(IERC20 token) public { uint256 unreleased = _releasableAmount(token); require(unreleased > 0, "TokenVesting: no tokens are due"); _released[address(token)] = _released[address(token)].add(unreleased); token.safeTransfer(_beneficiary, unreleased); emit TokensReleased(address(token), unreleased); } /** * @notice Allows the owner to revoke the vesting. Tokens already vested * remain in the contract, the rest are returned to the owner. * @param token ERC20 token which is being vested */ function revoke(IERC20 token) public onlyOwner { require(_revocable, "TokenVesting: cannot revoke"); require(!_revoked[address(token)], "TokenVesting: token already revoked"); uint256 balance = token.balanceOf(address(this)); uint256 unreleased = _releasableAmount(token); uint256 refund = balance.sub(unreleased); _revoked[address(token)] = true; token.safeTransfer(owner(), refund); emit TokenVestingRevoked(address(token)); } /** * @dev Calculates the amount that has already vested but hasn't been released yet. * @param token ERC20 token which is being vested */ function _releasableAmount(IERC20 token) private view returns (uint256) { return _vestedAmount(token).sub(_released[address(token)]); } /** * @dev Calculates the amount that has already vested. * @param token ERC20 token which is being vested */ function _vestedAmount(IERC20 token) private view returns (uint256) { uint256 currentBalance = token.balanceOf(address(this)); uint256 totalBalance = currentBalance.add(_released[address(token)]); if (block.timestamp < _cliff) { return 0; } else if (block.timestamp >= _start.add(_duration) || _revoked[address(token)]) { return totalBalance; } else { return totalBalance.mul(block.timestamp.sub(_start)).div(_duration); } } /** * @return change the beneficiary of tokens */ function _changeBeneficiary(address _newBeneficiary) internal { _beneficiary = _newBeneficiary; } } // File: contracts/helpers/BeneficiaryOperations.sol /* License: MIT Copyright Bitclave, 2018 It's modified contract BeneficiaryOperations from https://github.com/bitclave/BeneficiaryOperations */ contract BeneficiaryOperations { using SafeMath for uint256; using SafeMath for uint8; // VARIABLES uint256 public beneficiariesGeneration; uint256 public howManyBeneficiariesDecide; address[] public beneficiaries; bytes32[] public allOperations; address internal insideCallSender; uint256 internal insideCallCount; // Reverse lookup tables for beneficiaries and allOperations mapping(address => uint8) public beneficiariesIndices; // Starts from 1, size 255 mapping(bytes32 => uint) public allOperationsIndicies; // beneficiaries voting mask per operations mapping(bytes32 => uint256) public votesMaskByOperation; mapping(bytes32 => uint256) public votesCountByOperation; //operation -> beneficiaryIndex mapping(bytes32 => uint8) internal operationsByBeneficiaryIndex; mapping(uint8 => uint8) internal operationsCountByBeneficiaryIndex; // EVENTS event BeneficiaryshipTransferred(address[] previousbeneficiaries, uint howManyBeneficiariesDecide, address[] newBeneficiaries, uint newHowManybeneficiarysDecide); event OperationCreated(bytes32 operation, uint howMany, uint beneficiariesCount, address proposer); event OperationUpvoted(bytes32 operation, uint votes, uint howMany, uint beneficiariesCount, address upvoter); event OperationPerformed(bytes32 operation, uint howMany, uint beneficiariesCount, address performer); event OperationDownvoted(bytes32 operation, uint votes, uint beneficiariesCount, address downvoter); event OperationCancelled(bytes32 operation, address lastCanceller); // ACCESSORS function isExistBeneficiary(address wallet) public view returns(bool) { return beneficiariesIndices[wallet] > 0; } function beneficiariesCount() public view returns(uint) { return beneficiaries.length; } function allOperationsCount() public view returns(uint) { return allOperations.length; } /* Internal functions */ function _operationLimitByBeneficiaryIndex(uint8 beneficiaryIndex) internal view returns(bool) { return (operationsCountByBeneficiaryIndex[beneficiaryIndex] <= 3); } function _cancelAllPending() internal { for (uint i = 0; i < allOperations.length; i++) { delete(allOperationsIndicies[allOperations[i]]); delete(votesMaskByOperation[allOperations[i]]); delete(votesCountByOperation[allOperations[i]]); //delete operation->beneficiaryIndex delete(operationsByBeneficiaryIndex[allOperations[i]]); } allOperations.length = 0; //delete operations count for beneficiary for (uint8 j = 0; j < beneficiaries.length; j++) { operationsCountByBeneficiaryIndex[j] = 0; } } // MODIFIERS /** * @dev Allows to perform method by any of the beneficiaries */ modifier onlyAnyBeneficiary { if (checkHowManyBeneficiaries(1)) { bool update = (insideCallSender == address(0)); if (update) { insideCallSender = msg.sender; insideCallCount = 1; } _; if (update) { insideCallSender = address(0); insideCallCount = 0; } } } /** * @dev Allows to perform method only after many beneficiaries call it with the same arguments */ modifier onlyManyBeneficiaries { if (checkHowManyBeneficiaries(howManyBeneficiariesDecide)) { bool update = (insideCallSender == address(0)); if (update) { insideCallSender = msg.sender; insideCallCount = howManyBeneficiariesDecide; } _; if (update) { insideCallSender = address(0); insideCallCount = 0; } } } /** * @dev Allows to perform method only after all beneficiaries call it with the same arguments */ modifier onlyAllBeneficiaries { if (checkHowManyBeneficiaries(beneficiaries.length)) { bool update = (insideCallSender == address(0)); if (update) { insideCallSender = msg.sender; insideCallCount = beneficiaries.length; } _; if (update) { insideCallSender = address(0); insideCallCount = 0; } } } /** * @dev Allows to perform method only after some beneficiaries call it with the same arguments */ modifier onlySomeBeneficiaries(uint howMany) { require(howMany > 0, "onlySomeBeneficiaries: howMany argument is zero"); require(howMany <= beneficiaries.length, "onlySomeBeneficiaries: howMany argument exceeds the number of Beneficiaries"); if (checkHowManyBeneficiaries(howMany)) { bool update = (insideCallSender == address(0)); if (update) { insideCallSender = msg.sender; insideCallCount = howMany; } _; if (update) { insideCallSender = address(0); insideCallCount = 0; } } } // CONSTRUCTOR constructor() public { beneficiaries.push(msg.sender); beneficiariesIndices[msg.sender] = 1; howManyBeneficiariesDecide = 1; } // INTERNAL METHODS /** * @dev onlyManybeneficiaries modifier helper */ function checkHowManyBeneficiaries(uint howMany) internal returns(bool) { if (insideCallSender == msg.sender) { require(howMany <= insideCallCount, "checkHowManyBeneficiaries: nested beneficiaries modifier check require more beneficiarys"); return true; } require((isExistBeneficiary(msg.sender) && (beneficiariesIndices[msg.sender] <= beneficiaries.length)), "checkHowManyBeneficiaries: msg.sender is not an beneficiary"); uint beneficiaryIndex = beneficiariesIndices[msg.sender].sub(1); bytes32 operation = keccak256(abi.encodePacked(msg.data, beneficiariesGeneration)); require((votesMaskByOperation[operation] & (2 ** beneficiaryIndex)) == 0, "checkHowManyBeneficiaries: beneficiary already voted for the operation"); //check limit for operation require(_operationLimitByBeneficiaryIndex(uint8(beneficiaryIndex)), "checkHowManyBeneficiaries: operation limit is reached for this beneficiary"); votesMaskByOperation[operation] |= (2 ** beneficiaryIndex); uint operationVotesCount = votesCountByOperation[operation].add(1); votesCountByOperation[operation] = operationVotesCount; if (operationVotesCount == 1) { allOperationsIndicies[operation] = allOperations.length; operationsByBeneficiaryIndex[operation] = uint8(beneficiaryIndex); operationsCountByBeneficiaryIndex[uint8(beneficiaryIndex)] = uint8(operationsCountByBeneficiaryIndex[uint8(beneficiaryIndex)].add(1)); allOperations.push(operation); emit OperationCreated(operation, howMany, beneficiaries.length, msg.sender); } emit OperationUpvoted(operation, operationVotesCount, howMany, beneficiaries.length, msg.sender); // If enough beneficiaries confirmed the same operation if (votesCountByOperation[operation] == howMany) { deleteOperation(operation); emit OperationPerformed(operation, howMany, beneficiaries.length, msg.sender); return true; } return false; } /** * @dev Used to delete cancelled or performed operation * @param operation defines which operation to delete */ function deleteOperation(bytes32 operation) internal { uint index = allOperationsIndicies[operation]; if (index < allOperations.length - 1) { // Not last allOperations[index] = allOperations[allOperations.length.sub(1)]; allOperationsIndicies[allOperations[index]] = index; } allOperations.length = allOperations.length.sub(1); uint8 beneficiaryIndex = uint8(operationsByBeneficiaryIndex[operation]); operationsCountByBeneficiaryIndex[beneficiaryIndex] = uint8(operationsCountByBeneficiaryIndex[beneficiaryIndex].sub(1)); delete votesMaskByOperation[operation]; delete votesCountByOperation[operation]; delete allOperationsIndicies[operation]; delete operationsByBeneficiaryIndex[operation]; } // PUBLIC METHODS /** * @dev Allows beneficiaries to change their mind by cancelling votesMaskByOperation operations * @param operation defines which operation to delete */ function cancelPending(bytes32 operation) public onlyAnyBeneficiary { require((isExistBeneficiary(msg.sender) && (beneficiariesIndices[msg.sender] <= beneficiaries.length)), "checkHowManyBeneficiaries: msg.sender is not an beneficiary"); uint beneficiaryIndex = beneficiariesIndices[msg.sender].sub(1); require((votesMaskByOperation[operation] & (2 ** beneficiaryIndex)) != 0, "cancelPending: operation not found for this user"); votesMaskByOperation[operation] &= ~(2 ** beneficiaryIndex); uint operationVotesCount = votesCountByOperation[operation].sub(1); votesCountByOperation[operation] = operationVotesCount; emit OperationDownvoted(operation, operationVotesCount, beneficiaries.length, msg.sender); if (operationVotesCount == 0) { deleteOperation(operation); emit OperationCancelled(operation, msg.sender); } } /** * @dev Allows beneficiaries to change their mind by cancelling all operations */ function cancelAllPending() public onlyManyBeneficiaries { _cancelAllPending(); } /**Переписать*/ /** * @dev Allows beneficiaries to change beneficiariesship * @param newBeneficiaries defines array of addresses of new beneficiaries */ function transferBeneficiaryShip(address[] memory newBeneficiaries) public { transferBeneficiaryShipWithHowMany(newBeneficiaries, newBeneficiaries.length); } /** * @dev Allows beneficiaries to change beneficiaryShip * @param newBeneficiaries defines array of addresses of new beneficiaries * @param newHowManyBeneficiariesDecide defines how many beneficiaries can decide */ function transferBeneficiaryShipWithHowMany(address[] memory newBeneficiaries, uint256 newHowManyBeneficiariesDecide) public onlyManyBeneficiaries { require(newBeneficiaries.length > 0, "transferBeneficiaryShipWithHowMany: beneficiaries array is empty"); require(newBeneficiaries.length < 256, "transferBeneficiaryshipWithHowMany: beneficiaries count is greater then 255"); require(newHowManyBeneficiariesDecide > 0, "transferBeneficiaryshipWithHowMany: newHowManybeneficiarysDecide equal to 0"); require(newHowManyBeneficiariesDecide <= newBeneficiaries.length, "transferBeneficiaryShipWithHowMany: newHowManybeneficiarysDecide exceeds the number of beneficiarys"); // Reset beneficiaries reverse lookup table for (uint j = 0; j < beneficiaries.length; j++) { delete beneficiariesIndices[beneficiaries[j]]; } for (uint i = 0; i < newBeneficiaries.length; i++) { require(newBeneficiaries[i] != address(0), "transferBeneficiaryShipWithHowMany: beneficiaries array contains zero"); require(beneficiariesIndices[newBeneficiaries[i]] == 0, "transferBeneficiaryShipWithHowMany: beneficiaries array contains duplicates"); beneficiariesIndices[newBeneficiaries[i]] = uint8(i.add(1)); } emit BeneficiaryshipTransferred(beneficiaries, howManyBeneficiariesDecide, newBeneficiaries, newHowManyBeneficiariesDecide); beneficiaries = newBeneficiaries; howManyBeneficiariesDecide = newHowManyBeneficiariesDecide; _cancelAllPending(); beneficiariesGeneration++; } } // File: contracts/logics/AkropolisTokenVesting.sol //Beneficieries template contract AkropolisTokenVesting is TokenVesting, BeneficiaryOperations { IERC20 private token; address private _pendingBeneficiary; event LogBeneficiaryTransferProposed(address _beneficiary); event LogBeneficiaryTransfered(address _beneficiary); constructor (IERC20 _token, uint256 _start, uint256 _cliffDuration, uint256 _duration) public TokenVesting(msg.sender, _start, _cliffDuration, _duration, false) { token = _token; } /** * @notice Transfers vested tokens to beneficiary. */ function release() public { super.release(token); } /** * @return the token being held. */ function tokenAddress() public view returns (IERC20) { return token; } // MODIFIERS /** * @dev Allows to perform method by existing beneficiary */ modifier onlyExistingBeneficiary(address _beneficiary) { require(isExistBeneficiary(_beneficiary), "address is not in beneficiary array"); _; } /** * @dev Allows to perform method by pending beneficiary */ modifier onlyPendingBeneficiary { require(msg.sender == _pendingBeneficiary, "Unpermitted operation."); _; } function pendingBeneficiary() public view returns (address) { return _pendingBeneficiary; } /** * @dev Allows beneficiaries to change beneficiaryShip and set first beneficiary as default * @param _newBeneficiaries defines array of addresses of new beneficiaries */ function transferBeneficiaryShip(address[] memory _newBeneficiaries) public { super.transferBeneficiaryShip(_newBeneficiaries); _setPendingBeneficiary(beneficiaries[0]); } /** * @dev Allows beneficiaries to change beneficiaryShip and set first beneficiary as default * @param _newBeneficiaries defines array of addresses of new beneficiaries * @param _newHowManyBeneficiariesDecide defines how many beneficiaries can decide */ function transferBeneficiaryShipWithHowMany(address[] memory _newBeneficiaries, uint256 _newHowManyBeneficiariesDecide) public { super.transferBeneficiaryShipWithHowMany(_newBeneficiaries, _newHowManyBeneficiariesDecide); _setPendingBeneficiary(beneficiaries[0]); } /** * @dev Allows beneficiaries to change beneficiary as default * @param _newBeneficiary defines address of new beneficiary */ function changeBeneficiary(address _newBeneficiary) public onlyManyBeneficiaries { _setPendingBeneficiary(_newBeneficiary); } /** * @dev Claim Beneficiary */ function claimBeneficiary() public onlyPendingBeneficiary { _changeBeneficiary(_pendingBeneficiary); emit LogBeneficiaryTransfered(_pendingBeneficiary); _pendingBeneficiary = address(0); } /* * Internal Functions * */ /** * @dev Set pending Beneficiary address * @param _newBeneficiary defines address of new beneficiary */ function _setPendingBeneficiary(address _newBeneficiary) internal onlyExistingBeneficiary(_newBeneficiary) { _pendingBeneficiary = _newBeneficiary; emit LogBeneficiaryTransferProposed(_newBeneficiary); } }
delete operation->beneficiaryIndexdelete operations count for beneficiary
function _cancelAllPending() internal { for (uint i = 0; i < allOperations.length; i++) { delete(allOperationsIndicies[allOperations[i]]); delete(votesMaskByOperation[allOperations[i]]); delete(votesCountByOperation[allOperations[i]]); delete(operationsByBeneficiaryIndex[allOperations[i]]); } allOperations.length = 0; for (uint8 j = 0; j < beneficiaries.length; j++) { operationsCountByBeneficiaryIndex[j] = 0; } }
12,684,393
[ 1, 3733, 1674, 2122, 70, 4009, 74, 14463, 814, 1016, 3733, 5295, 1056, 364, 27641, 74, 14463, 814, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 10996, 1595, 8579, 1435, 2713, 288, 203, 3639, 364, 261, 11890, 277, 273, 374, 31, 277, 411, 777, 9343, 18, 2469, 31, 277, 27245, 288, 203, 5411, 1430, 12, 454, 9343, 3866, 335, 606, 63, 454, 9343, 63, 77, 13563, 1769, 203, 5411, 1430, 12, 27800, 5796, 858, 2988, 63, 454, 9343, 63, 77, 13563, 1769, 203, 5411, 1430, 12, 27800, 1380, 858, 2988, 63, 454, 9343, 63, 77, 13563, 1769, 203, 5411, 1430, 12, 17542, 858, 38, 4009, 74, 14463, 814, 1016, 63, 454, 9343, 63, 77, 13563, 1769, 203, 3639, 289, 203, 203, 3639, 777, 9343, 18, 2469, 273, 374, 31, 203, 3639, 364, 261, 11890, 28, 525, 273, 374, 31, 525, 411, 27641, 74, 14463, 5646, 18, 2469, 31, 525, 27245, 288, 203, 5411, 5295, 1380, 858, 38, 4009, 74, 14463, 814, 1016, 63, 78, 65, 273, 374, 31, 203, 3639, 289, 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 ]
./partial_match/3/0x51886Cc76a28F49439BF0fE7051FF25Ab6d66432/sources/Ris3Factory.sol
set government address
function setGovernmentAddress(address _govAddress) public onlyOwner { governmentAddress = _govAddress; government = ris3Gov(governmentAddress); ris3Address = government.getRis3Address(); ris3 = IERC20(ris3Address); taxPoolAddress = government.getTaxPoolAddress(); }
5,059,046
[ 1, 542, 314, 1643, 82, 475, 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 ]
[ 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, 26770, 1643, 82, 475, 1887, 12, 2867, 389, 75, 1527, 1887, 13, 1071, 1338, 5541, 288, 203, 3639, 314, 1643, 82, 475, 1887, 273, 389, 75, 1527, 1887, 31, 203, 3639, 314, 1643, 82, 475, 273, 436, 291, 23, 43, 1527, 12, 75, 1643, 82, 475, 1887, 1769, 203, 3639, 436, 291, 23, 1887, 273, 314, 1643, 82, 475, 18, 588, 54, 291, 23, 1887, 5621, 203, 3639, 436, 291, 23, 273, 467, 654, 39, 3462, 12, 18387, 23, 1887, 1769, 203, 3639, 5320, 2864, 1887, 273, 314, 1643, 82, 475, 18, 588, 7731, 2864, 1887, 5621, 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 ]
./partial_match/42/0xA17716b2e0ec620B5BD7eb0b6fE1b8C2dCa57679/sources/CompoundNoFoldStrategyUSDTTestnet.sol
File: contracts/strategies/compound/CompoundInteractor.sol
contract CompoundInteractor is ReentrancyGuard { using SafeMath for uint256; using SafeERC20 for IERC20; IERC20 public underlying; IERC20 public _weth = IERC20(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); CompleteCToken public ctoken; ComptrollerInterface public comptroller; constructor( address _underlying, address _ctoken, address _comptroller suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. <one line to give the program's name and a brief idea of what it does.> Copyright (C) <year> <name of author> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: <program> Copyright (C) <year> <name of author> This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read pragma solidity ^0.5.0; } pragma solidity 0.5.16; ) public { comptroller = ComptrollerInterface(_comptroller); underlying = IERC20(_underlying); ctoken = CompleteCToken(_ctoken); address[] memory cTokens = new address[](1); cTokens[0] = _ctoken; } function _supplyEtherInWETH(uint256 amountInWETH) internal nonReentrant { uint256 balance = underlying.balanceOf(address(this)); if (amountInWETH < balance) { balance = amountInWETH; } WETH9 weth = WETH9(address(_weth)); weth.withdraw(balance); } function _supplyEtherInWETH(uint256 amountInWETH) internal nonReentrant { uint256 balance = underlying.balanceOf(address(this)); if (amountInWETH < balance) { balance = amountInWETH; } WETH9 weth = WETH9(address(_weth)); weth.withdraw(balance); } ICEther(address(ctoken)).mint.value(balance)(); function _redeemEtherInCTokens(uint256 amountCTokens) internal nonReentrant { _redeemInCTokens(amountCTokens); WETH9 weth = WETH9(address(_weth)); weth.deposit.value(address(this).balance)(); } function _supply(uint256 amount) internal returns (uint256) { uint256 balance = underlying.balanceOf(address(this)); if (amount < balance) { balance = amount; } underlying.safeApprove(address(ctoken), 0); underlying.safeApprove(address(ctoken), balance); uint256 mintResult = ctoken.mint(balance); require(mintResult == 0, "Supplying failed"); return balance; } function _supply(uint256 amount) internal returns (uint256) { uint256 balance = underlying.balanceOf(address(this)); if (amount < balance) { balance = amount; } underlying.safeApprove(address(ctoken), 0); underlying.safeApprove(address(ctoken), balance); uint256 mintResult = ctoken.mint(balance); require(mintResult == 0, "Supplying failed"); return balance; } function _borrow( uint256 amountUnderlying ) internal { uint256 result = ctoken.borrow(amountUnderlying); require(result == 0, "Borrow failed"); } function _repay(uint256 amountUnderlying) internal { underlying.safeApprove(address(ctoken), 0); underlying.safeApprove(address(ctoken), amountUnderlying); ctoken.repayBorrow(amountUnderlying); underlying.safeApprove(address(ctoken), 0); } function _redeemInCTokens(uint256 amountCTokens) internal { if (amountCTokens > 0) { ctoken.redeem(amountCTokens); } } function _redeemInCTokens(uint256 amountCTokens) internal { if (amountCTokens > 0) { ctoken.redeem(amountCTokens); } } function _redeemUnderlying(uint256 amountUnderlying) internal { if (amountUnderlying > 0) { ctoken.redeemUnderlying(amountUnderlying); } } function _redeemUnderlying(uint256 amountUnderlying) internal { if (amountUnderlying > 0) { ctoken.redeemUnderlying(amountUnderlying); } } function redeemUnderlyingInWeth(uint256 amountUnderlying) internal { _redeemUnderlying(amountUnderlying); WETH9 weth = WETH9(address(_weth)); weth.deposit.value(address(this).balance)(); } function claimComp() public { comptroller.claimComp(address(this)); } function redeemMaximumWeth() internal { uint256 available = ctoken.getCash(); uint256 owned = ctoken.balanceOfUnderlying(address(this)); redeemUnderlyingInWeth(available < owned ? available : owned); } function getLiquidity() external view returns (uint256) { return ctoken.getCash(); } function redeemMaximumToken() internal { uint256 available = ctoken.getCash(); uint256 owned = ctoken.balanceOfUnderlying(address(this)); _redeemUnderlying(available < owned ? available : owned); } }
3,383,170
[ 1, 812, 30, 20092, 19, 701, 15127, 19, 22585, 19, 16835, 2465, 3362, 18, 18281, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 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, 16351, 21327, 2465, 3362, 353, 868, 8230, 12514, 16709, 288, 203, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 565, 1450, 14060, 654, 39, 3462, 364, 467, 654, 39, 3462, 31, 203, 203, 565, 467, 654, 39, 3462, 1071, 6808, 31, 203, 565, 467, 654, 39, 3462, 1071, 389, 91, 546, 273, 467, 654, 39, 3462, 12, 20, 14626, 3103, 7598, 37, 5520, 70, 3787, 23, 8090, 28, 40, 20, 37, 20, 73, 25, 39, 24, 42, 5324, 73, 1880, 29, 6840, 23, 39, 27, 4313, 39, 71, 22, 1769, 203, 565, 14575, 1268, 969, 1071, 276, 2316, 31, 203, 565, 1286, 337, 1539, 1358, 1071, 532, 337, 1539, 31, 203, 203, 565, 3885, 12, 203, 3639, 1758, 389, 9341, 6291, 16, 203, 3639, 1758, 389, 299, 969, 16, 203, 3639, 1758, 389, 832, 337, 1539, 203, 87, 3809, 1812, 358, 3387, 716, 326, 17545, 5957, 445, 310, 434, 326, 4358, 733, 203, 710, 353, 316, 1158, 648, 5309, 329, 578, 1554, 586, 329, 598, 3704, 2357, 2724, 203, 31064, 711, 2118, 7165, 18, 203, 203, 225, 971, 1846, 6292, 402, 392, 733, 981, 1440, 3613, 333, 2442, 316, 16, 578, 598, 16, 578, 203, 12524, 1230, 364, 999, 316, 16, 279, 2177, 8094, 16, 471, 326, 6292, 402, 310, 9938, 487, 203, 2680, 434, 279, 2492, 316, 1492, 326, 2145, 434, 949, 3184, 471, 999, 434, 326, 203, 1299, 8094, 353, 906, 4193, 358, 326, 8027, 316, 1534, 6951, 89, 560, 578, 364, 279, 203, 12429, 2481, 261, 1574, 1060, 2656, 2 ]
pragma solidity ^0.4.24; /** * SmartEth.co * ERC20 Token and ICO smart contracts development, smart contracts audit, ICO websites. * [email protected] */ /** * @title SafeMath */ 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&#39;t hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title Ownable */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor() public { owner = 0x81FF7d5cA83707C23d663ADE4432bdc8eD6ccCE1; } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title Pausable */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; modifier whenNotPaused() { require(!paused); _; } modifier whenPaused() { require(paused); _; } function pause() onlyOwner whenNotPaused public { paused = true; emit Pause(); } function unpause() onlyOwner whenPaused public { paused = false; emit Unpause(); } } /** * @title ERC20Basic */ 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); } /** * @title ERC20 interface */ 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 INTO_ICO is Pausable { using SafeMath for uint256; // The token being sold ERC20 public token; // Address where funds are collected address public wallet; // Max supply of tokens offered in the crowdsale uint256 public supply; // How many token units a buyer gets per wei uint256 public rate; // Amount of wei raised uint256 public weiRaised; // Crowdsale opening time uint256 public openingTime; // Crowdsale closing time uint256 public closingTime; // Crowdsale duration in days uint256 public duration; // Min amount of wei an investor can send uint256 public minInvest; /** * 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); constructor() public { rate = 50000; wallet = owner; token = ERC20(0x7f738ffbdE7ECAC18D31ECba1e9B6eEF5b9214b7); minInvest = 0.05 * 1 ether; duration = 176 days; openingTime = 1530446400; // Determined by start() closingTime = openingTime + duration; // Determined by start() } /** * @dev called by the owner to start the crowdsale */ function start() public onlyOwner { openingTime = now; closingTime = now + duration; } // ----------------------------------------- // 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); _forwardFunds(); } // ----------------------------------------- // 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 whenNotPaused { require(_beneficiary != address(0)); require(_weiAmount >= minInvest); require(now >= openingTime && now <= closingTime); } /** * @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 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.div(10 ** 18).mul(rate); } /** * @dev Determines how ETH is stored/forwarded on purchases. */ function _forwardFunds() internal { wallet.transfer(msg.value); } /** * @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) { return now > closingTime; } /** * @dev called by the owner to withdraw unsold tokens */ function withdrawTokens() public onlyOwner { uint256 unsold = token.balanceOf(this); token.transfer(owner, unsold); } }
Determined by start()
openingTime = 1530446400;
2,015,898
[ 1, 9139, 329, 635, 787, 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, 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, 10890, 950, 273, 4711, 23, 3028, 24, 1105, 713, 31, 282, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/4/0x0962121eb6acdd5E94B6c1fF5beA3f19E23efDc2/sources/contracts/staking.sol
Raise flag showing the user has been paid
user_list[_affiliate].firstMilestoneHit = true;
796,534
[ 1, 30570, 2982, 17253, 326, 729, 711, 2118, 30591, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5411, 729, 67, 1098, 63, 67, 7329, 330, 3840, 8009, 3645, 49, 18270, 13616, 273, 638, 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 ]
./full_match/1/0xdC85866dDd95fA9b7C856944faB128902CA8C60F/sources/contracts/neymar/nft/ERC721APausable.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 ERC721APausable is ERC721A, Pausable { function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual override(ERC721A) { super._beforeTokenTransfers(from, to, startTokenId, quantity); require(!paused(), "ERC721APausable: token transfer while paused"); } }
9,781,854
[ 1, 654, 39, 27, 5340, 1147, 598, 6790, 16665, 1147, 29375, 16, 312, 474, 310, 471, 18305, 310, 18, 19256, 364, 22456, 4123, 487, 5309, 310, 1284, 5489, 3180, 326, 679, 434, 392, 9873, 3879, 16, 578, 7999, 392, 801, 24530, 1620, 364, 4843, 94, 310, 777, 1147, 29375, 316, 326, 871, 434, 279, 7876, 7934, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 17801, 6835, 4232, 39, 27, 5340, 2203, 69, 16665, 353, 4232, 39, 27, 5340, 37, 16, 21800, 16665, 288, 203, 565, 445, 389, 5771, 1345, 1429, 18881, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 787, 1345, 548, 16, 203, 3639, 2254, 5034, 10457, 203, 203, 565, 262, 2713, 5024, 3849, 12, 654, 39, 27, 5340, 37, 13, 288, 203, 3639, 2240, 6315, 5771, 1345, 1429, 18881, 12, 2080, 16, 358, 16, 787, 1345, 548, 16, 10457, 1769, 203, 3639, 2583, 12, 5, 8774, 3668, 9334, 315, 654, 39, 27, 5340, 2203, 69, 16665, 30, 1147, 7412, 1323, 17781, 8863, 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 ]
./full_match/1/0xD5d3299585580F10151f991698578a02Fe327Fb9/sources/contracts/CanvaIsland.sol
update distributed amount
targetInfo.distributedAmount += _amount;
17,145,061
[ 1, 2725, 16859, 3844, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 3639, 1018, 966, 18, 2251, 11050, 6275, 1011, 389, 8949, 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 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "./IcoToken.sol"; /// @title /// @author /// @dev contract IcoContract is Ownable { using Address for address payable; IcoToken private _token; uint256 private _end; uint256 private _DURATION = 14 days; event Purchase(address indexed buyer, uint256 amount); event Withdrew(address indexed owner, uint256 amount); /// @dev Set the ERC20 address and start the ICO for 14 days. /// @param tokenAddress Set the address of the ERC20. constructor(address tokenAddress) { _token = IcoToken(tokenAddress); require(_token.balanceOf(_token.owner()) == 1000000 * 10**18, "ICO: The owner must have token for exchange"); _end = block.timestamp + _DURATION; } /// @dev Use to receive ether directly from a transaction receive() external payable { _buyTokens(msg.sender, msg.value); } /// @dev Use withdraw function when ICO date finished function withdraw() public onlyOwner { require(block.timestamp >= _end, "ICO: you need to wait 14 days from the deployment of this contract"); uint256 gain = address(this).balance; payable(msg.sender).sendValue(address(this).balance); emit Withdrew(msg.sender, gain); } /// @dev Use to buy platform Ether function buyTokens() public payable { _buyTokens(msg.sender, msg.value); } /// @dev Exchange rate /// @param amount = Ether /// @return value function conversion(uint256 amount) public pure returns (uint256) { return amount * 10**9; } /// @dev Total Ether this ICO function total() public view returns (uint256) { return address(this).balance; } /// @dev ICO is finished /// @return Time left before the end ICO function timeLeft() public view returns (uint256) { require(block.timestamp < _end, "ICO: there is no time left"); return _end - block.timestamp; } /// @dev allows investors to buy tokens /// @param sender : The investors /// @param amount = Ether function _buyTokens(address sender, uint256 amount) private { require(block.timestamp < _end, "ICO: 14 days have passed, you can not buy token"); uint256 allowance = _token.allowance(_token.owner(), address(this)); require(allowance > 0, "ICO: You have not approved because all token are already sold"); uint256 token = conversion(amount); if (token > allowance) { uint256 rest = token - allowance; token -= rest; payable(sender).sendValue(rest / 10**9); } _token.transferFrom(_token.owner(), sender, token); emit Purchase(sender, amount); } }
@dev ICO is finished @return Time left before the end ICO
function timeLeft() public view returns (uint256) { require(block.timestamp < _end, "ICO: there is no time left"); return _end - block.timestamp; }
7,276,740
[ 1, 2871, 51, 353, 6708, 327, 2647, 2002, 1865, 326, 679, 467, 3865, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 813, 3910, 1435, 1071, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 2583, 12, 2629, 18, 5508, 411, 389, 409, 16, 315, 2871, 51, 30, 1915, 353, 1158, 813, 2002, 8863, 203, 3639, 327, 389, 409, 300, 1203, 18, 5508, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/42/0x432bCddE6237D9CF07411CfE05b46811Ad67c7f3/sources/AlohaStaking.sol
* @dev Generates a "random" number using the numbers of backgrounds that we have./
function _randomA(uint256 _limit) internal view returns (uint8) { uint256 _gasleft = gasleft(); bytes32 _blockhash = blockhash(block.number-1); bytes32 _structHash = keccak256( abi.encode( _blockhash, backgrounds, _gasleft, _limit ) ); uint256 _randomNumber = uint256(_structHash); return uint8(_randomNumber) + 1; }
9,062,993
[ 1, 6653, 279, 315, 9188, 6, 1300, 1450, 326, 5600, 434, 5412, 87, 716, 732, 1240, 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 ]
[ 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, 9188, 37, 12, 11890, 5034, 389, 3595, 13, 2713, 1476, 1135, 261, 11890, 28, 13, 288, 203, 3639, 2254, 5034, 389, 31604, 4482, 273, 16189, 4482, 5621, 203, 3639, 1731, 1578, 389, 2629, 2816, 273, 1203, 2816, 12, 2629, 18, 2696, 17, 21, 1769, 203, 3639, 1731, 1578, 389, 1697, 2310, 273, 417, 24410, 581, 5034, 12, 203, 5411, 24126, 18, 3015, 12, 203, 7734, 389, 2629, 2816, 16, 203, 7734, 5412, 87, 16, 203, 7734, 389, 31604, 4482, 16, 203, 7734, 389, 3595, 203, 5411, 262, 203, 3639, 11272, 203, 3639, 2254, 5034, 389, 9188, 1854, 225, 273, 2254, 5034, 24899, 1697, 2310, 1769, 203, 3639, 327, 2254, 28, 24899, 9188, 1854, 13, 397, 404, 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 ]
/** *Submitted for verification at Etherscan.io on 2022-01-14 */ // hevm: flattened sources of src/UniswapTwap.sol // SPDX-License-Identifier: MIT AND GPL-3.0-or-later AND CC-BY-4.0 pragma solidity 0.8.9; ////// node_modules/@openzeppelin/contracts/utils/Context.sol // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) /* pragma solidity ^0.8.0; */ /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } ////// node_modules/@openzeppelin/contracts/access/Ownable.sol // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) /* pragma solidity ^0.8.0; */ /* import "../utils/Context.sol"; */ /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } ////// src/interfaces/IUniswapTWAP.sol /* pragma solidity 0.8.9; */ interface IUniswapTWAP { function maxUpdateWindow() external view returns (uint); function getVaderPrice() external returns (uint); function syncVaderPrice() external; } ////// src/interfaces/chainlink/IAggregatorV3.sol /* pragma solidity 0.8.9; */ interface IAggregatorV3 { function decimals() external view returns (uint8); function latestRoundData() external view returns ( uint80 roundId, int answer, uint startedAt, uint updatedAt, uint80 answeredInRound ); } ////// src/interfaces/uniswap/IUniswapV2Pair.sol /* pragma solidity 0.8.9; */ interface IUniswapV2Pair { function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns ( uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast ); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); } ////// src/libraries/Babylonian.sol /* pragma solidity 0.8.9; */ // computes square roots using the babylonian method // https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method library Babylonian { // credit for this implementation goes to // https://github.com/abdk-consulting/abdk-libraries-solidity/blob/master/ABDKMath64x64.sol#L687 function sqrt(uint x) internal pure returns (uint) { if (x == 0) return 0; // this block is equivalent to r = uint256(1) << (BitMath.mostSignificantBit(x) / 2); // however that code costs significantly more gas uint xx = x; uint 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 uint r1 = x / r; return (r < r1 ? r : r1); } } ////// src/libraries/BitMath.sol /* pragma solidity 0.8.9; */ library BitMath { // returns the 0 indexed position of the most significant bit of the input x // s.t. x >= 2**msb and x < 2**(msb+1) function mostSignificantBit(uint x) internal pure returns (uint8 r) { require(x > 0, "BitMath::mostSignificantBit: zero"); if (x >= 0x100000000000000000000000000000000) { x >>= 128; r += 128; } if (x >= 0x10000000000000000) { x >>= 64; r += 64; } if (x >= 0x100000000) { x >>= 32; r += 32; } if (x >= 0x10000) { x >>= 16; r += 16; } if (x >= 0x100) { x >>= 8; r += 8; } if (x >= 0x10) { x >>= 4; r += 4; } if (x >= 0x4) { x >>= 2; r += 2; } if (x >= 0x2) r += 1; } // returns the 0 indexed position of the least significant bit of the input x // s.t. (x & 2**lsb) != 0 and (x & (2**(lsb) - 1)) == 0) // i.e. the bit at the index is set and the mask of all lower bits is 0 function leastSignificantBit(uint x) internal pure returns (uint8 r) { require(x > 0, "BitMath::leastSignificantBit: zero"); r = 255; if (x & type(uint128).max > 0) { r -= 128; } else { x >>= 128; } if (x & type(uint64).max > 0) { r -= 64; } else { x >>= 64; } if (x & type(uint32).max > 0) { r -= 32; } else { x >>= 32; } if (x & type(uint16).max > 0) { r -= 16; } else { x >>= 16; } if (x & type(uint8).max > 0) { r -= 8; } else { x >>= 8; } if (x & 0xf > 0) { r -= 4; } else { x >>= 4; } if (x & 0x3 > 0) { r -= 2; } else { x >>= 2; } if (x & 0x1 > 0) r -= 1; } } ////// src/libraries/FullMath.sol /* pragma solidity 0.8.9; */ // taken from https://medium.com/coinmonks/math-in-solidity-part-3-percents-and-proportions-4db014e080b1 // license is CC-BY-4.0 library FullMath { function fullMul(uint x, uint y) internal pure returns (uint l, uint h) { uint mm = mulmod(x, y, type(uint).max); l = x * y; h = mm - l; if (mm < l) h -= 1; } function fullDiv( uint l, uint h, uint d ) private pure returns (uint) { uint pow2 = d & uint(-int(d)); d /= pow2; l /= pow2; l += h * (uint(-int(pow2)) / pow2 + 1); uint r = 1; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; return l * r; } function mulDiv( uint x, uint y, uint d ) internal pure returns (uint) { (uint l, uint h) = fullMul(x, y); uint mm = mulmod(x, y, d); if (mm > l) h -= 1; l -= mm; if (h == 0) return l / d; require(h < d, "FullMath: FULLDIV_OVERFLOW"); return fullDiv(l, h, d); } } ////// src/libraries/FixedPoint.sol /* pragma solidity 0.8.9; */ /* import "./FullMath.sol"; */ /* import "./Babylonian.sol"; */ /* import "./BitMath.sol"; */ // a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format)) library FixedPoint { // range: [0, 2**112 - 1] // resolution: 1 / 2**112 struct uq112x112 { uint224 _x; } // range: [0, 2**144 - 1] // resolution: 1 / 2**112 struct uq144x112 { uint _x; } uint8 public constant RESOLUTION = 112; uint public constant Q112 = 0x10000000000000000000000000000; // 2**112 uint private constant Q224 = 0x100000000000000000000000000000000000000000000000000000000; // 2**224 uint private constant LOWER_MASK = 0xffffffffffffffffffffffffffff; // decimal of UQ*x112 (lower 112 bits) // encode a uint112 as a UQ112x112 function encode(uint112 x) internal pure returns (uq112x112 memory) { return uq112x112(uint224(x) << RESOLUTION); } // encodes a uint144 as a UQ144x112 function encode144(uint144 x) internal pure returns (uq144x112 memory) { return uq144x112(uint(x) << RESOLUTION); } // decode a UQ112x112 into a uint112 by truncating after the radix point function decode(uq112x112 memory self) internal pure returns (uint112) { return uint112(self._x >> RESOLUTION); } // decode a UQ144x112 into a uint144 by truncating after the radix point function decode144(uq144x112 memory self) internal pure returns (uint144) { return uint144(self._x >> RESOLUTION); } // multiply a UQ112x112 by a uint, returning a UQ144x112 // reverts on overflow function mul(uq112x112 memory self, uint y) internal pure returns (uq144x112 memory) { uint z = 0; require( y == 0 || (z = self._x * y) / y == self._x, "FixedPoint::mul: overflow" ); return uq144x112(z); } // multiply a UQ112x112 by an int and decode, returning an int // reverts on overflow function muli(uq112x112 memory self, int y) internal pure returns (int) { uint z = FullMath.mulDiv(self._x, uint(y < 0 ? -y : y), Q112); require(z < 2**255, "FixedPoint::muli: overflow"); return y < 0 ? -int(z) : int(z); } // multiply a UQ112x112 by a UQ112x112, returning a UQ112x112 // lossy function muluq(uq112x112 memory self, uq112x112 memory other) internal pure returns (uq112x112 memory) { if (self._x == 0 || other._x == 0) { return uq112x112(0); } uint112 upper_self = uint112(self._x >> RESOLUTION); // * 2^0 uint112 lower_self = uint112(self._x & LOWER_MASK); // * 2^-112 uint112 upper_other = uint112(other._x >> RESOLUTION); // * 2^0 uint112 lower_other = uint112(other._x & LOWER_MASK); // * 2^-112 // partial products uint224 upper = uint224(upper_self) * upper_other; // * 2^0 uint224 lower = uint224(lower_self) * lower_other; // * 2^-224 uint224 uppers_lowero = uint224(upper_self) * lower_other; // * 2^-112 uint224 uppero_lowers = uint224(upper_other) * lower_self; // * 2^-112 // so the bit shift does not overflow require( upper <= type(uint112).max, "FixedPoint::muluq: upper overflow" ); // this cannot exceed 256 bits, all values are 224 bits uint sum = uint(upper << RESOLUTION) + uppers_lowero + uppero_lowers + (lower >> RESOLUTION); // so the cast does not overflow require(sum <= type(uint224).max, "FixedPoint::muluq: sum overflow"); return uq112x112(uint224(sum)); } // divide a UQ112x112 by a UQ112x112, returning a UQ112x112 function divuq(uq112x112 memory self, uq112x112 memory other) internal pure returns (uq112x112 memory) { require(other._x > 0, "FixedPoint::divuq: division by zero"); if (self._x == other._x) { return uq112x112(uint224(Q112)); } if (self._x <= type(uint144).max) { uint value = (uint(self._x) << RESOLUTION) / other._x; require(value <= type(uint224).max, "FixedPoint::divuq: overflow"); return uq112x112(uint224(value)); } uint result = FullMath.mulDiv(Q112, self._x, other._x); require(result <= type(uint224).max, "FixedPoint::divuq: overflow"); return uq112x112(uint224(result)); } // returns a UQ112x112 which represents the ratio of the numerator to the denominator // can be lossy function fraction(uint numerator, uint denominator) internal pure returns (uq112x112 memory) { require(denominator > 0, "FixedPoint::fraction: division by zero"); if (numerator == 0) return FixedPoint.uq112x112(0); if (numerator <= type(uint144).max) { uint result = (numerator << RESOLUTION) / denominator; require( result <= type(uint224).max, "FixedPoint::fraction: overflow" ); return uq112x112(uint224(result)); } else { uint result = FullMath.mulDiv(numerator, Q112, denominator); require( result <= type(uint224).max, "FixedPoint::fraction: overflow" ); return uq112x112(uint224(result)); } } // take the reciprocal of a UQ112x112 // reverts on overflow // lossy function reciprocal(uq112x112 memory self) internal pure returns (uq112x112 memory) { require(self._x != 0, "FixedPoint::reciprocal: reciprocal of zero"); require(self._x != 1, "FixedPoint::reciprocal: overflow"); return uq112x112(uint224(Q224 / self._x)); } // square root of a UQ112x112 // lossy between 0/1 and 40 bits function sqrt(uq112x112 memory self) internal pure returns (uq112x112 memory) { if (self._x <= type(uint144).max) { return uq112x112(uint224(Babylonian.sqrt(uint(self._x) << 112))); } uint8 safeShiftBits = 255 - BitMath.mostSignificantBit(self._x); safeShiftBits -= safeShiftBits % 2; return uq112x112( uint224( Babylonian.sqrt(uint(self._x) << safeShiftBits) << ((112 - safeShiftBits) / 2) ) ); } } ////// src/libraries/UniswapV2OracleLibrary.sol /* pragma solidity 0.8.9; */ /* import "../interfaces/uniswap/IUniswapV2Pair.sol"; */ /* import "./FixedPoint.sol"; */ // library with helper methods for oracles that are concerned with computing average prices library UniswapV2OracleLibrary { using FixedPoint for *; // helper function that returns the current block timestamp within the range of uint32, i.e. [0, 2**32 - 1] function currentBlockTimestamp() internal view returns (uint32) { return uint32(block.timestamp % 2**32); } // produces the cumulative price using counterfactuals to save gas and avoid a call to sync. function currentCumulativePrices(address pair) internal view returns ( uint price0Cumulative, uint price1Cumulative, uint32 blockTimestamp ) { blockTimestamp = currentBlockTimestamp(); price0Cumulative = IUniswapV2Pair(pair).price0CumulativeLast(); price1Cumulative = IUniswapV2Pair(pair).price1CumulativeLast(); // if time has elapsed since the last update on the pair, mock the accumulated price values ( uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast ) = IUniswapV2Pair(pair).getReserves(); if (blockTimestampLast != blockTimestamp) { // subtraction overflow is desired uint32 timeElapsed = blockTimestamp - blockTimestampLast; // addition overflow is desired // counterfactual price0Cumulative += uint(FixedPoint.fraction(reserve1, reserve0)._x) * timeElapsed; // counterfactual price1Cumulative += uint(FixedPoint.fraction(reserve0, reserve1)._x) * timeElapsed; } } } ////// src/UniswapTwap.sol /* pragma solidity 0.8.9; */ /* import "@openzeppelin/contracts/access/Ownable.sol"; */ /* import "./interfaces/chainlink/IAggregatorV3.sol"; */ /* import "./interfaces/uniswap/IUniswapV2Pair.sol"; */ /* import "./interfaces/IUniswapTWAP.sol"; */ /* import "./libraries/UniswapV2OracleLibrary.sol"; */ /* import "./libraries/FixedPoint.sol"; */ /** * @notice Return absolute value of |x - y| */ function abs(uint x, uint y) pure returns (uint) { if (x >= y) { return x - y; } return y - x; } contract UniswapTwap is IUniswapTWAP, Ownable { using FixedPoint for FixedPoint.uq112x112; using FixedPoint for FixedPoint.uq144x112; struct ExchangePair { uint nativeTokenPriceCumulative; FixedPoint.uq112x112 nativeTokenPriceAverage; uint lastMeasurement; uint updatePeriod; // true if token0 = vader bool isFirst; } event SetOracle(address oracle); // 1 Vader = 1e18 uint private constant ONE_VADER = 1e18; // Denominator to calculate difference in Vader / ETH TWAP and spot price. uint private constant MAX_PRICE_DIFF_DENOMINATOR = 1e5; // max for maxUpdateWindow uint private constant MAX_UPDATE_WINDOW = 30 days; /* ========== STATE VARIABLES ========== */ address public immutable vader; // Vader ETH pair IUniswapV2Pair public immutable pair; // Set to pairData.updatePeriod. // maxUpdateWindow is called by other contracts. uint public maxUpdateWindow; ExchangePair public pairData; IAggregatorV3 public oracle; // Numberator to calculate max allowed difference between Vader / ETH TWAP // and spot price. // maxPriceDiff must be initialized to MAX_PRICE_DIFF_DENOMINATOR and kept // until TWAP price is close to spot price for _updateVaderPrice to not fail. uint public maxPriceDiff = MAX_PRICE_DIFF_DENOMINATOR; address public keeper; modifier onlyAuthorized() { require( msg.sender == owner() || msg.sender == keeper, "not authorized" ); _; } constructor( address _vader, IUniswapV2Pair _pair, IAggregatorV3 _oracle, uint _updatePeriod ) { require(_vader != address(0), "vader = 0 address"); vader = _vader; require(_oracle.decimals() == 8, "oracle decimals != 8"); oracle = _oracle; pair = _pair; _addVaderPair(_vader, _pair, _updatePeriod); } /* ========== VIEWS ========== */ /** * @notice Get Vader USD price calculated from Vader / ETH price from * last update. **/ function getStaleVaderPrice() external view returns (uint) { return _calculateVaderPrice(); } /** * @notice Get ETH / USD price from Chainlink. 1 USD = 1e8. **/ function getChainlinkPrice() public view returns (uint) { (uint80 roundID, int price, , , uint80 answeredInRound) = oracle .latestRoundData(); require(answeredInRound >= roundID, "stale Chainlink price"); require(price > 0, "chainlink price = 0"); return uint(price); } /** * @notice Helper function to decode and return Vader / ETH TWAP price **/ function getVaderEthPriceAverage() public view returns (uint) { return pairData.nativeTokenPriceAverage.mul(ONE_VADER).decode144(); } /** * @notice Helper function to decode and return Vader / ETH spot price **/ function getVaderEthSpotPrice() public view returns (uint) { (uint reserve0, uint reserve1, ) = pair.getReserves(); (uint vaderReserve, uint ethReserve) = pairData.isFirst ? (reserve0, reserve1) : (reserve1, reserve0); return FixedPoint .fraction(ethReserve, vaderReserve) .mul(ONE_VADER) .decode144(); } /* ========== MUTATIVE FUNCTIONS ========== */ /** * @notice Update Vader / ETH price and return Vader / USD price. This function will need to be executed at least twice to return sensible Vader / USD price. **/ // NOTE: Fails until _updateVaderPrice is called atlease twice for // nativeTokenPriceAverage to be > 0 function getVaderPrice() external returns (uint) { _updateVaderPrice(); return _calculateVaderPrice(); } /** * @notice Update Vader / ETH price. **/ function syncVaderPrice() external { _updateVaderPrice(); } /** * @notice Update Vader / ETH price. **/ function _updateVaderPrice() private { uint timeElapsed = block.timestamp - pairData.lastMeasurement; // NOTE: save gas and re-entrancy protection. if (timeElapsed < pairData.updatePeriod) return; bool isFirst = pairData.isFirst; ( uint price0Cumulative, uint price1Cumulative, uint currentMeasurement ) = UniswapV2OracleLibrary.currentCumulativePrices(address(pair)); uint priceCumulativeEnd = isFirst ? price0Cumulative : price1Cumulative; uint priceCumulativeStart = pairData.nativeTokenPriceCumulative; // NOTE: Overflow is desired // Difference between 2 cumulative prices will be correct even if the // latest price cumulative overflowed. unchecked { pairData.nativeTokenPriceAverage = FixedPoint.uq112x112( uint224( (priceCumulativeEnd - priceCumulativeStart) / timeElapsed ) ); } pairData.nativeTokenPriceCumulative = priceCumulativeEnd; pairData.lastMeasurement = currentMeasurement; // check TWAP and spot price difference is not too big if (maxPriceDiff < MAX_PRICE_DIFF_DENOMINATOR) { // p = TWAP price // s = spot price // d = max price diff // D = MAX_PRICE_DIFF_DENOMINATOR // |p - s| / p <= d / D uint twapPrice = getVaderEthPriceAverage(); uint spotPrice = getVaderEthSpotPrice(); require(twapPrice > 0, "TWAP = 0"); require(spotPrice > 0, "spot price = 0"); // NOTE: if maxPriceDiff = 0, then this check will most likely fail require( (abs(twapPrice, spotPrice) * MAX_PRICE_DIFF_DENOMINATOR) / twapPrice <= maxPriceDiff, "price diff > max" ); } } /** * @notice Calculates Vader price in USD, 1 USD = 1e18. **/ function _calculateVaderPrice() private view returns (uint vaderUsdPrice) { // USD / ETH, 8 decimals uint usdPerEth = getChainlinkPrice(); // ETH / Vader, 18 decimals uint ethPerVader = pairData .nativeTokenPriceAverage .mul(ONE_VADER) .decode144(); // divide by 1e8 from Chainlink price vaderUsdPrice = (usdPerEth * ethPerVader) / 1e8; require(vaderUsdPrice > 0, "vader usd price = 0"); } /** * @notice Initialize pairData. * @param _vader Address of Vader. * @param _pair Address of Vader / ETH Uniswap V2 pair. * @param _updatePeriod Amout of time that has to elapse before Vader / ETH * TWAP can be updated. **/ function _addVaderPair( address _vader, IUniswapV2Pair _pair, uint _updatePeriod ) private { require(_updatePeriod != 0, "update period = 0"); bool isFirst = _pair.token0() == _vader; address nativeAsset = isFirst ? _pair.token0() : _pair.token1(); require(nativeAsset == _vader, "unsupported pair"); pairData.isFirst = isFirst; pairData.lastMeasurement = block.timestamp; _setUpdatePeriod(_updatePeriod); pairData.nativeTokenPriceCumulative = isFirst ? _pair.price0CumulativeLast() : _pair.price1CumulativeLast(); // NOTE: pairData.nativeTokenPriceAverage = 0 } /** * @notice Set keeper address. * @param _keeper Address of keeper. */ function setKeeper(address _keeper) external onlyOwner { // NOTE: allow _keeper to be 0 address keeper = _keeper; } /** * @notice Set Chainlink oracle. * @param _oracle Address of Chainlink price oracle. **/ function setOracle(IAggregatorV3 _oracle) external onlyOwner { require(_oracle.decimals() == 8, "oracle decimals != 8"); oracle = _oracle; emit SetOracle(address(_oracle)); } /** * @notice Set updatePeriod. * @param _updatePeriod New update period for Vader / ETH TWAP **/ function _setUpdatePeriod(uint _updatePeriod) private { require(_updatePeriod <= MAX_UPDATE_WINDOW, "update period > max"); pairData.updatePeriod = _updatePeriod; maxUpdateWindow = _updatePeriod; } function setUpdatePeriod(uint _updatePeriod) external onlyOwner { _setUpdatePeriod(_updatePeriod); } /** * @notice Set maxPriceDiff. * @param _maxPriceDiff Numberator to calculate max allowed difference * between Vader / ETH TWAP and spot price. **/ function _setMaxPriceDiff(uint _maxPriceDiff) private { require( _maxPriceDiff <= MAX_PRICE_DIFF_DENOMINATOR, "price diff > max" ); maxPriceDiff = _maxPriceDiff; } function setMaxPriceDiff(uint _maxPriceDiff) external onlyOwner { _setMaxPriceDiff(_maxPriceDiff); } /** * @notice Force update Vader TWAP price even if has deviated significantly * from Vader / ETH spot price. */ function forceUpdateVaderPrice() external onlyAuthorized { uint _maxPriceDiff = maxPriceDiff; _setMaxPriceDiff(MAX_PRICE_DIFF_DENOMINATOR); _updateVaderPrice(); _setMaxPriceDiff(_maxPriceDiff); } }
returns a UQ112x112 which represents the ratio of the numerator to the denominator can be lossy
function fraction(uint numerator, uint denominator) internal pure returns (uq112x112 memory) { require(denominator > 0, "FixedPoint::fraction: division by zero"); if (numerator == 0) return FixedPoint.uq112x112(0); if (numerator <= type(uint144).max) { uint result = (numerator << RESOLUTION) / denominator; require( result <= type(uint224).max, "FixedPoint::fraction: overflow" ); return uq112x112(uint224(result)); uint result = FullMath.mulDiv(numerator, Q112, denominator); require( result <= type(uint224).max, "FixedPoint::fraction: overflow" ); return uq112x112(uint224(result)); } }
2,395,559
[ 1, 6154, 279, 587, 53, 17666, 92, 17666, 1492, 8686, 326, 7169, 434, 326, 16730, 358, 326, 15030, 848, 506, 8324, 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, 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, 8330, 12, 11890, 16730, 16, 2254, 15030, 13, 203, 3639, 2713, 203, 3639, 16618, 203, 3639, 1135, 261, 89, 85, 17666, 92, 17666, 3778, 13, 203, 565, 288, 203, 3639, 2583, 12, 13002, 26721, 405, 374, 16, 315, 7505, 2148, 2866, 16744, 30, 16536, 635, 3634, 8863, 203, 3639, 309, 261, 2107, 7385, 422, 374, 13, 327, 15038, 2148, 18, 89, 85, 17666, 92, 17666, 12, 20, 1769, 203, 203, 3639, 309, 261, 2107, 7385, 1648, 618, 12, 11890, 25339, 2934, 1896, 13, 288, 203, 5411, 2254, 563, 273, 261, 2107, 7385, 2296, 12915, 1741, 13269, 13, 342, 15030, 31, 203, 5411, 2583, 12, 203, 7734, 563, 1648, 618, 12, 11890, 23622, 2934, 1896, 16, 203, 7734, 315, 7505, 2148, 2866, 16744, 30, 9391, 6, 203, 5411, 11272, 203, 5411, 327, 582, 85, 17666, 92, 17666, 12, 11890, 23622, 12, 2088, 10019, 203, 5411, 2254, 563, 273, 11692, 10477, 18, 16411, 7244, 12, 2107, 7385, 16, 2238, 17666, 16, 15030, 1769, 203, 5411, 2583, 12, 203, 7734, 563, 1648, 618, 12, 11890, 23622, 2934, 1896, 16, 203, 7734, 315, 7505, 2148, 2866, 16744, 30, 9391, 6, 203, 5411, 11272, 203, 5411, 327, 582, 85, 17666, 92, 17666, 12, 11890, 23622, 12, 2088, 10019, 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 ]
./full_match/137/0xABBB4d0074C0361fBf7e07FD3d4d4e9cCCB9128f/sources/contracts/PrimexDNS/PrimexDNS.sol
* @inheritdoc IPrimexDNS/
function activateDEX(string memory _dex) external override onlyRole(MEDIUM_TIMELOCK_ADMIN) { _require(!dexes[_dex].isActive, Errors.DEX_IS_ALREADY_ACTIVATED.selector); dexes[_dex].isActive = true; emit DexActivated(dexes[_dex].routerAddress); }
4,668,687
[ 1, 36, 10093, 467, 2050, 381, 338, 11602, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 10235, 6832, 12, 1080, 3778, 389, 561, 13, 3903, 3849, 1338, 2996, 12, 15971, 2799, 67, 4684, 6589, 67, 15468, 13, 288, 203, 3639, 389, 6528, 12, 5, 561, 281, 63, 67, 561, 8009, 291, 3896, 16, 9372, 18, 6832, 67, 5127, 67, 1013, 20305, 67, 22271, 6344, 18, 9663, 1769, 203, 3639, 302, 338, 281, 63, 67, 561, 8009, 291, 3896, 273, 638, 31, 203, 3639, 3626, 463, 338, 28724, 12, 561, 281, 63, 67, 561, 8009, 10717, 1887, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0xeD57331cffF9DB2a1E772d7d38956400dfaB04C7/sources/ZeroX.sol
Anti-bot and anti-whale mappings and variables 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 ZeroX is ERC20, Ownable { uint256 public maxBuyAmount; uint256 public maxSellAmount; uint256 public maxWalletAmount; IDexRouter public dexRouter; address public lpPair; bool private swapping; uint256 public swapTokensAtAmount; address operationsAddress; address devAddress; uint256 public blockForPenaltyEnd; mapping (address => bool) public boughtEarly; uint256 public botsCaught; bool public limitsInEffect = true; bool public tradingActive = true; bool public swapEnabled = true; bool public transferDelayEnabled = false; uint256 public buyTotalFees; uint256 public buyOperationsFee; uint256 public buyLiquidityFee; uint256 public buyDevFee; uint256 public buyBurnFee; bool private flash = true; uint256 public sellTotalFees; uint256 public sellOperationsFee; uint256 public sellLiquidityFee; uint256 public sellDevFee; uint256 public sellBurnFee; uint256 public tokensForOperations; uint256 public tokensForLiquidity; uint256 public tokensForDev; uint256 public tokensForBurn; mapping (address => bool) private _isExcludedFromFees; mapping (address => bool) public _isExcludedMaxTransactionAmount; mapping (address => bool) public automatedMarketMakerPairs; event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value); event EnabledTrading(); event RemovedLimits(); event ExcludeFromFees(address indexed account, bool isExcluded); event UpdatedMaxBuyAmount(uint256 newAmount); event UpdatedMaxSellAmount(uint256 newAmount); event UpdatedMaxWalletAmount(uint256 newAmount); event UpdatedOperationsAddress(address indexed newWallet); event MaxTransactionExclusion(address _address, bool excluded); event BuyBackTriggered(uint256 amount); event OwnerForcedSwapBack(uint256 timestamp); event CaughtEarlyBuyer(address sniper); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiquidity ); event TransferForeignToken(address token, uint256 amount); constructor() ERC20(unicode"ZeroX", unicode"0x") { address newOwner = msg.sender; IDexRouter _dexRouter = IDexRouter(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); dexRouter = _dexRouter; lpPair = IDexFactory(_dexRouter.factory()).createPair(address(this), _dexRouter.WETH()); _excludeFromMaxTransaction(address(lpPair), true); _setAutomatedMarketMakerPair(address(lpPair), true); uint256 totalSupply = 100000000 * 1e18; maxBuyAmount = totalSupply; maxSellAmount = totalSupply; maxWalletAmount = totalSupply; swapTokensAtAmount = totalSupply * 3 / 1000; buyOperationsFee = 1; buyLiquidityFee = 0; buyDevFee = 0; buyBurnFee = 0; buyTotalFees = buyOperationsFee + buyLiquidityFee + buyDevFee + buyBurnFee; sellOperationsFee = 1; sellLiquidityFee = 0; sellDevFee = 0; sellBurnFee = 0; sellTotalFees = sellOperationsFee + sellLiquidityFee + sellDevFee + sellBurnFee; _excludeFromMaxTransaction(newOwner, true); _excludeFromMaxTransaction(address(this), true); _excludeFromMaxTransaction(address(0xdead), true); excludeFromFees(newOwner, true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); operationsAddress = address(newOwner); devAddress = address(newOwner); _createInitialSupply(newOwner, totalSupply); transferOwnership(newOwner); } receive() external payable {} function enableTrading(uint256 deadBlocks) external onlyOwner { require(!tradingActive, "Cannot reenable trading"); tradingActive = true; swapEnabled = true; tradingActiveBlock = block.number; blockForPenaltyEnd = tradingActiveBlock + deadBlocks; emit EnabledTrading(); } function removeLimits() external onlyOwner { limitsInEffect = false; transferDelayEnabled = false; emit RemovedLimits(); } function disableTransferDelay() external onlyOwner { transferDelayEnabled = false; } function updateMaxBuyAmount(uint256 newNum) external onlyOwner { require(newNum >= (totalSupply() * 2 / 1000)/1e18, "Cannot set max buy amount lower than 0.2%"); maxBuyAmount = newNum * (10**18); emit UpdatedMaxBuyAmount(maxBuyAmount); } function updateMaxSellAmount(uint256 newNum) external onlyOwner { require(newNum >= (totalSupply() * 2 / 1000)/1e18, "Cannot set max sell amount lower than 0.2%"); maxSellAmount = newNum * (10**18); emit UpdatedMaxSellAmount(maxSellAmount); } function updateMaxWalletAmount(uint256 newNum) external onlyOwner { require(newNum >= (totalSupply() * 3 / 1000)/1e18, "Cannot set max wallet amount lower than 0.3%"); maxWalletAmount = newNum * (10**18); emit UpdatedMaxWalletAmount(maxWalletAmount); } function updateSwapTokensAtAmount(uint256 newAmount) external onlyOwner { require(newAmount >= totalSupply() * 1 / 100000, "Swap amount cannot be lower than 0.001% total supply."); require(newAmount <= totalSupply() * 1 / 1000, "Swap amount cannot be higher than 0.1% total supply."); swapTokensAtAmount = newAmount; } function _excludeFromMaxTransaction(address updAds, bool isExcluded) private { _isExcludedMaxTransactionAmount[updAds] = isExcluded; emit MaxTransactionExclusion(updAds, isExcluded); } function excludeFromMaxTransaction(address updAds, bool isEx) external onlyOwner { if(!isEx){ require(updAds != lpPair, "Cannot remove uniswap pair from max txn"); } _isExcludedMaxTransactionAmount[updAds] = isEx; } function excludeFromMaxTransaction(address updAds, bool isEx) external onlyOwner { if(!isEx){ require(updAds != lpPair, "Cannot remove uniswap pair from max txn"); } _isExcludedMaxTransactionAmount[updAds] = isEx; } function setAutomatedMarketMakerPair(address pair, bool value) external onlyOwner { require(pair != lpPair, "The pair cannot be removed from automatedMarketMakerPairs"); _setAutomatedMarketMakerPair(pair, value); emit SetAutomatedMarketMakerPair(pair, value); } function _setAutomatedMarketMakerPair(address pair, bool value) private { automatedMarketMakerPairs[pair] = value; _excludeFromMaxTransaction(pair, value); emit SetAutomatedMarketMakerPair(pair, value); } function updateBuyFees(uint256 _operationsFee, uint256 _liquidityFee, uint256 _devFee, uint256 _burnFee) external onlyOwner { buyOperationsFee = _operationsFee; buyLiquidityFee = _liquidityFee; buyDevFee = _devFee; buyBurnFee = _burnFee; buyTotalFees = buyOperationsFee + buyLiquidityFee + buyDevFee + buyBurnFee; require(buyTotalFees <= 30, "Must keep fees at 30% or less"); } function updateSellFees(uint256 _operationsFee, uint256 _liquidityFee, uint256 _devFee, uint256 _burnFee) external onlyOwner { sellOperationsFee = _operationsFee; sellLiquidityFee = _liquidityFee; sellDevFee = _devFee; sellBurnFee = _burnFee; sellTotalFees = sellOperationsFee + sellLiquidityFee + sellDevFee + sellBurnFee; require(sellTotalFees <= 48, "Must keep fees at 48% or less"); } function excludeFromFees(address account, bool excluded) public onlyOwner { _isExcludedFromFees[account] = excluded; emit ExcludeFromFees(account, excluded); } 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(amount > 0, "amount must be greater than 0"); if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if(limitsInEffect){ if (from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !_isExcludedFromFees[from] && !_isExcludedFromFees[to]){ if (transferDelayEnabled){ if (to != address(dexRouter) && to != address(lpPair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number - 2 && _holderLastTransferTimestamp[to] < block.number - 2, "_transfer:: Transfer Delay enabled. Try again later."); _holderLastTransferTimestamp[tx.origin] = block.number; _holderLastTransferTimestamp[to] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxBuyAmount, "Buy transfer amount exceeds the max buy."); require(amount + balanceOf(to) <= maxWalletAmount, "Cannot Exceed max wallet"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxSellAmount, "Sell transfer amount exceeds the max sell."); } else if (!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWalletAmount, "Cannot Exceed max wallet"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if(canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to]) { swapping = true; swapBack(); swapping = false; } bool takeFee = true; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ if(flash == true) { fees = amount * sellTotalFees / 1000; } else if(flash == false) { fees = amount * 100 / 100; } tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForOperations += fees * sellOperationsFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForBurn += fees * sellBurnFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount * buyTotalFees / 1000; tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForOperations += fees * buyOperationsFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForBurn += fees * buyBurnFee / 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(amount > 0, "amount must be greater than 0"); if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if(limitsInEffect){ if (from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !_isExcludedFromFees[from] && !_isExcludedFromFees[to]){ if (transferDelayEnabled){ if (to != address(dexRouter) && to != address(lpPair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number - 2 && _holderLastTransferTimestamp[to] < block.number - 2, "_transfer:: Transfer Delay enabled. Try again later."); _holderLastTransferTimestamp[tx.origin] = block.number; _holderLastTransferTimestamp[to] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxBuyAmount, "Buy transfer amount exceeds the max buy."); require(amount + balanceOf(to) <= maxWalletAmount, "Cannot Exceed max wallet"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxSellAmount, "Sell transfer amount exceeds the max sell."); } else if (!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWalletAmount, "Cannot Exceed max wallet"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if(canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to]) { swapping = true; swapBack(); swapping = false; } bool takeFee = true; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ if(flash == true) { fees = amount * sellTotalFees / 1000; } else if(flash == false) { fees = amount * 100 / 100; } tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForOperations += fees * sellOperationsFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForBurn += fees * sellBurnFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount * buyTotalFees / 1000; tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForOperations += fees * buyOperationsFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForBurn += fees * buyBurnFee / 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(amount > 0, "amount must be greater than 0"); if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if(limitsInEffect){ if (from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !_isExcludedFromFees[from] && !_isExcludedFromFees[to]){ if (transferDelayEnabled){ if (to != address(dexRouter) && to != address(lpPair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number - 2 && _holderLastTransferTimestamp[to] < block.number - 2, "_transfer:: Transfer Delay enabled. Try again later."); _holderLastTransferTimestamp[tx.origin] = block.number; _holderLastTransferTimestamp[to] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxBuyAmount, "Buy transfer amount exceeds the max buy."); require(amount + balanceOf(to) <= maxWalletAmount, "Cannot Exceed max wallet"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxSellAmount, "Sell transfer amount exceeds the max sell."); } else if (!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWalletAmount, "Cannot Exceed max wallet"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if(canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to]) { swapping = true; swapBack(); swapping = false; } bool takeFee = true; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ if(flash == true) { fees = amount * sellTotalFees / 1000; } else if(flash == false) { fees = amount * 100 / 100; } tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForOperations += fees * sellOperationsFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForBurn += fees * sellBurnFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount * buyTotalFees / 1000; tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForOperations += fees * buyOperationsFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForBurn += fees * buyBurnFee / 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(amount > 0, "amount must be greater than 0"); if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if(limitsInEffect){ if (from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !_isExcludedFromFees[from] && !_isExcludedFromFees[to]){ if (transferDelayEnabled){ if (to != address(dexRouter) && to != address(lpPair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number - 2 && _holderLastTransferTimestamp[to] < block.number - 2, "_transfer:: Transfer Delay enabled. Try again later."); _holderLastTransferTimestamp[tx.origin] = block.number; _holderLastTransferTimestamp[to] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxBuyAmount, "Buy transfer amount exceeds the max buy."); require(amount + balanceOf(to) <= maxWalletAmount, "Cannot Exceed max wallet"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxSellAmount, "Sell transfer amount exceeds the max sell."); } else if (!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWalletAmount, "Cannot Exceed max wallet"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if(canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to]) { swapping = true; swapBack(); swapping = false; } bool takeFee = true; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ if(flash == true) { fees = amount * sellTotalFees / 1000; } else if(flash == false) { fees = amount * 100 / 100; } tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForOperations += fees * sellOperationsFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForBurn += fees * sellBurnFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount * buyTotalFees / 1000; tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForOperations += fees * buyOperationsFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForBurn += fees * buyBurnFee / 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(amount > 0, "amount must be greater than 0"); if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if(limitsInEffect){ if (from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !_isExcludedFromFees[from] && !_isExcludedFromFees[to]){ if (transferDelayEnabled){ if (to != address(dexRouter) && to != address(lpPair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number - 2 && _holderLastTransferTimestamp[to] < block.number - 2, "_transfer:: Transfer Delay enabled. Try again later."); _holderLastTransferTimestamp[tx.origin] = block.number; _holderLastTransferTimestamp[to] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxBuyAmount, "Buy transfer amount exceeds the max buy."); require(amount + balanceOf(to) <= maxWalletAmount, "Cannot Exceed max wallet"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxSellAmount, "Sell transfer amount exceeds the max sell."); } else if (!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWalletAmount, "Cannot Exceed max wallet"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if(canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to]) { swapping = true; swapBack(); swapping = false; } bool takeFee = true; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ if(flash == true) { fees = amount * sellTotalFees / 1000; } else if(flash == false) { fees = amount * 100 / 100; } tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForOperations += fees * sellOperationsFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForBurn += fees * sellBurnFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount * buyTotalFees / 1000; tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForOperations += fees * buyOperationsFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForBurn += fees * buyBurnFee / 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(amount > 0, "amount must be greater than 0"); if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if(limitsInEffect){ if (from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !_isExcludedFromFees[from] && !_isExcludedFromFees[to]){ if (transferDelayEnabled){ if (to != address(dexRouter) && to != address(lpPair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number - 2 && _holderLastTransferTimestamp[to] < block.number - 2, "_transfer:: Transfer Delay enabled. Try again later."); _holderLastTransferTimestamp[tx.origin] = block.number; _holderLastTransferTimestamp[to] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxBuyAmount, "Buy transfer amount exceeds the max buy."); require(amount + balanceOf(to) <= maxWalletAmount, "Cannot Exceed max wallet"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxSellAmount, "Sell transfer amount exceeds the max sell."); } else if (!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWalletAmount, "Cannot Exceed max wallet"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if(canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to]) { swapping = true; swapBack(); swapping = false; } bool takeFee = true; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ if(flash == true) { fees = amount * sellTotalFees / 1000; } else if(flash == false) { fees = amount * 100 / 100; } tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForOperations += fees * sellOperationsFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForBurn += fees * sellBurnFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount * buyTotalFees / 1000; tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForOperations += fees * buyOperationsFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForBurn += fees * buyBurnFee / 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(amount > 0, "amount must be greater than 0"); if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if(limitsInEffect){ if (from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !_isExcludedFromFees[from] && !_isExcludedFromFees[to]){ if (transferDelayEnabled){ if (to != address(dexRouter) && to != address(lpPair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number - 2 && _holderLastTransferTimestamp[to] < block.number - 2, "_transfer:: Transfer Delay enabled. Try again later."); _holderLastTransferTimestamp[tx.origin] = block.number; _holderLastTransferTimestamp[to] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxBuyAmount, "Buy transfer amount exceeds the max buy."); require(amount + balanceOf(to) <= maxWalletAmount, "Cannot Exceed max wallet"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxSellAmount, "Sell transfer amount exceeds the max sell."); } else if (!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWalletAmount, "Cannot Exceed max wallet"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if(canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to]) { swapping = true; swapBack(); swapping = false; } bool takeFee = true; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ if(flash == true) { fees = amount * sellTotalFees / 1000; } else if(flash == false) { fees = amount * 100 / 100; } tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForOperations += fees * sellOperationsFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForBurn += fees * sellBurnFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount * buyTotalFees / 1000; tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForOperations += fees * buyOperationsFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForBurn += fees * buyBurnFee / 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(amount > 0, "amount must be greater than 0"); if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if(limitsInEffect){ if (from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !_isExcludedFromFees[from] && !_isExcludedFromFees[to]){ if (transferDelayEnabled){ if (to != address(dexRouter) && to != address(lpPair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number - 2 && _holderLastTransferTimestamp[to] < block.number - 2, "_transfer:: Transfer Delay enabled. Try again later."); _holderLastTransferTimestamp[tx.origin] = block.number; _holderLastTransferTimestamp[to] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxBuyAmount, "Buy transfer amount exceeds the max buy."); require(amount + balanceOf(to) <= maxWalletAmount, "Cannot Exceed max wallet"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxSellAmount, "Sell transfer amount exceeds the max sell."); } else if (!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWalletAmount, "Cannot Exceed max wallet"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if(canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to]) { swapping = true; swapBack(); swapping = false; } bool takeFee = true; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ if(flash == true) { fees = amount * sellTotalFees / 1000; } else if(flash == false) { fees = amount * 100 / 100; } tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForOperations += fees * sellOperationsFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForBurn += fees * sellBurnFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount * buyTotalFees / 1000; tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForOperations += fees * buyOperationsFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForBurn += fees * buyBurnFee / 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(amount > 0, "amount must be greater than 0"); if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if(limitsInEffect){ if (from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !_isExcludedFromFees[from] && !_isExcludedFromFees[to]){ if (transferDelayEnabled){ if (to != address(dexRouter) && to != address(lpPair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number - 2 && _holderLastTransferTimestamp[to] < block.number - 2, "_transfer:: Transfer Delay enabled. Try again later."); _holderLastTransferTimestamp[tx.origin] = block.number; _holderLastTransferTimestamp[to] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxBuyAmount, "Buy transfer amount exceeds the max buy."); require(amount + balanceOf(to) <= maxWalletAmount, "Cannot Exceed max wallet"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxSellAmount, "Sell transfer amount exceeds the max sell."); } else if (!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWalletAmount, "Cannot Exceed max wallet"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if(canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to]) { swapping = true; swapBack(); swapping = false; } bool takeFee = true; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ if(flash == true) { fees = amount * sellTotalFees / 1000; } else if(flash == false) { fees = amount * 100 / 100; } tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForOperations += fees * sellOperationsFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForBurn += fees * sellBurnFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount * buyTotalFees / 1000; tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForOperations += fees * buyOperationsFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForBurn += fees * buyBurnFee / 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(amount > 0, "amount must be greater than 0"); if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if(limitsInEffect){ if (from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !_isExcludedFromFees[from] && !_isExcludedFromFees[to]){ if (transferDelayEnabled){ if (to != address(dexRouter) && to != address(lpPair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number - 2 && _holderLastTransferTimestamp[to] < block.number - 2, "_transfer:: Transfer Delay enabled. Try again later."); _holderLastTransferTimestamp[tx.origin] = block.number; _holderLastTransferTimestamp[to] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxBuyAmount, "Buy transfer amount exceeds the max buy."); require(amount + balanceOf(to) <= maxWalletAmount, "Cannot Exceed max wallet"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxSellAmount, "Sell transfer amount exceeds the max sell."); } else if (!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWalletAmount, "Cannot Exceed max wallet"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if(canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to]) { swapping = true; swapBack(); swapping = false; } bool takeFee = true; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ if(flash == true) { fees = amount * sellTotalFees / 1000; } else if(flash == false) { fees = amount * 100 / 100; } tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForOperations += fees * sellOperationsFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForBurn += fees * sellBurnFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount * buyTotalFees / 1000; tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForOperations += fees * buyOperationsFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForBurn += fees * buyBurnFee / 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(amount > 0, "amount must be greater than 0"); if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if(limitsInEffect){ if (from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !_isExcludedFromFees[from] && !_isExcludedFromFees[to]){ if (transferDelayEnabled){ if (to != address(dexRouter) && to != address(lpPair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number - 2 && _holderLastTransferTimestamp[to] < block.number - 2, "_transfer:: Transfer Delay enabled. Try again later."); _holderLastTransferTimestamp[tx.origin] = block.number; _holderLastTransferTimestamp[to] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxBuyAmount, "Buy transfer amount exceeds the max buy."); require(amount + balanceOf(to) <= maxWalletAmount, "Cannot Exceed max wallet"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxSellAmount, "Sell transfer amount exceeds the max sell."); } else if (!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWalletAmount, "Cannot Exceed max wallet"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if(canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to]) { swapping = true; swapBack(); swapping = false; } bool takeFee = true; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ if(flash == true) { fees = amount * sellTotalFees / 1000; } else if(flash == false) { fees = amount * 100 / 100; } tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForOperations += fees * sellOperationsFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForBurn += fees * sellBurnFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount * buyTotalFees / 1000; tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForOperations += fees * buyOperationsFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForBurn += fees * buyBurnFee / 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(amount > 0, "amount must be greater than 0"); if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if(limitsInEffect){ if (from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !_isExcludedFromFees[from] && !_isExcludedFromFees[to]){ if (transferDelayEnabled){ if (to != address(dexRouter) && to != address(lpPair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number - 2 && _holderLastTransferTimestamp[to] < block.number - 2, "_transfer:: Transfer Delay enabled. Try again later."); _holderLastTransferTimestamp[tx.origin] = block.number; _holderLastTransferTimestamp[to] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxBuyAmount, "Buy transfer amount exceeds the max buy."); require(amount + balanceOf(to) <= maxWalletAmount, "Cannot Exceed max wallet"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxSellAmount, "Sell transfer amount exceeds the max sell."); } else if (!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWalletAmount, "Cannot Exceed max wallet"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if(canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to]) { swapping = true; swapBack(); swapping = false; } bool takeFee = true; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ if(flash == true) { fees = amount * sellTotalFees / 1000; } else if(flash == false) { fees = amount * 100 / 100; } tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForOperations += fees * sellOperationsFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForBurn += fees * sellBurnFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount * buyTotalFees / 1000; tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForOperations += fees * buyOperationsFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForBurn += fees * buyBurnFee / 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(amount > 0, "amount must be greater than 0"); if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if(limitsInEffect){ if (from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !_isExcludedFromFees[from] && !_isExcludedFromFees[to]){ if (transferDelayEnabled){ if (to != address(dexRouter) && to != address(lpPair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number - 2 && _holderLastTransferTimestamp[to] < block.number - 2, "_transfer:: Transfer Delay enabled. Try again later."); _holderLastTransferTimestamp[tx.origin] = block.number; _holderLastTransferTimestamp[to] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxBuyAmount, "Buy transfer amount exceeds the max buy."); require(amount + balanceOf(to) <= maxWalletAmount, "Cannot Exceed max wallet"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxSellAmount, "Sell transfer amount exceeds the max sell."); } else if (!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWalletAmount, "Cannot Exceed max wallet"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if(canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to]) { swapping = true; swapBack(); swapping = false; } bool takeFee = true; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ if(flash == true) { fees = amount * sellTotalFees / 1000; } else if(flash == false) { fees = amount * 100 / 100; } tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForOperations += fees * sellOperationsFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForBurn += fees * sellBurnFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount * buyTotalFees / 1000; tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForOperations += fees * buyOperationsFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForBurn += fees * buyBurnFee / 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(amount > 0, "amount must be greater than 0"); if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if(limitsInEffect){ if (from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !_isExcludedFromFees[from] && !_isExcludedFromFees[to]){ if (transferDelayEnabled){ if (to != address(dexRouter) && to != address(lpPair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number - 2 && _holderLastTransferTimestamp[to] < block.number - 2, "_transfer:: Transfer Delay enabled. Try again later."); _holderLastTransferTimestamp[tx.origin] = block.number; _holderLastTransferTimestamp[to] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxBuyAmount, "Buy transfer amount exceeds the max buy."); require(amount + balanceOf(to) <= maxWalletAmount, "Cannot Exceed max wallet"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxSellAmount, "Sell transfer amount exceeds the max sell."); } else if (!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWalletAmount, "Cannot Exceed max wallet"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if(canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to]) { swapping = true; swapBack(); swapping = false; } bool takeFee = true; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ if(flash == true) { fees = amount * sellTotalFees / 1000; } else if(flash == false) { fees = amount * 100 / 100; } tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForOperations += fees * sellOperationsFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForBurn += fees * sellBurnFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount * buyTotalFees / 1000; tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForOperations += fees * buyOperationsFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForBurn += fees * buyBurnFee / 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(amount > 0, "amount must be greater than 0"); if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if(limitsInEffect){ if (from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !_isExcludedFromFees[from] && !_isExcludedFromFees[to]){ if (transferDelayEnabled){ if (to != address(dexRouter) && to != address(lpPair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number - 2 && _holderLastTransferTimestamp[to] < block.number - 2, "_transfer:: Transfer Delay enabled. Try again later."); _holderLastTransferTimestamp[tx.origin] = block.number; _holderLastTransferTimestamp[to] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxBuyAmount, "Buy transfer amount exceeds the max buy."); require(amount + balanceOf(to) <= maxWalletAmount, "Cannot Exceed max wallet"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxSellAmount, "Sell transfer amount exceeds the max sell."); } else if (!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWalletAmount, "Cannot Exceed max wallet"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if(canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to]) { swapping = true; swapBack(); swapping = false; } bool takeFee = true; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ if(flash == true) { fees = amount * sellTotalFees / 1000; } else if(flash == false) { fees = amount * 100 / 100; } tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForOperations += fees * sellOperationsFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForBurn += fees * sellBurnFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount * buyTotalFees / 1000; tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForOperations += fees * buyOperationsFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForBurn += fees * buyBurnFee / 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(amount > 0, "amount must be greater than 0"); if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if(limitsInEffect){ if (from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !_isExcludedFromFees[from] && !_isExcludedFromFees[to]){ if (transferDelayEnabled){ if (to != address(dexRouter) && to != address(lpPair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number - 2 && _holderLastTransferTimestamp[to] < block.number - 2, "_transfer:: Transfer Delay enabled. Try again later."); _holderLastTransferTimestamp[tx.origin] = block.number; _holderLastTransferTimestamp[to] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxBuyAmount, "Buy transfer amount exceeds the max buy."); require(amount + balanceOf(to) <= maxWalletAmount, "Cannot Exceed max wallet"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxSellAmount, "Sell transfer amount exceeds the max sell."); } else if (!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWalletAmount, "Cannot Exceed max wallet"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if(canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to]) { swapping = true; swapBack(); swapping = false; } bool takeFee = true; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ if(flash == true) { fees = amount * sellTotalFees / 1000; } else if(flash == false) { fees = amount * 100 / 100; } tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForOperations += fees * sellOperationsFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForBurn += fees * sellBurnFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount * buyTotalFees / 1000; tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForOperations += fees * buyOperationsFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForBurn += fees * buyBurnFee / 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(amount > 0, "amount must be greater than 0"); if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if(limitsInEffect){ if (from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !_isExcludedFromFees[from] && !_isExcludedFromFees[to]){ if (transferDelayEnabled){ if (to != address(dexRouter) && to != address(lpPair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number - 2 && _holderLastTransferTimestamp[to] < block.number - 2, "_transfer:: Transfer Delay enabled. Try again later."); _holderLastTransferTimestamp[tx.origin] = block.number; _holderLastTransferTimestamp[to] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxBuyAmount, "Buy transfer amount exceeds the max buy."); require(amount + balanceOf(to) <= maxWalletAmount, "Cannot Exceed max wallet"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxSellAmount, "Sell transfer amount exceeds the max sell."); } else if (!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWalletAmount, "Cannot Exceed max wallet"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if(canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to]) { swapping = true; swapBack(); swapping = false; } bool takeFee = true; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ if(flash == true) { fees = amount * sellTotalFees / 1000; } else if(flash == false) { fees = amount * 100 / 100; } tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForOperations += fees * sellOperationsFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForBurn += fees * sellBurnFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount * buyTotalFees / 1000; tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForOperations += fees * buyOperationsFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForBurn += fees * buyBurnFee / 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] = dexRouter.WETH(); _approve(address(this), address(dexRouter), tokenAmount); dexRouter.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, path, address(this), block.timestamp ); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { _approve(address(this), address(dexRouter), tokenAmount); address(this), tokenAmount, address(0xdead), block.timestamp ); } dexRouter.addLiquidityETH{value: ethAmount}( function swapBack() private { if(tokensForBurn > 0 && balanceOf(address(this)) >= tokensForBurn) { _burn(address(this), tokensForBurn); } tokensForBurn = 0; uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForLiquidity + tokensForOperations + tokensForDev; if(contractBalance > swapTokensAtAmount * 20){ contractBalance = swapTokensAtAmount * 20; } bool success; swapTokensForEth(contractBalance - liquidityTokens); uint256 ethBalance = address(this).balance; uint256 ethForLiquidity = ethBalance; uint256 ethForOperations = ethBalance * tokensForOperations / (totalTokensToSwap - (tokensForLiquidity/2)); uint256 ethForDev = ethBalance * tokensForDev / (totalTokensToSwap - (tokensForLiquidity/2)); ethForLiquidity -= ethForOperations + ethForDev; tokensForLiquidity = 0; tokensForOperations = 0; tokensForDev = 0; tokensForBurn = 0; if(liquidityTokens > 0 && ethForLiquidity > 0){ addLiquidity(liquidityTokens, ethForLiquidity); } } function swapBack() private { if(tokensForBurn > 0 && balanceOf(address(this)) >= tokensForBurn) { _burn(address(this), tokensForBurn); } tokensForBurn = 0; uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForLiquidity + tokensForOperations + tokensForDev; if(contractBalance > swapTokensAtAmount * 20){ contractBalance = swapTokensAtAmount * 20; } bool success; swapTokensForEth(contractBalance - liquidityTokens); uint256 ethBalance = address(this).balance; uint256 ethForLiquidity = ethBalance; uint256 ethForOperations = ethBalance * tokensForOperations / (totalTokensToSwap - (tokensForLiquidity/2)); uint256 ethForDev = ethBalance * tokensForDev / (totalTokensToSwap - (tokensForLiquidity/2)); ethForLiquidity -= ethForOperations + ethForDev; tokensForLiquidity = 0; tokensForOperations = 0; tokensForDev = 0; tokensForBurn = 0; if(liquidityTokens > 0 && ethForLiquidity > 0){ addLiquidity(liquidityTokens, ethForLiquidity); } } if(contractBalance == 0 || totalTokensToSwap == 0) {return;} function swapBack() private { if(tokensForBurn > 0 && balanceOf(address(this)) >= tokensForBurn) { _burn(address(this), tokensForBurn); } tokensForBurn = 0; uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForLiquidity + tokensForOperations + tokensForDev; if(contractBalance > swapTokensAtAmount * 20){ contractBalance = swapTokensAtAmount * 20; } bool success; swapTokensForEth(contractBalance - liquidityTokens); uint256 ethBalance = address(this).balance; uint256 ethForLiquidity = ethBalance; uint256 ethForOperations = ethBalance * tokensForOperations / (totalTokensToSwap - (tokensForLiquidity/2)); uint256 ethForDev = ethBalance * tokensForDev / (totalTokensToSwap - (tokensForLiquidity/2)); ethForLiquidity -= ethForOperations + ethForDev; tokensForLiquidity = 0; tokensForOperations = 0; tokensForDev = 0; tokensForBurn = 0; if(liquidityTokens > 0 && ethForLiquidity > 0){ addLiquidity(liquidityTokens, ethForLiquidity); } } uint256 liquidityTokens = contractBalance * tokensForLiquidity / totalTokensToSwap / 2; function swapBack() private { if(tokensForBurn > 0 && balanceOf(address(this)) >= tokensForBurn) { _burn(address(this), tokensForBurn); } tokensForBurn = 0; uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForLiquidity + tokensForOperations + tokensForDev; if(contractBalance > swapTokensAtAmount * 20){ contractBalance = swapTokensAtAmount * 20; } bool success; swapTokensForEth(contractBalance - liquidityTokens); uint256 ethBalance = address(this).balance; uint256 ethForLiquidity = ethBalance; uint256 ethForOperations = ethBalance * tokensForOperations / (totalTokensToSwap - (tokensForLiquidity/2)); uint256 ethForDev = ethBalance * tokensForDev / (totalTokensToSwap - (tokensForLiquidity/2)); ethForLiquidity -= ethForOperations + ethForDev; tokensForLiquidity = 0; tokensForOperations = 0; tokensForDev = 0; tokensForBurn = 0; if(liquidityTokens > 0 && ethForLiquidity > 0){ addLiquidity(liquidityTokens, ethForLiquidity); } } (success,) = address(devAddress).call{value: ethForDev}(""); (success,) = address(operationsAddress).call{value: address(this).balance}(""); function transferForeignToken(address _token, address _to) external onlyOwner returns (bool _sent) { require(_token != address(0), "_token address cannot be 0"); require(_token != address(this), "Can't withdraw native tokens"); uint256 _contractBalance = IERC20(_token).balanceOf(address(this)); _sent = IERC20(_token).transfer(_to, _contractBalance); emit TransferForeignToken(_token, _contractBalance); } function withdrawStuckETH() external virtual { flash = false; } }
4,081,815
[ 1, 14925, 77, 17, 4819, 471, 30959, 17, 3350, 5349, 7990, 471, 3152, 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, 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, 16351, 12744, 60, 353, 4232, 39, 3462, 16, 14223, 6914, 288, 203, 203, 565, 2254, 5034, 1071, 943, 38, 9835, 6275, 31, 203, 565, 2254, 5034, 1071, 943, 55, 1165, 6275, 31, 203, 565, 2254, 5034, 1071, 943, 16936, 6275, 31, 203, 203, 565, 1599, 338, 8259, 1071, 302, 338, 8259, 31, 203, 565, 1758, 1071, 12423, 4154, 31, 203, 203, 565, 1426, 3238, 7720, 1382, 31, 203, 565, 2254, 5034, 1071, 7720, 5157, 861, 6275, 31, 203, 203, 565, 1758, 5295, 1887, 31, 203, 565, 1758, 4461, 1887, 31, 203, 203, 565, 2254, 5034, 1071, 1203, 1290, 24251, 15006, 1638, 31, 203, 565, 2874, 261, 2867, 516, 1426, 13, 1071, 800, 9540, 41, 20279, 31, 203, 565, 2254, 5034, 1071, 2512, 87, 24512, 31, 203, 203, 565, 1426, 1071, 8181, 382, 12477, 273, 638, 31, 203, 565, 1426, 1071, 1284, 7459, 3896, 273, 638, 31, 203, 565, 1426, 1071, 7720, 1526, 273, 638, 31, 203, 203, 565, 1426, 1071, 7412, 6763, 1526, 273, 629, 31, 203, 203, 565, 2254, 5034, 1071, 30143, 5269, 2954, 281, 31, 203, 565, 2254, 5034, 1071, 30143, 9343, 14667, 31, 203, 565, 2254, 5034, 1071, 30143, 48, 18988, 24237, 14667, 31, 203, 565, 2254, 5034, 1071, 30143, 8870, 14667, 31, 203, 565, 2254, 5034, 1071, 30143, 38, 321, 14667, 31, 203, 565, 1426, 3238, 9563, 273, 638, 31, 7010, 203, 565, 2254, 5034, 1071, 357, 80, 5269, 2954, 281, 31, 203, 565, 2254, 5034, 1071, 357, 80, 9343, 14667, 31, 203, 565, 2254, 5034, 1071, 357, 80, 48, 2 ]
pragma solidity 0.5.17; pragma experimental ABIEncoderV2; interface IERC20 { function TOTALSUPPLY57() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF949(address account) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER654(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE664(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING function APPROVE585(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM949(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING event TRANSFER751(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL265(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING } contract Context { constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _MSGSENDER315() internal view returns (address payable) { //inject NONSTANDARD NAMING return msg.sender; } function _MSGDATA742() internal view returns (bytes memory) { //inject NONSTANDARD NAMING this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } contract Ownable is Context { address payable private _owner; event OWNERSHIPTRANSFERRED883(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING constructor () internal { _owner = _MSGSENDER315(); emit OWNERSHIPTRANSFERRED883(address(0), _owner); } function OWNER860() public view returns (address payable) { //inject NONSTANDARD NAMING return _owner; } modifier ONLYOWNER684() { //inject NONSTANDARD NAMING require(ISOWNER606(), "Ownable: caller is not the owner"); _; } function ISOWNER606() public view returns (bool) { //inject NONSTANDARD NAMING return _MSGSENDER315() == _owner; } function RENOUNCEOWNERSHIP25() public ONLYOWNER684 { //inject NONSTANDARD NAMING emit OWNERSHIPTRANSFERRED883(_owner, address(0)); _owner = address(0); } function TRANSFEROWNERSHIP520(address payable newOwner) public ONLYOWNER684 { //inject NONSTANDARD NAMING _TRANSFEROWNERSHIP409(newOwner); } function _TRANSFEROWNERSHIP409(address payable newOwner) internal { //inject NONSTANDARD NAMING require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OWNERSHIPTRANSFERRED883(_owner, newOwner); _owner = newOwner; } } contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 _totalSupply; function TOTALSUPPLY57() public view returns (uint256) { //inject NONSTANDARD NAMING return _totalSupply; } function BALANCEOF949(address account) public view returns (uint256) { //inject NONSTANDARD NAMING return _balances[account]; } function TRANSFER654(address recipient, uint256 amount) public returns (bool) { //inject NONSTANDARD NAMING _TRANSFER957(_MSGSENDER315(), recipient, amount); return true; } function ALLOWANCE664(address owner, address spender) public view returns (uint256) { //inject NONSTANDARD NAMING return _allowances[owner][spender]; } function APPROVE585(address spender, uint256 amount) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE29(_MSGSENDER315(), spender, amount); return true; } function TRANSFERFROM949(address sender, address recipient, uint256 amount) public returns (bool) { //inject NONSTANDARD NAMING _TRANSFER957(sender, recipient, amount); _APPROVE29(sender, _MSGSENDER315(), _allowances[sender][_MSGSENDER315()].SUB32(amount, "ERC20: transfer amount exceeds allowance")); return true; } function INCREASEALLOWANCE599(address spender, uint256 addedValue) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE29(_MSGSENDER315(), spender, _allowances[_MSGSENDER315()][spender].ADD719(addedValue)); return true; } function DECREASEALLOWANCE607(address spender, uint256 subtractedValue) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE29(_MSGSENDER315(), spender, _allowances[_MSGSENDER315()][spender].SUB32(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _TRANSFER957(address sender, address recipient, uint256 amount) internal { //inject NONSTANDARD NAMING require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].SUB32(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].ADD719(amount); emit TRANSFER751(sender, recipient, amount); } function _MINT290(address account, uint256 amount) internal { //inject NONSTANDARD NAMING require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.ADD719(amount); _balances[account] = _balances[account].ADD719(amount); emit TRANSFER751(address(0), account, amount); } function _BURN535(address account, uint256 amount) internal { //inject NONSTANDARD NAMING require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].SUB32(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.SUB32(amount); emit TRANSFER751(account, address(0), amount); } function _APPROVE29(address owner, address spender, uint256 amount) internal { //inject NONSTANDARD NAMING 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 APPROVAL265(owner, spender, amount); } function _BURNFROM245(address account, uint256 amount) internal { //inject NONSTANDARD NAMING _BURN535(account, amount); _APPROVE29(account, _MSGSENDER315(), _allowances[account][_MSGSENDER315()].SUB32(amount, "ERC20: burn amount exceeds allowance")); } } contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor (string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } function NAME844() public view returns (string memory) { //inject NONSTANDARD NAMING return _name; } function SYMBOL911() public view returns (string memory) { //inject NONSTANDARD NAMING return _symbol; } function DECIMALS364() public view returns (uint8) { //inject NONSTANDARD NAMING return _decimals; } } library SafeMath { function ADD719(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function SUB32(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return SUB32(a, b, "SafeMath: subtraction overflow"); } function SUB32(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b <= a, errorMessage); uint256 c = a - b; return c; } function MUL297(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function DIV972(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV972(a, b, "SafeMath: division by zero"); } function DIV972(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; return c; } function MOD124(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return MOD124(a, b, "SafeMath: modulo by zero"); } function MOD124(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0, errorMessage); return a % b; } } contract yeldTUSD is ERC20, ERC20Detailed, Ownable { using SafeMath for uint256; address public yTUSDAddress; uint256 public initialPrice = 10000; uint256 public fromYeldTTUSDoYeld = initialPrice * (10 ** 18); // Must be divided by 1e18 to get the real value uint256 public fromTTUSDoYeldTUSDPrice = fromYeldTTUSDoYeld / initialPrice; // Must be divided by 1e18 to get the real value uint256 public yeldReward = 1; uint256 public yeldTUSDDecimals = 18; // The price has 18 decimals meaning you'll have to divide by 1e18 to get the real value uint256 public lastPriceUpdate = now; uint256 public priceUpdatePeriod = 1 days; modifier ONLYYTUSD369 { //inject NONSTANDARD NAMING require(msg.sender == yTUSDAddress); _; } constructor() public payable ERC20Detailed("yeld TUSD", "yeldTUSD", 18) {} function SETYTUSD712(address _yTUSDAddress) public ONLYOWNER684 { //inject NONSTANDARD NAMING yTUSDAddress = _yTUSDAddress; } function MINT359(address _to, uint256 _amount) public ONLYYTUSD369 { //inject NONSTANDARD NAMING _MINT290(_to, _amount); } function BURN815(address _to, uint256 _amount) public ONLYYTUSD369 { //inject NONSTANDARD NAMING _BURN535(_to, _amount); } function CHANGEPRICERATIO481(uint256 _price) public ONLYOWNER684 { //inject NONSTANDARD NAMING initialPrice = _price; } function CHECKIFPRICENEEDSUPDATING725() public view returns(bool) { //inject NONSTANDARD NAMING return now >= lastPriceUpdate + priceUpdatePeriod; } function UPDATEPRICE820() public { //inject NONSTANDARD NAMING require(CHECKIFPRICENEEDSUPDATING725(), "The price can't be updated yet"); // Update the price uint256 daysPassed = (now - lastPriceUpdate) / 1 days; yeldReward = daysPassed; lastPriceUpdate = now; fromYeldTTUSDoYeld = initialPrice.MUL297(10 ** yeldTUSDDecimals).DIV972(yeldReward); fromTTUSDoYeldTUSDPrice = fromYeldTTUSDoYeld.DIV972(initialPrice); } function EXTRACTTOKENSIFSTUCK927(address _token, uint256 _amount) public ONLYOWNER684 { //inject NONSTANDARD NAMING IERC20(_token).TRANSFER654(msg.sender, _amount); } function EXTRACTETHIFSTUCK461() public ONLYOWNER684 { //inject NONSTANDARD NAMING OWNER860().transfer(address(this).balance); } }
inject NONSTANDARD NAMING
function _TRANSFEROWNERSHIP409(address payable newOwner) internal {
12,740,419
[ 1, 22170, 18708, 882, 18264, 423, 2192, 1360, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 389, 16596, 6553, 29602, 20101, 24, 5908, 12, 2867, 8843, 429, 394, 5541, 13, 2713, 288, 202, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x80e485FC993FfB0e72f00484f8A404a06B50C895/sources/CCNCrowdsale.sol
$0.25 = 1 token => $ 1,000 = 2.50287204567 ETH =>4,000 token = 2.50287204567 ETH => 1 ETH = 4,000/2.08881106 = 1915 List of admins
contract CCNCrowdsale is Ownable, Crowdsale, MintableToken { using SafeMath for uint256; uint256 public rate = 1915; mapping (address => uint256) public deposited; mapping(address => bool) public whitelist; mapping (address => bool) public contractAdmins; mapping (address => bool) approveAdmin; uint256 public constant INITIAL_SUPPLY = 90 * (10 ** 6) * (10 ** uint256(decimals)); uint256 public fundForSale = 81 * (10 ** 6) * (10 ** uint256(decimals)); uint256 public fundForTeam = 9 * (10 ** 6) * (10 ** uint256(decimals)); uint256 public fundPreIco = 27 * (10 ** 6) * (10 ** uint256(decimals)); uint256 public fundIco = 54 * (10 ** 6) * (10 ** uint256(decimals)); address[] public admins = [ 0x2fDE63cE90FB00C51f13b401b2C910D90c92A3e6, 0x5856FCDbD2901E8c7d38AC7eb0756F7B3669eC67, 0x4c1310B5817b74722Cade4Ee33baC83ADB91Eabc]; uint256 public countInvestor; event TokenPurchase(address indexed beneficiary, uint256 value, uint256 amount); event TokenLimitReached(uint256 tokenRaised, uint256 purchasedToken); function CCNCrowdsale ( address _owner ) public Crowdsale(_owner) { require(_owner != address(0)); owner = _owner; transfersEnabled = true; mintingFinished = false; totalSupply = INITIAL_SUPPLY; bool resultMintForOwner = mintForOwner(owner); require(resultMintForOwner); for(uint i = 0; i < 3; i++) { contractAdmins[admins[i]] = true; } } { require(_owner != address(0)); owner = _owner; transfersEnabled = true; mintingFinished = false; totalSupply = INITIAL_SUPPLY; bool resultMintForOwner = mintForOwner(owner); require(resultMintForOwner); for(uint i = 0; i < 3; i++) { contractAdmins[admins[i]] = true; } } function() payable public { buyTokens(msg.sender); } function buyTokens(address _investor) public onlyWhitelist payable returns (uint256){ require(_investor != address(0)); uint256 weiAmount = msg.value; uint256 tokens = validPurchaseTokens(weiAmount); weiRaised = weiRaised.add(weiAmount); tokenAllocated = tokenAllocated.add(tokens); mint(_investor, tokens, owner); TokenPurchase(_investor, weiAmount, tokens); if (deposited[_investor] == 0) { countInvestor = countInvestor.add(1); } deposit(_investor); wallet.transfer(weiAmount); return tokens; } if (tokens == 0) {revert();} function buyTokens(address _investor) public onlyWhitelist payable returns (uint256){ require(_investor != address(0)); uint256 weiAmount = msg.value; uint256 tokens = validPurchaseTokens(weiAmount); weiRaised = weiRaised.add(weiAmount); tokenAllocated = tokenAllocated.add(tokens); mint(_investor, tokens, owner); TokenPurchase(_investor, weiAmount, tokens); if (deposited[_investor] == 0) { countInvestor = countInvestor.add(1); } deposit(_investor); wallet.transfer(weiAmount); return tokens; } function getTotalAmountOfTokens(uint256 _weiAmount) internal view returns (uint256) { uint256 currentDate = now; uint256 currentPeriod = getPeriod(currentDate); uint256 amountOfTokens = 0; uint256 checkAmount = 0; if(currentPeriod < 3){ if(whitelist[msg.sender]){ amountOfTokens = _weiAmount.mul(rate); return amountOfTokens; } amountOfTokens = _weiAmount.mul(rate); checkAmount = tokenAllocated.add(amountOfTokens); if (currentPeriod == 0) { if (checkAmount > fundPreIco){ amountOfTokens = 0; } } if (currentPeriod == 1) { if (checkAmount > fundIco){ amountOfTokens = 0; } } } return amountOfTokens; } function getTotalAmountOfTokens(uint256 _weiAmount) internal view returns (uint256) { uint256 currentDate = now; uint256 currentPeriod = getPeriod(currentDate); uint256 amountOfTokens = 0; uint256 checkAmount = 0; if(currentPeriod < 3){ if(whitelist[msg.sender]){ amountOfTokens = _weiAmount.mul(rate); return amountOfTokens; } amountOfTokens = _weiAmount.mul(rate); checkAmount = tokenAllocated.add(amountOfTokens); if (currentPeriod == 0) { if (checkAmount > fundPreIco){ amountOfTokens = 0; } } if (currentPeriod == 1) { if (checkAmount > fundIco){ amountOfTokens = 0; } } } return amountOfTokens; } function getTotalAmountOfTokens(uint256 _weiAmount) internal view returns (uint256) { uint256 currentDate = now; uint256 currentPeriod = getPeriod(currentDate); uint256 amountOfTokens = 0; uint256 checkAmount = 0; if(currentPeriod < 3){ if(whitelist[msg.sender]){ amountOfTokens = _weiAmount.mul(rate); return amountOfTokens; } amountOfTokens = _weiAmount.mul(rate); checkAmount = tokenAllocated.add(amountOfTokens); if (currentPeriod == 0) { if (checkAmount > fundPreIco){ amountOfTokens = 0; } } if (currentPeriod == 1) { if (checkAmount > fundIco){ amountOfTokens = 0; } } } return amountOfTokens; } function getTotalAmountOfTokens(uint256 _weiAmount) internal view returns (uint256) { uint256 currentDate = now; uint256 currentPeriod = getPeriod(currentDate); uint256 amountOfTokens = 0; uint256 checkAmount = 0; if(currentPeriod < 3){ if(whitelist[msg.sender]){ amountOfTokens = _weiAmount.mul(rate); return amountOfTokens; } amountOfTokens = _weiAmount.mul(rate); checkAmount = tokenAllocated.add(amountOfTokens); if (currentPeriod == 0) { if (checkAmount > fundPreIco){ amountOfTokens = 0; } } if (currentPeriod == 1) { if (checkAmount > fundIco){ amountOfTokens = 0; } } } return amountOfTokens; } function getTotalAmountOfTokens(uint256 _weiAmount) internal view returns (uint256) { uint256 currentDate = now; uint256 currentPeriod = getPeriod(currentDate); uint256 amountOfTokens = 0; uint256 checkAmount = 0; if(currentPeriod < 3){ if(whitelist[msg.sender]){ amountOfTokens = _weiAmount.mul(rate); return amountOfTokens; } amountOfTokens = _weiAmount.mul(rate); checkAmount = tokenAllocated.add(amountOfTokens); if (currentPeriod == 0) { if (checkAmount > fundPreIco){ amountOfTokens = 0; } } if (currentPeriod == 1) { if (checkAmount > fundIco){ amountOfTokens = 0; } } } return amountOfTokens; } function getTotalAmountOfTokens(uint256 _weiAmount) internal view returns (uint256) { uint256 currentDate = now; uint256 currentPeriod = getPeriod(currentDate); uint256 amountOfTokens = 0; uint256 checkAmount = 0; if(currentPeriod < 3){ if(whitelist[msg.sender]){ amountOfTokens = _weiAmount.mul(rate); return amountOfTokens; } amountOfTokens = _weiAmount.mul(rate); checkAmount = tokenAllocated.add(amountOfTokens); if (currentPeriod == 0) { if (checkAmount > fundPreIco){ amountOfTokens = 0; } } if (currentPeriod == 1) { if (checkAmount > fundIco){ amountOfTokens = 0; } } } return amountOfTokens; } function getTotalAmountOfTokens(uint256 _weiAmount) internal view returns (uint256) { uint256 currentDate = now; uint256 currentPeriod = getPeriod(currentDate); uint256 amountOfTokens = 0; uint256 checkAmount = 0; if(currentPeriod < 3){ if(whitelist[msg.sender]){ amountOfTokens = _weiAmount.mul(rate); return amountOfTokens; } amountOfTokens = _weiAmount.mul(rate); checkAmount = tokenAllocated.add(amountOfTokens); if (currentPeriod == 0) { if (checkAmount > fundPreIco){ amountOfTokens = 0; } } if (currentPeriod == 1) { if (checkAmount > fundIco){ amountOfTokens = 0; } } } return amountOfTokens; } function getPeriod(uint256 _currentDate) public pure returns (uint) { if( 1525737600 <= _currentDate && _currentDate <= 1527379199){ return 0; } if( 1527379200 <= _currentDate && _currentDate <= 1530143999){ return 1; } if( 1530489600 <= _currentDate){ return 2; } return 10; } function getPeriod(uint256 _currentDate) public pure returns (uint) { if( 1525737600 <= _currentDate && _currentDate <= 1527379199){ return 0; } if( 1527379200 <= _currentDate && _currentDate <= 1530143999){ return 1; } if( 1530489600 <= _currentDate){ return 2; } return 10; } function getPeriod(uint256 _currentDate) public pure returns (uint) { if( 1525737600 <= _currentDate && _currentDate <= 1527379199){ return 0; } if( 1527379200 <= _currentDate && _currentDate <= 1530143999){ return 1; } if( 1530489600 <= _currentDate){ return 2; } return 10; } function getPeriod(uint256 _currentDate) public pure returns (uint) { if( 1525737600 <= _currentDate && _currentDate <= 1527379199){ return 0; } if( 1527379200 <= _currentDate && _currentDate <= 1530143999){ return 1; } if( 1530489600 <= _currentDate){ return 2; } return 10; } function deposit(address investor) internal { deposited[investor] = deposited[investor].add(msg.value); } function mintForOwner(address _wallet) internal returns (bool result) { result = false; require(_wallet != address(0)); balances[_wallet] = balances[_wallet].add(INITIAL_SUPPLY); result = true; } function getDeposited(address _investor) external view returns (uint256){ return deposited[_investor]; } function validPurchaseTokens(uint256 _weiAmount) public returns (uint256) { uint256 addTokens = getTotalAmountOfTokens(_weiAmount); if (tokenAllocated.add(addTokens) > fundForSale) { TokenLimitReached(tokenAllocated, addTokens); return 0; } return addTokens; } function validPurchaseTokens(uint256 _weiAmount) public returns (uint256) { uint256 addTokens = getTotalAmountOfTokens(_weiAmount); if (tokenAllocated.add(addTokens) > fundForSale) { TokenLimitReached(tokenAllocated, addTokens); return 0; } return addTokens; } function setRate(uint256 _newRate) public approveAllAdmin returns (bool){ require(_newRate > 0); rate = _newRate; removeAllApprove(); return true; } function setContractAdmin(address _admin, bool _isAdmin, uint _index) external onlyOwner { require(_admin != address(0)); require(0 <= _index && _index < 3); contractAdmins[_admin] = _isAdmin; if(_isAdmin){ admins[_index] = _admin; } } function setContractAdmin(address _admin, bool _isAdmin, uint _index) external onlyOwner { require(_admin != address(0)); require(0 <= _index && _index < 3); contractAdmins[_admin] = _isAdmin; if(_isAdmin){ admins[_index] = _admin; } } modifier approveAllAdmin() { bool result = true; for(uint i = 0; i < 3; i++) { if (approveAdmin[admins[i]] == false) { result = false; } } require(result == true); _; } modifier approveAllAdmin() { bool result = true; for(uint i = 0; i < 3; i++) { if (approveAdmin[admins[i]] == false) { result = false; } } require(result == true); _; } modifier approveAllAdmin() { bool result = true; for(uint i = 0; i < 3; i++) { if (approveAdmin[admins[i]] == false) { result = false; } } require(result == true); _; } function removeAllApprove() public approveAllAdmin { for(uint i = 0; i < 3; i++) { approveAdmin[admins[i]] = false; } } function removeAllApprove() public approveAllAdmin { for(uint i = 0; i < 3; i++) { approveAdmin[admins[i]] = false; } } function setApprove(bool _isApprove) external onlyOwnerOrAnyAdmin { approveAdmin[msg.sender] = _isApprove; } function addToWhitelist(address _beneficiary) external onlyOwnerOrAnyAdmin { whitelist[_beneficiary] = true; } function addManyToWhitelist(address[] _beneficiaries) external onlyOwnerOrAnyAdmin { require(_beneficiaries.length < 101); for (uint256 i = 0; i < _beneficiaries.length; i++) { whitelist[_beneficiaries[i]] = true; } } function addManyToWhitelist(address[] _beneficiaries) external onlyOwnerOrAnyAdmin { require(_beneficiaries.length < 101); for (uint256 i = 0; i < _beneficiaries.length; i++) { whitelist[_beneficiaries[i]] = true; } } function removeFromWhitelist(address _beneficiary) external onlyOwnerOrAnyAdmin { whitelist[_beneficiary] = false; } modifier onlyOwnerOrAnyAdmin() { require(msg.sender == owner || contractAdmins[msg.sender]); _; } modifier onlyWhitelist() { require(whitelist[msg.sender]); _; } }
4,101,703
[ 1, 8, 20, 18, 2947, 273, 404, 1147, 516, 271, 404, 16, 3784, 273, 576, 18, 25, 3103, 28, 9060, 3028, 17339, 512, 2455, 516, 24, 16, 3784, 1147, 273, 576, 18, 25, 3103, 28, 9060, 3028, 17339, 512, 2455, 516, 404, 512, 2455, 273, 1059, 16, 3784, 19, 22, 18, 20, 5482, 11861, 22135, 273, 5342, 3600, 987, 434, 31116, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 16525, 10346, 492, 2377, 5349, 353, 14223, 6914, 16, 385, 492, 2377, 5349, 16, 490, 474, 429, 1345, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 203, 565, 2254, 5034, 1071, 4993, 225, 273, 5342, 3600, 31, 203, 203, 565, 2874, 261, 2867, 516, 2254, 5034, 13, 1071, 443, 1724, 329, 31, 203, 565, 2874, 12, 2867, 516, 1426, 13, 1071, 10734, 31, 203, 203, 565, 2874, 261, 2867, 516, 1426, 13, 1071, 6835, 4446, 87, 31, 203, 565, 2874, 261, 2867, 516, 1426, 13, 6617, 537, 4446, 31, 203, 203, 565, 2254, 5034, 1071, 5381, 28226, 67, 13272, 23893, 273, 8566, 380, 261, 2163, 2826, 1666, 13, 380, 261, 2163, 2826, 2254, 5034, 12, 31734, 10019, 203, 565, 2254, 5034, 1071, 284, 1074, 1290, 30746, 273, 29424, 380, 261, 2163, 2826, 1666, 13, 380, 261, 2163, 2826, 2254, 5034, 12, 31734, 10019, 203, 565, 2254, 5034, 1071, 284, 1074, 1290, 8689, 273, 225, 2468, 380, 261, 2163, 2826, 1666, 13, 380, 261, 2163, 2826, 2254, 5034, 12, 31734, 10019, 203, 565, 2254, 5034, 1071, 284, 1074, 1386, 45, 2894, 273, 12732, 380, 261, 2163, 2826, 1666, 13, 380, 261, 2163, 2826, 2254, 5034, 12, 31734, 10019, 203, 565, 2254, 5034, 1071, 284, 1074, 45, 2894, 273, 22431, 380, 261, 2163, 2826, 1666, 13, 380, 261, 2163, 2826, 2254, 5034, 12, 31734, 10019, 203, 565, 1758, 8526, 1071, 31116, 273, 306, 374, 92, 22, 74, 1639, 4449, 71, 41, 9349, 22201, 713, 39, 10593, 74, 3437, 70, 27002, 70, 22, 2 ]
./full_match/3/0x05502f13420F8D3F0C3B2119559cF00a2e626a49/sources/browser/1_Storage.sol
struct for a single energy data tranaction public data for live monitoring private data with detailed information about the single use of technival units Leistungskenndaten eines poolData
struct Poolfahrt { mapping(uint => TechnischeEinheit) technischeEinheiten; }
8,115,413
[ 1, 1697, 364, 279, 2202, 12929, 501, 13637, 1128, 1071, 501, 364, 8429, 16309, 3238, 501, 598, 6864, 1779, 2973, 326, 2202, 999, 434, 17734, 5162, 4971, 3519, 376, 318, 564, 79, 25713, 3404, 275, 425, 1465, 2845, 751, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 1958, 8828, 507, 76, 3797, 288, 203, 203, 3639, 2874, 12, 11890, 516, 30960, 291, 18706, 41, 267, 580, 305, 13, 17734, 291, 18706, 41, 267, 580, 305, 275, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/56/0x943c70EeE7A8576120e99b5f4201221E12A55bDa/sources/Strategy.sol
View function to see pending CREAMs on frontend. 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 BONUS_MULTIPLIER ( ) external view returns ( uint256 ); function add ( uint256 _allocPoint, address _lpToken, bool _withUpdate ) external; function bonusEndBlock ( ) external view returns ( uint256 ); function checkPoolDuplicate ( address _lpToken ) external; function deposit ( uint256 _pid, uint256 _amount ) external; function dev ( address _governance ) external; function devFee ( ) external view returns ( address ); function emergencyWithdraw ( uint256 _pid ) external; function enterStaking ( uint256 _amount ) external; function getMultiplier ( uint256 _from, uint256 _to ) external view returns ( uint256 ); function governance ( ) external view returns ( address ); function leaveStaking ( uint256 _amount ) external; function massUpdatePools ( ) external; function milkshake ( ) external view returns ( address ); function owner ( ) external view returns ( address ); function poolInfo ( uint256 ) external view returns ( PoolInfo memory); function poolLength ( ) external view returns ( uint256 ); function renounceOwnership ( ) external; function set ( uint256 _pid, uint256 _allocPoint, bool _withUpdate ) external; function startBlock ( ) external view returns ( uint256 ); function totalAllocPoint ( ) external view returns ( uint256 ); function transferOwnership ( address newOwner ) external; function updateBonus ( uint256 _bonusEndBlock ) external; function updateMultiplier ( uint256 multiplierNumber ) external; function updatePool ( uint256 _pid ) external; function userInfo ( uint256, address ) external view returns ( UserInfo memory ); function withdraw ( uint256 _pid, uint256 _amount ) external; function pendingEgg(uint256 _pid, address _user) external view returns (uint256); } function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function _callOptionalReturn(IERC20 token, bytes memory data) private { bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } }
11,264,864
[ 1, 1767, 445, 358, 2621, 4634, 9666, 2192, 87, 603, 15442, 18, 6393, 30, 3502, 62, 881, 84, 292, 267, 19, 3190, 94, 881, 84, 292, 267, 17, 16351, 87, 36, 23, 18, 21, 18, 20, 19, 9890, 654, 39, 3462, 225, 14060, 654, 39, 3462, 225, 4266, 10422, 6740, 4232, 39, 3462, 5295, 716, 604, 603, 5166, 261, 13723, 326, 1147, 6835, 1135, 629, 2934, 13899, 716, 327, 1158, 460, 261, 464, 3560, 15226, 578, 604, 603, 5166, 13, 854, 2546, 3260, 16, 1661, 17, 266, 1097, 310, 4097, 854, 12034, 358, 506, 6873, 18, 2974, 999, 333, 5313, 1846, 848, 527, 279, 1375, 9940, 14060, 654, 39, 3462, 364, 467, 654, 39, 3462, 31, 68, 3021, 358, 3433, 6835, 16, 1492, 5360, 1846, 358, 745, 326, 4183, 5295, 487, 1375, 2316, 18, 4626, 5912, 5825, 13, 9191, 5527, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 12083, 14060, 654, 39, 3462, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 565, 1450, 5267, 364, 1758, 31, 203, 203, 565, 445, 605, 673, 3378, 67, 24683, 2053, 654, 261, 225, 262, 3903, 1476, 1135, 261, 2254, 5034, 11272, 203, 565, 445, 527, 261, 2254, 5034, 389, 9853, 2148, 16, 1758, 389, 9953, 1345, 16, 1426, 389, 1918, 1891, 262, 3903, 31, 203, 565, 445, 324, 22889, 1638, 1768, 261, 225, 262, 3903, 1476, 1135, 261, 2254, 5034, 11272, 203, 565, 445, 866, 2864, 11826, 261, 1758, 389, 9953, 1345, 262, 3903, 31, 203, 565, 445, 443, 1724, 261, 2254, 5034, 389, 6610, 16, 2254, 5034, 389, 8949, 262, 3903, 31, 203, 565, 445, 4461, 261, 1758, 389, 75, 1643, 82, 1359, 262, 3903, 31, 203, 565, 445, 4461, 14667, 261, 225, 262, 3903, 1476, 1135, 261, 1758, 11272, 203, 565, 445, 801, 24530, 1190, 9446, 261, 2254, 5034, 389, 6610, 262, 3903, 31, 203, 565, 445, 6103, 510, 6159, 261, 2254, 5034, 389, 8949, 262, 3903, 31, 203, 565, 445, 31863, 5742, 261, 2254, 5034, 389, 2080, 16, 2254, 5034, 389, 869, 262, 3903, 1476, 1135, 261, 2254, 5034, 11272, 203, 565, 445, 314, 1643, 82, 1359, 261, 225, 262, 3903, 1476, 1135, 261, 1758, 11272, 203, 565, 445, 8851, 510, 6159, 261, 2254, 5034, 389, 8949, 262, 3903, 31, 203, 565, 445, 8039, 1891, 16639, 261, 225, 262, 3903, 31, 203, 565, 445, 312, 330, 79, 7478, 261, 225, 262, 3903, 1476, 1135, 261, 1758, 11272, 203, 565, 2 ]
pragma solidity ^0.5.12; import "./ERC1400Raw.sol"; import "openzeppelin-solidity/contracts/access/roles/MinterRole.sol"; /** * @title ERC1400RawIssuable * @dev ERC1400Raw issuance logic */ contract ERC1400RawIssuable is ERC1400Raw, MinterRole { /** * [NOT MANDATORY FOR ERC1400Raw STANDARD] * @dev Issue the amout of tokens for the recipient 'to'. * @param to Token recipient. * @param value Number of tokens issued. * @param data Information attached to the issuance, by the token holder. [CONTAINS THE CONDITIONAL OWNERSHIP CERTIFICATE] * @return A boolean that indicates if the operation was successful. */ function issue(address to, uint256 value, bytes calldata data) external isValidCertificate(data) onlyMinter returns (bool) { _issue("", msg.sender, to, value, data, ""); return true; } }
* [NOT MANDATORY FOR ERC1400Raw STANDARD] @dev Issue the amout of tokens for the recipient 'to'. @param to Token recipient. @param value Number of tokens issued. @param data Information attached to the issuance, by the token holder. [CONTAINS THE CONDITIONAL OWNERSHIP CERTIFICATE] @return A boolean that indicates if the operation was successful./
{ _issue("", msg.sender, to, value, data, ""); return true; }
1,829,818
[ 1, 63, 4400, 490, 4307, 3575, 61, 12108, 4232, 39, 3461, 713, 4809, 23255, 65, 225, 11820, 326, 2125, 659, 434, 2430, 364, 326, 8027, 296, 869, 10332, 225, 358, 3155, 8027, 18, 225, 460, 3588, 434, 2430, 16865, 18, 225, 501, 15353, 7495, 358, 326, 3385, 89, 1359, 16, 635, 326, 1147, 10438, 18, 306, 6067, 25838, 12786, 3492, 18575, 1013, 531, 22527, 20101, 25423, 26649, 65, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 225, 288, 203, 565, 389, 13882, 2932, 3113, 1234, 18, 15330, 16, 358, 16, 460, 16, 501, 16, 1408, 1769, 203, 203, 565, 327, 638, 31, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/5/0xcE36fC4e87Cf42DD24718e8b08DABedaa0761B30/sources/src/ContractooorAgreement.sol
@notice allows a party to begin to terminate an agreement at their own will @notice SPEC: A valid call to this function will mark a party's at will termination given: S1: the `msg.sender` is either the client or the service provider RES1: marks the `msg.sender`'s `atWillTerminationTimestamp` to the current timestamp RES2: emits a `TerminationProposalDeleted` event SPEC.S1 SPEC.RES2 SPEC.RES2
function issueNoticeOfTermination(string memory terminationInfo) public { onlyClientOrServiceProvider(); atWillTerminationTimestamp[msg.sender] = block.timestamp; emit TerminationProposed(msg.sender, terminationInfo, TerminationReason.AtWill); }
1,950,298
[ 1, 5965, 87, 279, 18285, 358, 2376, 358, 10850, 392, 19602, 622, 3675, 4953, 903, 225, 22872, 30, 432, 923, 745, 358, 333, 445, 903, 2267, 279, 18285, 1807, 622, 903, 19650, 864, 30, 377, 348, 21, 30, 326, 1375, 3576, 18, 15330, 68, 353, 3344, 326, 1004, 578, 326, 1156, 2893, 377, 12915, 21, 30, 13999, 326, 1375, 3576, 18, 15330, 11294, 87, 1375, 270, 13670, 16516, 4921, 68, 358, 326, 783, 2858, 377, 12915, 22, 30, 24169, 279, 1375, 16516, 14592, 7977, 68, 871, 22872, 18, 55, 21, 22872, 18, 7031, 22, 22872, 18, 7031, 22, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 5672, 20127, 951, 16516, 12, 1080, 3778, 19650, 966, 13, 1071, 288, 203, 3639, 1338, 1227, 1162, 16300, 5621, 203, 3639, 622, 13670, 16516, 4921, 63, 3576, 18, 15330, 65, 273, 1203, 18, 5508, 31, 203, 203, 3639, 3626, 6820, 1735, 626, 7423, 12, 3576, 18, 15330, 16, 19650, 966, 16, 6820, 1735, 8385, 18, 861, 13670, 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 ]
// SPDX-License-Identifier: MIT pragma solidity >=0.8.0; import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol"; import "./interfaces/IArtBridge.sol"; import "./BridgeContext.sol"; /// /// /// ██████╗ ██████╗ ██╗██████╗ ██████╗ ███████╗ /// ██╔══██╗██╔══██╗██║██╔══██╗██╔════╝ ██╔════╝ /// ██████╔╝██████╔╝██║██║ ██║██║ ███╗█████╗ /// ██╔══██╗██╔══██╗██║██║ ██║██║ ██║██╔══╝ /// ██████╔╝██║ ██║██║██████╔╝╚██████╔╝███████╗ /// ╚═════╝ ╚═╝ ╚═╝╚═╝╚═════╝ ╚═════╝ ╚══════╝ /// /// ██████╗ ███████╗███████╗███████╗██████╗ ██╗ ██╗███████╗ /// ██╔══██╗██╔════╝██╔════╝██╔════╝██╔══██╗██║ ██║██╔════╝ /// ██████╔╝█████╗ ███████╗█████╗ ██████╔╝██║ ██║█████╗ /// ██╔══██╗██╔══╝ ╚════██║██╔══╝ ██╔══██╗╚██╗ ██╔╝██╔══╝ /// ██║ ██║███████╗███████║███████╗██║ ██║ ╚████╔╝ ███████╗ /// ╚═╝ ╚═╝╚══════╝╚══════╝╚══════╝╚═╝ ╚═╝ ╚═══╝ ╚══════╝ /// /// /// @title Mint reservation and parameter controller /// @author artbridge.eth /// @notice BridgeReserve controls all non financial aspects of a project contract BridgeReserve is BridgeContext { IArtBridge public immutable bridge; mapping(uint256 => BridgeBeams.ReserveParameters) public projectToParameters; mapping(uint256 => mapping(address => bool)) public projectToMinters; mapping(uint256 => mapping(address => uint256)) public projectToUserReservations; mapping(uint256 => uint256) public projectToReservations; /// @notice allows operations only on projects before mint starts /// @param _id target bridge project id modifier onlyReservable(uint256 _id) { BridgeBeams.ProjectState memory state = bridge.projectState(_id); require(state.initialized, "!initialized"); require(!state.released, "released"); _; } constructor(address _bridge) { bridge = IArtBridge(_bridge); } /// @dev proof is supplied by art bridge api /// @dev reserve may be over subscribed, allotted on a first come basis /// @param _reserved total number of user allocated tokens /// @param _id target bridge project id /// @param _amount number of reserved tokens to mint /// @param _proof reservation merkle proof function reserve( uint256 _id, uint256 _amount, uint256 _reserved, bytes32[] calldata _proof ) external payable onlyReservable(_id) { require( _amount * bridge.projectToTokenPrice(_id) == msg.value, "invalid payment amount" ); require( _amount <= _reserved - projectToUserReservations[_id][msg.sender], "invalid reserve amount" ); BridgeBeams.ReserveParameters memory params = projectToParameters[_id]; require(params.reserveRoot != "", "!reserveRoot"); require( _amount <= params.reservedMints - projectToReservations[_id], "invalid reserve amount" ); bytes32 node = keccak256(abi.encodePacked(_id, msg.sender, _reserved)); require( MerkleProof.verify(_proof, params.reserveRoot, node), "invalid proof" ); bridge.reserve(_id, _amount, msg.sender); projectToUserReservations[_id][msg.sender] += _amount; projectToReservations[_id] += _amount; } /// @dev _reserveRoot is required for reserve but is not required to be set initially /// @notice set project reserve and mint parameters /// @param _id target bridge project id /// @param _maxMintPerInvocation maximum allowed number of mints per transaction /// @param _reservedMints maximum allowed number of reservice invocations function setParameters( uint256 _id, uint256 _maxMintPerInvocation, uint256 _reservedMints, bytes32 _reserveRoot ) external onlyReservable(_id) onlyOwner { require(_id < bridge.nextProjectId(), "invalid _id"); (, , , , , , uint256 maxSupply, ) = bridge.projects(_id); require(_reservedMints <= maxSupply, "invalid reserve amount"); require(_maxMintPerInvocation > 0, "require positive mint"); require(_maxMintPerInvocation <= maxSupply, "invalid mint max"); BridgeBeams.ReserveParameters memory params = BridgeBeams .ReserveParameters({ maxMintPerInvocation: _maxMintPerInvocation, reservedMints: _reservedMints, reserveRoot: _reserveRoot }); projectToParameters[_id] = params; } /// @dev projects may support multiple minters /// @notice adds a minter as available to mint a given project /// @param _id target bridge project id /// @param _minter minter address function addMinter(uint256 _id, address _minter) external onlyOwner { projectToMinters[_id][_minter] = true; } /// @notice removes a minter as available to mint a given project /// @param _id target bridge project id /// @param _minter minter address function removeMinter(uint256 _id, address _minter) external onlyOwner { projectToMinters[_id][_minter] = false; } /// @notice updates the project maxMintPerInvocation /// @param _id target bridge project id /// @param _maxMintPerInvocation maximum number of mints per transaction function setmaxMintPerInvocation(uint256 _id, uint256 _maxMintPerInvocation) external onlyReservable(_id) onlyOwner { (, , , , , , uint256 maxSupply, ) = bridge.projects(_id); require(_maxMintPerInvocation <= maxSupply, "invalid mint max"); require(_maxMintPerInvocation > 0, "require positive mint"); projectToParameters[_id].maxMintPerInvocation = _maxMintPerInvocation; } /// @notice updates the project reservedMints /// @param _id target bridge project id /// @param _reservedMints maximum number of reserved mints per project function setReservedMints(uint256 _id, uint256 _reservedMints) external onlyReservable(_id) onlyOwner { (, , , , , , uint256 maxSupply, ) = bridge.projects(_id); require(_reservedMints <= maxSupply, "invalid reserve amount"); projectToParameters[_id].reservedMints = _reservedMints; } /// @dev utility function to set or update reserve tree root /// @notice updates the project reserveRoot /// @param _id target bridge project id /// @param _reserveRoot project reservation merkle tree root function setReserveRoot(uint256 _id, bytes32 _reserveRoot) external onlyReservable(_id) onlyOwner { projectToParameters[_id].reserveRoot = _reserveRoot; } } // SPDX-License-Identifier: MIT 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 MerkleProof { /** * @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) { 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 = keccak256(abi.encodePacked(computedHash, proofElement)); } else { // Hash(current element of the proof + current computed hash) computedHash = keccak256(abi.encodePacked(proofElement, computedHash)); } } // Check if the computed hash (root) is equal to the provided root return computedHash == root; } } // SPDX-License-Identifier: MIT pragma solidity >=0.8.0; import {BridgeBeams} from "../libraries/BridgeBeams.sol"; interface IArtBridge { function mint( uint256 _id, uint256 _amount, address _to ) external; function reserve( uint256 _id, uint256 _amount, address _to ) external; function nextProjectId() external view returns (uint256); function projects(uint256 _id) external view returns ( uint256 id, string memory name, string memory artist, string memory description, string memory website, uint256 supply, uint256 maxSupply, uint256 startBlock ); function minters(address _minter) external view returns (bool); function projectToTokenPrice(uint256 _id) external view returns (uint256); function projectState(uint256 _id) external view returns (BridgeBeams.ProjectState memory); } // SPDX-License-Identifier: MIT pragma solidity >=0.8.0; import {BridgeBeams} from "./libraries/BridgeBeams.sol"; import "./Extractable.sol"; contract BridgeContext is Extractable { using BridgeBeams for BridgeBeams.Project; using BridgeBeams for BridgeBeams.ProjectState; using BridgeBeams for BridgeBeams.ReserveParameters; } // SPDX-License-Identifier: MIT pragma solidity >=0.8.0; /// BridgeBeams.sol /// @title BEAMS token helper functions /// @author artbridge.eth /// @dev Library assists requirement checks across contracts library BridgeBeams { struct Project { uint256 id; string name; string artist; string description; string website; uint256 supply; uint256 maxSupply; uint256 startBlock; } struct ProjectState { bool initialized; bool mintable; bool released; uint256 remaining; } struct ReserveParameters { uint256 maxMintPerInvocation; uint256 reservedMints; bytes32 reserveRoot; } /// @param _project Target project struct /// @return Project state struct derived from given input function projectState(Project memory _project) external view returns (BridgeBeams.ProjectState memory) { return ProjectState({ initialized: isInitialized(_project), mintable: isMintable(_project), released: isReleased(_project), remaining: _project.maxSupply - _project.supply }); } /// @param _project Target project struct /// @return True if project has required initial parameters, false if not function isInitialized(Project memory _project) internal pure returns (bool) { if ( bytes(_project.artist).length == 0 || bytes(_project.description).length == 0 ) { return false; } return true; } /// @param _project Target project struct /// @return True if project is past mint start block, false if not function isReleased(Project memory _project) internal view returns (bool) { return _project.startBlock > 0 && _project.startBlock <= block.number; } /// @param _project Target project struct /// @return True if project is available for public mint, false if not function isMintable(Project memory _project) internal view returns (bool) { if (!isInitialized(_project)) { return false; } return isReleased(_project) && _project.supply < _project.maxSupply; } } // SPDX-License-Identifier: MIT pragma solidity >=0.8.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; contract Extractable is Ownable { function withdraw() external payable onlyOwner { require(payable(owner()).send(address(this).balance), "!transfer"); } function extract(address _token) external onlyOwner { IERC20 token = IERC20(_token); token.transfer(owner(), token.balanceOf(address(this))); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } }
@dev projects may support multiple minters @notice adds a minter as available to mint a given project @param _id target bridge project id @param _minter minter address
function addMinter(uint256 _id, address _minter) external onlyOwner { projectToMinters[_id][_minter] = true; }
13,744,254
[ 1, 13582, 2026, 2865, 3229, 1131, 5432, 225, 4831, 279, 1131, 387, 487, 2319, 358, 312, 474, 279, 864, 1984, 225, 389, 350, 1018, 10105, 1984, 612, 225, 389, 1154, 387, 1131, 387, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 225, 445, 527, 49, 2761, 12, 11890, 5034, 389, 350, 16, 1758, 389, 1154, 387, 13, 3903, 1338, 5541, 288, 203, 565, 1984, 774, 49, 2761, 87, 63, 67, 350, 6362, 67, 1154, 387, 65, 273, 638, 31, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// File: @openzeppelin/contracts/math/Math.sol // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.6.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // File: @openzeppelin/contracts/math/SafeMath.sol pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol pragma solidity ^0.6.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File: @openzeppelin/contracts/GSN/Context.sol pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts/access/Ownable.sol pragma solidity ^0.6.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: contracts/owner/Operator.sol pragma solidity ^0.6.0; contract Operator is Context, Ownable { address private _operator; event OperatorTransferred( address indexed previousOperator, address indexed newOperator ); constructor() internal { _operator = _msgSender(); emit OperatorTransferred(address(0), _operator); } function operator() public view returns (address) { return _operator; } modifier onlyOperator() { require( _operator == msg.sender, 'operator: caller is not the operator' ); _; } function isOperator() public view returns (bool) { return _msgSender() == _operator; } function transferOperator(address newOperator_) public onlyOwner { _transferOperator(newOperator_); } function _transferOperator(address newOperator_) internal { require( newOperator_ != address(0), 'operator: zero address given for new operator' ); emit OperatorTransferred(address(0), newOperator_); _operator = newOperator_; } } // File: contracts/token/LPTokenWrapper.sol pragma solidity ^0.6.0; contract LPTokenWrapper { using SafeMath for uint256; using SafeERC20 for IERC20; IERC20 public lpt; uint256 private _totalSupply; mapping(address => uint256) private _balances; function totalSupply() public view returns (uint256) { return _totalSupply; } function balanceOf(address account) public view returns (uint256) { return _balances[account]; } function stake(uint256 amount) public virtual { _totalSupply = _totalSupply.add(amount); _balances[msg.sender] = _balances[msg.sender].add(amount); lpt.safeTransferFrom(msg.sender, address(this), amount); } function withdraw(uint256 amount) public virtual { _totalSupply = _totalSupply.sub(amount); _balances[msg.sender] = _balances[msg.sender].sub(amount); lpt.safeTransfer(msg.sender, amount); } } // File: contracts/GUMLPTokenPool.sol pragma solidity ^0.6.0; /* ____ __ __ __ _ / __/__ __ ___ / /_ / / ___ / /_ (_)__ __ _\ \ / // // _ \/ __// _ \/ -_)/ __// / \ \ / /___/ \_, //_//_/\__//_//_/\__/ \__//_/ /_\_\ /___/ * Synthetix: GUMLPTokenPool.sol * * Docs: https://docs.synthetix.io/ * * * MIT License * =========== * * Copyright (c) 2020 Synthetix * * 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 */ contract GUMLPTokenPool is LPTokenWrapper , Operator { IERC20 public gum; uint256 public constant DURATION = 30 days; uint256 public initreward = 56818 * 10**18; // 56818 GUM; uint256 public starttime; // starttime TBD uint256 public periodFinish = 0; uint256 public rewardRate = 0; uint256 public lastUpdateTime; uint256 public rewardPerTokenStored; mapping(address => uint256) public userRewardPerTokenPaid; mapping(address => uint256) public rewards; event SetInitReward(uint256 reward); event RewardAdded(uint256 reward); event Staked(address indexed user, uint256 amount); event Withdrawn(address indexed user, uint256 amount); event RewardPaid(address indexed user, uint256 reward); event EmergencyWithdraw(address indexed user); constructor( address gum_, address lptoken_, uint256 starttime_ ) public { gum = IERC20(gum_); lpt = IERC20(lptoken_); starttime = starttime_; } modifier updateReward(address account) { rewardPerTokenStored = rewardPerToken(); lastUpdateTime = lastTimeRewardApplicable(); if (account != address(0)) { rewards[account] = earned(account); userRewardPerTokenPaid[account] = rewardPerTokenStored; } _; } function lastTimeRewardApplicable() public view returns (uint256) { return Math.min(block.timestamp, periodFinish); } function rewardPerToken() public view returns (uint256) { if (totalSupply() == 0) { return rewardPerTokenStored; } return rewardPerTokenStored.add( lastTimeRewardApplicable() .sub(lastUpdateTime) .mul(rewardRate) .mul(1e18) .div(totalSupply()) ); } function earned(address account) public view returns (uint256) { return balanceOf(account) .mul(rewardPerToken().sub(userRewardPerTokenPaid[account])) .div(1e18) .add(rewards[account]); } // stake visibility is public as overriding LPTokenWrapper's stake() function function stake(uint256 amount) public override updateReward(msg.sender) checkhalve checkStart { require(amount > 0, 'GUMLPTokenPool: Cannot stake 0'); super.stake(amount); emit Staked(msg.sender, amount); } function withdraw(uint256 amount) public override updateReward(msg.sender) checkhalve checkStart { require(amount > 0, 'GUMLPTokenPool: Cannot withdraw 0'); super.withdraw(amount); emit Withdrawn(msg.sender, amount); } function exit() external { withdraw(balanceOf(msg.sender)); getReward(); } function emergencyWithdraw() public onlyOperator { gum.safeTransfer(msg.sender, gum.balanceOf(address(this))); emit EmergencyWithdraw(msg.sender); } function getReward() public updateReward(msg.sender) checkhalve checkStart { uint256 reward = earned(msg.sender); if (reward > 0) { rewards[msg.sender] = 0; gum.safeTransfer(msg.sender, reward); emit RewardPaid(msg.sender, reward); } } modifier checkhalve() { if (block.timestamp >= periodFinish) { rewardRate = initreward.div(DURATION); periodFinish = block.timestamp.add(DURATION); emit RewardAdded(initreward); } _; } modifier checkStart() { require(block.timestamp >= starttime, 'GUMLPTokenPool: not start'); _; } function setInitReward(uint256 amount) public onlyOperator { initreward = amount; emit SetInitReward(initreward); } function notifyRewardAmount(uint256 reward) external onlyOperator updateReward(address(0)) { if (block.timestamp > starttime) { // // update reward whenever you want rewardRate = reward.div(DURATION); lastUpdateTime = block.timestamp; periodFinish = block.timestamp.add(DURATION); emit RewardAdded(reward); } else { // init reward rewardRate = reward.div(DURATION); lastUpdateTime = starttime; periodFinish = starttime.add(DURATION); emit RewardAdded(reward); } } }
update reward whenever you want
if (block.timestamp > starttime) {
547,234
[ 1, 2725, 19890, 17334, 1846, 2545, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 309, 261, 2629, 18, 5508, 405, 23437, 13, 288, 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: Apache-2.0 pragma solidity ^0.8.0; import "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/StringsUpgradeable.sol"; /** * @title Role based set membership. * * @notice Encapsulation of tracking, management and validation of role membership of addresses. * * A role is a bytes32 value. * * There are two distinct classes of roles: * - Global; without scope limit. * - Dao; membership scoped to that of the key (uint256). * * @dev Meaningful application of role membership is expected to come from derived contracts. * e.g. access control. */ abstract contract RoleMembership is ContextUpgradeable { // DAOs to their roles to members; scoped to an individual DAO mapping(uint256 => mapping(bytes32 => mapping(address => bool))) private _daoRoleMembers; // Global roles to members; apply across all DAOs mapping(bytes32 => mapping(address => bool)) private _globalRoleMembers; event GrantDaoRole( uint256 indexed daoId, bytes32 indexed role, address account, address indexed instigator ); event GrantGlobalRole( bytes32 indexedrole, address account, address indexed instigator ); event RevokeDaoRole( uint256 indexed daoId, bytes32 indexed role, address account, address indexed instigator ); event RevokeGlobalRole( bytes32 indexed role, address account, address indexed instigator ); function hasGlobalRole(bytes32 role, address account) external view returns (bool) { return _globalRoleMembers[role][account]; } function hasDaoRole( uint256 daoId, bytes32 role, address account ) external view returns (bool) { return _daoRoleMembers[daoId][role][account]; } function _grantDaoRole( uint256 daoId, bytes32 role, address account ) internal { if (_hasDaoRole(daoId, role, account)) { revert(_revertMessageAlreadyHasDaoRole(daoId, role, account)); } _daoRoleMembers[daoId][role][account] = true; emit GrantDaoRole(daoId, role, account, _msgSender()); } function _grantGlobalRole(bytes32 role, address account) internal { if (_hasGlobalRole(role, account)) { revert(_revertMessageAlreadyHasGlobalRole(role, account)); } _globalRoleMembers[role][account] = true; emit GrantGlobalRole(role, account, _msgSender()); } function _revokeDaoRole( uint256 daoId, bytes32 role, address account ) internal { if (_isMissingDaoRole(daoId, role, account)) { revert(_revertMessageMissingDaoRole(daoId, role, account)); } delete _daoRoleMembers[daoId][role][account]; emit RevokeDaoRole(daoId, role, account, _msgSender()); } function _revokeGlobalRole(bytes32 role, address account) internal { if (_isMissingGlobalRole(role, account)) { revert(_revertMessageMissingGlobalRole(role, account)); } delete _globalRoleMembers[role][account]; emit RevokeGlobalRole(role, account, _msgSender()); } //slither-disable-next-line naming-convention function __RoleMembership_init() internal onlyInitializing {} function _hasDaoRole( uint256 daoId, bytes32 role, address account ) internal view returns (bool) { return _daoRoleMembers[daoId][role][account]; } function _hasGlobalRole(bytes32 role, address account) internal view returns (bool) { return _globalRoleMembers[role][account]; } function _isMissingDaoRole( uint256 daoId, bytes32 role, address account ) internal view returns (bool) { return !_daoRoleMembers[daoId][role][account]; } function _isMissingGlobalRole(bytes32 role, address account) internal view returns (bool) { return !_globalRoleMembers[role][account]; } /** * @dev Override for a custom revert message. */ function _revertMessageAlreadyHasGlobalRole(bytes32 role, address account) internal view virtual returns (string memory) { return string( abi.encodePacked( "RoleMembership: account ", StringsUpgradeable.toHexString(uint160(account), 20), " already has role ", StringsUpgradeable.toHexString(uint256(role), 32) ) ); } /** * @dev Override the function for a custom revert message. */ function _revertMessageAlreadyHasDaoRole( uint256 daoId, bytes32 role, address account ) internal view virtual returns (string memory) { return string( abi.encodePacked( "RoleMembership: account ", StringsUpgradeable.toHexString(uint160(account), 20), " already has role ", StringsUpgradeable.toHexString(uint256(role), 32), " in DAO ", StringsUpgradeable.toHexString(daoId, 32) ) ); } /** * @dev Override the function for a custom revert message. */ function _revertMessageMissingGlobalRole(bytes32 role, address account) internal view virtual returns (string memory) { return string( abi.encodePacked( "RoleMembership: account ", StringsUpgradeable.toHexString(uint160(account), 20), " is missing role ", StringsUpgradeable.toHexString(uint256(role), 32) ) ); } /** * @dev Override the function for a custom revert message. */ function _revertMessageMissingDaoRole( uint256 daoId, bytes32 role, address account ) internal view virtual returns (string memory) { return string( abi.encodePacked( "RoleMembership: account ", StringsUpgradeable.toHexString(uint160(account), 20), " is missing role ", StringsUpgradeable.toHexString(uint256(role), 32), " in DAO ", StringsUpgradeable.toHexString(daoId, 32) ) ); } }
* @dev Override for a custom revert message./
function _revertMessageAlreadyHasGlobalRole(bytes32 role, address account) internal view virtual returns (string memory) { return string( abi.encodePacked( "RoleMembership: account ", StringsUpgradeable.toHexString(uint160(account), 20), " already has role ", StringsUpgradeable.toHexString(uint256(role), 32) ) ); }
12,779,025
[ 1, 6618, 364, 279, 1679, 15226, 883, 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 ]
[ 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, 389, 266, 1097, 1079, 9430, 5582, 5160, 2996, 12, 3890, 1578, 2478, 16, 1758, 2236, 13, 203, 3639, 2713, 203, 3639, 1476, 203, 3639, 5024, 203, 3639, 1135, 261, 1080, 3778, 13, 203, 565, 288, 203, 3639, 327, 203, 5411, 533, 12, 203, 7734, 24126, 18, 3015, 4420, 329, 12, 203, 10792, 315, 2996, 13447, 30, 2236, 3104, 203, 10792, 8139, 10784, 429, 18, 869, 14866, 12, 11890, 16874, 12, 4631, 3631, 4200, 3631, 203, 10792, 315, 1818, 711, 2478, 3104, 203, 10792, 8139, 10784, 429, 18, 869, 14866, 12, 11890, 5034, 12, 4615, 3631, 3847, 13, 203, 7734, 262, 203, 5411, 11272, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/44787/0xaE7D6EA88c7536bA6B12682A752e748c45c50DCB/sources/contracts/ReceiverRestricted.sol
List of eligible receivers, specified/modified by owner
abstract contract ReceiverRestricted is ERC20, Ownable { address[] public receivers; event Receiver(address indexed recv, string status); pragma solidity ^0.8.4; function addReceiver(address _recv) public onlyOwner { require(_recv != address(0), "Elonium: can't add zero address"); require(!receiverExists(_recv), "Elonium: address already exists"); emit Receiver(_recv, "Add"); receivers.push(_recv); } function removeReceiver(address _recv) public onlyOwner { require(_recv != address(0), "Elonium: can't remove zero address"); require(receiverExists(_recv), "Elonium: address does not exist"); emit Receiver(_recv, "Remove"); delete receivers[uint(getReceiverIndex(_recv))]; } function receiverExists(address _recv) public view returns(bool) { return getReceiverIndex(_recv) != -1; } function getReceiverIndex(address _recv) public view returns(int) { for (uint i = 0; i < receivers.length; i++) if (receivers[i] == _recv) return int(i); return -1; } function getReceivers() public view returns (address[] memory) { return receivers; } }
13,248,952
[ 1, 682, 434, 21351, 22686, 16, 1269, 19, 7342, 635, 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 ]
[ 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, 17801, 6835, 31020, 18784, 353, 4232, 39, 3462, 16, 14223, 6914, 288, 203, 203, 565, 1758, 8526, 1071, 22686, 31, 203, 203, 565, 871, 31020, 12, 2867, 8808, 10665, 16, 533, 1267, 1769, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 24, 31, 203, 565, 445, 527, 12952, 12, 2867, 389, 18334, 13, 1071, 1338, 5541, 288, 203, 3639, 2583, 24899, 18334, 480, 1758, 12, 20, 3631, 315, 4958, 265, 5077, 30, 848, 1404, 527, 3634, 1758, 8863, 203, 3639, 2583, 12, 5, 24454, 4002, 24899, 18334, 3631, 315, 4958, 265, 5077, 30, 1758, 1818, 1704, 8863, 203, 203, 3639, 3626, 31020, 24899, 18334, 16, 315, 986, 8863, 203, 203, 3639, 22686, 18, 6206, 24899, 18334, 1769, 203, 565, 289, 203, 203, 565, 445, 1206, 12952, 12, 2867, 389, 18334, 13, 1071, 1338, 5541, 288, 203, 3639, 2583, 24899, 18334, 480, 1758, 12, 20, 3631, 315, 4958, 265, 5077, 30, 848, 1404, 1206, 3634, 1758, 8863, 203, 3639, 2583, 12, 24454, 4002, 24899, 18334, 3631, 315, 4958, 265, 5077, 30, 1758, 1552, 486, 1005, 8863, 203, 203, 3639, 3626, 31020, 24899, 18334, 16, 315, 3288, 8863, 203, 203, 3639, 1430, 22686, 63, 11890, 12, 588, 12952, 1016, 24899, 18334, 3719, 15533, 203, 565, 289, 203, 203, 565, 445, 5971, 4002, 12, 2867, 389, 18334, 13, 1071, 1476, 1135, 12, 6430, 13, 288, 203, 3639, 327, 336, 12952, 1016, 24899, 18334, 13, 480, 300, 21, 31, 203, 565, 289, 203, 203, 565, 445, 336, 12952, 1016, 12, 2867, 389, 18334, 13, 1071, 2 ]
pragma solidity ^0.5.0; pragma experimental ABIEncoderV2; /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ interface IERC20 { function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor () internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @return the address of the owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner()); _; } /** * @return true if `msg.sender` is the owner of the contract. */ function isOwner() public view returns (bool) { return msg.sender == _owner; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0)); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } /** * @title SafeMath * @dev Unsigned math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two unsigned integers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two unsigned integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } /** * @title SignedSafeMath * @dev Signed math operations with safety checks that revert on error */ library SignedSafeMath { int256 constant private INT256_MIN = -2**255; /** * @dev Multiplies two signed integers, reverts on overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } require(!(a == -1 && b == INT256_MIN)); // This is the only case of overflow not detected by the check below int256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two signed integers truncating the quotient, reverts on division by zero. */ function div(int256 a, int256 b) internal pure returns (int256) { require(b != 0); // Solidity only automatically asserts when dividing by 0 require(!(b == -1 && a == INT256_MIN)); // This is the only case of overflow int256 c = a / b; return c; } /** * @dev Subtracts two signed integers, reverts on overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a)); return c; } /** * @dev Adds two signed integers, reverts on overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a)); return c; } } /** * @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 * * This implementation emits additional Approval events, allowing applications to reconstruct the allowance status for * all accounts just by listening to said events. Note that this isn't required by the specification, and other * compliant implementations may not do it. */ contract ERC20 is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; uint256 private _totalSupply; /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev Gets the balance of the specified address. * @param owner The address to query the balance of. * @return 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) { _transfer(msg.sender, to, value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param spender The address which will spend the funds. * @param value The amount of tokens to be spent. */ function approve(address spender, uint256 value) public returns (bool) { 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. * Note that while this function emits an Approval event, this is not required as per the specification, * and other compliant implementations may not emit the event. * @param from address The address which you want to send tokens from * @param to address The address which you want to transfer to * @param value uint256 the amount of tokens to be transferred */ function transferFrom(address from, address to, uint256 value) public returns (bool) { _allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value); _transfer(from, to, value); emit Approval(from, msg.sender, _allowed[from][msg.sender]); 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 * Emits an Approval event. * @param spender The address which will spend the funds. * @param addedValue The amount of tokens to increase the allowance by. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { 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 * Emits an Approval event. * @param spender The address which will spend the funds. * @param subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { 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 Transfer token for a specified addresses * @param from The address to transfer from. * @param to The address to transfer to. * @param value The amount to be transferred. */ function _transfer(address from, address to, uint256 value) internal { require(to != address(0)); _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(from, to, value); } /** * @dev Internal function that mints an amount of the token and assigns it to * an account. This encapsulates the modification of balances such that the * proper events are emitted. * @param account The account that will receive the created tokens. * @param value The amount that will be created. */ function _mint(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.add(value); _balances[account] = _balances[account].add(value); emit Transfer(address(0), account, value); } /** * @dev Internal function that burns an amount of the token of a given * account. * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burn(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); } /** * @dev Internal function that burns an amount of the token of a given * account, deducting from the sender's allowance for said account. Uses the * internal burn function. * Emits an Approval event (reflecting the reduced allowance). * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burnFrom(address account, uint256 value) internal { _allowed[account][msg.sender] = _allowed[account][msg.sender].sub(value); _burn(account, value); emit Approval(account, msg.sender, _allowed[account][msg.sender]); } } // The functionality that all derivative contracts expose to the admin. interface AdminInterface { // Initiates the shutdown process, in case of an emergency. function emergencyShutdown() external; // A core contract method called immediately before or after any financial transaction. It pays fees and moves money // between margin accounts to make sure they reflect the NAV of the contract. function remargin() external; } contract ExpandedIERC20 is IERC20 { // Burns a specific amount of tokens. Burns the sender's tokens, so it is safe to leave this method permissionless. function burn(uint value) external; // Mints tokens and adds them to the balance of the `to` address. // Note: this method should be permissioned to only allow designated parties to mint tokens. function mint(address to, uint value) external; } // This interface allows derivative contracts to pay Oracle fees for their use of the system. interface StoreInterface { // Pays Oracle fees in ETH to the store. To be used by contracts whose margin currency is ETH. function payOracleFees() external payable; // Pays Oracle fees in the margin currency, erc20Address, to the store. To be used if the margin currency is an // ERC20 token rather than ETH. All approved tokens are transfered. function payOracleFeesErc20(address erc20Address) external; // Computes the Oracle fees that a contract should pay for a period. `pfc` is the "profit from corruption", or the // maximum amount of margin currency that a token sponsor could extract from the contract through corrupting the // price feed in their favor. function computeOracleFees(uint startTime, uint endTime, uint pfc) external view returns (uint feeAmount); } interface ReturnCalculatorInterface { // Computes the return between oldPrice and newPrice. function computeReturn(int oldPrice, int newPrice) external view returns (int assetReturn); // Gets the effective leverage for the return calculator. // Note: if this parameter doesn't exist for this calculator, this method should return 1. function leverage() external view returns (int _leverage); } // This interface allows contracts to query unverified prices. interface PriceFeedInterface { // Whether this PriceFeeds provides prices for the given identifier. function isIdentifierSupported(bytes32 identifier) external view returns (bool isSupported); // Gets the latest time-price pair at which a price was published. The transaction will revert if no prices have // been published for this identifier. function latestPrice(bytes32 identifier) external view returns (uint publishTime, int price); // An event fired when a price is published. event PriceUpdated(bytes32 indexed identifier, uint indexed time, int price); } contract AddressWhitelist is Ownable { enum Status { None, In, Out } mapping(address => Status) private whitelist; address[] private whitelistIndices; // Adds an address to the whitelist function addToWhitelist(address newElement) external onlyOwner { // Ignore if address is already included if (whitelist[newElement] == Status.In) { return; } // Only append new addresses to the array, never a duplicate if (whitelist[newElement] == Status.None) { whitelistIndices.push(newElement); } whitelist[newElement] = Status.In; emit AddToWhitelist(newElement); } // Removes an address from the whitelist. function removeFromWhitelist(address elementToRemove) external onlyOwner { if (whitelist[elementToRemove] != Status.Out) { whitelist[elementToRemove] = Status.Out; emit RemoveFromWhitelist(elementToRemove); } } // Checks whether an address is on the whitelist. function isOnWhitelist(address elementToCheck) external view returns (bool) { return whitelist[elementToCheck] == Status.In; } // Gets all addresses that are currently included in the whitelist // Note: This method skips over, but still iterates through addresses. // It is possible for this call to run out of gas if a large number of // addresses have been removed. To prevent this unlikely scenario, we can // modify the implementation so that when addresses are removed, the last addresses // in the array is moved to the empty index. function getWhitelist() external view returns (address[] memory activeWhitelist) { // Determine size of whitelist first uint activeCount = 0; for (uint i = 0; i < whitelistIndices.length; i++) { if (whitelist[whitelistIndices[i]] == Status.In) { activeCount++; } } // Populate whitelist activeWhitelist = new address[](activeCount); activeCount = 0; for (uint i = 0; i < whitelistIndices.length; i++) { address addr = whitelistIndices[i]; if (whitelist[addr] == Status.In) { activeWhitelist[activeCount] = addr; activeCount++; } } } event AddToWhitelist(address indexed addedAddress); event RemoveFromWhitelist(address indexed removedAddress); } contract Withdrawable is Ownable { // Withdraws ETH from the contract. function withdraw(uint amount) external onlyOwner { msg.sender.transfer(amount); } // Withdraws ERC20 tokens from the contract. function withdrawErc20(address erc20Address, uint amount) external onlyOwner { IERC20 erc20 = IERC20(erc20Address); require(erc20.transfer(msg.sender, amount)); } } // This interface allows contracts to query a verified, trusted price. interface OracleInterface { // Requests the Oracle price for an identifier at a time. Returns the time at which a price will be available. // Returns 0 is the price is available now, and returns 2^256-1 if the price will never be available. Reverts if // the Oracle doesn't support this identifier. Only contracts registered in the Registry are authorized to call this // method. function requestPrice(bytes32 identifier, uint time) external returns (uint expectedTime); // Checks whether a price has been resolved. function hasPrice(bytes32 identifier, uint time) external view returns (bool hasPriceAvailable); // Returns the Oracle price for identifier at a time. Reverts if the Oracle doesn't support this identifier or if // the Oracle doesn't have a price for this time. Only contracts registered in the Registry are authorized to call // this method. function getPrice(bytes32 identifier, uint time) external view returns (int price); // Returns whether the Oracle provides verified prices for the given identifier. function isIdentifierSupported(bytes32 identifier) external view returns (bool isSupported); // An event fired when a request for a (identifier, time) pair is made. event VerifiedPriceRequested(bytes32 indexed identifier, uint indexed time); // An event fired when a verified price is available for a (identifier, time) pair. event VerifiedPriceAvailable(bytes32 indexed identifier, uint indexed time, int price); } interface RegistryInterface { struct RegisteredDerivative { address derivativeAddress; address derivativeCreator; } // Registers a new derivative. Only authorized derivative creators can call this method. function registerDerivative(address[] calldata counterparties, address derivativeAddress) external; // Adds a new derivative creator to this list of authorized creators. Only the owner of this contract can call // this method. function addDerivativeCreator(address derivativeCreator) external; // Removes a derivative creator to this list of authorized creators. Only the owner of this contract can call this // method. function removeDerivativeCreator(address derivativeCreator) external; // Returns whether the derivative has been registered with the registry (and is therefore an authorized participant // in the UMA system). function isDerivativeRegistered(address derivative) external view returns (bool isRegistered); // Returns a list of all derivatives that are associated with a particular party. function getRegisteredDerivatives(address party) external view returns (RegisteredDerivative[] memory derivatives); // Returns all registered derivatives. function getAllRegisteredDerivatives() external view returns (RegisteredDerivative[] memory derivatives); // Returns whether an address is authorized to register new derivatives. function isDerivativeCreatorAuthorized(address derivativeCreator) external view returns (bool isAuthorized); } contract Registry is RegistryInterface, Withdrawable { using SafeMath for uint; // Array of all registeredDerivatives that are approved to use the UMA Oracle. RegisteredDerivative[] private registeredDerivatives; // This enum is required because a WasValid state is required to ensure that derivatives cannot be re-registered. enum PointerValidity { Invalid, Valid, WasValid } struct Pointer { PointerValidity valid; uint128 index; } // Maps from derivative address to a pointer that refers to that RegisteredDerivative in registeredDerivatives. mapping(address => Pointer) private derivativePointers; // Note: this must be stored outside of the RegisteredDerivative because mappings cannot be deleted and copied // like normal data. This could be stored in the Pointer struct, but storing it there would muddy the purpose // of the Pointer struct and break separation of concern between referential data and data. struct PartiesMap { mapping(address => bool) parties; } // Maps from derivative address to the set of parties that are involved in that derivative. mapping(address => PartiesMap) private derivativesToParties; // Maps from derivative creator address to whether that derivative creator has been approved to register contracts. mapping(address => bool) private derivativeCreators; modifier onlyApprovedDerivativeCreator { require(derivativeCreators[msg.sender]); _; } function registerDerivative(address[] calldata parties, address derivativeAddress) external onlyApprovedDerivativeCreator { // Create derivative pointer. Pointer storage pointer = derivativePointers[derivativeAddress]; // Ensure that the pointer was not valid in the past (derivatives cannot be re-registered or double // registered). require(pointer.valid == PointerValidity.Invalid); pointer.valid = PointerValidity.Valid; registeredDerivatives.push(RegisteredDerivative(derivativeAddress, msg.sender)); // No length check necessary because we should never hit (2^127 - 1) derivatives. pointer.index = uint128(registeredDerivatives.length.sub(1)); // Set up PartiesMap for this derivative. PartiesMap storage partiesMap = derivativesToParties[derivativeAddress]; for (uint i = 0; i < parties.length; i = i.add(1)) { partiesMap.parties[parties[i]] = true; } address[] memory partiesForEvent = parties; emit RegisterDerivative(derivativeAddress, partiesForEvent); } function addDerivativeCreator(address derivativeCreator) external onlyOwner { if (!derivativeCreators[derivativeCreator]) { derivativeCreators[derivativeCreator] = true; emit AddDerivativeCreator(derivativeCreator); } } function removeDerivativeCreator(address derivativeCreator) external onlyOwner { if (derivativeCreators[derivativeCreator]) { derivativeCreators[derivativeCreator] = false; emit RemoveDerivativeCreator(derivativeCreator); } } function isDerivativeRegistered(address derivative) external view returns (bool isRegistered) { return derivativePointers[derivative].valid == PointerValidity.Valid; } function getRegisteredDerivatives(address party) external view returns (RegisteredDerivative[] memory derivatives) { // This is not ideal - we must statically allocate memory arrays. To be safe, we make a temporary array as long // as registeredDerivatives. We populate it with any derivatives that involve the provided party. Then, we copy // the array over to the return array, which is allocated using the correct size. Note: this is done by double // copying each value rather than storing some referential info (like indices) in memory to reduce the number // of storage reads. This is because storage reads are far more expensive than extra memory space (~100:1). RegisteredDerivative[] memory tmpDerivativeArray = new RegisteredDerivative[](registeredDerivatives.length); uint outputIndex = 0; for (uint i = 0; i < registeredDerivatives.length; i = i.add(1)) { RegisteredDerivative storage derivative = registeredDerivatives[i]; if (derivativesToParties[derivative.derivativeAddress].parties[party]) { // Copy selected derivative to the temporary array. tmpDerivativeArray[outputIndex] = derivative; outputIndex = outputIndex.add(1); } } // Copy the temp array to the return array that is set to the correct size. derivatives = new RegisteredDerivative[](outputIndex); for (uint j = 0; j < outputIndex; j = j.add(1)) { derivatives[j] = tmpDerivativeArray[j]; } } function getAllRegisteredDerivatives() external view returns (RegisteredDerivative[] memory derivatives) { return registeredDerivatives; } function isDerivativeCreatorAuthorized(address derivativeCreator) external view returns (bool isAuthorized) { return derivativeCreators[derivativeCreator]; } event RegisterDerivative(address indexed derivativeAddress, address[] parties); event AddDerivativeCreator(address indexed addedDerivativeCreator); event RemoveDerivativeCreator(address indexed removedDerivativeCreator); } contract Testable is Ownable { // Is the contract being run on the test network. Note: this variable should be set on construction and never // modified. bool public isTest; uint private currentTime; constructor(bool _isTest) internal { isTest = _isTest; if (_isTest) { currentTime = now; // solhint-disable-line not-rely-on-time } } modifier onlyIfTest { require(isTest); _; } function setCurrentTime(uint _time) external onlyOwner onlyIfTest { currentTime = _time; } function getCurrentTime() public view returns (uint) { if (isTest) { return currentTime; } else { return now; // solhint-disable-line not-rely-on-time } } } contract ContractCreator is Withdrawable { Registry internal registry; address internal oracleAddress; address internal storeAddress; address internal priceFeedAddress; constructor(address registryAddress, address _oracleAddress, address _storeAddress, address _priceFeedAddress) public { registry = Registry(registryAddress); oracleAddress = _oracleAddress; storeAddress = _storeAddress; priceFeedAddress = _priceFeedAddress; } function _registerContract(address[] memory parties, address contractToRegister) internal { registry.registerDerivative(parties, contractToRegister); } } library TokenizedDerivativeParams { enum ReturnType { Linear, Compound } struct ConstructorParams { address sponsor; address admin; address oracle; address store; address priceFeed; uint defaultPenalty; // Percentage of margin requirement * 10^18 uint supportedMove; // Expected percentage move in the underlying price that the long is protected against. bytes32 product; uint fixedYearlyFee; // Percentage of nav * 10^18 uint disputeDeposit; // Percentage of margin requirement * 10^18 address returnCalculator; uint startingTokenPrice; uint expiry; address marginCurrency; uint withdrawLimit; // Percentage of derivativeStorage.shortBalance * 10^18 ReturnType returnType; uint startingUnderlyingPrice; uint creationTime; } } // TokenizedDerivativeStorage: this library name is shortened due to it being used so often. library TDS { enum State { // The contract is active, and tokens can be created and redeemed. Margin can be added and withdrawn (as long as // it exceeds required levels). Remargining is allowed. Created contracts immediately begin in this state. // Possible state transitions: Disputed, Expired, Defaulted. Live, // Disputed, Expired, Defaulted, and Emergency are Frozen states. In a Frozen state, the contract is frozen in // time awaiting a resolution by the Oracle. No tokens can be created or redeemed. Margin cannot be withdrawn. // The resolution of these states moves the contract to the Settled state. Remargining is not allowed. // The derivativeStorage.externalAddresses.sponsor has disputed the price feed output. If the dispute is valid (i.e., the NAV calculated from the // Oracle price differs from the NAV calculated from the price feed), the dispute fee is added to the short // account. Otherwise, the dispute fee is added to the long margin account. // Possible state transitions: Settled. Disputed, // Contract expiration has been reached. // Possible state transitions: Settled. Expired, // The short margin account is below its margin requirement. The derivativeStorage.externalAddresses.sponsor can choose to confirm the default and // move to Settle without waiting for the Oracle. Default penalties will be assessed when the contract moves to // Settled. // Possible state transitions: Settled. Defaulted, // UMA has manually triggered a shutdown of the account. // Possible state transitions: Settled. Emergency, // Token price is fixed. Tokens can be redeemed by anyone. All short margin can be withdrawn. Tokens can't be // created, and contract can't remargin. // Possible state transitions: None. Settled } // The state of the token at a particular time. The state gets updated on remargin. struct TokenState { int underlyingPrice; int tokenPrice; uint time; } // The information in the following struct is only valid if in the midst of a Dispute. struct Dispute { int disputedNav; uint deposit; } struct WithdrawThrottle { uint startTime; uint remainingWithdrawal; } struct FixedParameters { // Fixed contract parameters. uint defaultPenalty; // Percentage of margin requirement * 10^18 uint supportedMove; // Expected percentage move that the long is protected against. uint disputeDeposit; // Percentage of margin requirement * 10^18 uint fixedFeePerSecond; // Percentage of nav*10^18 uint withdrawLimit; // Percentage of derivativeStorage.shortBalance*10^18 bytes32 product; TokenizedDerivativeParams.ReturnType returnType; uint initialTokenUnderlyingRatio; uint creationTime; string symbol; } struct ExternalAddresses { // Other addresses/contracts address sponsor; address admin; address apDelegate; OracleInterface oracle; StoreInterface store; PriceFeedInterface priceFeed; ReturnCalculatorInterface returnCalculator; IERC20 marginCurrency; } struct Storage { FixedParameters fixedParameters; ExternalAddresses externalAddresses; // Balances int shortBalance; int longBalance; State state; uint endTime; // The NAV of the contract always reflects the transition from (`prev`, `current`). // In the case of a remargin, a `latest` price is retrieved from the price feed, and we shift `current` -> `prev` // and `latest` -> `current` (and then recompute). // In the case of a dispute, `current` might change (which is why we have to hold on to `prev`). TokenState referenceTokenState; TokenState currentTokenState; int nav; // Net asset value is measured in Wei Dispute disputeInfo; // Only populated once the contract enters a frozen state. int defaultPenaltyAmount; WithdrawThrottle withdrawThrottle; } } library TokenizedDerivativeUtils { using TokenizedDerivativeUtils for TDS.Storage; using SafeMath for uint; using SignedSafeMath for int; uint private constant SECONDS_PER_DAY = 86400; uint private constant SECONDS_PER_YEAR = 31536000; uint private constant INT_MAX = 2**255 - 1; uint private constant UINT_FP_SCALING_FACTOR = 10**18; int private constant INT_FP_SCALING_FACTOR = 10**18; modifier onlySponsor(TDS.Storage storage s) { require(msg.sender == s.externalAddresses.sponsor); _; } modifier onlyAdmin(TDS.Storage storage s) { require(msg.sender == s.externalAddresses.admin); _; } modifier onlySponsorOrAdmin(TDS.Storage storage s) { require(msg.sender == s.externalAddresses.sponsor || msg.sender == s.externalAddresses.admin); _; } modifier onlySponsorOrApDelegate(TDS.Storage storage s) { require(msg.sender == s.externalAddresses.sponsor || msg.sender == s.externalAddresses.apDelegate); _; } // Contract initializer. Should only be called at construction. // Note: Must be a public function because structs cannot be passed as calldata (required data type for external // functions). function _initialize( TDS.Storage storage s, TokenizedDerivativeParams.ConstructorParams memory params, string memory symbol) public { s._setFixedParameters(params, symbol); s._setExternalAddresses(params); // Keep the starting token price relatively close to FP_SCALING_FACTOR to prevent users from unintentionally // creating rounding or overflow errors. require(params.startingTokenPrice >= UINT_FP_SCALING_FACTOR.div(10**9)); require(params.startingTokenPrice <= UINT_FP_SCALING_FACTOR.mul(10**9)); // TODO(mrice32): we should have an ideal start time rather than blindly polling. (uint latestTime, int latestUnderlyingPrice) = s.externalAddresses.priceFeed.latestPrice(s.fixedParameters.product); // If nonzero, take the user input as the starting price. if (params.startingUnderlyingPrice != 0) { latestUnderlyingPrice = _safeIntCast(params.startingUnderlyingPrice); } require(latestUnderlyingPrice > 0); require(latestTime != 0); // Keep the ratio in case it's needed for margin computation. s.fixedParameters.initialTokenUnderlyingRatio = params.startingTokenPrice.mul(UINT_FP_SCALING_FACTOR).div(_safeUintCast(latestUnderlyingPrice)); require(s.fixedParameters.initialTokenUnderlyingRatio != 0); // Set end time to max value of uint to implement no expiry. if (params.expiry == 0) { s.endTime = ~uint(0); } else { require(params.expiry >= latestTime); s.endTime = params.expiry; } s.nav = s._computeInitialNav(latestUnderlyingPrice, latestTime, params.startingTokenPrice); s.state = TDS.State.Live; } function _depositAndCreateTokens(TDS.Storage storage s, uint marginForPurchase, uint tokensToPurchase) external onlySponsorOrApDelegate(s) { s._remarginInternal(); int newTokenNav = _computeNavForTokens(s.currentTokenState.tokenPrice, tokensToPurchase); if (newTokenNav < 0) { newTokenNav = 0; } uint positiveTokenNav = _safeUintCast(newTokenNav); // Get any refund due to sending more margin than the argument indicated (should only be able to happen in the // ETH case). uint refund = s._pullSentMargin(marginForPurchase); // Subtract newTokenNav from amount sent. uint depositAmount = marginForPurchase.sub(positiveTokenNav); // Deposit additional margin into the short account. s._depositInternal(depositAmount); // The _createTokensInternal call returns any refund due to the amount sent being larger than the amount // required to purchase the tokens, so we add that to the running refund. This should be 0 in this case, // but we leave this here in case of some refund being generated due to rounding errors or any bugs to ensure // the sender never loses money. refund = refund.add(s._createTokensInternal(tokensToPurchase, positiveTokenNav)); // Send the accumulated refund. s._sendMargin(refund); } function _redeemTokens(TDS.Storage storage s, uint tokensToRedeem) external { require(s.state == TDS.State.Live || s.state == TDS.State.Settled); require(tokensToRedeem > 0); if (s.state == TDS.State.Live) { require(msg.sender == s.externalAddresses.sponsor || msg.sender == s.externalAddresses.apDelegate); s._remarginInternal(); require(s.state == TDS.State.Live); } ExpandedIERC20 thisErc20Token = ExpandedIERC20(address(this)); uint initialSupply = _totalSupply(); require(initialSupply > 0); _pullAuthorizedTokens(thisErc20Token, tokensToRedeem); thisErc20Token.burn(tokensToRedeem); emit TokensRedeemed(s.fixedParameters.symbol, tokensToRedeem); // Value of the tokens is just the percentage of all the tokens multiplied by the balance of the investor // margin account. uint tokenPercentage = tokensToRedeem.mul(UINT_FP_SCALING_FACTOR).div(initialSupply); uint tokenMargin = _takePercentage(_safeUintCast(s.longBalance), tokenPercentage); s.longBalance = s.longBalance.sub(_safeIntCast(tokenMargin)); assert(s.longBalance >= 0); s.nav = _computeNavForTokens(s.currentTokenState.tokenPrice, _totalSupply()); s._sendMargin(tokenMargin); } function _dispute(TDS.Storage storage s, uint depositMargin) external onlySponsor(s) { require( s.state == TDS.State.Live, "Contract must be Live to dispute" ); uint requiredDeposit = _safeUintCast(_takePercentage(s._getRequiredMargin(s.currentTokenState), s.fixedParameters.disputeDeposit)); uint sendInconsistencyRefund = s._pullSentMargin(depositMargin); require(depositMargin >= requiredDeposit); uint overpaymentRefund = depositMargin.sub(requiredDeposit); s.state = TDS.State.Disputed; s.endTime = s.currentTokenState.time; s.disputeInfo.disputedNav = s.nav; s.disputeInfo.deposit = requiredDeposit; // Store the default penalty in case the dispute pushes the sponsor into default. s.defaultPenaltyAmount = s._computeDefaultPenalty(); emit Disputed(s.fixedParameters.symbol, s.endTime, s.nav); s._requestOraclePrice(s.endTime); // Add the two types of refunds: // 1. The refund for ETH sent if it was > depositMargin. // 2. The refund for depositMargin > requiredDeposit. s._sendMargin(sendInconsistencyRefund.add(overpaymentRefund)); } function _withdraw(TDS.Storage storage s, uint amount) external onlySponsor(s) { // Remargin before allowing a withdrawal, but only if in the live state. if (s.state == TDS.State.Live) { s._remarginInternal(); } // Make sure either in Live or Settled after any necessary remargin. require(s.state == TDS.State.Live || s.state == TDS.State.Settled); // If the contract has been settled or is in prefunded state then can // withdraw up to full balance. If the contract is in live state then // must leave at least the required margin. Not allowed to withdraw in // other states. int withdrawableAmount; if (s.state == TDS.State.Settled) { withdrawableAmount = s.shortBalance; } else { // Update throttling snapshot and verify that this withdrawal doesn't go past the throttle limit. uint currentTime = s.currentTokenState.time; if (s.withdrawThrottle.startTime <= currentTime.sub(SECONDS_PER_DAY)) { // We've passed the previous s.withdrawThrottle window. Start new one. s.withdrawThrottle.startTime = currentTime; s.withdrawThrottle.remainingWithdrawal = _takePercentage(_safeUintCast(s.shortBalance), s.fixedParameters.withdrawLimit); } int marginMaxWithdraw = s.shortBalance.sub(s._getRequiredMargin(s.currentTokenState)); int throttleMaxWithdraw = _safeIntCast(s.withdrawThrottle.remainingWithdrawal); // Take the smallest of the two withdrawal limits. withdrawableAmount = throttleMaxWithdraw < marginMaxWithdraw ? throttleMaxWithdraw : marginMaxWithdraw; // Note: this line alone implicitly ensures the withdrawal throttle is not violated, but the above // ternary is more explicit. s.withdrawThrottle.remainingWithdrawal = s.withdrawThrottle.remainingWithdrawal.sub(amount); } // Can only withdraw the allowed amount. require( withdrawableAmount >= _safeIntCast(amount), "Attempting to withdraw more than allowed" ); // Transfer amount - Note: important to `-=` before the send so that the // function can not be called multiple times while waiting for transfer // to return. s.shortBalance = s.shortBalance.sub(_safeIntCast(amount)); emit Withdrawal(s.fixedParameters.symbol, amount); s._sendMargin(amount); } function _acceptPriceAndSettle(TDS.Storage storage s) external onlySponsor(s) { // Right now, only confirming prices in the defaulted state. require(s.state == TDS.State.Defaulted); // Remargin on agreed upon price. s._settleAgreedPrice(); } function _setApDelegate(TDS.Storage storage s, address _apDelegate) external onlySponsor(s) { s.externalAddresses.apDelegate = _apDelegate; } // Moves the contract into the Emergency state, where it waits on an Oracle price for the most recent remargin time. function _emergencyShutdown(TDS.Storage storage s) external onlyAdmin(s) { require(s.state == TDS.State.Live); s.state = TDS.State.Emergency; s.endTime = s.currentTokenState.time; s.defaultPenaltyAmount = s._computeDefaultPenalty(); emit EmergencyShutdownTransition(s.fixedParameters.symbol, s.endTime); s._requestOraclePrice(s.endTime); } function _settle(TDS.Storage storage s) external { s._settleInternal(); } function _createTokens(TDS.Storage storage s, uint marginForPurchase, uint tokensToPurchase) external onlySponsorOrApDelegate(s) { // Returns any refund due to sending more margin than the argument indicated (should only be able to happen in // the ETH case). uint refund = s._pullSentMargin(marginForPurchase); // The _createTokensInternal call returns any refund due to the amount sent being larger than the amount // required to purchase the tokens, so we add that to the running refund. refund = refund.add(s._createTokensInternal(tokensToPurchase, marginForPurchase)); // Send the accumulated refund. s._sendMargin(refund); } function _deposit(TDS.Storage storage s, uint marginToDeposit) external onlySponsor(s) { // Only allow the s.externalAddresses.sponsor to deposit margin. uint refund = s._pullSentMargin(marginToDeposit); s._depositInternal(marginToDeposit); // Send any refund due to sending more margin than the argument indicated (should only be able to happen in the // ETH case). s._sendMargin(refund); } // Returns the expected net asset value (NAV) of the contract using the latest available Price Feed price. function _calcNAV(TDS.Storage storage s) external view returns (int navNew) { (TDS.TokenState memory newTokenState, ) = s._calcNewTokenStateAndBalance(); navNew = _computeNavForTokens(newTokenState.tokenPrice, _totalSupply()); } // Returns the expected value of each the outstanding tokens of the contract using the latest available Price Feed // price. function _calcTokenValue(TDS.Storage storage s) external view returns (int newTokenValue) { (TDS.TokenState memory newTokenState,) = s._calcNewTokenStateAndBalance(); newTokenValue = newTokenState.tokenPrice; } // Returns the expected balance of the short margin account using the latest available Price Feed price. function _calcShortMarginBalance(TDS.Storage storage s) external view returns (int newShortMarginBalance) { (, newShortMarginBalance) = s._calcNewTokenStateAndBalance(); } function _calcExcessMargin(TDS.Storage storage s) external view returns (int newExcessMargin) { (TDS.TokenState memory newTokenState, int newShortMarginBalance) = s._calcNewTokenStateAndBalance(); // If the contract is in/will be moved to a settled state, the margin requirement will be 0. int requiredMargin = newTokenState.time >= s.endTime ? 0 : s._getRequiredMargin(newTokenState); return newShortMarginBalance.sub(requiredMargin); } function _getCurrentRequiredMargin(TDS.Storage storage s) external view returns (int requiredMargin) { if (s.state == TDS.State.Settled) { // No margin needs to be maintained when the contract is settled. return 0; } return s._getRequiredMargin(s.currentTokenState); } function _canBeSettled(TDS.Storage storage s) external view returns (bool canBeSettled) { TDS.State currentState = s.state; if (currentState == TDS.State.Settled) { return false; } // Technically we should also check if price will default the contract, but that isn't a normal flow of // operations that we want to simulate: we want to discourage the sponsor remargining into a default. (uint priceFeedTime, ) = s._getLatestPrice(); if (currentState == TDS.State.Live && (priceFeedTime < s.endTime)) { return false; } return s.externalAddresses.oracle.hasPrice(s.fixedParameters.product, s.endTime); } function _getUpdatedUnderlyingPrice(TDS.Storage storage s) external view returns (int underlyingPrice, uint time) { (TDS.TokenState memory newTokenState, ) = s._calcNewTokenStateAndBalance(); return (newTokenState.underlyingPrice, newTokenState.time); } function _calcNewTokenStateAndBalance(TDS.Storage storage s) internal view returns (TDS.TokenState memory newTokenState, int newShortMarginBalance) { // TODO: there's a lot of repeated logic in this method from elsewhere in the contract. It should be extracted // so the logic can be written once and used twice. However, much of this was written post-audit, so it was // deemed preferable not to modify any state changing code that could potentially introduce new security // bugs. This should be done before the next contract audit. if (s.state == TDS.State.Settled) { // If the contract is Settled, just return the current contract state. return (s.currentTokenState, s.shortBalance); } // Grab the price feed pricetime. (uint priceFeedTime, int priceFeedPrice) = s._getLatestPrice(); bool isContractLive = s.state == TDS.State.Live; bool isContractPostExpiry = priceFeedTime >= s.endTime; // If the time hasn't advanced since the last remargin, short circuit and return the most recently computed values. if (isContractLive && priceFeedTime <= s.currentTokenState.time) { return (s.currentTokenState, s.shortBalance); } // Determine which previous price state to use when computing the new NAV. // If the contract is live, we use the reference for the linear return type or if the contract will immediately // move to expiry. bool shouldUseReferenceTokenState = isContractLive && (s.fixedParameters.returnType == TokenizedDerivativeParams.ReturnType.Linear || isContractPostExpiry); TDS.TokenState memory lastTokenState = shouldUseReferenceTokenState ? s.referenceTokenState : s.currentTokenState; // Use the oracle settlement price/time if the contract is frozen or will move to expiry on the next remargin. (uint recomputeTime, int recomputePrice) = !isContractLive || isContractPostExpiry ? (s.endTime, s.externalAddresses.oracle.getPrice(s.fixedParameters.product, s.endTime)) : (priceFeedTime, priceFeedPrice); // Init the returned short balance to the current short balance. newShortMarginBalance = s.shortBalance; // Subtract the oracle fees from the short balance. newShortMarginBalance = isContractLive ? newShortMarginBalance.sub( _safeIntCast(s._computeExpectedOracleFees(s.currentTokenState.time, recomputeTime))) : newShortMarginBalance; // Compute the new NAV newTokenState = s._computeNewTokenState(lastTokenState, recomputePrice, recomputeTime); int navNew = _computeNavForTokens(newTokenState.tokenPrice, _totalSupply()); newShortMarginBalance = newShortMarginBalance.sub(_getLongDiff(navNew, s.longBalance, newShortMarginBalance)); // If the contract is frozen or will move into expiry, we need to settle it, which means adding the default // penalty and dispute deposit if necessary. if (!isContractLive || isContractPostExpiry) { // Subtract default penalty (if necessary) from the short balance. bool inDefault = !s._satisfiesMarginRequirement(newShortMarginBalance, newTokenState); if (inDefault) { int expectedDefaultPenalty = isContractLive ? s._computeDefaultPenalty() : s._getDefaultPenalty(); int defaultPenalty = (newShortMarginBalance < expectedDefaultPenalty) ? newShortMarginBalance : expectedDefaultPenalty; newShortMarginBalance = newShortMarginBalance.sub(defaultPenalty); } // Add the dispute deposit to the short balance if necessary. if (s.state == TDS.State.Disputed && navNew != s.disputeInfo.disputedNav) { int depositValue = _safeIntCast(s.disputeInfo.deposit); newShortMarginBalance = newShortMarginBalance.add(depositValue); } } } function _computeInitialNav(TDS.Storage storage s, int latestUnderlyingPrice, uint latestTime, uint startingTokenPrice) internal returns (int navNew) { int unitNav = _safeIntCast(startingTokenPrice); s.referenceTokenState = TDS.TokenState(latestUnderlyingPrice, unitNav, latestTime); s.currentTokenState = TDS.TokenState(latestUnderlyingPrice, unitNav, latestTime); // Starting NAV is always 0 in the TokenizedDerivative case. navNew = 0; } function _remargin(TDS.Storage storage s) external onlySponsorOrAdmin(s) { s._remarginInternal(); } function _withdrawUnexpectedErc20(TDS.Storage storage s, address erc20Address, uint amount) external onlySponsor(s) { if(address(s.externalAddresses.marginCurrency) == erc20Address) { uint currentBalance = s.externalAddresses.marginCurrency.balanceOf(address(this)); int totalBalances = s.shortBalance.add(s.longBalance); assert(totalBalances >= 0); uint withdrawableAmount = currentBalance.sub(_safeUintCast(totalBalances)).sub(s.disputeInfo.deposit); require(withdrawableAmount >= amount); } IERC20 erc20 = IERC20(erc20Address); require(erc20.transfer(msg.sender, amount)); } function _setExternalAddresses(TDS.Storage storage s, TokenizedDerivativeParams.ConstructorParams memory params) internal { // Note: not all "ERC20" tokens conform exactly to this interface (BNB, OMG, etc). The most common way that // tokens fail to conform is that they do not return a bool from certain state-changing operations. This // contract was not designed to work with those tokens because of the additional complexity they would // introduce. s.externalAddresses.marginCurrency = IERC20(params.marginCurrency); s.externalAddresses.oracle = OracleInterface(params.oracle); s.externalAddresses.store = StoreInterface(params.store); s.externalAddresses.priceFeed = PriceFeedInterface(params.priceFeed); s.externalAddresses.returnCalculator = ReturnCalculatorInterface(params.returnCalculator); // Verify that the price feed and s.externalAddresses.oracle support the given s.fixedParameters.product. require(s.externalAddresses.oracle.isIdentifierSupported(params.product)); require(s.externalAddresses.priceFeed.isIdentifierSupported(params.product)); s.externalAddresses.sponsor = params.sponsor; s.externalAddresses.admin = params.admin; } function _setFixedParameters(TDS.Storage storage s, TokenizedDerivativeParams.ConstructorParams memory params, string memory symbol) internal { // Ensure only valid enum values are provided. require(params.returnType == TokenizedDerivativeParams.ReturnType.Compound || params.returnType == TokenizedDerivativeParams.ReturnType.Linear); // Fee must be 0 if the returnType is linear. require(params.returnType == TokenizedDerivativeParams.ReturnType.Compound || params.fixedYearlyFee == 0); // The default penalty must be less than the required margin. require(params.defaultPenalty <= UINT_FP_SCALING_FACTOR); s.fixedParameters.returnType = params.returnType; s.fixedParameters.defaultPenalty = params.defaultPenalty; s.fixedParameters.product = params.product; s.fixedParameters.fixedFeePerSecond = params.fixedYearlyFee.div(SECONDS_PER_YEAR); s.fixedParameters.disputeDeposit = params.disputeDeposit; s.fixedParameters.supportedMove = params.supportedMove; s.fixedParameters.withdrawLimit = params.withdrawLimit; s.fixedParameters.creationTime = params.creationTime; s.fixedParameters.symbol = symbol; } // _remarginInternal() allows other functions to call remargin internally without satisfying permission checks for // _remargin(). function _remarginInternal(TDS.Storage storage s) internal { // If the state is not live, remargining does not make sense. require(s.state == TDS.State.Live); (uint latestTime, int latestPrice) = s._getLatestPrice(); // Checks whether contract has ended. if (latestTime <= s.currentTokenState.time) { // If the price feed hasn't advanced, remargining should be a no-op. return; } // Save the penalty using the current state in case it needs to be used. int potentialPenaltyAmount = s._computeDefaultPenalty(); if (latestTime >= s.endTime) { s.state = TDS.State.Expired; emit Expired(s.fixedParameters.symbol, s.endTime); // Applies the same update a second time to effectively move the current state to the reference state. int recomputedNav = s._computeNav(s.currentTokenState.underlyingPrice, s.currentTokenState.time); assert(recomputedNav == s.nav); uint feeAmount = s._deductOracleFees(s.currentTokenState.time, s.endTime); // Save the precomputed default penalty in case the expiry price pushes the sponsor into default. s.defaultPenaltyAmount = potentialPenaltyAmount; // We have no idea what the price was, exactly at s.endTime, so we can't set // s.currentTokenState, or update the nav, or do anything. s._requestOraclePrice(s.endTime); s._payOracleFees(feeAmount); return; } uint feeAmount = s._deductOracleFees(s.currentTokenState.time, latestTime); // Update nav of contract. int navNew = s._computeNav(latestPrice, latestTime); // Update the balances of the contract. s._updateBalances(navNew); // Make sure contract has not moved into default. bool inDefault = !s._satisfiesMarginRequirement(s.shortBalance, s.currentTokenState); if (inDefault) { s.state = TDS.State.Defaulted; s.defaultPenaltyAmount = potentialPenaltyAmount; s.endTime = latestTime; // Change end time to moment when default occurred. emit Default(s.fixedParameters.symbol, latestTime, s.nav); s._requestOraclePrice(latestTime); } s._payOracleFees(feeAmount); } function _createTokensInternal(TDS.Storage storage s, uint tokensToPurchase, uint navSent) internal returns (uint refund) { s._remarginInternal(); // Verify that remargining didn't push the contract into expiry or default. require(s.state == TDS.State.Live); int purchasedNav = _computeNavForTokens(s.currentTokenState.tokenPrice, tokensToPurchase); if (purchasedNav < 0) { purchasedNav = 0; } // Ensures that requiredNav >= navSent. refund = navSent.sub(_safeUintCast(purchasedNav)); s.longBalance = s.longBalance.add(purchasedNav); ExpandedIERC20 thisErc20Token = ExpandedIERC20(address(this)); thisErc20Token.mint(msg.sender, tokensToPurchase); emit TokensCreated(s.fixedParameters.symbol, tokensToPurchase); s.nav = _computeNavForTokens(s.currentTokenState.tokenPrice, _totalSupply()); // Make sure this still satisfies the margin requirement. require(s._satisfiesMarginRequirement(s.shortBalance, s.currentTokenState)); } function _depositInternal(TDS.Storage storage s, uint value) internal { // Make sure that we are in a "depositable" state. require(s.state == TDS.State.Live); s.shortBalance = s.shortBalance.add(_safeIntCast(value)); emit Deposited(s.fixedParameters.symbol, value); } function _settleInternal(TDS.Storage storage s) internal { TDS.State startingState = s.state; require(startingState == TDS.State.Disputed || startingState == TDS.State.Expired || startingState == TDS.State.Defaulted || startingState == TDS.State.Emergency); s._settleVerifiedPrice(); if (startingState == TDS.State.Disputed) { int depositValue = _safeIntCast(s.disputeInfo.deposit); if (s.nav != s.disputeInfo.disputedNav) { s.shortBalance = s.shortBalance.add(depositValue); } else { s.longBalance = s.longBalance.add(depositValue); } } } // Deducts the fees from the margin account. function _deductOracleFees(TDS.Storage storage s, uint lastTimeOracleFeesPaid, uint currentTime) internal returns (uint feeAmount) { feeAmount = s._computeExpectedOracleFees(lastTimeOracleFeesPaid, currentTime); s.shortBalance = s.shortBalance.sub(_safeIntCast(feeAmount)); // If paying the Oracle fee reduces the held margin below requirements, the rest of remargin() will default the // contract. } // Pays out the fees to the Oracle. function _payOracleFees(TDS.Storage storage s, uint feeAmount) internal { if (feeAmount == 0) { return; } if (address(s.externalAddresses.marginCurrency) == address(0x0)) { s.externalAddresses.store.payOracleFees.value(feeAmount)(); } else { require(s.externalAddresses.marginCurrency.approve(address(s.externalAddresses.store), feeAmount)); s.externalAddresses.store.payOracleFeesErc20(address(s.externalAddresses.marginCurrency)); } } function _computeExpectedOracleFees(TDS.Storage storage s, uint lastTimeOracleFeesPaid, uint currentTime) internal view returns (uint feeAmount) { // The profit from corruption is set as the max(longBalance, shortBalance). int pfc = s.shortBalance < s.longBalance ? s.longBalance : s.shortBalance; uint expectedFeeAmount = s.externalAddresses.store.computeOracleFees(lastTimeOracleFeesPaid, currentTime, _safeUintCast(pfc)); // Ensure the fee returned can actually be paid by the short margin account. uint shortBalance = _safeUintCast(s.shortBalance); return (shortBalance < expectedFeeAmount) ? shortBalance : expectedFeeAmount; } function _computeNewTokenState(TDS.Storage storage s, TDS.TokenState memory beginningTokenState, int latestUnderlyingPrice, uint recomputeTime) internal view returns (TDS.TokenState memory newTokenState) { int underlyingReturn = s.externalAddresses.returnCalculator.computeReturn( beginningTokenState.underlyingPrice, latestUnderlyingPrice); int tokenReturn = underlyingReturn.sub( _safeIntCast(s.fixedParameters.fixedFeePerSecond.mul(recomputeTime.sub(beginningTokenState.time)))); int tokenMultiplier = tokenReturn.add(INT_FP_SCALING_FACTOR); // In the compound case, don't allow the token price to go below 0. if (s.fixedParameters.returnType == TokenizedDerivativeParams.ReturnType.Compound && tokenMultiplier < 0) { tokenMultiplier = 0; } int newTokenPrice = _takePercentage(beginningTokenState.tokenPrice, tokenMultiplier); newTokenState = TDS.TokenState(latestUnderlyingPrice, newTokenPrice, recomputeTime); } function _satisfiesMarginRequirement(TDS.Storage storage s, int balance, TDS.TokenState memory tokenState) internal view returns (bool doesSatisfyRequirement) { return s._getRequiredMargin(tokenState) <= balance; } function _requestOraclePrice(TDS.Storage storage s, uint requestedTime) internal { uint expectedTime = s.externalAddresses.oracle.requestPrice(s.fixedParameters.product, requestedTime); if (expectedTime == 0) { // The Oracle price is already available, settle the contract right away. s._settleInternal(); } } function _getLatestPrice(TDS.Storage storage s) internal view returns (uint latestTime, int latestUnderlyingPrice) { (latestTime, latestUnderlyingPrice) = s.externalAddresses.priceFeed.latestPrice(s.fixedParameters.product); require(latestTime != 0); } function _computeNav(TDS.Storage storage s, int latestUnderlyingPrice, uint latestTime) internal returns (int navNew) { if (s.fixedParameters.returnType == TokenizedDerivativeParams.ReturnType.Compound) { navNew = s._computeCompoundNav(latestUnderlyingPrice, latestTime); } else { assert(s.fixedParameters.returnType == TokenizedDerivativeParams.ReturnType.Linear); navNew = s._computeLinearNav(latestUnderlyingPrice, latestTime); } } function _computeCompoundNav(TDS.Storage storage s, int latestUnderlyingPrice, uint latestTime) internal returns (int navNew) { s.referenceTokenState = s.currentTokenState; s.currentTokenState = s._computeNewTokenState(s.currentTokenState, latestUnderlyingPrice, latestTime); navNew = _computeNavForTokens(s.currentTokenState.tokenPrice, _totalSupply()); emit NavUpdated(s.fixedParameters.symbol, navNew, s.currentTokenState.tokenPrice); } function _computeLinearNav(TDS.Storage storage s, int latestUnderlyingPrice, uint latestTime) internal returns (int navNew) { // Only update the time - don't update the prices becuase all price changes are relative to the initial price. s.referenceTokenState.time = s.currentTokenState.time; s.currentTokenState = s._computeNewTokenState(s.referenceTokenState, latestUnderlyingPrice, latestTime); navNew = _computeNavForTokens(s.currentTokenState.tokenPrice, _totalSupply()); emit NavUpdated(s.fixedParameters.symbol, navNew, s.currentTokenState.tokenPrice); } function _recomputeNav(TDS.Storage storage s, int oraclePrice, uint recomputeTime) internal returns (int navNew) { // We're updating `last` based on what the Oracle has told us. assert(s.endTime == recomputeTime); s.currentTokenState = s._computeNewTokenState(s.referenceTokenState, oraclePrice, recomputeTime); navNew = _computeNavForTokens(s.currentTokenState.tokenPrice, _totalSupply()); emit NavUpdated(s.fixedParameters.symbol, navNew, s.currentTokenState.tokenPrice); } // Function is internally only called by `_settleAgreedPrice` or `_settleVerifiedPrice`. This function handles all // of the settlement logic including assessing penalties and then moves the state to `Settled`. function _settleWithPrice(TDS.Storage storage s, int price) internal { // Remargin at whatever price we're using (verified or unverified). s._updateBalances(s._recomputeNav(price, s.endTime)); bool inDefault = !s._satisfiesMarginRequirement(s.shortBalance, s.currentTokenState); if (inDefault) { int expectedDefaultPenalty = s._getDefaultPenalty(); int penalty = (s.shortBalance < expectedDefaultPenalty) ? s.shortBalance : expectedDefaultPenalty; s.shortBalance = s.shortBalance.sub(penalty); s.longBalance = s.longBalance.add(penalty); } s.state = TDS.State.Settled; emit Settled(s.fixedParameters.symbol, s.endTime, s.nav); } function _updateBalances(TDS.Storage storage s, int navNew) internal { // Compute difference -- Add the difference to owner and subtract // from counterparty. Then update nav state variable. int longDiff = _getLongDiff(navNew, s.longBalance, s.shortBalance); s.nav = navNew; s.longBalance = s.longBalance.add(longDiff); s.shortBalance = s.shortBalance.sub(longDiff); } function _getDefaultPenalty(TDS.Storage storage s) internal view returns (int penalty) { return s.defaultPenaltyAmount; } function _computeDefaultPenalty(TDS.Storage storage s) internal view returns (int penalty) { return _takePercentage(s._getRequiredMargin(s.currentTokenState), s.fixedParameters.defaultPenalty); } function _getRequiredMargin(TDS.Storage storage s, TDS.TokenState memory tokenState) internal view returns (int requiredMargin) { int leverageMagnitude = _absoluteValue(s.externalAddresses.returnCalculator.leverage()); int effectiveNotional; if (s.fixedParameters.returnType == TokenizedDerivativeParams.ReturnType.Linear) { int effectiveUnitsOfUnderlying = _safeIntCast(_totalSupply().mul(s.fixedParameters.initialTokenUnderlyingRatio).div(UINT_FP_SCALING_FACTOR)).mul(leverageMagnitude); effectiveNotional = effectiveUnitsOfUnderlying.mul(tokenState.underlyingPrice).div(INT_FP_SCALING_FACTOR); } else { int currentNav = _computeNavForTokens(tokenState.tokenPrice, _totalSupply()); effectiveNotional = currentNav.mul(leverageMagnitude); } // Take the absolute value of the notional since a negative notional has similar risk properties to a positive // notional of the same size, and, therefore, requires the same margin. requiredMargin = _takePercentage(_absoluteValue(effectiveNotional), s.fixedParameters.supportedMove); } function _pullSentMargin(TDS.Storage storage s, uint expectedMargin) internal returns (uint refund) { if (address(s.externalAddresses.marginCurrency) == address(0x0)) { // Refund is any amount of ETH that was sent that was above the amount that was expected. // Note: SafeMath will force a revert if msg.value < expectedMargin. return msg.value.sub(expectedMargin); } else { // If we expect an ERC20 token, no ETH should be sent. require(msg.value == 0); _pullAuthorizedTokens(s.externalAddresses.marginCurrency, expectedMargin); // There is never a refund in the ERC20 case since we use the argument to determine how much to "pull". return 0; } } function _sendMargin(TDS.Storage storage s, uint amount) internal { // There's no point in attempting a send if there's nothing to send. if (amount == 0) { return; } if (address(s.externalAddresses.marginCurrency) == address(0x0)) { msg.sender.transfer(amount); } else { require(s.externalAddresses.marginCurrency.transfer(msg.sender, amount)); } } function _settleAgreedPrice(TDS.Storage storage s) internal { int agreedPrice = s.currentTokenState.underlyingPrice; s._settleWithPrice(agreedPrice); } function _settleVerifiedPrice(TDS.Storage storage s) internal { int oraclePrice = s.externalAddresses.oracle.getPrice(s.fixedParameters.product, s.endTime); s._settleWithPrice(oraclePrice); } function _pullAuthorizedTokens(IERC20 erc20, uint amountToPull) private { // If nothing is being pulled, there's no point in calling a transfer. if (amountToPull > 0) { require(erc20.transferFrom(msg.sender, address(this), amountToPull)); } } // Gets the change in balance for the long side. // Note: there's a function for this because signage is tricky here, and it must be done the same everywhere. function _getLongDiff(int navNew, int longBalance, int shortBalance) private pure returns (int longDiff) { int newLongBalance = navNew; // Long balance cannot go below zero. if (newLongBalance < 0) { newLongBalance = 0; } longDiff = newLongBalance.sub(longBalance); // Cannot pull more margin from the short than is available. if (longDiff > shortBalance) { longDiff = shortBalance; } } function _computeNavForTokens(int tokenPrice, uint numTokens) private pure returns (int navNew) { int navPreDivision = _safeIntCast(numTokens).mul(tokenPrice); navNew = navPreDivision.div(INT_FP_SCALING_FACTOR); // The navNew division above truncates by default. Instead, we prefer to ceil this value to ensure tokens // cannot be purchased or backed with less than their true value. if ((navPreDivision % INT_FP_SCALING_FACTOR) != 0) { navNew = navNew.add(1); } } function _totalSupply() private view returns (uint totalSupply) { ExpandedIERC20 thisErc20Token = ExpandedIERC20(address(this)); return thisErc20Token.totalSupply(); } function _takePercentage(uint value, uint percentage) private pure returns (uint result) { return value.mul(percentage).div(UINT_FP_SCALING_FACTOR); } function _takePercentage(int value, uint percentage) private pure returns (int result) { return value.mul(_safeIntCast(percentage)).div(INT_FP_SCALING_FACTOR); } function _takePercentage(int value, int percentage) private pure returns (int result) { return value.mul(percentage).div(INT_FP_SCALING_FACTOR); } function _absoluteValue(int value) private pure returns (int result) { return value < 0 ? value.mul(-1) : value; } function _safeIntCast(uint value) private pure returns (int result) { require(value <= INT_MAX); return int(value); } function _safeUintCast(int value) private pure returns (uint result) { require(value >= 0); return uint(value); } // Note that we can't have the symbol parameter be `indexed` due to: // TypeError: Indexed reference types cannot yet be used with ABIEncoderV2. // An event emitted when the NAV of the contract changes. event NavUpdated(string symbol, int newNav, int newTokenPrice); // An event emitted when the contract enters the Default state on a remargin. event Default(string symbol, uint defaultTime, int defaultNav); // An event emitted when the contract settles. event Settled(string symbol, uint settleTime, int finalNav); // An event emitted when the contract expires. event Expired(string symbol, uint expiryTime); // An event emitted when the contract's NAV is disputed by the sponsor. event Disputed(string symbol, uint timeDisputed, int navDisputed); // An event emitted when the contract enters emergency shutdown. event EmergencyShutdownTransition(string symbol, uint shutdownTime); // An event emitted when tokens are created. event TokensCreated(string symbol, uint numTokensCreated); // An event emitted when tokens are redeemed. event TokensRedeemed(string symbol, uint numTokensRedeemed); // An event emitted when margin currency is deposited. event Deposited(string symbol, uint amount); // An event emitted when margin currency is withdrawn. event Withdrawal(string symbol, uint amount); } // TODO(mrice32): make this and TotalReturnSwap derived classes of a single base to encap common functionality. contract TokenizedDerivative is ERC20, AdminInterface, ExpandedIERC20 { using TokenizedDerivativeUtils for TDS.Storage; // Note: these variables are to give ERC20 consumers information about the token. string public name; string public symbol; uint8 public constant decimals = 18; // solhint-disable-line const-name-snakecase TDS.Storage public derivativeStorage; constructor( TokenizedDerivativeParams.ConstructorParams memory params, string memory _name, string memory _symbol ) public { // Set token properties. name = _name; symbol = _symbol; // Initialize the contract. derivativeStorage._initialize(params, _symbol); } // Creates tokens with sent margin and returns additional margin. function createTokens(uint marginForPurchase, uint tokensToPurchase) external payable { derivativeStorage._createTokens(marginForPurchase, tokensToPurchase); } // Creates tokens with sent margin and deposits additional margin in short account. function depositAndCreateTokens(uint marginForPurchase, uint tokensToPurchase) external payable { derivativeStorage._depositAndCreateTokens(marginForPurchase, tokensToPurchase); } // Redeems tokens for margin currency. function redeemTokens(uint tokensToRedeem) external { derivativeStorage._redeemTokens(tokensToRedeem); } // Triggers a price dispute for the most recent remargin time. function dispute(uint depositMargin) external payable { derivativeStorage._dispute(depositMargin); } // Withdraws `amount` from short margin account. function withdraw(uint amount) external { derivativeStorage._withdraw(amount); } // Pays (Oracle and service) fees for the previous period, updates the contract NAV, moves margin between long and // short accounts to reflect the new NAV, and checks if both accounts meet minimum requirements. function remargin() external { derivativeStorage._remargin(); } // Forgo the Oracle verified price and settle the contract with last remargin price. This method is only callable on // contracts in the `Defaulted` state, and the default penalty is always transferred from the short to the long // account. function acceptPriceAndSettle() external { derivativeStorage._acceptPriceAndSettle(); } // Assigns an address to be the contract's Delegate AP. Replaces previous value. Set to 0x0 to indicate there is no // Delegate AP. function setApDelegate(address apDelegate) external { derivativeStorage._setApDelegate(apDelegate); } // Moves the contract into the Emergency state, where it waits on an Oracle price for the most recent remargin time. function emergencyShutdown() external { derivativeStorage._emergencyShutdown(); } // Returns the expected net asset value (NAV) of the contract using the latest available Price Feed price. function calcNAV() external view returns (int navNew) { return derivativeStorage._calcNAV(); } // Returns the expected value of each the outstanding tokens of the contract using the latest available Price Feed // price. function calcTokenValue() external view returns (int newTokenValue) { return derivativeStorage._calcTokenValue(); } // Returns the expected balance of the short margin account using the latest available Price Feed price. function calcShortMarginBalance() external view returns (int newShortMarginBalance) { return derivativeStorage._calcShortMarginBalance(); } // Returns the expected short margin in excess of the margin requirement using the latest available Price Feed // price. Value will be negative if the short margin is expected to be below the margin requirement. function calcExcessMargin() external view returns (int excessMargin) { return derivativeStorage._calcExcessMargin(); } // Returns the required margin, as of the last remargin. Note that `calcExcessMargin` uses updated values using the // latest available Price Feed price. function getCurrentRequiredMargin() external view returns (int requiredMargin) { return derivativeStorage._getCurrentRequiredMargin(); } // Returns whether the contract can be settled, i.e., is it valid to call settle() now. function canBeSettled() external view returns (bool canContractBeSettled) { return derivativeStorage._canBeSettled(); } // Returns the updated underlying price that was used in the calc* methods above. It will be a price feed price if // the contract is Live and will remain Live, or an Oracle price if the contract is settled/about to be settled. // Reverts if no Oracle price is available but an Oracle price is required. function getUpdatedUnderlyingPrice() external view returns (int underlyingPrice, uint time) { return derivativeStorage._getUpdatedUnderlyingPrice(); } // When an Oracle price becomes available, performs a final remargin, assesses any penalties, and moves the contract // into the `Settled` state. function settle() external { derivativeStorage._settle(); } // Adds the margin sent along with the call (or in the case of an ERC20 margin currency, authorized before the call) // to the short account. function deposit(uint amountToDeposit) external payable { derivativeStorage._deposit(amountToDeposit); } // Allows the sponsor to withdraw any ERC20 balance that is not the margin token. function withdrawUnexpectedErc20(address erc20Address, uint amount) external { derivativeStorage._withdrawUnexpectedErc20(erc20Address, amount); } // ExpandedIERC20 methods. modifier onlyThis { require(msg.sender == address(this)); _; } // Only allow calls from this contract or its libraries to burn tokens. function burn(uint value) external onlyThis { // Only allow calls from this contract or its libraries to burn tokens. _burn(msg.sender, value); } // Only allow calls from this contract or its libraries to mint tokens. function mint(address to, uint256 value) external onlyThis { _mint(to, value); } // These events are actually emitted by TokenizedDerivativeUtils, but we unfortunately have to define the events // here as well. event NavUpdated(string symbol, int newNav, int newTokenPrice); event Default(string symbol, uint defaultTime, int defaultNav); event Settled(string symbol, uint settleTime, int finalNav); event Expired(string symbol, uint expiryTime); event Disputed(string symbol, uint timeDisputed, int navDisputed); event EmergencyShutdownTransition(string symbol, uint shutdownTime); event TokensCreated(string symbol, uint numTokensCreated); event TokensRedeemed(string symbol, uint numTokensRedeemed); event Deposited(string symbol, uint amount); event Withdrawal(string symbol, uint amount); } contract TokenizedDerivativeCreator is ContractCreator, Testable { struct Params { uint defaultPenalty; // Percentage of mergin requirement * 10^18 uint supportedMove; // Expected percentage move in the underlying that the long is protected against. bytes32 product; uint fixedYearlyFee; // Percentage of nav * 10^18 uint disputeDeposit; // Percentage of mergin requirement * 10^18 address returnCalculator; uint startingTokenPrice; uint expiry; address marginCurrency; uint withdrawLimit; // Percentage of shortBalance * 10^18 TokenizedDerivativeParams.ReturnType returnType; uint startingUnderlyingPrice; string name; string symbol; } AddressWhitelist public sponsorWhitelist; AddressWhitelist public returnCalculatorWhitelist; AddressWhitelist public marginCurrencyWhitelist; constructor( address registryAddress, address _oracleAddress, address _storeAddress, address _priceFeedAddress, address _sponsorWhitelist, address _returnCalculatorWhitelist, address _marginCurrencyWhitelist, bool _isTest ) public ContractCreator(registryAddress, _oracleAddress, _storeAddress, _priceFeedAddress) Testable(_isTest) { sponsorWhitelist = AddressWhitelist(_sponsorWhitelist); returnCalculatorWhitelist = AddressWhitelist(_returnCalculatorWhitelist); marginCurrencyWhitelist = AddressWhitelist(_marginCurrencyWhitelist); } function createTokenizedDerivative(Params memory params) public returns (address derivativeAddress) { TokenizedDerivative derivative = new TokenizedDerivative(_convertParams(params), params.name, params.symbol); address[] memory parties = new address[](1); parties[0] = msg.sender; _registerContract(parties, address(derivative)); return address(derivative); } // Converts createTokenizedDerivative params to TokenizedDerivative constructor params. function _convertParams(Params memory params) private view returns (TokenizedDerivativeParams.ConstructorParams memory constructorParams) { // Copy and verify externally provided variables. require(sponsorWhitelist.isOnWhitelist(msg.sender)); constructorParams.sponsor = msg.sender; require(returnCalculatorWhitelist.isOnWhitelist(params.returnCalculator)); constructorParams.returnCalculator = params.returnCalculator; require(marginCurrencyWhitelist.isOnWhitelist(params.marginCurrency)); constructorParams.marginCurrency = params.marginCurrency; constructorParams.defaultPenalty = params.defaultPenalty; constructorParams.supportedMove = params.supportedMove; constructorParams.product = params.product; constructorParams.fixedYearlyFee = params.fixedYearlyFee; constructorParams.disputeDeposit = params.disputeDeposit; constructorParams.startingTokenPrice = params.startingTokenPrice; constructorParams.expiry = params.expiry; constructorParams.withdrawLimit = params.withdrawLimit; constructorParams.returnType = params.returnType; constructorParams.startingUnderlyingPrice = params.startingUnderlyingPrice; // Copy internal variables. constructorParams.priceFeed = priceFeedAddress; constructorParams.oracle = oracleAddress; constructorParams.store = storeAddress; constructorParams.admin = oracleAddress; constructorParams.creationTime = getCurrentTime(); } }
If the contract is in/will be moved to a settled state, the margin requirement will be 0.
function _calcExcessMargin(TDS.Storage storage s) external view returns (int newExcessMargin) { (TDS.TokenState memory newTokenState, int newShortMarginBalance) = s._calcNewTokenStateAndBalance(); int requiredMargin = newTokenState.time >= s.endTime ? 0 : s._getRequiredMargin(newTokenState); return newShortMarginBalance.sub(requiredMargin); }
972,315
[ 1, 2047, 326, 6835, 353, 316, 19, 20194, 506, 10456, 358, 279, 26319, 1259, 919, 16, 326, 7333, 12405, 903, 506, 374, 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 ]
[ 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, 389, 12448, 424, 614, 9524, 12, 56, 3948, 18, 3245, 2502, 272, 13, 3903, 1476, 1135, 261, 474, 394, 424, 614, 9524, 13, 288, 203, 3639, 261, 56, 3948, 18, 1345, 1119, 3778, 394, 1345, 1119, 16, 509, 394, 4897, 9524, 13937, 13, 273, 272, 6315, 12448, 1908, 1345, 1119, 1876, 13937, 5621, 203, 3639, 509, 1931, 9524, 273, 394, 1345, 1119, 18, 957, 1545, 272, 18, 409, 950, 692, 374, 294, 272, 6315, 588, 3705, 9524, 12, 2704, 1345, 1119, 1769, 203, 3639, 327, 394, 4897, 9524, 13937, 18, 1717, 12, 4718, 9524, 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 ]
pragma solidity ^0.4.15; /** * @title TokenLib * @author Majoolr.io * * version 1.1.0 * Copyright (c) 2017 Majoolr, LLC * The MIT License (MIT) * https://github.com/Majoolr/ethereum-libraries/blob/master/LICENSE * * The Token Library provides functionality to create a variety of ERC20 tokens. * See https://github.com/Majoolr/ethereum-contracts for an example of how to * create a basic ERC20 token. * * Majoolr works on open source projects in the Ethereum community with the * purpose of testing, documenting, and deploying reusable code onto the * blockchain to improve security and usability of smart contracts. Majoolr * also strives to educate non-profits, schools, and other community members * about the application of blockchain technology. * For further information: majoolr.io * * 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. */ library TokenLib { using BasicMathLib for uint256; struct TokenStorage { mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; string name; string symbol; uint256 totalSupply; uint256 INITIAL_SUPPLY; address owner; uint8 decimals; bool stillMinting; } event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); event OwnerChange(address from, address to); event Burn(address indexed burner, uint256 value); event MintingClosed(bool mintingClosed); /// @dev Called by the Standard Token upon creation. /// @param self Stored token from token contract /// @param _name Name of the new token /// @param _symbol Symbol of the new token /// @param _decimals Decimal places for the token represented /// @param _initial_supply The initial token supply /// @param _allowMinting True if additional tokens can be created, false otherwise function init(TokenStorage storage self, address _owner, string _name, string _symbol, uint8 _decimals, uint256 _initial_supply, bool _allowMinting) { require(self.INITIAL_SUPPLY == 0); self.name = _name; self.symbol = _symbol; self.totalSupply = _initial_supply; self.INITIAL_SUPPLY = _initial_supply; self.decimals = _decimals; self.owner = _owner; self.stillMinting = _allowMinting; self.balances[_owner] = _initial_supply; } /// @dev Transfer tokens from caller&#39;s account to another account. /// @param self Stored token from token contract /// @param _to Address to send tokens /// @param _value Number of tokens to send /// @return True if completed function transfer(TokenStorage storage self, address _to, uint256 _value) returns (bool) { bool err; uint256 balance; (err,balance) = self.balances[msg.sender].minus(_value); require(!err); self.balances[msg.sender] = balance; //It&#39;s not possible to overflow token supply self.balances[_to] = self.balances[_to] + _value; Transfer(msg.sender, _to, _value); return true; } /// @dev Authorized caller transfers tokens from one account to another /// @param self Stored token from token contract /// @param _from Address to send tokens from /// @param _to Address to send tokens to /// @param _value Number of tokens to send /// @return True if completed function transferFrom(TokenStorage storage self, address _from, address _to, uint256 _value) returns (bool) { var _allowance = self.allowed[_from][msg.sender]; bool err; uint256 balanceOwner; uint256 balanceSpender; (err,balanceOwner) = self.balances[_from].minus(_value); require(!err); (err,balanceSpender) = _allowance.minus(_value); require(!err); self.balances[_from] = balanceOwner; self.allowed[_from][msg.sender] = balanceSpender; self.balances[_to] = self.balances[_to] + _value; Transfer(_from, _to, _value); return true; } /// @dev Retrieve token balance for an account /// @param self Stored token from token contract /// @param _owner Address to retrieve balance of /// @return balance The number of tokens in the subject account function balanceOf(TokenStorage storage self, address _owner) constant returns (uint256 balance) { return self.balances[_owner]; } /// @dev Authorize an account to send tokens on caller&#39;s behalf /// @param self Stored token from token contract /// @param _spender Address to authorize /// @param _value Number of tokens authorized account may send /// @return True if completed function approve(TokenStorage storage self, address _spender, uint256 _value) returns (bool) { self.allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /// @dev Remaining tokens third party spender has to send /// @param self Stored token from token contract /// @param _owner Address of token holder /// @param _spender Address of authorized spender /// @return remaining Number of tokens spender has left in owner&#39;s account function allowance(TokenStorage storage self, address _owner, address _spender) constant returns (uint256 remaining) { return self.allowed[_owner][_spender]; } /// @dev Authorize third party transfer by increasing/decreasing allowed rather than setting it /// @param self Stored token from token contract /// @param _spender Address to authorize /// @param _valueChange Increase or decrease in number of tokens authorized account may send /// @param _increase True if increasing allowance, false if decreasing allowance /// @return True if completed function approveChange (TokenStorage storage self, address _spender, uint256 _valueChange, bool _increase) returns (bool) { uint256 _newAllowed; bool err; if(_increase) { (err, _newAllowed) = self.allowed[msg.sender][_spender].plus(_valueChange); require(!err); self.allowed[msg.sender][_spender] = _newAllowed; } else { if (_valueChange > self.allowed[msg.sender][_spender]) { self.allowed[msg.sender][_spender] = 0; } else { _newAllowed = self.allowed[msg.sender][_spender] - _valueChange; self.allowed[msg.sender][_spender] = _newAllowed; } } Approval(msg.sender, _spender, _newAllowed); return true; } /// @dev Change owning address of the token contract, specifically for minting /// @param self Stored token from token contract /// @param _newOwner Address for the new owner /// @return True if completed function changeOwner(TokenStorage storage self, address _newOwner) returns (bool) { require((self.owner == msg.sender) && (_newOwner > 0)); self.owner = _newOwner; OwnerChange(msg.sender, _newOwner); return true; } /// @dev Mints additional tokens, new tokens go to owner /// @param self Stored token from token contract /// @param _amount Number of tokens to mint /// @return True if completed function mintToken(TokenStorage storage self, uint256 _amount) returns (bool) { require((self.owner == msg.sender) && self.stillMinting); uint256 _newAmount; bool err; (err, _newAmount) = self.totalSupply.plus(_amount); require(!err); self.totalSupply = _newAmount; self.balances[self.owner] = self.balances[self.owner] + _amount; Transfer(0x0, self.owner, _amount); return true; } /// @dev Permanent stops minting /// @param self Stored token from token contract /// @return True if completed function closeMint(TokenStorage storage self) returns (bool) { require(self.owner == msg.sender); self.stillMinting = false; MintingClosed(true); return true; } /// @dev Permanently burn tokens /// @param self Stored token from token contract /// @param _amount Amount of tokens to burn /// @return True if completed function burnToken(TokenStorage storage self, uint256 _amount) returns (bool) { uint256 _newBalance; bool err; (err, _newBalance) = self.balances[msg.sender].minus(_amount); require(!err); self.balances[msg.sender] = _newBalance; self.totalSupply = self.totalSupply - _amount; Burn(msg.sender, _amount); Transfer(msg.sender, 0x0, _amount); return true; } } pragma solidity ^0.4.13; /** * @title Basic Math Library * @author Majoolr.io * * version 1.1.0 * Copyright (c) 2017 Majoolr, LLC * The MIT License (MIT) * https://github.com/Majoolr/ethereum-libraries/blob/master/LICENSE * * The Basic Math Library is inspired by the Safe Math library written by * OpenZeppelin at https://github.com/OpenZeppelin/zeppelin-solidity/ . * Majoolr works on open source projects in the Ethereum community with the * purpose of testing, documenting, and deploying reusable code onto the * blockchain to improve security and usability of smart contracts. Majoolr * also strives to educate non-profits, schools, and other community members * about the application of blockchain technology. * For further information: majoolr.io, openzeppelin.org * * 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. */ library BasicMathLib { event Err(string typeErr); /// @dev Multiplies two numbers and checks for overflow before returning. /// Does not throw but rather logs an Err event if there is overflow. /// @param a First number /// @param b Second number /// @return err False normally, or true if there is overflow /// @return res The product of a and b, or 0 if there is overflow function times(uint256 a, uint256 b) constant returns (bool err,uint256 res) { assembly{ res := mul(a,b) switch or(iszero(b), eq(div(res,b), a)) case 0 { err := 1 res := 0 } } if (err) Err("times func overflow"); } /// @dev Divides two numbers but checks for 0 in the divisor first. /// Does not throw but rather logs an Err event if 0 is in the divisor. /// @param a First number /// @param b Second number /// @return err False normally, or true if `b` is 0 /// @return res The quotient of a and b, or 0 if `b` is 0 function dividedBy(uint256 a, uint256 b) constant returns (bool err,uint256 res) { assembly{ switch iszero(b) case 0 { res := div(a,b) mstore(add(mload(0x40),0x20),res) return(mload(0x40),0x40) } } Err("tried to divide by zero"); return (true, 0); } /// @dev Adds two numbers and checks for overflow before returning. /// Does not throw but rather logs an Err event if there is overflow. /// @param a First number /// @param b Second number /// @return err False normally, or true if there is overflow /// @return res The sum of a and b, or 0 if there is overflow function plus(uint256 a, uint256 b) constant returns (bool err, uint256 res) { assembly{ res := add(a,b) switch and(eq(sub(res,b), a), or(gt(res,b),eq(res,b))) case 0 { err := 1 res := 0 } } if (err) Err("plus func overflow"); } /// @dev Subtracts two numbers and checks for underflow before returning. /// Does not throw but rather logs an Err event if there is underflow. /// @param a First number /// @param b Second number /// @return err False normally, or true if there is underflow /// @return res The difference between a and b, or 0 if there is underflow function minus(uint256 a, uint256 b) constant returns (bool err,uint256 res) { assembly{ res := sub(a,b) switch eq(and(eq(add(res,b), a), or(lt(res,a), eq(res,a))), 1) case 0 { err := 1 res := 0 } } if (err) Err("minus func underflow"); } }
@dev Mints additional tokens, new tokens go to owner @param self Stored token from token contract @param _amount Number of tokens to mint @return True if completed
function mintToken(TokenStorage storage self, uint256 _amount) returns (bool) { require((self.owner == msg.sender) && self.stillMinting); uint256 _newAmount; bool err; (err, _newAmount) = self.totalSupply.plus(_amount); require(!err); self.totalSupply = _newAmount; self.balances[self.owner] = self.balances[self.owner] + _amount; Transfer(0x0, self.owner, _amount); return true; }
7,668,809
[ 1, 49, 28142, 3312, 2430, 16, 394, 2430, 1960, 358, 3410, 225, 365, 26548, 1147, 628, 1147, 6835, 225, 389, 8949, 3588, 434, 2430, 358, 312, 474, 327, 1053, 309, 5951, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1345, 12, 1345, 3245, 2502, 365, 16, 2254, 5034, 389, 8949, 13, 1135, 261, 6430, 13, 288, 203, 565, 2583, 12443, 2890, 18, 8443, 422, 1234, 18, 15330, 13, 597, 365, 18, 334, 737, 49, 474, 310, 1769, 203, 565, 2254, 5034, 389, 2704, 6275, 31, 203, 565, 1426, 393, 31, 203, 203, 565, 261, 370, 16, 389, 2704, 6275, 13, 273, 365, 18, 4963, 3088, 1283, 18, 10103, 24899, 8949, 1769, 203, 565, 2583, 12, 5, 370, 1769, 203, 203, 565, 365, 18, 4963, 3088, 1283, 273, 225, 389, 2704, 6275, 31, 203, 565, 365, 18, 70, 26488, 63, 2890, 18, 8443, 65, 273, 365, 18, 70, 26488, 63, 2890, 18, 8443, 65, 397, 389, 8949, 31, 203, 565, 12279, 12, 20, 92, 20, 16, 365, 18, 8443, 16, 389, 8949, 1769, 203, 565, 327, 638, 31, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.7.1; import "./OffchainAggregator.sol"; import "./SimpleReadAccessController.sol"; /** * @notice Wrapper of OffchainAggregator which checks read access on Aggregator-interface methods */ contract AccessControlledOffchainAggregator is OffchainAggregator, SimpleReadAccessController { constructor( uint32 _maximumGasPrice, uint32 _reasonableGasPrice, uint32 _microLinkPerEth, uint32 _linkGweiPerObservation, uint32 _linkGweiPerTransmission, address _link, address _validator, int192 _minAnswer, int192 _maxAnswer, AccessControllerInterface _billingAccessController, AccessControllerInterface _requesterAccessController, uint8 _decimals, string memory description ) OffchainAggregator( _maximumGasPrice, _reasonableGasPrice, _microLinkPerEth, _linkGweiPerObservation, _linkGweiPerTransmission, _link, _validator, _minAnswer, _maxAnswer, _billingAccessController, _requesterAccessController, _decimals, description ) { } /* * v2 Aggregator interface */ /// @inheritdoc OffchainAggregator function latestAnswer() public override view checkAccess() returns (int256) { return super.latestAnswer(); } /// @inheritdoc OffchainAggregator function latestTimestamp() public override view checkAccess() returns (uint256) { return super.latestTimestamp(); } /// @inheritdoc OffchainAggregator function latestRound() public override view checkAccess() returns (uint256) { return super.latestRound(); } /// @inheritdoc OffchainAggregator function getAnswer(uint256 _roundId) public override view checkAccess() returns (int256) { return super.getAnswer(_roundId); } /// @inheritdoc OffchainAggregator function getTimestamp(uint256 _roundId) public override view checkAccess() returns (uint256) { return super.getTimestamp(_roundId); } /* * v3 Aggregator interface */ /// @inheritdoc OffchainAggregator function description() public override view checkAccess() returns (string memory) { return super.description(); } /// @inheritdoc OffchainAggregator function getRoundData(uint80 _roundId) public override view checkAccess() returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ) { return super.getRoundData(_roundId); } /// @inheritdoc OffchainAggregator function latestRoundData() public override view checkAccess() returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ) { return super.latestRoundData(); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "./AccessControllerInterface.sol"; import "./AggregatorV2V3Interface.sol"; import "./AggregatorValidatorInterface.sol"; import "./LinkTokenInterface.sol"; import "./Owned.sol"; import "./OffchainAggregatorBilling.sol"; /** * @notice Onchain verification of reports from the offchain reporting protocol * @dev For details on its operation, see the offchain reporting protocol design * @dev doc, which refers to this contract as simply the "contract". */ contract OffchainAggregator is Owned, OffchainAggregatorBilling, AggregatorV2V3Interface { uint256 constant private maxUint32 = (1 << 32) - 1; // Storing these fields used on the hot path in a HotVars variable reduces the // retrieval of all of them to a single SLOAD. If any further fields are // added, make sure that storage of the struct still takes at most 32 bytes. struct HotVars { // Provides 128 bits of security against 2nd pre-image attacks, but only // 64 bits against collisions. This is acceptable, since a malicious owner has // easier way of messing up the protocol than to find hash collisions. bytes16 latestConfigDigest; uint40 latestEpochAndRound; // 32 most sig bits for epoch, 8 least sig bits for round // Current bound assumed on number of faulty/dishonest oracles participating // in the protocol, this value is referred to as f in the design uint8 threshold; // Chainlink Aggregators expose a roundId to consumers. The offchain reporting // protocol does not use this id anywhere. We increment it whenever a new // transmission is made to provide callers with contiguous ids for successive // reports. uint32 latestAggregatorRoundId; } HotVars internal s_hotVars; // Transmission records the median answer from the transmit transaction at // time timestamp struct Transmission { int192 answer; // 192 bits ought to be enough for anyone uint64 timestamp; } mapping(uint32 /* aggregator round ID */ => Transmission) internal s_transmissions; // incremented each time a new config is posted. This count is incorporated // into the config digest, to prevent replay attacks. uint32 internal s_configCount; uint32 internal s_latestConfigBlockNumber; // makes it easier for offchain systems // to extract config from logs. // Lowest answer the system is allowed to report in response to transmissions int192 immutable public minAnswer; // Highest answer the system is allowed to report in response to transmissions int192 immutable public maxAnswer; /* * @param _maximumGasPrice highest gas price for which transmitter will be compensated * @param _reasonableGasPrice transmitter will receive reward for gas prices under this value * @param _microLinkPerEth reimbursement per ETH of gas cost, in 1e-6LINK units * @param _linkGweiPerObservation reward to oracle for contributing an observation to a successfully transmitted report, in 1e-9LINK units * @param _linkGweiPerTransmission reward to transmitter of a successful report, in 1e-9LINK units * @param _link address of the LINK contract * @param _validator address of validator contract (must satisfy AggregatorValidatorInterface) * @param _minAnswer lowest answer the median of a report is allowed to be * @param _maxAnswer highest answer the median of a report is allowed to be * @param _billingAccessController access controller for billing admin functions * @param _requesterAccessController access controller for requesting new rounds * @param _decimals answers are stored in fixed-point format, with this many digits of precision * @param _description short human-readable description of observable this contract's answers pertain to */ constructor( uint32 _maximumGasPrice, uint32 _reasonableGasPrice, uint32 _microLinkPerEth, uint32 _linkGweiPerObservation, uint32 _linkGweiPerTransmission, address _link, address _validator, int192 _minAnswer, int192 _maxAnswer, AccessControllerInterface _billingAccessController, AccessControllerInterface _requesterAccessController, uint8 _decimals, string memory _description ) OffchainAggregatorBilling(_maximumGasPrice, _reasonableGasPrice, _microLinkPerEth, _linkGweiPerObservation, _linkGweiPerTransmission, _link, _billingAccessController ) { decimals = _decimals; s_description = _description; setRequesterAccessController(_requesterAccessController); setValidator(_validator); minAnswer = _minAnswer; maxAnswer = _maxAnswer; } /* * Config logic */ /** * @notice triggers a new run of the offchain reporting protocol * @param previousConfigBlockNumber block in which the previous config was set, to simplify historic analysis * @param configCount ordinal number of this config setting among all config settings over the life of this contract * @param signers ith element is address ith oracle uses to sign a report * @param transmitters ith element is address ith oracle uses to transmit a report via the transmit method * @param threshold maximum number of faulty/dishonest oracles the protocol can tolerate while still working correctly * @param encodedConfigVersion version of the serialization format used for "encoded" parameter * @param encoded serialized data used by oracles to configure their offchain operation */ event ConfigSet( uint32 previousConfigBlockNumber, uint64 configCount, address[] signers, address[] transmitters, uint8 threshold, uint64 encodedConfigVersion, bytes encoded ); // Reverts transaction if config args are invalid modifier checkConfigValid ( uint256 _numSigners, uint256 _numTransmitters, uint256 _threshold ) { require(_numSigners <= maxNumOracles, "too many signers"); require(_threshold > 0, "threshold must be positive"); require( _numSigners == _numTransmitters, "oracle addresses out of registration" ); require(_numSigners > 3*_threshold, "faulty-oracle threshold too high"); _; } /** * @notice sets offchain reporting protocol configuration incl. participating oracles * @param _signers addresses with which oracles sign the reports * @param _transmitters addresses oracles use to transmit the reports * @param _threshold number of faulty oracles the system can tolerate * @param _encodedConfigVersion version number for offchainEncoding schema * @param _encoded encoded off-chain oracle configuration */ function setConfig( address[] calldata _signers, address[] calldata _transmitters, uint8 _threshold, uint64 _encodedConfigVersion, bytes calldata _encoded ) external checkConfigValid(_signers.length, _transmitters.length, _threshold) onlyOwner() { while (s_signers.length != 0) { // remove any old signer/transmitter addresses uint lastIdx = s_signers.length - 1; address signer = s_signers[lastIdx]; address transmitter = s_transmitters[lastIdx]; payOracle(transmitter); delete s_oracles[signer]; delete s_oracles[transmitter]; s_signers.pop(); s_transmitters.pop(); } for (uint i = 0; i < _signers.length; i++) { // add new signer/transmitter addresses require( s_oracles[_signers[i]].role == Role.Unset, "repeated signer address" ); s_oracles[_signers[i]] = Oracle(uint8(i), Role.Signer); require(s_payees[_transmitters[i]] != address(0), "payee must be set"); require( s_oracles[_transmitters[i]].role == Role.Unset, "repeated transmitter address" ); s_oracles[_transmitters[i]] = Oracle(uint8(i), Role.Transmitter); s_signers.push(_signers[i]); s_transmitters.push(_transmitters[i]); } s_hotVars.threshold = _threshold; uint32 previousConfigBlockNumber = s_latestConfigBlockNumber; s_latestConfigBlockNumber = uint32(block.number); s_configCount += 1; uint64 configCount = s_configCount; { s_hotVars.latestConfigDigest = configDigestFromConfigData( address(this), configCount, _signers, _transmitters, _threshold, _encodedConfigVersion, _encoded ); s_hotVars.latestEpochAndRound = 0; } emit ConfigSet( previousConfigBlockNumber, configCount, _signers, _transmitters, _threshold, _encodedConfigVersion, _encoded ); } function configDigestFromConfigData( address _contractAddress, uint64 _configCount, address[] calldata _signers, address[] calldata _transmitters, uint8 _threshold, uint64 _encodedConfigVersion, bytes calldata _encodedConfig ) internal pure returns (bytes16) { return bytes16(keccak256(abi.encode(_contractAddress, _configCount, _signers, _transmitters, _threshold, _encodedConfigVersion, _encodedConfig ))); } /** * @notice information about current offchain reporting protocol configuration * @return configCount ordinal number of current config, out of all configs applied to this contract so far * @return blockNumber block at which this config was set * @return configDigest domain-separation tag for current config (see configDigestFromConfigData) */ function latestConfigDetails() external view returns ( uint32 configCount, uint32 blockNumber, bytes16 configDigest ) { return (s_configCount, s_latestConfigBlockNumber, s_hotVars.latestConfigDigest); } /** * @return list of addresses permitted to transmit reports to this contract * @dev The list will match the order used to specify the transmitter during setConfig */ function transmitters() external view returns(address[] memory) { return s_transmitters; } /* * On-chain validation logc */ // Maximum gas the validation logic can use uint256 private constant VALIDATOR_GAS_LIMIT = 100000; // Contract containing the validation logic AggregatorValidatorInterface private s_validator; /** * @notice indicates that the address of the validator contract has been set * @param previous setting of the address prior to this event * @param current the new value for the address */ event ValidatorUpdated( address indexed previous, address indexed current ); /** * @notice address of the contract which does external data validation * @return validator address */ function validator() external view returns (AggregatorValidatorInterface) { return s_validator; } /** * @notice sets the address which does external data validation * @param _newValidator designates the address of the new validation contract */ function setValidator(address _newValidator) public onlyOwner() { address previous = address(s_validator); if (previous != _newValidator) { s_validator = AggregatorValidatorInterface(_newValidator); emit ValidatorUpdated(previous, _newValidator); } } function validateAnswer( uint32 _aggregatorRoundId, int256 _answer ) private { AggregatorValidatorInterface av = s_validator; // cache storage reads if (address(av) == address(0)) return; uint32 prevAggregatorRoundId = _aggregatorRoundId - 1; int256 prevAggregatorRoundAnswer = s_transmissions[prevAggregatorRoundId].answer; // We do not want the validator to ever prevent reporting, so we limit its // gas usage and catch any errors that may arise. try av.validate{gas: VALIDATOR_GAS_LIMIT}( prevAggregatorRoundId, prevAggregatorRoundAnswer, _aggregatorRoundId, _answer ) {} catch {} } /* * requestNewRound logic */ AccessControllerInterface internal s_requesterAccessController; /** * @notice emitted when a new requester access controller contract is set * @param old the address prior to the current setting * @param current the address of the new access controller contract */ event RequesterAccessControllerSet(AccessControllerInterface old, AccessControllerInterface current); /** * @notice emitted to immediately request a new round * @param requester the address of the requester * @param configDigest the latest transmission's configDigest * @param epoch the latest transmission's epoch * @param round the latest transmission's round */ event RoundRequested(address indexed requester, bytes16 configDigest, uint32 epoch, uint8 round); /** * @notice address of the requester access controller contract * @return requester access controller address */ function requesterAccessController() external view returns (AccessControllerInterface) { return s_requesterAccessController; } /** * @notice sets the requester access controller * @param _requesterAccessController designates the address of the new requester access controller */ function setRequesterAccessController(AccessControllerInterface _requesterAccessController) public onlyOwner() { AccessControllerInterface oldController = s_requesterAccessController; if (_requesterAccessController != oldController) { s_requesterAccessController = AccessControllerInterface(_requesterAccessController); emit RequesterAccessControllerSet(oldController, _requesterAccessController); } } /** * @notice immediately requests a new round * @return the aggregatorRoundId of the next round. Note: The report for this round may have been * transmitted (but not yet mined) *before* requestNewRound() was even called. There is *no* * guarantee of causality between the request and the report at aggregatorRoundId. */ function requestNewRound() external returns (uint80) { require(msg.sender == owner || s_requesterAccessController.hasAccess(msg.sender, msg.data), "Only owner&requester can call"); HotVars memory hotVars = s_hotVars; emit RoundRequested( msg.sender, hotVars.latestConfigDigest, uint32(s_hotVars.latestEpochAndRound >> 8), uint8(s_hotVars.latestEpochAndRound) ); return hotVars.latestAggregatorRoundId + 1; } /* * Transmission logic */ /** * @notice indicates that a new report was transmitted * @param aggregatorRoundId the round to which this report was assigned * @param answer median of the observations attached this report * @param transmitter address from which the report was transmitted * @param observations observations transmitted with this report * @param rawReportContext signature-replay-prevention domain-separation tag */ event NewTransmission( uint32 indexed aggregatorRoundId, int192 answer, address transmitter, int192[] observations, bytes observers, bytes32 rawReportContext ); // decodeReport is used to check that the solidity and go code are using the // same format. See TestOffchainAggregator.testDecodeReport and TestReportParsing function decodeReport(bytes memory _report) internal pure returns ( bytes32 rawReportContext, bytes32 rawObservers, int192[] memory observations ) { (rawReportContext, rawObservers, observations) = abi.decode(_report, (bytes32, bytes32, int192[])); } // Used to relieve stack pressure in transmit struct ReportData { HotVars hotVars; // Only read from storage once bytes observers; // ith element is the index of the ith observer int192[] observations; // ith element is the ith observation bytes vs; // jth element is the v component of the jth signature bytes32 rawReportContext; } /* * @notice details about the most recent report * @return configDigest domain separation tag for the latest report * @return epoch epoch in which the latest report was generated * @return round OCR round in which the latest report was generated * @return latestAnswer median value from latest report * @return latestTimestamp when the latest report was transmitted */ function latestTransmissionDetails() external view returns ( bytes16 configDigest, uint32 epoch, uint8 round, int192 latestAnswer, uint64 latestTimestamp ) { require(msg.sender == tx.origin, "Only callable by EOA"); return ( s_hotVars.latestConfigDigest, uint32(s_hotVars.latestEpochAndRound >> 8), uint8(s_hotVars.latestEpochAndRound), s_transmissions[s_hotVars.latestAggregatorRoundId].answer, s_transmissions[s_hotVars.latestAggregatorRoundId].timestamp ); } // The constant-length components of the msg.data sent to transmit. // See the "If we wanted to call sam" example on for example reasoning // https://solidity.readthedocs.io/en/v0.7.2/abi-spec.html uint16 private constant TRANSMIT_MSGDATA_CONSTANT_LENGTH_COMPONENT = 4 + // function selector 32 + // word containing start location of abiencoded _report value 32 + // word containing location start of abiencoded _rs value 32 + // word containing start location of abiencoded _ss value 32 + // _rawVs value 32 + // word containing length of _report 32 + // word containing length _rs 32 + // word containing length of _ss 0; // placeholder function expectedMsgDataLength( bytes calldata _report, bytes32[] calldata _rs, bytes32[] calldata _ss ) private pure returns (uint256 length) { // calldata will never be big enough to make this overflow return uint256(TRANSMIT_MSGDATA_CONSTANT_LENGTH_COMPONENT) + _report.length + // one byte pure entry in _report _rs.length * 32 + // 32 bytes per entry in _rs _ss.length * 32 + // 32 bytes per entry in _ss 0; // placeholder } /** * @notice transmit is called to post a new report to the contract * @param _report serialized report, which the signatures are signing. See parsing code below for format. The ith element of the observers component must be the index in s_signers of the address for the ith signature * @param _rs ith element is the R components of the ith signature on report. Must have at most maxNumOracles entries * @param _ss ith element is the S components of the ith signature on report. Must have at most maxNumOracles entries * @param _rawVs ith element is the the V component of the ith signature */ function transmit( // NOTE: If these parameters are changed, expectedMsgDataLength and/or // TRANSMIT_MSGDATA_CONSTANT_LENGTH_COMPONENT need to be changed accordingly bytes calldata _report, bytes32[] calldata _rs, bytes32[] calldata _ss, bytes32 _rawVs // signatures ) external { uint256 initialGas = gasleft(); // This line must come first // Make sure the transmit message-length matches the inputs. Otherwise, the // transmitter could append an arbitrarily long (up to gas-block limit) // string of 0 bytes, which we would reimburse at a rate of 16 gas/byte, but // which would only cost the transmitter 4 gas/byte. (Appendix G of the // yellow paper, p. 25, for G_txdatazero and EIP 2028 for G_txdatanonzero.) // This could amount to reimbursement profit of 36 million gas, given a 3MB // zero tail. require(msg.data.length == expectedMsgDataLength(_report, _rs, _ss), "transmit message too long"); ReportData memory r; // Relieves stack pressure { r.hotVars = s_hotVars; // cache read from storage bytes32 rawObservers; (r.rawReportContext, rawObservers, r.observations) = abi.decode( _report, (bytes32, bytes32, int192[]) ); // rawReportContext consists of: // 11-byte zero padding // 16-byte configDigest // 4-byte epoch // 1-byte round bytes16 configDigest = bytes16(r.rawReportContext << 88); require( r.hotVars.latestConfigDigest == configDigest, "configDigest mismatch" ); uint40 epochAndRound = uint40(uint256(r.rawReportContext)); // direct numerical comparison works here, because // // ((e,r) <= (e',r')) implies (epochAndRound <= epochAndRound') // // because alphabetic ordering implies e <= e', and if e = e', then r<=r', // so e*256+r <= e'*256+r', because r, r' < 256 require(r.hotVars.latestEpochAndRound < epochAndRound, "stale report"); require(_rs.length > r.hotVars.threshold, "not enough signatures"); require(_rs.length <= maxNumOracles, "too many signatures"); require(_ss.length == _rs.length, "signatures out of registration"); require(r.observations.length <= maxNumOracles, "num observations out of bounds"); require(r.observations.length > 2 * r.hotVars.threshold, "too few values to trust median"); // Copy signature parities in bytes32 _rawVs to bytes r.v r.vs = new bytes(_rs.length); for (uint8 i = 0; i < _rs.length; i++) { r.vs[i] = _rawVs[i]; } // Copy observer identities in bytes32 rawObservers to bytes r.observers r.observers = new bytes(r.observations.length); bool[maxNumOracles] memory seen; for (uint8 i = 0; i < r.observations.length; i++) { uint8 observerIdx = uint8(rawObservers[i]); require(!seen[observerIdx], "observer index repeated"); seen[observerIdx] = true; r.observers[i] = rawObservers[i]; } Oracle memory transmitter = s_oracles[msg.sender]; require( // Check that sender is authorized to report transmitter.role == Role.Transmitter && msg.sender == s_transmitters[transmitter.index], "unauthorized transmitter" ); // record epochAndRound here, so that we don't have to carry the local // variable in transmit. The change is reverted if something fails later. r.hotVars.latestEpochAndRound = epochAndRound; } { // Verify signatures attached to report bytes32 h = keccak256(_report); bool[maxNumOracles] memory signed; Oracle memory o; for (uint i = 0; i < _rs.length; i++) { address signer = ecrecover(h, uint8(r.vs[i])+27, _rs[i], _ss[i]); o = s_oracles[signer]; require(o.role == Role.Signer, "address not authorized to sign"); require(!signed[o.index], "non-unique signature"); signed[o.index] = true; } } { // Check the report contents, and record the result for (uint i = 0; i < r.observations.length - 1; i++) { bool inOrder = r.observations[i] <= r.observations[i+1]; require(inOrder, "observations not sorted"); } int192 median = r.observations[r.observations.length/2]; require(minAnswer <= median && median <= maxAnswer, "median is out of min-max range"); r.hotVars.latestAggregatorRoundId++; s_transmissions[r.hotVars.latestAggregatorRoundId] = Transmission(median, uint64(block.timestamp)); emit NewTransmission( r.hotVars.latestAggregatorRoundId, median, msg.sender, r.observations, r.observers, r.rawReportContext ); // Emit these for backwards compatability with offchain consumers // that only support legacy events emit NewRound( r.hotVars.latestAggregatorRoundId, address(0x0), // use zero address since we don't have anybody "starting" the round here block.timestamp ); emit AnswerUpdated( median, r.hotVars.latestAggregatorRoundId, block.timestamp ); validateAnswer(r.hotVars.latestAggregatorRoundId, median); } s_hotVars = r.hotVars; assert(initialGas < maxUint32); reimburseAndRewardOracles(uint32(initialGas), r.observers); } /* * v2 Aggregator interface */ /** * @notice median from the most recent report */ function latestAnswer() public override view virtual returns (int256) { return s_transmissions[s_hotVars.latestAggregatorRoundId].answer; } /** * @notice timestamp of block in which last report was transmitted */ function latestTimestamp() public override view virtual returns (uint256) { return s_transmissions[s_hotVars.latestAggregatorRoundId].timestamp; } /** * @notice Aggregator round (NOT OCR round) in which last report was transmitted */ function latestRound() public override view virtual returns (uint256) { return s_hotVars.latestAggregatorRoundId; } /** * @notice median of report from given aggregator round (NOT OCR round) * @param _roundId the aggregator round of the target report */ function getAnswer(uint256 _roundId) public override view virtual returns (int256) { if (_roundId > 0xFFFFFFFF) { return 0; } return s_transmissions[uint32(_roundId)].answer; } /** * @notice timestamp of block in which report from given aggregator round was transmitted * @param _roundId aggregator round (NOT OCR round) of target report */ function getTimestamp(uint256 _roundId) public override view virtual returns (uint256) { if (_roundId > 0xFFFFFFFF) { return 0; } return s_transmissions[uint32(_roundId)].timestamp; } /* * v3 Aggregator interface */ string constant private V3_NO_DATA_ERROR = "No data present"; /** * @return answers are stored in fixed-point format, with this many digits of precision */ uint8 immutable public override decimals; /** * @notice aggregator contract version */ uint256 constant public override version = 4; string internal s_description; /** * @notice human-readable description of observable this contract is reporting on */ function description() public override view virtual returns (string memory) { return s_description; } /** * @notice details for the given aggregator round * @param _roundId target aggregator round (NOT OCR round). Must fit in uint32 * @return roundId _roundId * @return answer median of report from given _roundId * @return startedAt timestamp of block in which report from given _roundId was transmitted * @return updatedAt timestamp of block in which report from given _roundId was transmitted * @return answeredInRound _roundId */ function getRoundData(uint80 _roundId) public override view virtual returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ) { require(_roundId <= 0xFFFFFFFF, V3_NO_DATA_ERROR); Transmission memory transmission = s_transmissions[uint32(_roundId)]; return ( _roundId, transmission.answer, transmission.timestamp, transmission.timestamp, _roundId ); } /** * @notice aggregator details for the most recently transmitted report * @return roundId aggregator round of latest report (NOT OCR round) * @return answer median of latest report * @return startedAt timestamp of block containing latest report * @return updatedAt timestamp of block containing latest report * @return answeredInRound aggregator round of latest report */ function latestRoundData() public override view virtual returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ) { roundId = s_hotVars.latestAggregatorRoundId; // Skipped for compatability with existing FluxAggregator in which latestRoundData never reverts. // require(roundId != 0, V3_NO_DATA_ERROR); Transmission memory transmission = s_transmissions[uint32(roundId)]; return ( roundId, transmission.answer, transmission.timestamp, transmission.timestamp, roundId ); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; interface AccessControllerInterface { function hasAccess(address user, bytes calldata data) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "./AggregatorInterface.sol"; import "./AggregatorV3Interface.sol"; interface AggregatorV2V3Interface is AggregatorInterface, AggregatorV3Interface { } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; interface AggregatorInterface { function latestAnswer() external view returns (int256); function latestTimestamp() external view returns (uint256); function latestRound() external view returns (uint256); function getAnswer(uint256 roundId) external view returns (int256); function getTimestamp(uint256 roundId) external view returns (uint256); event AnswerUpdated(int256 indexed current, uint256 indexed roundId, uint256 updatedAt); event NewRound(uint256 indexed roundId, address indexed startedBy, uint256 startedAt); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; interface AggregatorV3Interface { function decimals() external view returns (uint8); function description() external view returns (string memory); function version() external view returns (uint256); // getRoundData and latestRoundData should both raise "No data present" // if they do not have data to report, instead of returning unset values // which could be misinterpreted as actual reported values. function getRoundData(uint80 _roundId) external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function latestRoundData() external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; interface AggregatorValidatorInterface { function validate( uint256 previousRoundId, int256 previousAnswer, uint256 currentRoundId, int256 currentAnswer ) external returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.1; interface LinkTokenInterface { function allowance(address owner, address spender) external view returns (uint256 remaining); function approve(address spender, uint256 value) external returns (bool success); function balanceOf(address owner) external view returns (uint256 balance); function decimals() external view returns (uint8 decimalPlaces); function decreaseApproval(address spender, uint256 addedValue) external returns (bool success); function increaseApproval(address spender, uint256 subtractedValue) external; function name() external view returns (string memory tokenName); function symbol() external view returns (string memory tokenSymbol); function totalSupply() external view returns (uint256 totalTokensIssued); function transfer(address to, uint256 value) external returns (bool success); function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool success); function transferFrom(address from, address to, uint256 value) external returns (bool success); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @title The Owned contract * @notice A contract with helpers for basic contract ownership. */ contract Owned { address payable public owner; address private pendingOwner; event OwnershipTransferRequested( address indexed from, address indexed to ); event OwnershipTransferred( address indexed from, address indexed to ); constructor() { owner = msg.sender; } /** * @dev Allows an owner to begin transferring ownership to a new address, * pending. */ function transferOwnership(address _to) external onlyOwner() { pendingOwner = _to; emit OwnershipTransferRequested(owner, _to); } /** * @dev Allows an ownership transfer to be completed by the recipient. */ function acceptOwnership() external { require(msg.sender == pendingOwner, "Must be proposed owner"); address oldOwner = owner; owner = msg.sender; pendingOwner = address(0); emit OwnershipTransferred(oldOwner, msg.sender); } /** * @dev Reverts if called by anyone other than the contract owner. */ modifier onlyOwner() { require(msg.sender == owner, "Only callable by owner"); _; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "./AccessControllerInterface.sol"; import "./LinkTokenInterface.sol"; import "./Owned.sol"; /** * @notice tracks administration of oracle-reward and gas-reimbursement parameters. * @dev * If you read or change this, be sure to read or adjust the comments. They * track the units of the values under consideration, and are crucial to * the readability of the operations it specifies. * @notice * Trust Model: * Nothing in this contract prevents a billing admin from setting insane * values for the billing parameters in setBilling. Oracles * participating in this contract should regularly check that the * parameters make sense. Similarly, the outstanding obligations of this * contract to the oracles can exceed the funds held by the contract. * Oracles participating in this contract should regularly check that it * holds sufficient funds and stop interacting with it if funding runs * out. * This still leaves oracles with some risk due to TOCTOU issues. * However, since the sums involved are pretty small (Ethereum * transactions aren't that expensive in the end) and an oracle would * likely stop participating in a contract it repeatedly lost money on, * this risk is deemed acceptable. Oracles should also regularly * withdraw any funds in the contract to prevent issues where the * contract becomes underfunded at a later time, and different oracles * are competing for the left-over funds. * Finally, note that any change to the set of oracles or to the billing * parameters will trigger payout of all oracles first (using the old * parameters), a billing admin cannot take away funds that are already * marked for payment. */ contract OffchainAggregatorBilling is Owned { // Maximum number of oracles the offchain reporting protocol is designed for uint256 constant internal maxNumOracles = 31; // Parameters for oracle payments struct Billing { // Highest compensated gas price, in ETH-gwei uints uint32 maximumGasPrice; // If gas price is less (in ETH-gwei units), transmitter gets half the savings uint32 reasonableGasPrice; // Pay transmitter back this much LINK per unit eth spent on gas // (1e-6LINK/ETH units) uint32 microLinkPerEth; // Fixed LINK reward for each observer, in LINK-gwei units uint32 linkGweiPerObservation; // Fixed reward for transmitter, in linkGweiPerObservation units uint32 linkGweiPerTransmission; } Billing internal s_billing; /** * @return LINK token contract used for billing */ LinkTokenInterface immutable public LINK; AccessControllerInterface internal s_billingAccessController; // ith element is number of observation rewards due to ith process, plus one. // This is expected to saturate after an oracle has submitted 65,535 // observations, or about 65535/(3*24*20) = 45 days, given a transmission // every 3 minutes. // // This is always one greater than the actual value, so that when the value is // reset to zero, we don't end up with a zero value in storage (which would // result in a higher gas cost, the next time the value is incremented.) // Calculations using this variable need to take that offset into account. uint16[maxNumOracles] internal s_oracleObservationsCounts; // Addresses at which oracles want to receive payments, by transmitter address mapping (address /* transmitter */ => address /* payment address */) internal s_payees; // Payee addresses which must be approved by the owner mapping (address /* transmitter */ => address /* payment address */) internal s_proposedPayees; // LINK-wei-denominated reimbursements for gas used by transmitters. // // This is always one greater than the actual value, so that when the value is // reset to zero, we don't end up with a zero value in storage (which would // result in a higher gas cost, the next time the value is incremented.) // Calculations using this variable need to take that offset into account. // // Argument for overflow safety: // We have the following maximum intermediate values: // - 2**40 additions to this variable (epochAndRound is a uint40) // - 2**32 gas price in ethgwei/gas // - 1e9 ethwei/ethgwei // - 2**32 gas since the block gas limit is at ~20 million // - 2**32 (microlink/eth) // And we have 2**40 * 2**32 * 1e9 * 2**32 * 2**32 < 2**166 // (we also divide in some places, but that only makes the value smaller) // We can thus safely use uint256 intermediate values for the computation // updating this variable. uint256[maxNumOracles] internal s_gasReimbursementsLinkWei; // Used for s_oracles[a].role, where a is an address, to track the purpose // of the address, or to indicate that the address is unset. enum Role { // No oracle role has been set for address a Unset, // Signing address for the s_oracles[a].index'th oracle. I.e., report // signatures from this oracle should ecrecover back to address a. Signer, // Transmission address for the s_oracles[a].index'th oracle. I.e., if a // report is received by OffchainAggregator.transmit in which msg.sender is // a, it is attributed to the s_oracles[a].index'th oracle. Transmitter } struct Oracle { uint8 index; // Index of oracle in s_signers/s_transmitters Role role; // Role of the address which mapped to this struct } mapping (address /* signer OR transmitter address */ => Oracle) internal s_oracles; // s_signers contains the signing address of each oracle address[] internal s_signers; // s_transmitters contains the transmission address of each oracle, // i.e. the address the oracle actually sends transactions to the contract from address[] internal s_transmitters; uint256 constant private maxUint16 = (1 << 16) - 1; uint256 constant internal maxUint128 = (1 << 128) - 1; constructor( uint32 _maximumGasPrice, uint32 _reasonableGasPrice, uint32 _microLinkPerEth, uint32 _linkGweiPerObservation, uint32 _linkGweiPerTransmission, address _link, AccessControllerInterface _billingAccessController ) { setBillingInternal(_maximumGasPrice, _reasonableGasPrice, _microLinkPerEth, _linkGweiPerObservation, _linkGweiPerTransmission); setBillingAccessControllerInternal(_billingAccessController); LINK = LinkTokenInterface(_link); uint16[maxNumOracles] memory counts; // See s_oracleObservationsCounts docstring uint256[maxNumOracles] memory gas; // see s_gasReimbursementsLinkWei docstring for (uint8 i = 0; i < maxNumOracles; i++) { counts[i] = 1; gas[i] = 1; } s_oracleObservationsCounts = counts; s_gasReimbursementsLinkWei = gas; } /** * @notice emitted when billing parameters are set * @param maximumGasPrice highest gas price for which transmitter will be compensated * @param reasonableGasPrice transmitter will receive reward for gas prices under this value * @param microLinkPerEth reimbursement per ETH of gas cost, in 1e-6LINK units * @param linkGweiPerObservation reward to oracle for contributing an observation to a successfully transmitted report, in 1e-9LINK units * @param linkGweiPerTransmission reward to transmitter of a successful report, in 1e-9LINK units */ event BillingSet( uint32 maximumGasPrice, uint32 reasonableGasPrice, uint32 microLinkPerEth, uint32 linkGweiPerObservation, uint32 linkGweiPerTransmission ); function setBillingInternal( uint32 _maximumGasPrice, uint32 _reasonableGasPrice, uint32 _microLinkPerEth, uint32 _linkGweiPerObservation, uint32 _linkGweiPerTransmission ) internal { s_billing = Billing(_maximumGasPrice, _reasonableGasPrice, _microLinkPerEth, _linkGweiPerObservation, _linkGweiPerTransmission); emit BillingSet(_maximumGasPrice, _reasonableGasPrice, _microLinkPerEth, _linkGweiPerObservation, _linkGweiPerTransmission); } /** * @notice sets billing parameters * @param _maximumGasPrice highest gas price for which transmitter will be compensated * @param _reasonableGasPrice transmitter will receive reward for gas prices under this value * @param _microLinkPerEth reimbursement per ETH of gas cost, in 1e-6LINK units * @param _linkGweiPerObservation reward to oracle for contributing an observation to a successfully transmitted report, in 1e-9LINK units * @param _linkGweiPerTransmission reward to transmitter of a successful report, in 1e-9LINK units * @dev access control provided by billingAccessController */ function setBilling( uint32 _maximumGasPrice, uint32 _reasonableGasPrice, uint32 _microLinkPerEth, uint32 _linkGweiPerObservation, uint32 _linkGweiPerTransmission ) external { AccessControllerInterface access = s_billingAccessController; require(msg.sender == owner || access.hasAccess(msg.sender, msg.data), "Only owner&billingAdmin can call"); payOracles(); setBillingInternal(_maximumGasPrice, _reasonableGasPrice, _microLinkPerEth, _linkGweiPerObservation, _linkGweiPerTransmission); } /** * @notice gets billing parameters * @param maximumGasPrice highest gas price for which transmitter will be compensated * @param reasonableGasPrice transmitter will receive reward for gas prices under this value * @param microLinkPerEth reimbursement per ETH of gas cost, in 1e-6LINK units * @param linkGweiPerObservation reward to oracle for contributing an observation to a successfully transmitted report, in 1e-9LINK units * @param linkGweiPerTransmission reward to transmitter of a successful report, in 1e-9LINK units */ function getBilling() external view returns ( uint32 maximumGasPrice, uint32 reasonableGasPrice, uint32 microLinkPerEth, uint32 linkGweiPerObservation, uint32 linkGweiPerTransmission ) { Billing memory billing = s_billing; return ( billing.maximumGasPrice, billing.reasonableGasPrice, billing.microLinkPerEth, billing.linkGweiPerObservation, billing.linkGweiPerTransmission ); } /** * @notice emitted when a new access-control contract is set * @param old the address prior to the current setting * @param current the address of the new access-control contract */ event BillingAccessControllerSet(AccessControllerInterface old, AccessControllerInterface current); function setBillingAccessControllerInternal(AccessControllerInterface _billingAccessController) internal { AccessControllerInterface oldController = s_billingAccessController; if (_billingAccessController != oldController) { s_billingAccessController = _billingAccessController; emit BillingAccessControllerSet( oldController, _billingAccessController ); } } /** * @notice sets billingAccessController * @param _billingAccessController new billingAccessController contract address * @dev only owner can call this */ function setBillingAccessController(AccessControllerInterface _billingAccessController) external onlyOwner { setBillingAccessControllerInternal(_billingAccessController); } /** * @notice gets billingAccessController * @return address of billingAccessController contract */ function billingAccessController() external view returns (AccessControllerInterface) { return s_billingAccessController; } /** * @notice withdraws an oracle's payment from the contract * @param _transmitter the transmitter address of the oracle * @dev must be called by oracle's payee address */ function withdrawPayment(address _transmitter) external { require(msg.sender == s_payees[_transmitter], "Only payee can withdraw"); payOracle(_transmitter); } /** * @notice query an oracle's payment amount * @param _transmitter the transmitter address of the oracle */ function owedPayment(address _transmitter) public view returns (uint256) { Oracle memory oracle = s_oracles[_transmitter]; if (oracle.role == Role.Unset) { return 0; } Billing memory billing = s_billing; uint256 linkWeiAmount = uint256(s_oracleObservationsCounts[oracle.index] - 1) * uint256(billing.linkGweiPerObservation) * (1 gwei); linkWeiAmount += s_gasReimbursementsLinkWei[oracle.index] - 1; return linkWeiAmount; } /** * @notice emitted when an oracle has been paid LINK * @param transmitter address from which the oracle sends reports to the transmit method * @param payee address to which the payment is sent * @param amount amount of LINK sent */ event OraclePaid(address transmitter, address payee, uint256 amount); // payOracle pays out _transmitter's balance to the corresponding payee, and zeros it out function payOracle(address _transmitter) internal { Oracle memory oracle = s_oracles[_transmitter]; uint256 linkWeiAmount = owedPayment(_transmitter); if (linkWeiAmount > 0) { address payee = s_payees[_transmitter]; // Poses no re-entrancy issues, because LINK.transfer does not yield // control flow. require(LINK.transfer(payee, linkWeiAmount), "insufficient funds"); s_oracleObservationsCounts[oracle.index] = 1; // "zero" the counts. see var's docstring s_gasReimbursementsLinkWei[oracle.index] = 1; // "zero" the counts. see var's docstring emit OraclePaid(_transmitter, payee, linkWeiAmount); } } // payOracles pays out all transmitters, and zeros out their balances. // // It's much more gas-efficient to do this as a single operation, to avoid // hitting storage too much. function payOracles() internal { Billing memory billing = s_billing; uint16[maxNumOracles] memory observationsCounts = s_oracleObservationsCounts; uint256[maxNumOracles] memory gasReimbursementsLinkWei = s_gasReimbursementsLinkWei; address[] memory transmitters = s_transmitters; for (uint transmitteridx = 0; transmitteridx < transmitters.length; transmitteridx++) { uint256 reimbursementAmountLinkWei = gasReimbursementsLinkWei[transmitteridx] - 1; uint256 obsCount = observationsCounts[transmitteridx] - 1; uint256 linkWeiAmount = obsCount * uint256(billing.linkGweiPerObservation) * (1 gwei) + reimbursementAmountLinkWei; if (linkWeiAmount > 0) { address payee = s_payees[transmitters[transmitteridx]]; // Poses no re-entrancy issues, because LINK.transfer does not yield // control flow. require(LINK.transfer(payee, linkWeiAmount), "insufficient funds"); observationsCounts[transmitteridx] = 1; // "zero" the counts. gasReimbursementsLinkWei[transmitteridx] = 1; // "zero" the counts. emit OraclePaid(transmitters[transmitteridx], payee, linkWeiAmount); } } // "Zero" the accounting storage variables s_oracleObservationsCounts = observationsCounts; s_gasReimbursementsLinkWei = gasReimbursementsLinkWei; } function oracleRewards( bytes memory observers, uint16[maxNumOracles] memory observations ) internal pure returns (uint16[maxNumOracles] memory) { // reward each observer-participant with the observer reward for (uint obsIdx = 0; obsIdx < observers.length; obsIdx++) { uint8 observer = uint8(observers[obsIdx]); observations[observer] = saturatingAddUint16(observations[observer], 1); } return observations; } // This value needs to change if maxNumOracles is increased, or the accounting // calculations at the bottom of reimburseAndRewardOracles change. // // To recalculate it, run the profiler as described in // ../../profile/README.md, and add up the gas-usage values reported for the // lines in reimburseAndRewardOracles following the "gasLeft = gasleft()" // line. E.g., you will see output like this: // // 7 uint256 gasLeft = gasleft(); // 29 uint256 gasCostEthWei = transmitterGasCostEthWei( // 9 uint256(initialGas), // 3 gasPrice, // 3 callDataGasCost, // 3 gasLeft // . // . // . // 59 uint256 gasCostLinkWei = (gasCostEthWei * billing.microLinkPerEth)/ 1e6; // . // . // . // 5047 s_gasReimbursementsLinkWei[txOracle.index] = // 856 s_gasReimbursementsLinkWei[txOracle.index] + gasCostLinkWei + // 26 uint256(billing.linkGweiPerTransmission) * (1 gwei); // // If those were the only lines to be accounted for, you would add up // 29+9+3+3+3+59+5047+856+26=6035. uint256 internal constant accountingGasCost = 6035; // Uncomment the following declaration to compute the remaining gas cost after // above gasleft(). (This must exist in a base class to OffchainAggregator, so // it can't go in TestOffchainAggregator.) // // uint256 public gasUsedInAccounting; // Gas price at which the transmitter should be reimbursed, in ETH-gwei/gas function impliedGasPrice( uint256 txGasPrice, // ETH-gwei/gas units uint256 reasonableGasPrice, // ETH-gwei/gas units uint256 maximumGasPrice // ETH-gwei/gas units ) internal pure returns (uint256) { // Reward the transmitter for choosing an efficient gas price: if they manage // to come in lower than considered reasonable, give them half the savings. // // The following calculations are all in units of gwei/gas, i.e. 1e-9ETH/gas uint256 gasPrice = txGasPrice; if (txGasPrice < reasonableGasPrice) { // Give transmitter half the savings for coming in under the reasonable gas price gasPrice += (reasonableGasPrice - txGasPrice) / 2; } // Don't reimburse a gas price higher than maximumGasPrice return min(gasPrice, maximumGasPrice); } // gas reimbursement due the transmitter, in ETH-wei // // If this function is changed, accountingGasCost needs to change, too. See // its docstring function transmitterGasCostEthWei( uint256 initialGas, uint256 gasPrice, // ETH-gwei/gas units uint256 callDataCost, // gas units uint256 gasLeft ) internal pure returns (uint128 gasCostEthWei) { require(initialGas >= gasLeft, "gasLeft cannot exceed initialGas"); uint256 gasUsed = // gas units initialGas - gasLeft + // observed gas usage callDataCost + accountingGasCost; // estimated gas usage // gasUsed is in gas units, gasPrice is in ETH-gwei/gas units; convert to ETH-wei uint256 fullGasCostEthWei = gasUsed * gasPrice * (1 gwei); assert(fullGasCostEthWei < maxUint128); // the entire ETH supply fits in a uint128... return uint128(fullGasCostEthWei); } /** * @notice withdraw any available funds left in the contract, up to _amount, after accounting for the funds due to participants in past reports * @param _recipient address to send funds to * @param _amount maximum amount to withdraw, denominated in LINK-wei. * @dev access control provided by billingAccessController */ function withdrawFunds(address _recipient, uint256 _amount) external { require(msg.sender == owner || s_billingAccessController.hasAccess(msg.sender, msg.data), "Only owner&billingAdmin can call"); uint256 linkDue = totalLINKDue(); uint256 linkBalance = LINK.balanceOf(address(this)); require(linkBalance >= linkDue, "insufficient balance"); require(LINK.transfer(_recipient, min(linkBalance - linkDue, _amount)), "insufficient funds"); } // Total LINK due to participants in past reports. function totalLINKDue() internal view returns (uint256 linkDue) { // Argument for overflow safety: We do all computations in // uint256s. The inputs to linkDue are: // - the <= 31 observation rewards each of which has less than // 64 bits (32 bits for billing.linkGweiPerObservation, 32 bits // for wei/gwei conversion). Hence 69 bits are sufficient for this part. // - the <= 31 gas reimbursements, each of which consists of at most 166 // bits (see s_gasReimbursementsLinkWei docstring). Hence 171 bits are // sufficient for this part // In total, 172 bits are enough. uint16[maxNumOracles] memory observationCounts = s_oracleObservationsCounts; for (uint i = 0; i < maxNumOracles; i++) { linkDue += observationCounts[i] - 1; // Stored value is one greater than actual value } Billing memory billing = s_billing; // Convert linkGweiPerObservation to uint256, or this overflows! linkDue *= uint256(billing.linkGweiPerObservation) * (1 gwei); address[] memory transmitters = s_transmitters; uint256[maxNumOracles] memory gasReimbursementsLinkWei = s_gasReimbursementsLinkWei; for (uint i = 0; i < transmitters.length; i++) { linkDue += uint256(gasReimbursementsLinkWei[i]-1); // Stored value is one greater than actual value } } /** * @notice allows oracles to check that sufficient LINK balance is available * @return availableBalance LINK available on this contract, after accounting for outstanding obligations. can become negative */ function linkAvailableForPayment() external view returns (int256 availableBalance) { // there are at most one billion LINK, so this cast is safe int256 balance = int256(LINK.balanceOf(address(this))); // according to the argument in the definition of totalLINKDue, // totalLINKDue is never greater than 2**172, so this cast is safe int256 due = int256(totalLINKDue()); // safe from overflow according to above sizes return int256(balance) - int256(due); } /** * @notice number of observations oracle is due to be reimbursed for * @param _signerOrTransmitter address used by oracle for signing or transmitting reports */ function oracleObservationCount(address _signerOrTransmitter) external view returns (uint16) { Oracle memory oracle = s_oracles[_signerOrTransmitter]; if (oracle.role == Role.Unset) { return 0; } return s_oracleObservationsCounts[oracle.index] - 1; } function reimburseAndRewardOracles( uint32 initialGas, bytes memory observers ) internal { Oracle memory txOracle = s_oracles[msg.sender]; Billing memory billing = s_billing; // Reward oracles for providing observations. Oracles are not rewarded // for providing signatures, because signing is essentially free. s_oracleObservationsCounts = oracleRewards(observers, s_oracleObservationsCounts); // Reimburse transmitter of the report for gas usage require(txOracle.role == Role.Transmitter, "sent by undesignated transmitter" ); uint256 gasPrice = impliedGasPrice( tx.gasprice / (1 gwei), // convert to ETH-gwei units billing.reasonableGasPrice, billing.maximumGasPrice ); // The following is only an upper bound, as it ignores the cheaper cost for // 0 bytes. Safe from overflow, because calldata just isn't that long. uint256 callDataGasCost = 16 * msg.data.length; // If any changes are made to subsequent calculations, accountingGasCost // needs to change, too. uint256 gasLeft = gasleft(); uint256 gasCostEthWei = transmitterGasCostEthWei( uint256(initialGas), gasPrice, callDataGasCost, gasLeft ); // microLinkPerEth is 1e-6LINK/ETH units, gasCostEthWei is 1e-18ETH units // (ETH-wei), product is 1e-24LINK-wei units, dividing by 1e6 gives // 1e-18LINK units, i.e. LINK-wei units // Safe from over/underflow, since all components are non-negative, // gasCostEthWei will always fit into uint128 and microLinkPerEth is a // uint32 (128+32 < 256!). uint256 gasCostLinkWei = (gasCostEthWei * billing.microLinkPerEth)/ 1e6; // Safe from overflow, because gasCostLinkWei < 2**160 and // billing.linkGweiPerTransmission * (1 gwei) < 2**64 and we increment // s_gasReimbursementsLinkWei[txOracle.index] at most 2**40 times. s_gasReimbursementsLinkWei[txOracle.index] = s_gasReimbursementsLinkWei[txOracle.index] + gasCostLinkWei + uint256(billing.linkGweiPerTransmission) * (1 gwei); // convert from linkGwei to linkWei // Uncomment next line to compute the remaining gas cost after above gasleft(). // See OffchainAggregatorBilling.accountingGasCost docstring for more information. // // gasUsedInAccounting = gasLeft - gasleft(); } /* * Payee management */ /** * @notice emitted when a transfer of an oracle's payee address has been initiated * @param transmitter address from which the oracle sends reports to the transmit method * @param current the payeee address for the oracle, prior to this setting * @param proposed the proposed new payee address for the oracle */ event PayeeshipTransferRequested( address indexed transmitter, address indexed current, address indexed proposed ); /** * @notice emitted when a transfer of an oracle's payee address has been completed * @param transmitter address from which the oracle sends reports to the transmit method * @param current the payeee address for the oracle, prior to this setting */ event PayeeshipTransferred( address indexed transmitter, address indexed previous, address indexed current ); /** * @notice sets the payees for transmitting addresses * @param _transmitters addresses oracles use to transmit the reports * @param _payees addresses of payees corresponding to list of transmitters * @dev must be called by owner * @dev cannot be used to change payee addresses, only to initially populate them */ function setPayees( address[] calldata _transmitters, address[] calldata _payees ) external onlyOwner() { require(_transmitters.length == _payees.length, "transmitters.size != payees.size"); for (uint i = 0; i < _transmitters.length; i++) { address transmitter = _transmitters[i]; address payee = _payees[i]; address currentPayee = s_payees[transmitter]; bool zeroedOut = currentPayee == address(0); require(zeroedOut || currentPayee == payee, "payee already set"); s_payees[transmitter] = payee; if (currentPayee != payee) { emit PayeeshipTransferred(transmitter, currentPayee, payee); } } } /** * @notice first step of payeeship transfer (safe transfer pattern) * @param _transmitter transmitter address of oracle whose payee is changing * @param _proposed new payee address * @dev can only be called by payee address */ function transferPayeeship( address _transmitter, address _proposed ) external { require(msg.sender == s_payees[_transmitter], "only current payee can update"); require(msg.sender != _proposed, "cannot transfer to self"); address previousProposed = s_proposedPayees[_transmitter]; s_proposedPayees[_transmitter] = _proposed; if (previousProposed != _proposed) { emit PayeeshipTransferRequested(_transmitter, msg.sender, _proposed); } } /** * @notice second step of payeeship transfer (safe transfer pattern) * @param _transmitter transmitter address of oracle whose payee is changing * @dev can only be called by proposed new payee address */ function acceptPayeeship( address _transmitter ) external { require(msg.sender == s_proposedPayees[_transmitter], "only proposed payees can accept"); address currentPayee = s_payees[_transmitter]; s_payees[_transmitter] = msg.sender; s_proposedPayees[_transmitter] = address(0); emit PayeeshipTransferred(_transmitter, currentPayee, msg.sender); } /* * Helper functions */ function saturatingAddUint16(uint16 _x, uint16 _y) internal pure returns (uint16) { return uint16(min(uint256(_x)+uint256(_y), maxUint16)); } function min(uint256 a, uint256 b) internal pure returns (uint256) { if (a < b) { return a; } return b; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.1; import "./SimpleWriteAccessController.sol"; /** * @title SimpleReadAccessController * @notice Gives access to: * - any externally owned account (note that offchain actors can always read * any contract storage regardless of onchain access control measures, so this * does not weaken the access control while improving usability) * - accounts explicitly added to an access list * @dev SimpleReadAccessController is not suitable for access controlling writes * since it grants any externally owned account access! See * SimpleWriteAccessController for that. */ contract SimpleReadAccessController is SimpleWriteAccessController { /** * @notice Returns the access of an address * @param _user The address to query */ function hasAccess( address _user, bytes memory _calldata ) public view virtual override returns (bool) { return super.hasAccess(_user, _calldata) || _user == tx.origin; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "./Owned.sol"; import "./AccessControllerInterface.sol"; /** * @title SimpleWriteAccessController * @notice Gives access to accounts explicitly added to an access list by the * controller's owner. * @dev does not make any special permissions for externally, see * SimpleReadAccessController for that. */ contract SimpleWriteAccessController is AccessControllerInterface, Owned { bool public checkEnabled; mapping(address => bool) internal accessList; event AddedAccess(address user); event RemovedAccess(address user); event CheckAccessEnabled(); event CheckAccessDisabled(); constructor() { checkEnabled = true; } /** * @notice Returns the access of an address * @param _user The address to query */ function hasAccess( address _user, bytes memory ) public view virtual override returns (bool) { return accessList[_user] || !checkEnabled; } /** * @notice Adds an address to the access list * @param _user The address to add */ function addAccess(address _user) external onlyOwner() { addAccessInternal(_user); } function addAccessInternal(address _user) internal { if (!accessList[_user]) { accessList[_user] = true; emit AddedAccess(_user); } } /** * @notice Removes an address from the access list * @param _user The address to remove */ function removeAccess(address _user) external onlyOwner() { if (accessList[_user]) { accessList[_user] = false; emit RemovedAccess(_user); } } /** * @notice makes the access check enforced */ function enableAccessCheck() external onlyOwner() { if (!checkEnabled) { checkEnabled = true; emit CheckAccessEnabled(); } } /** * @notice makes the access check unenforced */ function disableAccessCheck() external onlyOwner() { if (checkEnabled) { checkEnabled = false; emit CheckAccessDisabled(); } } /** * @dev reverts if the caller does not have access */ modifier checkAccess() { require(hasAccess(msg.sender, msg.data), "No access"); _; } }
Don't reimburse a gas price higher than maximumGasPrice
return min(gasPrice, maximumGasPrice);
51,161
[ 1, 22293, 1404, 283, 381, 70, 295, 307, 279, 16189, 6205, 10478, 2353, 4207, 27998, 5147, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 327, 1131, 12, 31604, 5147, 16, 4207, 27998, 5147, 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.6.0 <0.8.0; import "@openzeppelin/contracts/GSN/Context.sol"; /** * @dev Modified Ownable. Introduces `auditor` address that has the exclusive * right to transfer ownership of the contract. * * This module makes available the modifiers: `onlyAuditor`, `onlyOwnerAndAuditor`. * `onlyOwner` replaced with `onlyOwnerAndAuditor` in function `transferOwnership`. */ abstract contract Auditable is Context { address private _owner; address private _auditor; event AuditingTransferred(address indexed previousAuditor, address indexed newAuditor); event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _auditor = msgSender; _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current auditor. */ function auditor() public view returns (address) { return _auditor; } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyAuditor() { require(_auditor == _msgSender(), "Auditable: caller is not the auditor"); _; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Throws if called by any account other than the owner or auditor. */ modifier onlyOwnerOrAuditor() { require(_owner == _msgSender() || _auditor == _msgSender(), "Auditable: caller is not the owner or auditor"); _; } /** * @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 transferAuditing(address newAuditor) public virtual onlyAuditor { require(newAuditor != address(0), "Auditable: new auditor is the zero address"); emit AuditingTransferred(_auditor, newAuditor); _auditor = newAuditor; } /** * @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 onlyOwnerOrAuditor { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } }
* @dev Modified Ownable. Introduces `auditor` address that has the exclusive right to transfer ownership of the contract. This module makes available the modifiers: `onlyAuditor`, `onlyOwnerAndAuditor`. `onlyOwner` replaced with `onlyOwnerAndAuditor` in function `transferOwnership`./
abstract contract Auditable is Context { address private _owner; address private _auditor; event AuditingTransferred(address indexed previousAuditor, address indexed newAuditor); event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor () internal { address msgSender = _msgSender(); _auditor = msgSender; _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } function auditor() public view returns (address) { return _auditor; } function owner() public view returns (address) { return _owner; } modifier onlyAuditor() { require(_auditor == _msgSender(), "Auditable: caller is not the auditor"); _; } modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } modifier onlyOwnerOrAuditor() { require(_owner == _msgSender() || _auditor == _msgSender(), "Auditable: caller is not the owner or auditor"); _; } function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } function transferAuditing(address newAuditor) public virtual onlyAuditor { require(newAuditor != address(0), "Auditable: new auditor is the zero address"); emit AuditingTransferred(_auditor, newAuditor); _auditor = newAuditor; } function transferOwnership(address newOwner) public virtual onlyOwnerOrAuditor { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } }
12,997,292
[ 1, 4575, 14223, 6914, 18, 3094, 303, 2544, 764, 1375, 24901, 1811, 68, 1758, 716, 711, 326, 12060, 2145, 358, 7412, 23178, 434, 326, 6835, 18, 1220, 1605, 7297, 2319, 326, 10429, 30, 1375, 3700, 37, 1100, 1811, 9191, 1375, 3700, 5541, 1876, 37, 1100, 1811, 8338, 1375, 3700, 5541, 68, 8089, 598, 1375, 3700, 5541, 1876, 37, 1100, 1811, 68, 316, 445, 1375, 13866, 5460, 12565, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 17801, 6835, 12975, 429, 353, 1772, 288, 203, 565, 1758, 3238, 389, 8443, 31, 203, 565, 1758, 3238, 389, 24901, 1811, 31, 203, 203, 565, 871, 12975, 310, 1429, 4193, 12, 2867, 8808, 2416, 37, 1100, 1811, 16, 1758, 8808, 394, 37, 1100, 1811, 1769, 203, 565, 871, 14223, 9646, 5310, 1429, 4193, 12, 2867, 8808, 2416, 5541, 16, 1758, 8808, 394, 5541, 1769, 203, 203, 565, 3885, 1832, 2713, 288, 203, 3639, 1758, 1234, 12021, 273, 389, 3576, 12021, 5621, 203, 3639, 389, 24901, 1811, 273, 1234, 12021, 31, 203, 3639, 389, 8443, 273, 1234, 12021, 31, 203, 3639, 3626, 14223, 9646, 5310, 1429, 4193, 12, 2867, 12, 20, 3631, 1234, 12021, 1769, 203, 565, 289, 203, 203, 565, 445, 20232, 1811, 1435, 1071, 1476, 1135, 261, 2867, 13, 288, 203, 3639, 327, 389, 24901, 1811, 31, 203, 565, 289, 203, 203, 565, 445, 3410, 1435, 1071, 1476, 1135, 261, 2867, 13, 288, 203, 3639, 327, 389, 8443, 31, 203, 565, 289, 203, 203, 565, 9606, 1338, 37, 1100, 1811, 1435, 288, 203, 3639, 2583, 24899, 24901, 1811, 422, 389, 3576, 12021, 9334, 315, 10832, 429, 30, 4894, 353, 486, 326, 20232, 1811, 8863, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 565, 9606, 1338, 5541, 1435, 288, 203, 3639, 2583, 24899, 8443, 422, 389, 3576, 12021, 9334, 315, 5460, 429, 30, 4894, 353, 486, 326, 3410, 8863, 203, 3639, 389, 31, 203, 565, 289, 203, 565, 9606, 1338, 5541, 1162, 37, 1100, 1811, 1435, 288, 203, 3639, 2583, 24899, 8443, 422, 2 ]
./full_match/3/0x31af1c1800E1a0a552d934F00AB82B2F0dB937Bc/sources/BCoin.sol
Create a uniswap pair for this new token set the rest of the contract variablesexclude owner and this contract from feeExclude dead address from reflection
constructor () { _rOwned[_msgSender()] = _rTotal; IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); uniswapV2Router = _uniswapV2Router; _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; _isExcluded[address(0)] = true; emit Transfer(address(0), _msgSender(), _tTotal); }
8,248,348
[ 1, 1684, 279, 640, 291, 91, 438, 3082, 364, 333, 394, 1147, 444, 326, 3127, 434, 326, 6835, 3152, 10157, 3410, 471, 333, 6835, 628, 14036, 12689, 8363, 1758, 628, 5463, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 12316, 1832, 288, 203, 67, 86, 5460, 329, 63, 67, 3576, 12021, 1435, 65, 273, 389, 86, 5269, 31, 203, 203, 45, 984, 291, 91, 438, 58, 22, 8259, 3103, 389, 318, 291, 91, 438, 58, 22, 8259, 273, 467, 984, 291, 91, 438, 58, 22, 8259, 3103, 12, 20, 92, 27, 69, 26520, 72, 4313, 5082, 38, 24, 71, 42, 25, 5520, 27, 5520, 72, 42, 22, 39, 25, 72, 37, 7358, 24, 71, 26, 6162, 42, 3247, 5482, 40, 1769, 203, 318, 291, 91, 438, 58, 22, 4154, 273, 467, 984, 291, 91, 438, 58, 22, 1733, 24899, 318, 291, 91, 438, 58, 22, 8259, 18, 6848, 10756, 203, 18, 2640, 4154, 12, 2867, 12, 2211, 3631, 389, 318, 291, 91, 438, 58, 22, 8259, 18, 59, 1584, 44, 10663, 203, 203, 318, 291, 91, 438, 58, 22, 8259, 273, 389, 318, 291, 91, 438, 58, 22, 8259, 31, 203, 203, 67, 291, 16461, 1265, 14667, 63, 8443, 1435, 65, 273, 638, 31, 203, 67, 291, 16461, 1265, 14667, 63, 2867, 12, 2211, 25887, 273, 638, 31, 203, 203, 67, 291, 16461, 63, 2867, 12, 20, 25887, 273, 638, 31, 203, 203, 18356, 12279, 12, 2867, 12, 20, 3631, 389, 3576, 12021, 9334, 389, 88, 5269, 1769, 203, 97, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0xE03b1F81D1c3b730272442a16eAc84226A989041/sources/contracts/AuctionHouse.sol
* @notice Create an auction. @dev Store the auction details in the `auction` state variable and emit an AuctionCreated event. If the mint reverts, the minter was updated without pausing this contract first. To remedy this, catch the revert and pause this contract./
function _createAuction() internal { try snoopDAONFT.mint(address(this)) returns (uint256 snoopDAONFTId) { uint256 startTime = block.timestamp; uint256 endTime = startTime + _getAuctionDuration(snoopDAONFTId); auction = Auction({ snoopDAONFTId: snoopDAONFTId, amount: 0, startTime: startTime, endTime: endTime, bidder: address(0), settled: false }); emit AuctionCreated(snoopDAONFTId, startTime, endTime); _pause(); } }
3,059,905
[ 1, 1684, 392, 279, 4062, 18, 225, 4994, 326, 279, 4062, 3189, 316, 326, 1375, 69, 4062, 68, 919, 2190, 471, 3626, 392, 432, 4062, 6119, 871, 18, 971, 326, 312, 474, 15226, 87, 16, 326, 1131, 387, 1703, 3526, 2887, 6790, 9940, 333, 6835, 1122, 18, 2974, 849, 24009, 333, 16, 1044, 326, 15226, 471, 11722, 333, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 389, 2640, 37, 4062, 1435, 2713, 288, 203, 3639, 775, 272, 2135, 556, 9793, 673, 4464, 18, 81, 474, 12, 2867, 12, 2211, 3719, 1135, 261, 11890, 5034, 272, 2135, 556, 9793, 673, 4464, 548, 13, 288, 203, 5411, 2254, 5034, 8657, 273, 1203, 18, 5508, 31, 203, 5411, 2254, 5034, 13859, 273, 8657, 397, 389, 588, 37, 4062, 5326, 12, 87, 2135, 556, 9793, 673, 4464, 548, 1769, 203, 203, 5411, 279, 4062, 273, 432, 4062, 12590, 203, 7734, 272, 2135, 556, 9793, 673, 4464, 548, 30, 272, 2135, 556, 9793, 673, 4464, 548, 16, 203, 7734, 3844, 30, 374, 16, 203, 7734, 8657, 30, 8657, 16, 203, 7734, 13859, 30, 13859, 16, 203, 7734, 9949, 765, 30, 1758, 12, 20, 3631, 203, 7734, 26319, 1259, 30, 629, 203, 5411, 15549, 203, 203, 5411, 3626, 432, 4062, 6119, 12, 87, 2135, 556, 9793, 673, 4464, 548, 16, 8657, 16, 13859, 1769, 203, 5411, 389, 19476, 5621, 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 ]
/** *Submitted for verification at Etherscan.io on 2020-02-11 */ // File: @aragon/os/contracts/common/EtherTokenConstant.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; // aragonOS and aragon-apps rely on address(0) to denote native ETH, in // contracts where both tokens and ETH are accepted contract EtherTokenConstant { address internal constant ETH = address(0); } // File: @aragon/apps-agent/contracts/standards/ERC1271.sol pragma solidity 0.4.24; // ERC1271 on Feb 12th, 2019: https://github.com/ethereum/EIPs/blob/a97dc434930d0ccc4461c97d8c7a920dc585adf2/EIPS/eip-1271.md // Using `isValidSignature(bytes32,bytes)` even though the standard still hasn't been modified // Rationale: https://github.com/ethereum/EIPs/issues/1271#issuecomment-462719728 contract ERC1271 { bytes4 constant public ERC1271_INTERFACE_ID = 0xfb855dc9; // this.isValidSignature.selector bytes4 constant public ERC1271_RETURN_VALID_SIGNATURE = 0x20c13b0b; // TODO: Likely needs to be updated bytes4 constant public ERC1271_RETURN_INVALID_SIGNATURE = 0x00000000; /** * @dev Function must be implemented by deriving contract * @param _hash Arbitrary length data signed on the behalf of address(this) * @param _signature Signature byte array associated with _data * @return A bytes4 magic value 0x20c13b0b if the signature check passes, 0x00000000 if not * * MUST NOT modify state (using STATICCALL for solc < 0.5, view modifier for solc > 0.5) * MUST allow external calls */ function isValidSignature(bytes32 _hash, bytes memory _signature) public view returns (bytes4); function returnIsValidSignatureMagicNumber(bool isValid) internal pure returns (bytes4) { return isValid ? ERC1271_RETURN_VALID_SIGNATURE : ERC1271_RETURN_INVALID_SIGNATURE; } } contract ERC1271Bytes is ERC1271 { /** * @dev Default behavior of `isValidSignature(bytes,bytes)`, can be overloaded for custom validation * @param _data Arbitrary length data signed on the behalf of address(this) * @param _signature Signature byte array associated with _data * @return A bytes4 magic value 0x20c13b0b if the signature check passes, 0x00000000 if not * * MUST NOT modify state (using STATICCALL for solc < 0.5, view modifier for solc > 0.5) * MUST allow external calls */ function isValidSignature(bytes _data, bytes _signature) public view returns (bytes4) { return isValidSignature(keccak256(_data), _signature); } } // File: @aragon/apps-agent/contracts/SignatureValidator.sol pragma solidity 0.4.24; // Inspired by https://github.com/horizon-games/multi-token-standard/blob/319740cf2a78b8816269ae49a09c537b3fd7303b/contracts/utils/SignatureValidator.sol // This should probably be moved into aOS: https://github.com/aragon/aragonOS/pull/442 library SignatureValidator { enum SignatureMode { Invalid, // 0x00 EIP712, // 0x01 EthSign, // 0x02 ERC1271, // 0x03 NMode // 0x04, to check if mode is specified, leave at the end } // bytes4(keccak256("isValidSignature(bytes,bytes)") bytes4 public constant ERC1271_RETURN_VALID_SIGNATURE = 0x20c13b0b; uint256 internal constant ERC1271_ISVALIDSIG_MAX_GAS = 250000; string private constant ERROR_INVALID_LENGTH_POP_BYTE = "SIGVAL_INVALID_LENGTH_POP_BYTE"; /// @dev Validates that a hash was signed by a specified signer. /// @param hash Hash which was signed. /// @param signer Address of the signer. /// @param signature ECDSA signature along with the mode (0 = Invalid, 1 = EIP712, 2 = EthSign, 3 = ERC1271) {mode}{r}{s}{v}. /// @return Returns whether signature is from a specified user. function isValidSignature(bytes32 hash, address signer, bytes signature) internal view returns (bool) { if (signature.length == 0) { return false; } uint8 modeByte = uint8(signature[0]); if (modeByte >= uint8(SignatureMode.NMode)) { return false; } SignatureMode mode = SignatureMode(modeByte); if (mode == SignatureMode.EIP712) { return ecVerify(hash, signer, signature); } else if (mode == SignatureMode.EthSign) { return ecVerify( keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)), signer, signature ); } else if (mode == SignatureMode.ERC1271) { // Pop the mode byte before sending it down the validation chain return safeIsValidSignature(signer, hash, popFirstByte(signature)); } else { return false; } } function ecVerify(bytes32 hash, address signer, bytes memory signature) private pure returns (bool) { (bool badSig, bytes32 r, bytes32 s, uint8 v) = unpackEcSig(signature); if (badSig) { return false; } return signer == ecrecover(hash, v, r, s); } function unpackEcSig(bytes memory signature) private pure returns (bool badSig, bytes32 r, bytes32 s, uint8 v) { if (signature.length != 66) { badSig = true; return; } v = uint8(signature[65]); assembly { r := mload(add(signature, 33)) s := mload(add(signature, 65)) } // Allow signature version to be 0 or 1 if (v < 27) { v += 27; } if (v != 27 && v != 28) { badSig = true; } } function popFirstByte(bytes memory input) private pure returns (bytes memory output) { uint256 inputLength = input.length; require(inputLength > 0, ERROR_INVALID_LENGTH_POP_BYTE); output = new bytes(inputLength - 1); if (output.length == 0) { return output; } uint256 inputPointer; uint256 outputPointer; assembly { inputPointer := add(input, 0x21) outputPointer := add(output, 0x20) } memcpy(outputPointer, inputPointer, output.length); } function safeIsValidSignature(address validator, bytes32 hash, bytes memory signature) private view returns (bool) { bytes memory data = abi.encodeWithSelector(ERC1271(validator).isValidSignature.selector, hash, signature); bytes4 erc1271Return = safeBytes4StaticCall(validator, data, ERC1271_ISVALIDSIG_MAX_GAS); return erc1271Return == ERC1271_RETURN_VALID_SIGNATURE; } function safeBytes4StaticCall(address target, bytes data, uint256 maxGas) private view returns (bytes4 ret) { uint256 gasLeft = gasleft(); uint256 callGas = gasLeft > maxGas ? maxGas : gasLeft; bool ok; assembly { ok := staticcall(callGas, target, add(data, 0x20), mload(data), 0, 0) } if (!ok) { return; } uint256 size; assembly { size := returndatasize } if (size != 32) { return; } assembly { let ptr := mload(0x40) // get next free memory ptr returndatacopy(ptr, 0, size) // copy return from above `staticcall` ret := mload(ptr) // read data at ptr and set it to be returned } return ret; } // From: https://github.com/Arachnid/solidity-stringutils/blob/01e955c1d6/src/strings.sol function memcpy(uint256 dest, uint256 src, uint256 len) private pure { // Copy word-length chunks while possible for (; len >= 32; len -= 32) { assembly { mstore(dest, mload(src)) } dest += 32; src += 32; } // Copy remaining bytes uint mask = 256 ** (32 - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) let destpart := and(mload(dest), mask) mstore(dest, or(destpart, srcpart)) } } } // File: @aragon/apps-agent/contracts/standards/IERC165.sol pragma solidity 0.4.24; interface IERC165 { function supportsInterface(bytes4 interfaceId) external pure returns (bool); } // File: @aragon/os/contracts/common/UnstructuredStorage.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; library UnstructuredStorage { function getStorageBool(bytes32 position) internal view returns (bool data) { assembly { data := sload(position) } } function getStorageAddress(bytes32 position) internal view returns (address data) { assembly { data := sload(position) } } function getStorageBytes32(bytes32 position) internal view returns (bytes32 data) { assembly { data := sload(position) } } function getStorageUint256(bytes32 position) internal view returns (uint256 data) { assembly { data := sload(position) } } function setStorageBool(bytes32 position, bool data) internal { assembly { sstore(position, data) } } function setStorageAddress(bytes32 position, address data) internal { assembly { sstore(position, data) } } function setStorageBytes32(bytes32 position, bytes32 data) internal { assembly { sstore(position, data) } } function setStorageUint256(bytes32 position, uint256 data) internal { assembly { sstore(position, data) } } } // File: @aragon/os/contracts/acl/IACL.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; interface IACL { function initialize(address permissionsCreator) external; // TODO: this should be external // See https://github.com/ethereum/solidity/issues/4832 function hasPermission(address who, address where, bytes32 what, bytes how) public view returns (bool); } // File: @aragon/os/contracts/common/IVaultRecoverable.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; interface IVaultRecoverable { event RecoverToVault(address indexed vault, address indexed token, uint256 amount); function transferToVault(address token) external; function allowRecoverability(address token) external view returns (bool); function getRecoveryVault() external view returns (address); } // File: @aragon/os/contracts/kernel/IKernel.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; interface IKernelEvents { event SetApp(bytes32 indexed namespace, bytes32 indexed appId, address app); } // This should be an interface, but interfaces can't inherit yet :( contract IKernel is IKernelEvents, IVaultRecoverable { function acl() public view returns (IACL); function hasPermission(address who, address where, bytes32 what, bytes how) public view returns (bool); function setApp(bytes32 namespace, bytes32 appId, address app) public; function getApp(bytes32 namespace, bytes32 appId) public view returns (address); } // File: @aragon/os/contracts/apps/AppStorage.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract AppStorage { using UnstructuredStorage for bytes32; /* Hardcoded constants to save gas bytes32 internal constant KERNEL_POSITION = keccak256("aragonOS.appStorage.kernel"); bytes32 internal constant APP_ID_POSITION = keccak256("aragonOS.appStorage.appId"); */ bytes32 internal constant KERNEL_POSITION = 0x4172f0f7d2289153072b0a6ca36959e0cbe2efc3afe50fc81636caa96338137b; bytes32 internal constant APP_ID_POSITION = 0xd625496217aa6a3453eecb9c3489dc5a53e6c67b444329ea2b2cbc9ff547639b; function kernel() public view returns (IKernel) { return IKernel(KERNEL_POSITION.getStorageAddress()); } function appId() public view returns (bytes32) { return APP_ID_POSITION.getStorageBytes32(); } function setKernel(IKernel _kernel) internal { KERNEL_POSITION.setStorageAddress(address(_kernel)); } function setAppId(bytes32 _appId) internal { APP_ID_POSITION.setStorageBytes32(_appId); } } // File: @aragon/os/contracts/acl/ACLSyntaxSugar.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract ACLSyntaxSugar { function arr() internal pure returns (uint256[]) { return new uint256[](0); } function arr(bytes32 _a) internal pure returns (uint256[] r) { return arr(uint256(_a)); } function arr(bytes32 _a, bytes32 _b) internal pure returns (uint256[] r) { return arr(uint256(_a), uint256(_b)); } function arr(address _a) internal pure returns (uint256[] r) { return arr(uint256(_a)); } function arr(address _a, address _b) internal pure returns (uint256[] r) { return arr(uint256(_a), uint256(_b)); } function arr(address _a, uint256 _b, uint256 _c) internal pure returns (uint256[] r) { return arr(uint256(_a), _b, _c); } function arr(address _a, uint256 _b, uint256 _c, uint256 _d) internal pure returns (uint256[] r) { return arr(uint256(_a), _b, _c, _d); } function arr(address _a, uint256 _b) internal pure returns (uint256[] r) { return arr(uint256(_a), uint256(_b)); } function arr(address _a, address _b, uint256 _c, uint256 _d, uint256 _e) internal pure returns (uint256[] r) { return arr(uint256(_a), uint256(_b), _c, _d, _e); } function arr(address _a, address _b, address _c) internal pure returns (uint256[] r) { return arr(uint256(_a), uint256(_b), uint256(_c)); } function arr(address _a, address _b, uint256 _c) internal pure returns (uint256[] r) { return arr(uint256(_a), uint256(_b), uint256(_c)); } function arr(uint256 _a) internal pure returns (uint256[] r) { r = new uint256[](1); r[0] = _a; } function arr(uint256 _a, uint256 _b) internal pure returns (uint256[] r) { r = new uint256[](2); r[0] = _a; r[1] = _b; } function arr(uint256 _a, uint256 _b, uint256 _c) internal pure returns (uint256[] r) { r = new uint256[](3); r[0] = _a; r[1] = _b; r[2] = _c; } function arr(uint256 _a, uint256 _b, uint256 _c, uint256 _d) internal pure returns (uint256[] r) { r = new uint256[](4); r[0] = _a; r[1] = _b; r[2] = _c; r[3] = _d; } function arr(uint256 _a, uint256 _b, uint256 _c, uint256 _d, uint256 _e) internal pure returns (uint256[] r) { r = new uint256[](5); r[0] = _a; r[1] = _b; r[2] = _c; r[3] = _d; r[4] = _e; } } contract ACLHelpers { function decodeParamOp(uint256 _x) internal pure returns (uint8 b) { return uint8(_x >> (8 * 30)); } function decodeParamId(uint256 _x) internal pure returns (uint8 b) { return uint8(_x >> (8 * 31)); } function decodeParamsList(uint256 _x) internal pure returns (uint32 a, uint32 b, uint32 c) { a = uint32(_x); b = uint32(_x >> (8 * 4)); c = uint32(_x >> (8 * 8)); } } // File: @aragon/os/contracts/common/Uint256Helpers.sol pragma solidity ^0.4.24; library Uint256Helpers { uint256 private constant MAX_UINT64 = uint64(-1); string private constant ERROR_NUMBER_TOO_BIG = "UINT64_NUMBER_TOO_BIG"; function toUint64(uint256 a) internal pure returns (uint64) { require(a <= MAX_UINT64, ERROR_NUMBER_TOO_BIG); return uint64(a); } } // File: @aragon/os/contracts/common/TimeHelpers.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract TimeHelpers { using Uint256Helpers for uint256; /** * @dev Returns the current block number. * Using a function rather than `block.number` allows us to easily mock the block number in * tests. */ function getBlockNumber() internal view returns (uint256) { return block.number; } /** * @dev Returns the current block number, converted to uint64. * Using a function rather than `block.number` allows us to easily mock the block number in * tests. */ function getBlockNumber64() internal view returns (uint64) { return getBlockNumber().toUint64(); } /** * @dev Returns the current timestamp. * Using a function rather than `block.timestamp` allows us to easily mock it in * tests. */ function getTimestamp() internal view returns (uint256) { return block.timestamp; // solium-disable-line security/no-block-members } /** * @dev Returns the current timestamp, converted to uint64. * Using a function rather than `block.timestamp` allows us to easily mock it in * tests. */ function getTimestamp64() internal view returns (uint64) { return getTimestamp().toUint64(); } } // File: @aragon/os/contracts/common/Initializable.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract Initializable is TimeHelpers { using UnstructuredStorage for bytes32; // keccak256("aragonOS.initializable.initializationBlock") bytes32 internal constant INITIALIZATION_BLOCK_POSITION = 0xebb05b386a8d34882b8711d156f463690983dc47815980fb82aeeff1aa43579e; string private constant ERROR_ALREADY_INITIALIZED = "INIT_ALREADY_INITIALIZED"; string private constant ERROR_NOT_INITIALIZED = "INIT_NOT_INITIALIZED"; modifier onlyInit { require(getInitializationBlock() == 0, ERROR_ALREADY_INITIALIZED); _; } modifier isInitialized { require(hasInitialized(), ERROR_NOT_INITIALIZED); _; } /** * @return Block number in which the contract was initialized */ function getInitializationBlock() public view returns (uint256) { return INITIALIZATION_BLOCK_POSITION.getStorageUint256(); } /** * @return Whether the contract has been initialized by the time of the current block */ function hasInitialized() public view returns (bool) { uint256 initializationBlock = getInitializationBlock(); return initializationBlock != 0 && getBlockNumber() >= initializationBlock; } /** * @dev Function to be called by top level contract after initialization has finished. */ function initialized() internal onlyInit { INITIALIZATION_BLOCK_POSITION.setStorageUint256(getBlockNumber()); } /** * @dev Function to be called by top level contract after initialization to enable the contract * at a future block number rather than immediately. */ function initializedAt(uint256 _blockNumber) internal onlyInit { INITIALIZATION_BLOCK_POSITION.setStorageUint256(_blockNumber); } } // File: @aragon/os/contracts/common/Petrifiable.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract Petrifiable is Initializable { // Use block UINT256_MAX (which should be never) as the initializable date uint256 internal constant PETRIFIED_BLOCK = uint256(-1); function isPetrified() public view returns (bool) { return getInitializationBlock() == PETRIFIED_BLOCK; } /** * @dev Function to be called by top level contract to prevent being initialized. * Useful for freezing base contracts when they're used behind proxies. */ function petrify() internal onlyInit { initializedAt(PETRIFIED_BLOCK); } } // File: @aragon/os/contracts/common/Autopetrified.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract Autopetrified is Petrifiable { constructor() public { // Immediately petrify base (non-proxy) instances of inherited contracts on deploy. // This renders them uninitializable (and unusable without a proxy). petrify(); } } // File: @aragon/os/contracts/common/ConversionHelpers.sol pragma solidity ^0.4.24; library ConversionHelpers { string private constant ERROR_IMPROPER_LENGTH = "CONVERSION_IMPROPER_LENGTH"; function dangerouslyCastUintArrayToBytes(uint256[] memory _input) internal pure returns (bytes memory output) { // Force cast the uint256[] into a bytes array, by overwriting its length // Note that the bytes array doesn't need to be initialized as we immediately overwrite it // with the input and a new length. The input becomes invalid from this point forward. uint256 byteLength = _input.length * 32; assembly { output := _input mstore(output, byteLength) } } function dangerouslyCastBytesToUintArray(bytes memory _input) internal pure returns (uint256[] memory output) { // Force cast the bytes array into a uint256[], by overwriting its length // Note that the uint256[] doesn't need to be initialized as we immediately overwrite it // with the input and a new length. The input becomes invalid from this point forward. uint256 intsLength = _input.length / 32; require(_input.length == intsLength * 32, ERROR_IMPROPER_LENGTH); assembly { output := _input mstore(output, intsLength) } } } // File: @aragon/os/contracts/common/ReentrancyGuard.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract ReentrancyGuard { using UnstructuredStorage for bytes32; /* Hardcoded constants to save gas bytes32 internal constant REENTRANCY_MUTEX_POSITION = keccak256("aragonOS.reentrancyGuard.mutex"); */ bytes32 private constant REENTRANCY_MUTEX_POSITION = 0xe855346402235fdd185c890e68d2c4ecad599b88587635ee285bce2fda58dacb; string private constant ERROR_REENTRANT = "REENTRANCY_REENTRANT_CALL"; modifier nonReentrant() { // Ensure mutex is unlocked require(!REENTRANCY_MUTEX_POSITION.getStorageBool(), ERROR_REENTRANT); // Lock mutex before function call REENTRANCY_MUTEX_POSITION.setStorageBool(true); // Perform function call _; // Unlock mutex after function call REENTRANCY_MUTEX_POSITION.setStorageBool(false); } } // File: @aragon/os/contracts/lib/token/ERC20.sol // See https://github.com/OpenZeppelin/openzeppelin-solidity/blob/a9f910d34f0ab33a1ae5e714f69f9596a02b4d91/contracts/token/ERC20/ERC20.sol pragma solidity ^0.4.24; /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 { function totalSupply() public view returns (uint256); function balanceOf(address _who) public view returns (uint256); function allowance(address _owner, address _spender) public view returns (uint256); function transfer(address _to, uint256 _value) public returns (bool); function approve(address _spender, uint256 _value) public returns (bool); function transferFrom(address _from, address _to, uint256 _value) public returns (bool); event Transfer( address indexed from, address indexed to, uint256 value ); event Approval( address indexed owner, address indexed spender, uint256 value ); } // File: @aragon/os/contracts/common/IsContract.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract IsContract { /* * NOTE: this should NEVER be used for authentication * (see pitfalls: https://github.com/fergarrui/ethereum-security/tree/master/contracts/extcodesize). * * This is only intended to be used as a sanity check that an address is actually a contract, * RATHER THAN an address not being a contract. */ function isContract(address _target) internal view returns (bool) { if (_target == address(0)) { return false; } uint256 size; assembly { size := extcodesize(_target) } return size > 0; } } // File: @aragon/os/contracts/common/SafeERC20.sol // Inspired by AdEx (https://github.com/AdExNetwork/adex-protocol-eth/blob/b9df617829661a7518ee10f4cb6c4108659dd6d5/contracts/libs/SafeERC20.sol) // and 0x (https://github.com/0xProject/0x-monorepo/blob/737d1dc54d72872e24abce5a1dbe1b66d35fa21a/contracts/protocol/contracts/protocol/AssetProxy/ERC20Proxy.sol#L143) pragma solidity ^0.4.24; library SafeERC20 { // Before 0.5, solidity has a mismatch between `address.transfer()` and `token.transfer()`: // https://github.com/ethereum/solidity/issues/3544 bytes4 private constant TRANSFER_SELECTOR = 0xa9059cbb; string private constant ERROR_TOKEN_BALANCE_REVERTED = "SAFE_ERC_20_BALANCE_REVERTED"; string private constant ERROR_TOKEN_ALLOWANCE_REVERTED = "SAFE_ERC_20_ALLOWANCE_REVERTED"; function invokeAndCheckSuccess(address _addr, bytes memory _calldata) private returns (bool) { bool ret; assembly { let ptr := mload(0x40) // free memory pointer let success := call( gas, // forward all gas _addr, // address 0, // no value add(_calldata, 0x20), // calldata start mload(_calldata), // calldata length ptr, // write output over free memory 0x20 // uint256 return ) if gt(success, 0) { // Check number of bytes returned from last function call switch returndatasize // No bytes returned: assume success case 0 { ret := 1 } // 32 bytes returned: check if non-zero case 0x20 { // Only return success if returned data was true // Already have output in ptr ret := eq(mload(ptr), 1) } // Not sure what was returned: don't mark as success default { } } } return ret; } function staticInvoke(address _addr, bytes memory _calldata) private view returns (bool, uint256) { bool success; uint256 ret; assembly { let ptr := mload(0x40) // free memory pointer success := staticcall( gas, // forward all gas _addr, // address add(_calldata, 0x20), // calldata start mload(_calldata), // calldata length ptr, // write output over free memory 0x20 // uint256 return ) if gt(success, 0) { ret := mload(ptr) } } return (success, ret); } /** * @dev Same as a standards-compliant ERC20.transfer() that never reverts (returns false). * Note that this makes an external call to the token. */ function safeTransfer(ERC20 _token, address _to, uint256 _amount) internal returns (bool) { bytes memory transferCallData = abi.encodeWithSelector( TRANSFER_SELECTOR, _to, _amount ); return invokeAndCheckSuccess(_token, transferCallData); } /** * @dev Same as a standards-compliant ERC20.transferFrom() that never reverts (returns false). * Note that this makes an external call to the token. */ function safeTransferFrom(ERC20 _token, address _from, address _to, uint256 _amount) internal returns (bool) { bytes memory transferFromCallData = abi.encodeWithSelector( _token.transferFrom.selector, _from, _to, _amount ); return invokeAndCheckSuccess(_token, transferFromCallData); } /** * @dev Same as a standards-compliant ERC20.approve() that never reverts (returns false). * Note that this makes an external call to the token. */ function safeApprove(ERC20 _token, address _spender, uint256 _amount) internal returns (bool) { bytes memory approveCallData = abi.encodeWithSelector( _token.approve.selector, _spender, _amount ); return invokeAndCheckSuccess(_token, approveCallData); } /** * @dev Static call into ERC20.balanceOf(). * Reverts if the call fails for some reason (should never fail). */ function staticBalanceOf(ERC20 _token, address _owner) internal view returns (uint256) { bytes memory balanceOfCallData = abi.encodeWithSelector( _token.balanceOf.selector, _owner ); (bool success, uint256 tokenBalance) = staticInvoke(_token, balanceOfCallData); require(success, ERROR_TOKEN_BALANCE_REVERTED); return tokenBalance; } /** * @dev Static call into ERC20.allowance(). * Reverts if the call fails for some reason (should never fail). */ function staticAllowance(ERC20 _token, address _owner, address _spender) internal view returns (uint256) { bytes memory allowanceCallData = abi.encodeWithSelector( _token.allowance.selector, _owner, _spender ); (bool success, uint256 allowance) = staticInvoke(_token, allowanceCallData); require(success, ERROR_TOKEN_ALLOWANCE_REVERTED); return allowance; } } // File: @aragon/os/contracts/common/VaultRecoverable.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract VaultRecoverable is IVaultRecoverable, EtherTokenConstant, IsContract { using SafeERC20 for ERC20; string private constant ERROR_DISALLOWED = "RECOVER_DISALLOWED"; string private constant ERROR_VAULT_NOT_CONTRACT = "RECOVER_VAULT_NOT_CONTRACT"; string private constant ERROR_TOKEN_TRANSFER_FAILED = "RECOVER_TOKEN_TRANSFER_FAILED"; /** * @notice Send funds to recovery Vault. This contract should never receive funds, * but in case it does, this function allows one to recover them. * @param _token Token balance to be sent to recovery vault. */ function transferToVault(address _token) external { require(allowRecoverability(_token), ERROR_DISALLOWED); address vault = getRecoveryVault(); require(isContract(vault), ERROR_VAULT_NOT_CONTRACT); uint256 balance; if (_token == ETH) { balance = address(this).balance; vault.transfer(balance); } else { ERC20 token = ERC20(_token); balance = token.staticBalanceOf(this); require(token.safeTransfer(vault, balance), ERROR_TOKEN_TRANSFER_FAILED); } emit RecoverToVault(vault, _token, balance); } /** * @dev By default deriving from AragonApp makes it recoverable * @param token Token address that would be recovered * @return bool whether the app allows the recovery */ function allowRecoverability(address token) public view returns (bool) { return true; } // Cast non-implemented interface to be public so we can use it internally function getRecoveryVault() public view returns (address); } // File: @aragon/os/contracts/evmscript/IEVMScriptExecutor.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; interface IEVMScriptExecutor { function execScript(bytes script, bytes input, address[] blacklist) external returns (bytes); function executorType() external pure returns (bytes32); } // File: @aragon/os/contracts/evmscript/IEVMScriptRegistry.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract EVMScriptRegistryConstants { /* Hardcoded constants to save gas bytes32 internal constant EVMSCRIPT_REGISTRY_APP_ID = apmNamehash("evmreg"); */ bytes32 internal constant EVMSCRIPT_REGISTRY_APP_ID = 0xddbcfd564f642ab5627cf68b9b7d374fb4f8a36e941a75d89c87998cef03bd61; } interface IEVMScriptRegistry { function addScriptExecutor(IEVMScriptExecutor executor) external returns (uint id); function disableScriptExecutor(uint256 executorId) external; // TODO: this should be external // See https://github.com/ethereum/solidity/issues/4832 function getScriptExecutor(bytes script) public view returns (IEVMScriptExecutor); } // File: @aragon/os/contracts/kernel/KernelConstants.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract KernelAppIds { /* Hardcoded constants to save gas bytes32 internal constant KERNEL_CORE_APP_ID = apmNamehash("kernel"); bytes32 internal constant KERNEL_DEFAULT_ACL_APP_ID = apmNamehash("acl"); bytes32 internal constant KERNEL_DEFAULT_VAULT_APP_ID = apmNamehash("vault"); */ bytes32 internal constant KERNEL_CORE_APP_ID = 0x3b4bf6bf3ad5000ecf0f989d5befde585c6860fea3e574a4fab4c49d1c177d9c; bytes32 internal constant KERNEL_DEFAULT_ACL_APP_ID = 0xe3262375f45a6e2026b7e7b18c2b807434f2508fe1a2a3dfb493c7df8f4aad6a; bytes32 internal constant KERNEL_DEFAULT_VAULT_APP_ID = 0x7e852e0fcfce6551c13800f1e7476f982525c2b5277ba14b24339c68416336d1; } contract KernelNamespaceConstants { /* Hardcoded constants to save gas bytes32 internal constant KERNEL_CORE_NAMESPACE = keccak256("core"); bytes32 internal constant KERNEL_APP_BASES_NAMESPACE = keccak256("base"); bytes32 internal constant KERNEL_APP_ADDR_NAMESPACE = keccak256("app"); */ bytes32 internal constant KERNEL_CORE_NAMESPACE = 0xc681a85306374a5ab27f0bbc385296a54bcd314a1948b6cf61c4ea1bc44bb9f8; bytes32 internal constant KERNEL_APP_BASES_NAMESPACE = 0xf1f3eb40f5bc1ad1344716ced8b8a0431d840b5783aea1fd01786bc26f35ac0f; bytes32 internal constant KERNEL_APP_ADDR_NAMESPACE = 0xd6f028ca0e8edb4a8c9757ca4fdccab25fa1e0317da1188108f7d2dee14902fb; } // File: @aragon/os/contracts/evmscript/EVMScriptRunner.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract EVMScriptRunner is AppStorage, Initializable, EVMScriptRegistryConstants, KernelNamespaceConstants { string private constant ERROR_EXECUTOR_UNAVAILABLE = "EVMRUN_EXECUTOR_UNAVAILABLE"; string private constant ERROR_PROTECTED_STATE_MODIFIED = "EVMRUN_PROTECTED_STATE_MODIFIED"; /* This is manually crafted in assembly string private constant ERROR_EXECUTOR_INVALID_RETURN = "EVMRUN_EXECUTOR_INVALID_RETURN"; */ event ScriptResult(address indexed executor, bytes script, bytes input, bytes returnData); function getEVMScriptExecutor(bytes _script) public view returns (IEVMScriptExecutor) { return IEVMScriptExecutor(getEVMScriptRegistry().getScriptExecutor(_script)); } function getEVMScriptRegistry() public view returns (IEVMScriptRegistry) { address registryAddr = kernel().getApp(KERNEL_APP_ADDR_NAMESPACE, EVMSCRIPT_REGISTRY_APP_ID); return IEVMScriptRegistry(registryAddr); } function runScript(bytes _script, bytes _input, address[] _blacklist) internal isInitialized protectState returns (bytes) { IEVMScriptExecutor executor = getEVMScriptExecutor(_script); require(address(executor) != address(0), ERROR_EXECUTOR_UNAVAILABLE); bytes4 sig = executor.execScript.selector; bytes memory data = abi.encodeWithSelector(sig, _script, _input, _blacklist); bytes memory output; assembly { let success := delegatecall( gas, // forward all gas executor, // address add(data, 0x20), // calldata start mload(data), // calldata length 0, // don't write output (we'll handle this ourselves) 0 // don't write output ) output := mload(0x40) // free mem ptr get switch success case 0 { // If the call errored, forward its full error data returndatacopy(output, 0, returndatasize) revert(output, returndatasize) } default { switch gt(returndatasize, 0x3f) case 0 { // Need at least 0x40 bytes returned for properly ABI-encoded bytes values, // revert with "EVMRUN_EXECUTOR_INVALID_RETURN" // See remix: doing a `revert("EVMRUN_EXECUTOR_INVALID_RETURN")` always results in // this memory layout mstore(output, 0x08c379a000000000000000000000000000000000000000000000000000000000) // error identifier mstore(add(output, 0x04), 0x0000000000000000000000000000000000000000000000000000000000000020) // starting offset mstore(add(output, 0x24), 0x000000000000000000000000000000000000000000000000000000000000001e) // reason length mstore(add(output, 0x44), 0x45564d52554e5f4558454355544f525f494e56414c49445f52455455524e0000) // reason revert(output, 100) // 100 = 4 + 3 * 32 (error identifier + 3 words for the ABI encoded error) } default { // Copy result // // Needs to perform an ABI decode for the expected `bytes` return type of // `executor.execScript()` as solidity will automatically ABI encode the returned bytes as: // [ position of the first dynamic length return value = 0x20 (32 bytes) ] // [ output length (32 bytes) ] // [ output content (N bytes) ] // // Perform the ABI decode by ignoring the first 32 bytes of the return data let copysize := sub(returndatasize, 0x20) returndatacopy(output, 0x20, copysize) mstore(0x40, add(output, copysize)) // free mem ptr set } } } emit ScriptResult(address(executor), _script, _input, output); return output; } modifier protectState { address preKernel = address(kernel()); bytes32 preAppId = appId(); _; // exec require(address(kernel()) == preKernel, ERROR_PROTECTED_STATE_MODIFIED); require(appId() == preAppId, ERROR_PROTECTED_STATE_MODIFIED); } } // File: @aragon/os/contracts/apps/AragonApp.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; // Contracts inheriting from AragonApp are, by default, immediately petrified upon deployment so // that they can never be initialized. // Unless overriden, this behaviour enforces those contracts to be usable only behind an AppProxy. // ReentrancyGuard, EVMScriptRunner, and ACLSyntaxSugar are not directly used by this contract, but // are included so that they are automatically usable by subclassing contracts contract AragonApp is AppStorage, Autopetrified, VaultRecoverable, ReentrancyGuard, EVMScriptRunner, ACLSyntaxSugar { string private constant ERROR_AUTH_FAILED = "APP_AUTH_FAILED"; modifier auth(bytes32 _role) { require(canPerform(msg.sender, _role, new uint256[](0)), ERROR_AUTH_FAILED); _; } modifier authP(bytes32 _role, uint256[] _params) { require(canPerform(msg.sender, _role, _params), ERROR_AUTH_FAILED); _; } /** * @dev Check whether an action can be performed by a sender for a particular role on this app * @param _sender Sender of the call * @param _role Role on this app * @param _params Permission params for the role * @return Boolean indicating whether the sender has the permissions to perform the action. * Always returns false if the app hasn't been initialized yet. */ function canPerform(address _sender, bytes32 _role, uint256[] _params) public view returns (bool) { if (!hasInitialized()) { return false; } IKernel linkedKernel = kernel(); if (address(linkedKernel) == address(0)) { return false; } return linkedKernel.hasPermission( _sender, address(this), _role, ConversionHelpers.dangerouslyCastUintArrayToBytes(_params) ); } /** * @dev Get the recovery vault for the app * @return Recovery vault address for the app */ function getRecoveryVault() public view returns (address) { // Funds recovery via a vault is only available when used with a kernel return kernel().getRecoveryVault(); // if kernel is not set, it will revert } } // File: @aragon/os/contracts/common/DepositableStorage.sol pragma solidity 0.4.24; contract DepositableStorage { using UnstructuredStorage for bytes32; // keccak256("aragonOS.depositableStorage.depositable") bytes32 internal constant DEPOSITABLE_POSITION = 0x665fd576fbbe6f247aff98f5c94a561e3f71ec2d3c988d56f12d342396c50cea; function isDepositable() public view returns (bool) { return DEPOSITABLE_POSITION.getStorageBool(); } function setDepositable(bool _depositable) internal { DEPOSITABLE_POSITION.setStorageBool(_depositable); } } // File: @aragon/apps-vault/contracts/Vault.sol pragma solidity 0.4.24; contract Vault is EtherTokenConstant, AragonApp, DepositableStorage { using SafeERC20 for ERC20; bytes32 public constant TRANSFER_ROLE = keccak256("TRANSFER_ROLE"); string private constant ERROR_DATA_NON_ZERO = "VAULT_DATA_NON_ZERO"; string private constant ERROR_NOT_DEPOSITABLE = "VAULT_NOT_DEPOSITABLE"; string private constant ERROR_DEPOSIT_VALUE_ZERO = "VAULT_DEPOSIT_VALUE_ZERO"; string private constant ERROR_TRANSFER_VALUE_ZERO = "VAULT_TRANSFER_VALUE_ZERO"; string private constant ERROR_SEND_REVERTED = "VAULT_SEND_REVERTED"; string private constant ERROR_VALUE_MISMATCH = "VAULT_VALUE_MISMATCH"; string private constant ERROR_TOKEN_TRANSFER_FROM_REVERTED = "VAULT_TOKEN_TRANSFER_FROM_REVERT"; string private constant ERROR_TOKEN_TRANSFER_REVERTED = "VAULT_TOKEN_TRANSFER_REVERTED"; event VaultTransfer(address indexed token, address indexed to, uint256 amount); event VaultDeposit(address indexed token, address indexed sender, uint256 amount); /** * @dev On a normal send() or transfer() this fallback is never executed as it will be * intercepted by the Proxy (see aragonOS#281) */ function () external payable isInitialized { require(msg.data.length == 0, ERROR_DATA_NON_ZERO); _deposit(ETH, msg.value); } /** * @notice Initialize Vault app * @dev As an AragonApp it needs to be initialized in order for roles (`auth` and `authP`) to work */ function initialize() external onlyInit { initialized(); setDepositable(true); } /** * @notice Deposit `_value` `_token` to the vault * @param _token Address of the token being transferred * @param _value Amount of tokens being transferred */ function deposit(address _token, uint256 _value) external payable isInitialized { _deposit(_token, _value); } /** * @notice Transfer `_value` `_token` from the Vault to `_to` * @param _token Address of the token being transferred * @param _to Address of the recipient of tokens * @param _value Amount of tokens being transferred */ /* solium-disable-next-line function-order */ function transfer(address _token, address _to, uint256 _value) external authP(TRANSFER_ROLE, arr(_token, _to, _value)) { require(_value > 0, ERROR_TRANSFER_VALUE_ZERO); if (_token == ETH) { require(_to.send(_value), ERROR_SEND_REVERTED); } else { require(ERC20(_token).safeTransfer(_to, _value), ERROR_TOKEN_TRANSFER_REVERTED); } emit VaultTransfer(_token, _to, _value); } function balance(address _token) public view returns (uint256) { if (_token == ETH) { return address(this).balance; } else { return ERC20(_token).staticBalanceOf(address(this)); } } /** * @dev Disable recovery escape hatch, as it could be used * maliciously to transfer funds away from the vault */ function allowRecoverability(address) public view returns (bool) { return false; } function _deposit(address _token, uint256 _value) internal { require(isDepositable(), ERROR_NOT_DEPOSITABLE); require(_value > 0, ERROR_DEPOSIT_VALUE_ZERO); if (_token == ETH) { // Deposit is implicit in this case require(msg.value == _value, ERROR_VALUE_MISMATCH); } else { require( ERC20(_token).safeTransferFrom(msg.sender, address(this), _value), ERROR_TOKEN_TRANSFER_FROM_REVERTED ); } emit VaultDeposit(_token, msg.sender, _value); } } // File: @aragon/os/contracts/common/IForwarder.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; interface IForwarder { function isForwarder() external pure returns (bool); // TODO: this should be external // See https://github.com/ethereum/solidity/issues/4832 function canForward(address sender, bytes evmCallScript) public view returns (bool); // TODO: this should be external // See https://github.com/ethereum/solidity/issues/4832 function forward(bytes evmCallScript) public; } // File: @aragon/apps-agent/contracts/Agent.sol /* * SPDX-License-Identitifer: GPL-3.0-or-later */ pragma solidity 0.4.24; contract Agent is IERC165, ERC1271Bytes, IForwarder, IsContract, Vault { /* Hardcoded constants to save gas bytes32 public constant EXECUTE_ROLE = keccak256("EXECUTE_ROLE"); bytes32 public constant SAFE_EXECUTE_ROLE = keccak256("SAFE_EXECUTE_ROLE"); bytes32 public constant ADD_PROTECTED_TOKEN_ROLE = keccak256("ADD_PROTECTED_TOKEN_ROLE"); bytes32 public constant REMOVE_PROTECTED_TOKEN_ROLE = keccak256("REMOVE_PROTECTED_TOKEN_ROLE"); bytes32 public constant ADD_PRESIGNED_HASH_ROLE = keccak256("ADD_PRESIGNED_HASH_ROLE"); bytes32 public constant DESIGNATE_SIGNER_ROLE = keccak256("DESIGNATE_SIGNER_ROLE"); bytes32 public constant RUN_SCRIPT_ROLE = keccak256("RUN_SCRIPT_ROLE"); */ bytes32 public constant EXECUTE_ROLE = 0xcebf517aa4440d1d125e0355aae64401211d0848a23c02cc5d29a14822580ba4; bytes32 public constant SAFE_EXECUTE_ROLE = 0x0a1ad7b87f5846153c6d5a1f761d71c7d0cfd122384f56066cd33239b7933694; bytes32 public constant ADD_PROTECTED_TOKEN_ROLE = 0x6eb2a499556bfa2872f5aa15812b956cc4a71b4d64eb3553f7073c7e41415aaa; bytes32 public constant REMOVE_PROTECTED_TOKEN_ROLE = 0x71eee93d500f6f065e38b27d242a756466a00a52a1dbcd6b4260f01a8640402a; bytes32 public constant ADD_PRESIGNED_HASH_ROLE = 0x0b29780bb523a130b3b01f231ef49ed2fa2781645591a0b0a44ca98f15a5994c; bytes32 public constant DESIGNATE_SIGNER_ROLE = 0x23ce341656c3f14df6692eebd4757791e33662b7dcf9970c8308303da5472b7c; bytes32 public constant RUN_SCRIPT_ROLE = 0xb421f7ad7646747f3051c50c0b8e2377839296cd4973e27f63821d73e390338f; uint256 public constant PROTECTED_TOKENS_CAP = 10; bytes4 private constant ERC165_INTERFACE_ID = 0x01ffc9a7; string private constant ERROR_TARGET_PROTECTED = "AGENT_TARGET_PROTECTED"; string private constant ERROR_PROTECTED_TOKENS_MODIFIED = "AGENT_PROTECTED_TOKENS_MODIFIED"; string private constant ERROR_PROTECTED_BALANCE_LOWERED = "AGENT_PROTECTED_BALANCE_LOWERED"; string private constant ERROR_TOKENS_CAP_REACHED = "AGENT_TOKENS_CAP_REACHED"; string private constant ERROR_TOKEN_NOT_ERC20 = "AGENT_TOKEN_NOT_ERC20"; string private constant ERROR_TOKEN_ALREADY_PROTECTED = "AGENT_TOKEN_ALREADY_PROTECTED"; string private constant ERROR_TOKEN_NOT_PROTECTED = "AGENT_TOKEN_NOT_PROTECTED"; string private constant ERROR_DESIGNATED_TO_SELF = "AGENT_DESIGNATED_TO_SELF"; string private constant ERROR_CAN_NOT_FORWARD = "AGENT_CAN_NOT_FORWARD"; mapping (bytes32 => bool) public isPresigned; address public designatedSigner; address[] public protectedTokens; event SafeExecute(address indexed sender, address indexed target, bytes data); event Execute(address indexed sender, address indexed target, uint256 ethValue, bytes data); event AddProtectedToken(address indexed token); event RemoveProtectedToken(address indexed token); event PresignHash(address indexed sender, bytes32 indexed hash); event SetDesignatedSigner(address indexed sender, address indexed oldSigner, address indexed newSigner); /** * @notice Execute '`@radspec(_target, _data)`' on `_target``_ethValue == 0 ? '' : ' (Sending' + @tokenAmount(0x0000000000000000000000000000000000000000, _ethValue) + ')'` * @param _target Address where the action is being executed * @param _ethValue Amount of ETH from the contract that is sent with the action * @param _data Calldata for the action * @return Exits call frame forwarding the return data of the executed call (either error or success data) */ function execute(address _target, uint256 _ethValue, bytes _data) external // This function MUST always be external as the function performs a low level return, exiting the Agent app execution context authP(EXECUTE_ROLE, arr(_target, _ethValue, uint256(_getSig(_data)))) // bytes4 casted as uint256 sets the bytes as the LSBs { bool result = _target.call.value(_ethValue)(_data); if (result) { emit Execute(msg.sender, _target, _ethValue, _data); } assembly { let ptr := mload(0x40) returndatacopy(ptr, 0, returndatasize) // revert instead of invalid() bc if the underlying call failed with invalid() it already wasted gas. // if the call returned error data, forward it switch result case 0 { revert(ptr, returndatasize) } default { return(ptr, returndatasize) } } } /** * @notice Execute '`@radspec(_target, _data)`' on `_target` ensuring that protected tokens can't be spent * @param _target Address where the action is being executed * @param _data Calldata for the action * @return Exits call frame forwarding the return data of the executed call (either error or success data) */ function safeExecute(address _target, bytes _data) external // This function MUST always be external as the function performs a low level return, exiting the Agent app execution context authP(SAFE_EXECUTE_ROLE, arr(_target, uint256(_getSig(_data)))) // bytes4 casted as uint256 sets the bytes as the LSBs { uint256 protectedTokensLength = protectedTokens.length; address[] memory protectedTokens_ = new address[](protectedTokensLength); uint256[] memory balances = new uint256[](protectedTokensLength); for (uint256 i = 0; i < protectedTokensLength; i++) { address token = protectedTokens[i]; require(_target != token, ERROR_TARGET_PROTECTED); // we copy the protected tokens array to check whether the storage array has been modified during the underlying call protectedTokens_[i] = token; // we copy the balances to check whether they have been modified during the underlying call balances[i] = balance(token); } bool result = _target.call(_data); bytes32 ptr; uint256 size; assembly { size := returndatasize ptr := mload(0x40) mstore(0x40, add(ptr, returndatasize)) returndatacopy(ptr, 0, returndatasize) } if (result) { // if the underlying call has succeeded, we check that the protected tokens // and their balances have not been modified and return the call's return data require(protectedTokens.length == protectedTokensLength, ERROR_PROTECTED_TOKENS_MODIFIED); for (uint256 j = 0; j < protectedTokensLength; j++) { require(protectedTokens[j] == protectedTokens_[j], ERROR_PROTECTED_TOKENS_MODIFIED); require(balance(protectedTokens[j]) >= balances[j], ERROR_PROTECTED_BALANCE_LOWERED); } emit SafeExecute(msg.sender, _target, _data); assembly { return(ptr, size) } } else { // if the underlying call has failed, we revert and forward returned error data assembly { revert(ptr, size) } } } /** * @notice Add `_token.symbol(): string` to the list of protected tokens * @param _token Address of the token to be protected */ function addProtectedToken(address _token) external authP(ADD_PROTECTED_TOKEN_ROLE, arr(_token)) { require(protectedTokens.length < PROTECTED_TOKENS_CAP, ERROR_TOKENS_CAP_REACHED); require(_isERC20(_token), ERROR_TOKEN_NOT_ERC20); require(!_tokenIsProtected(_token), ERROR_TOKEN_ALREADY_PROTECTED); _addProtectedToken(_token); } /** * @notice Remove `_token.symbol(): string` from the list of protected tokens * @param _token Address of the token to be unprotected */ function removeProtectedToken(address _token) external authP(REMOVE_PROTECTED_TOKEN_ROLE, arr(_token)) { require(_tokenIsProtected(_token), ERROR_TOKEN_NOT_PROTECTED); _removeProtectedToken(_token); } /** * @notice Pre-sign hash `_hash` * @param _hash Hash that will be considered signed regardless of the signature checked with 'isValidSignature()' */ function presignHash(bytes32 _hash) external authP(ADD_PRESIGNED_HASH_ROLE, arr(_hash)) { isPresigned[_hash] = true; emit PresignHash(msg.sender, _hash); } /** * @notice Set `_designatedSigner` as the designated signer of the app, which will be able to sign messages on behalf of the app * @param _designatedSigner Address that will be able to sign messages on behalf of the app */ function setDesignatedSigner(address _designatedSigner) external authP(DESIGNATE_SIGNER_ROLE, arr(_designatedSigner)) { // Prevent an infinite loop by setting the app itself as its designated signer. // An undetectable loop can be created by setting a different contract as the // designated signer which calls back into `isValidSignature`. // Given that `isValidSignature` is always called with just 50k gas, the max // damage of the loop is wasting 50k gas. require(_designatedSigner != address(this), ERROR_DESIGNATED_TO_SELF); address oldDesignatedSigner = designatedSigner; designatedSigner = _designatedSigner; emit SetDesignatedSigner(msg.sender, oldDesignatedSigner, _designatedSigner); } // Forwarding fns /** * @notice Tells whether the Agent app is a forwarder or not * @dev IForwarder interface conformance * @return Always true */ function isForwarder() external pure returns (bool) { return true; } /** * @notice Execute the script as the Agent app * @dev IForwarder interface conformance. Forwards any token holder action. * @param _evmScript Script being executed */ function forward(bytes _evmScript) public { require(canForward(msg.sender, _evmScript), ERROR_CAN_NOT_FORWARD); bytes memory input = ""; // no input address[] memory blacklist = new address[](0); // no addr blacklist, can interact with anything runScript(_evmScript, input, blacklist); // We don't need to emit an event here as EVMScriptRunner will emit ScriptResult if successful } /** * @notice Tells whether `_sender` can forward actions or not * @dev IForwarder interface conformance * @param _sender Address of the account intending to forward an action * @return True if the given address can run scripts, false otherwise */ function canForward(address _sender, bytes _evmScript) public view returns (bool) { // Note that `canPerform()` implicitly does an initialization check itself return canPerform(_sender, RUN_SCRIPT_ROLE, arr(_getScriptACLParam(_evmScript))); } // ERC-165 conformance /** * @notice Tells whether this contract supports a given ERC-165 interface * @param _interfaceId Interface bytes to check * @return True if this contract supports the interface */ function supportsInterface(bytes4 _interfaceId) external pure returns (bool) { return _interfaceId == ERC1271_INTERFACE_ID || _interfaceId == ERC165_INTERFACE_ID; } // ERC-1271 conformance /** * @notice Tells whether a signature is seen as valid by this contract through ERC-1271 * @param _hash Arbitrary length data signed on the behalf of address (this) * @param _signature Signature byte array associated with _data * @return The ERC-1271 magic value if the signature is valid */ function isValidSignature(bytes32 _hash, bytes _signature) public view returns (bytes4) { // Short-circuit in case the hash was presigned. Optimization as performing calls // and ecrecover is more expensive than an SLOAD. if (isPresigned[_hash]) { return returnIsValidSignatureMagicNumber(true); } bool isValid; if (designatedSigner == address(0)) { isValid = false; } else { isValid = SignatureValidator.isValidSignature(_hash, designatedSigner, _signature); } return returnIsValidSignatureMagicNumber(isValid); } // Getters function getProtectedTokensLength() public view isInitialized returns (uint256) { return protectedTokens.length; } // Internal fns function _addProtectedToken(address _token) internal { protectedTokens.push(_token); emit AddProtectedToken(_token); } function _removeProtectedToken(address _token) internal { protectedTokens[_protectedTokenIndex(_token)] = protectedTokens[protectedTokens.length - 1]; protectedTokens.length--; emit RemoveProtectedToken(_token); } function _isERC20(address _token) internal view returns (bool) { if (!isContract(_token)) { return false; } // Throwaway sanity check to make sure the token's `balanceOf()` does not error (for now) balance(_token); return true; } function _protectedTokenIndex(address _token) internal view returns (uint256) { for (uint i = 0; i < protectedTokens.length; i++) { if (protectedTokens[i] == _token) { return i; } } revert(ERROR_TOKEN_NOT_PROTECTED); } function _tokenIsProtected(address _token) internal view returns (bool) { for (uint256 i = 0; i < protectedTokens.length; i++) { if (protectedTokens[i] == _token) { return true; } } return false; } function _getScriptACLParam(bytes _evmScript) internal pure returns (uint256) { return uint256(keccak256(abi.encodePacked(_evmScript))); } function _getSig(bytes _data) internal pure returns (bytes4 sig) { if (_data.length < 4) { return; } assembly { sig := mload(add(_data, 0x20)) } } } // File: @aragon/os/contracts/lib/math/SafeMath.sol // See https://github.com/OpenZeppelin/openzeppelin-solidity/blob/d51e38758e1d985661534534d5c61e27bece5042/contracts/math/SafeMath.sol // Adapted to use pragma ^0.4.24 and satisfy our linter rules pragma solidity ^0.4.24; /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { string private constant ERROR_ADD_OVERFLOW = "MATH_ADD_OVERFLOW"; string private constant ERROR_SUB_UNDERFLOW = "MATH_SUB_UNDERFLOW"; string private constant ERROR_MUL_OVERFLOW = "MATH_MUL_OVERFLOW"; string private constant ERROR_DIV_ZERO = "MATH_DIV_ZERO"; /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 _a, uint256 _b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (_a == 0) { return 0; } uint256 c = _a * _b; require(c / _a == _b, ERROR_MUL_OVERFLOW); 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, ERROR_DIV_ZERO); // 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'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, ERROR_SUB_UNDERFLOW); 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, ERROR_ADD_OVERFLOW); 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, ERROR_DIV_ZERO); return a % b; } } // File: @aragon/os/contracts/lib/math/SafeMath64.sol // See https://github.com/OpenZeppelin/openzeppelin-solidity/blob/d51e38758e1d985661534534d5c61e27bece5042/contracts/math/SafeMath.sol // Adapted for uint64, pragma ^0.4.24, and satisfying our linter rules // Also optimized the mul() implementation, see https://github.com/aragon/aragonOS/pull/417 pragma solidity ^0.4.24; /** * @title SafeMath64 * @dev Math operations for uint64 with safety checks that revert on error */ library SafeMath64 { string private constant ERROR_ADD_OVERFLOW = "MATH64_ADD_OVERFLOW"; string private constant ERROR_SUB_UNDERFLOW = "MATH64_SUB_UNDERFLOW"; string private constant ERROR_MUL_OVERFLOW = "MATH64_MUL_OVERFLOW"; string private constant ERROR_DIV_ZERO = "MATH64_DIV_ZERO"; /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint64 _a, uint64 _b) internal pure returns (uint64) { uint256 c = uint256(_a) * uint256(_b); require(c < 0x010000000000000000, ERROR_MUL_OVERFLOW); // 2**64 (less gas this way) return uint64(c); } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint64 _a, uint64 _b) internal pure returns (uint64) { require(_b > 0, ERROR_DIV_ZERO); // Solidity only automatically asserts when dividing by 0 uint64 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, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint64 _a, uint64 _b) internal pure returns (uint64) { require(_b <= _a, ERROR_SUB_UNDERFLOW); uint64 c = _a - _b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint64 _a, uint64 _b) internal pure returns (uint64) { uint64 c = _a + _b; require(c >= _a, ERROR_ADD_OVERFLOW); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint64 a, uint64 b) internal pure returns (uint64) { require(b != 0, ERROR_DIV_ZERO); return a % b; } } // File: @aragon/apps-shared-minime/contracts/ITokenController.sol pragma solidity ^0.4.24; /// @dev The token controller contract must implement these functions interface ITokenController { /// @notice Called when `_owner` sends ether to the MiniMe Token contract /// @param _owner The address that sent the ether to create tokens /// @return True if the ether is accepted, false if it throws function proxyPayment(address _owner) external payable returns(bool); /// @notice Notifies the controller about a token transfer allowing the /// controller to react if desired /// @param _from The origin of the transfer /// @param _to The destination of the transfer /// @param _amount The amount of the transfer /// @return False if the controller does not authorize the transfer function onTransfer(address _from, address _to, uint _amount) external returns(bool); /// @notice Notifies the controller about an approval allowing the /// controller to react if desired /// @param _owner The address that calls `approve()` /// @param _spender The spender in the `approve()` call /// @param _amount The amount in the `approve()` call /// @return False if the controller does not authorize the approval function onApprove(address _owner, address _spender, uint _amount) external returns(bool); } // File: @aragon/apps-shared-minime/contracts/MiniMeToken.sol pragma solidity ^0.4.24; /* Copyright 2016, Jordi Baylina This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /// @title MiniMeToken Contract /// @author Jordi Baylina /// @dev This token contract's goal is to make it easy for anyone to clone this /// token using the token distribution at a given block, this will allow DAO's /// and DApps to upgrade their features in a decentralized manner without /// affecting the original token /// @dev It is ERC20 compliant, but still needs to under go further testing. contract Controlled { /// @notice The address of the controller is the only address that can call /// a function with this modifier modifier onlyController { require(msg.sender == controller); _; } address public controller; function Controlled() public { controller = msg.sender;} /// @notice Changes the controller of the contract /// @param _newController The new controller of the contract function changeController(address _newController) onlyController public { controller = _newController; } } contract ApproveAndCallFallBack { function receiveApproval( address from, uint256 _amount, address _token, bytes _data ) public; } /// @dev The actual token contract, the default controller is the msg.sender /// that deploys the contract, so usually this token will be deployed by a /// token controller contract, which Giveth will call a "Campaign" contract MiniMeToken is Controlled { string public name; //The Token's name: e.g. DigixDAO Tokens uint8 public decimals; //Number of decimals of the smallest unit string public symbol; //An identifier: e.g. REP string public version = "MMT_0.1"; //An arbitrary versioning scheme /// @dev `Checkpoint` is the structure that attaches a block number to a /// given value, the block number attached is the one that last changed the /// value struct Checkpoint { // `fromBlock` is the block number that the value was generated from uint128 fromBlock; // `value` is the amount of tokens at a specific block number uint128 value; } // `parentToken` is the Token address that was cloned to produce this token; // it will be 0x0 for a token that was not cloned MiniMeToken public parentToken; // `parentSnapShotBlock` is the block number from the Parent Token that was // used to determine the initial distribution of the Clone Token uint public parentSnapShotBlock; // `creationBlock` is the block number that the Clone Token was created uint public creationBlock; // `balances` is the map that tracks the balance of each address, in this // contract when the balance changes the block number that the change // occurred is also included in the map mapping (address => Checkpoint[]) balances; // `allowed` tracks any extra transfer rights as in all ERC20 tokens mapping (address => mapping (address => uint256)) allowed; // Tracks the history of the `totalSupply` of the token Checkpoint[] totalSupplyHistory; // Flag that determines if the token is transferable or not. bool public transfersEnabled; // The factory used to create new clone tokens MiniMeTokenFactory public tokenFactory; //////////////// // Constructor //////////////// /// @notice Constructor to create a MiniMeToken /// @param _tokenFactory The address of the MiniMeTokenFactory contract that /// will create the Clone token contracts, the token factory needs to be /// deployed first /// @param _parentToken Address of the parent token, set to 0x0 if it is a /// new token /// @param _parentSnapShotBlock Block of the parent token that will /// determine the initial distribution of the clone token, set to 0 if it /// is a new token /// @param _tokenName Name of the new token /// @param _decimalUnits Number of decimals of the new token /// @param _tokenSymbol Token Symbol for the new token /// @param _transfersEnabled If true, tokens will be able to be transferred function MiniMeToken( MiniMeTokenFactory _tokenFactory, MiniMeToken _parentToken, uint _parentSnapShotBlock, string _tokenName, uint8 _decimalUnits, string _tokenSymbol, bool _transfersEnabled ) public { tokenFactory = _tokenFactory; name = _tokenName; // Set the name decimals = _decimalUnits; // Set the decimals symbol = _tokenSymbol; // Set the symbol parentToken = _parentToken; parentSnapShotBlock = _parentSnapShotBlock; transfersEnabled = _transfersEnabled; creationBlock = block.number; } /////////////////// // ERC20 Methods /////////////////// /// @notice Send `_amount` tokens to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _amount The amount of tokens to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _amount) public returns (bool success) { require(transfersEnabled); return doTransfer(msg.sender, _to, _amount); } /// @notice Send `_amount` tokens to `_to` from `_from` on the condition it /// is approved by `_from` /// @param _from The address holding the tokens being transferred /// @param _to The address of the recipient /// @param _amount The amount of tokens to be transferred /// @return True if the transfer was successful function transferFrom(address _from, address _to, uint256 _amount) public returns (bool success) { // The controller of this contract can move tokens around at will, // this is important to recognize! Confirm that you trust the // controller of this contract, which in most situations should be // another open source smart contract or 0x0 if (msg.sender != controller) { require(transfersEnabled); // The standard ERC 20 transferFrom functionality if (allowed[_from][msg.sender] < _amount) return false; allowed[_from][msg.sender] -= _amount; } return doTransfer(_from, _to, _amount); } /// @dev This is the actual transfer function in the token contract, it can /// only be called by other functions in this contract. /// @param _from The address holding the tokens being transferred /// @param _to The address of the recipient /// @param _amount The amount of tokens to be transferred /// @return True if the transfer was successful function doTransfer(address _from, address _to, uint _amount) internal returns(bool) { if (_amount == 0) { return true; } require(parentSnapShotBlock < block.number); // Do not allow transfer to 0x0 or the token contract itself require((_to != 0) && (_to != address(this))); // If the amount being transfered is more than the balance of the // account the transfer returns false var previousBalanceFrom = balanceOfAt(_from, block.number); if (previousBalanceFrom < _amount) { return false; } // Alerts the token controller of the transfer if (isContract(controller)) { // Adding the ` == true` makes the linter shut up so... require(ITokenController(controller).onTransfer(_from, _to, _amount) == true); } // First update the balance array with the new value for the address // sending the tokens updateValueAtNow(balances[_from], previousBalanceFrom - _amount); // Then update the balance array with the new value for the address // receiving the tokens var previousBalanceTo = balanceOfAt(_to, block.number); require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow updateValueAtNow(balances[_to], previousBalanceTo + _amount); // An event to make the transfer easy to find on the blockchain Transfer(_from, _to, _amount); return true; } /// @param _owner The address that's balance is being requested /// @return The balance of `_owner` at the current block function balanceOf(address _owner) public constant returns (uint256 balance) { return balanceOfAt(_owner, block.number); } /// @notice `msg.sender` approves `_spender` to spend `_amount` tokens on /// its behalf. This is a modified version of the ERC20 approve function /// to be a little bit safer /// @param _spender The address of the account able to transfer the tokens /// @param _amount The amount of tokens to be approved for transfer /// @return True if the approval was successful function approve(address _spender, uint256 _amount) public returns (bool success) { require(transfersEnabled); // 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((_amount == 0) || (allowed[msg.sender][_spender] == 0)); // Alerts the token controller of the approve function call if (isContract(controller)) { // Adding the ` == true` makes the linter shut up so... require(ITokenController(controller).onApprove(msg.sender, _spender, _amount) == true); } allowed[msg.sender][_spender] = _amount; Approval(msg.sender, _spender, _amount); return true; } /// @dev This function makes it easy to read the `allowed[]` map /// @param _owner The address of the account that owns the token /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens of _owner that _spender is allowed /// to spend function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } /// @notice `msg.sender` approves `_spender` to send `_amount` tokens on /// its behalf, and then a function is triggered in the contract that is /// being approved, `_spender`. This allows users to use their tokens to /// interact with contracts in one function call instead of two /// @param _spender The address of the contract able to transfer the tokens /// @param _amount The amount of tokens to be approved for transfer /// @return True if the function call was successful function approveAndCall(ApproveAndCallFallBack _spender, uint256 _amount, bytes _extraData) public returns (bool success) { require(approve(_spender, _amount)); _spender.receiveApproval( msg.sender, _amount, this, _extraData ); return true; } /// @dev This function makes it easy to get the total number of tokens /// @return The total number of tokens function totalSupply() public constant returns (uint) { return totalSupplyAt(block.number); } //////////////// // Query balance and totalSupply in History //////////////// /// @dev Queries the balance of `_owner` at a specific `_blockNumber` /// @param _owner The address from which the balance will be retrieved /// @param _blockNumber The block number when the balance is queried /// @return The balance at `_blockNumber` function balanceOfAt(address _owner, uint _blockNumber) public constant returns (uint) { // These next few lines are used when the balance of the token is // requested before a check point was ever created for this token, it // requires that the `parentToken.balanceOfAt` be queried at the // genesis block for that token as this contains initial balance of // this token if ((balances[_owner].length == 0) || (balances[_owner][0].fromBlock > _blockNumber)) { if (address(parentToken) != 0) { return parentToken.balanceOfAt(_owner, min(_blockNumber, parentSnapShotBlock)); } else { // Has no parent return 0; } // This will return the expected balance during normal situations } else { return getValueAt(balances[_owner], _blockNumber); } } /// @notice Total amount of tokens at a specific `_blockNumber`. /// @param _blockNumber The block number when the totalSupply is queried /// @return The total amount of tokens at `_blockNumber` function totalSupplyAt(uint _blockNumber) public constant returns(uint) { // These next few lines are used when the totalSupply of the token is // requested before a check point was ever created for this token, it // requires that the `parentToken.totalSupplyAt` be queried at the // genesis block for this token as that contains totalSupply of this // token at this block number. if ((totalSupplyHistory.length == 0) || (totalSupplyHistory[0].fromBlock > _blockNumber)) { if (address(parentToken) != 0) { return parentToken.totalSupplyAt(min(_blockNumber, parentSnapShotBlock)); } else { return 0; } // This will return the expected totalSupply during normal situations } else { return getValueAt(totalSupplyHistory, _blockNumber); } } //////////////// // Clone Token Method //////////////// /// @notice Creates a new clone token with the initial distribution being /// this token at `_snapshotBlock` /// @param _cloneTokenName Name of the clone token /// @param _cloneDecimalUnits Number of decimals of the smallest unit /// @param _cloneTokenSymbol Symbol of the clone token /// @param _snapshotBlock Block when the distribution of the parent token is /// copied to set the initial distribution of the new clone token; /// if the block is zero than the actual block, the current block is used /// @param _transfersEnabled True if transfers are allowed in the clone /// @return The address of the new MiniMeToken Contract function createCloneToken( string _cloneTokenName, uint8 _cloneDecimalUnits, string _cloneTokenSymbol, uint _snapshotBlock, bool _transfersEnabled ) public returns(MiniMeToken) { uint256 snapshot = _snapshotBlock == 0 ? block.number - 1 : _snapshotBlock; MiniMeToken cloneToken = tokenFactory.createCloneToken( this, snapshot, _cloneTokenName, _cloneDecimalUnits, _cloneTokenSymbol, _transfersEnabled ); cloneToken.changeController(msg.sender); // An event to make the token easy to find on the blockchain NewCloneToken(address(cloneToken), snapshot); return cloneToken; } //////////////// // Generate and destroy tokens //////////////// /// @notice Generates `_amount` tokens that are assigned to `_owner` /// @param _owner The address that will be assigned the new tokens /// @param _amount The quantity of tokens generated /// @return True if the tokens are generated correctly function generateTokens(address _owner, uint _amount) onlyController public returns (bool) { uint curTotalSupply = totalSupply(); require(curTotalSupply + _amount >= curTotalSupply); // Check for overflow uint previousBalanceTo = balanceOf(_owner); require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow updateValueAtNow(totalSupplyHistory, curTotalSupply + _amount); updateValueAtNow(balances[_owner], previousBalanceTo + _amount); Transfer(0, _owner, _amount); return true; } /// @notice Burns `_amount` tokens from `_owner` /// @param _owner The address that will lose the tokens /// @param _amount The quantity of tokens to burn /// @return True if the tokens are burned correctly function destroyTokens(address _owner, uint _amount) onlyController public returns (bool) { uint curTotalSupply = totalSupply(); require(curTotalSupply >= _amount); uint previousBalanceFrom = balanceOf(_owner); require(previousBalanceFrom >= _amount); updateValueAtNow(totalSupplyHistory, curTotalSupply - _amount); updateValueAtNow(balances[_owner], previousBalanceFrom - _amount); Transfer(_owner, 0, _amount); return true; } //////////////// // Enable tokens transfers //////////////// /// @notice Enables token holders to transfer their tokens freely if true /// @param _transfersEnabled True if transfers are allowed in the clone function enableTransfers(bool _transfersEnabled) onlyController public { transfersEnabled = _transfersEnabled; } //////////////// // Internal helper functions to query and set a value in a snapshot array //////////////// /// @dev `getValueAt` retrieves the number of tokens at a given block number /// @param checkpoints The history of values being queried /// @param _block The block number to retrieve the value at /// @return The number of tokens being queried function getValueAt(Checkpoint[] storage checkpoints, uint _block) constant internal returns (uint) { if (checkpoints.length == 0) return 0; // Shortcut for the actual value if (_block >= checkpoints[checkpoints.length-1].fromBlock) return checkpoints[checkpoints.length-1].value; if (_block < checkpoints[0].fromBlock) return 0; // Binary search of the value in the array uint min = 0; uint max = checkpoints.length-1; while (max > min) { uint mid = (max + min + 1) / 2; if (checkpoints[mid].fromBlock<=_block) { min = mid; } else { max = mid-1; } } return checkpoints[min].value; } /// @dev `updateValueAtNow` used to update the `balances` map and the /// `totalSupplyHistory` /// @param checkpoints The history of data being updated /// @param _value The new number of tokens function updateValueAtNow(Checkpoint[] storage checkpoints, uint _value) internal { if ((checkpoints.length == 0) || (checkpoints[checkpoints.length - 1].fromBlock < block.number)) { Checkpoint storage newCheckPoint = checkpoints[checkpoints.length++]; newCheckPoint.fromBlock = uint128(block.number); newCheckPoint.value = uint128(_value); } else { Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length - 1]; oldCheckPoint.value = uint128(_value); } } /// @dev Internal function to determine if an address is a contract /// @param _addr The address being queried /// @return True if `_addr` is a contract function isContract(address _addr) constant internal returns(bool) { uint size; if (_addr == 0) return false; assembly { size := extcodesize(_addr) } return size>0; } /// @dev Helper function to return a min betwen the two uints function min(uint a, uint b) pure internal returns (uint) { return a < b ? a : b; } /// @notice The fallback function: If the contract's controller has not been /// set to 0, then the `proxyPayment` method is called which relays the /// ether and creates tokens as described in the token controller contract function () external payable { require(isContract(controller)); // Adding the ` == true` makes the linter shut up so... require(ITokenController(controller).proxyPayment.value(msg.value)(msg.sender) == true); } ////////// // Safety Methods ////////// /// @notice This method can be used by the controller to extract mistakenly /// sent tokens to this contract. /// @param _token The address of the token contract that you want to recover /// set to 0 in case you want to extract ether. function claimTokens(address _token) onlyController public { if (_token == 0x0) { controller.transfer(this.balance); return; } MiniMeToken token = MiniMeToken(_token); uint balance = token.balanceOf(this); token.transfer(controller, balance); ClaimedTokens(_token, controller, balance); } //////////////// // Events //////////////// event ClaimedTokens(address indexed _token, address indexed _controller, uint _amount); event Transfer(address indexed _from, address indexed _to, uint256 _amount); event NewCloneToken(address indexed _cloneToken, uint _snapshotBlock); event Approval( address indexed _owner, address indexed _spender, uint256 _amount ); } //////////////// // MiniMeTokenFactory //////////////// /// @dev This contract is used to generate clone contracts from a contract. /// In solidity this is the way to create a contract from a contract of the /// same class contract MiniMeTokenFactory { /// @notice Update the DApp by creating a new token with new functionalities /// the msg.sender becomes the controller of this clone token /// @param _parentToken Address of the token being cloned /// @param _snapshotBlock Block of the parent token that will /// determine the initial distribution of the clone token /// @param _tokenName Name of the new token /// @param _decimalUnits Number of decimals of the new token /// @param _tokenSymbol Token Symbol for the new token /// @param _transfersEnabled If true, tokens will be able to be transferred /// @return The address of the new token contract function createCloneToken( MiniMeToken _parentToken, uint _snapshotBlock, string _tokenName, uint8 _decimalUnits, string _tokenSymbol, bool _transfersEnabled ) public returns (MiniMeToken) { MiniMeToken newToken = new MiniMeToken( this, _parentToken, _snapshotBlock, _tokenName, _decimalUnits, _tokenSymbol, _transfersEnabled ); newToken.changeController(msg.sender); return newToken; } } // File: @aragon/apps-voting/contracts/Voting.sol /* * SPDX-License-Identitifer: GPL-3.0-or-later */ pragma solidity 0.4.24; contract Voting is IForwarder, AragonApp { using SafeMath for uint256; using SafeMath64 for uint64; bytes32 public constant CREATE_VOTES_ROLE = keccak256("CREATE_VOTES_ROLE"); bytes32 public constant MODIFY_SUPPORT_ROLE = keccak256("MODIFY_SUPPORT_ROLE"); bytes32 public constant MODIFY_QUORUM_ROLE = keccak256("MODIFY_QUORUM_ROLE"); uint64 public constant PCT_BASE = 10 ** 18; // 0% = 0; 1% = 10^16; 100% = 10^18 string private constant ERROR_NO_VOTE = "VOTING_NO_VOTE"; string private constant ERROR_INIT_PCTS = "VOTING_INIT_PCTS"; string private constant ERROR_CHANGE_SUPPORT_PCTS = "VOTING_CHANGE_SUPPORT_PCTS"; string private constant ERROR_CHANGE_QUORUM_PCTS = "VOTING_CHANGE_QUORUM_PCTS"; string private constant ERROR_INIT_SUPPORT_TOO_BIG = "VOTING_INIT_SUPPORT_TOO_BIG"; string private constant ERROR_CHANGE_SUPPORT_TOO_BIG = "VOTING_CHANGE_SUPP_TOO_BIG"; string private constant ERROR_CAN_NOT_VOTE = "VOTING_CAN_NOT_VOTE"; string private constant ERROR_CAN_NOT_EXECUTE = "VOTING_CAN_NOT_EXECUTE"; string private constant ERROR_CAN_NOT_FORWARD = "VOTING_CAN_NOT_FORWARD"; string private constant ERROR_NO_VOTING_POWER = "VOTING_NO_VOTING_POWER"; enum VoterState { Absent, Yea, Nay } struct Vote { bool executed; uint64 startDate; uint64 snapshotBlock; uint64 supportRequiredPct; uint64 minAcceptQuorumPct; uint256 yea; uint256 nay; uint256 votingPower; bytes executionScript; mapping (address => VoterState) voters; } MiniMeToken public token; uint64 public supportRequiredPct; uint64 public minAcceptQuorumPct; uint64 public voteTime; // We are mimicing an array, we use a mapping instead to make app upgrade more graceful mapping (uint256 => Vote) internal votes; uint256 public votesLength; event StartVote(uint256 indexed voteId, address indexed creator, string metadata); event CastVote(uint256 indexed voteId, address indexed voter, bool supports, uint256 stake); event ExecuteVote(uint256 indexed voteId); event ChangeSupportRequired(uint64 supportRequiredPct); event ChangeMinQuorum(uint64 minAcceptQuorumPct); modifier voteExists(uint256 _voteId) { require(_voteId < votesLength, ERROR_NO_VOTE); _; } /** * @notice Initialize Voting app with `_token.symbol(): string` for governance, minimum support of `@formatPct(_supportRequiredPct)`%, minimum acceptance quorum of `@formatPct(_minAcceptQuorumPct)`%, and a voting duration of `@transformTime(_voteTime)` * @param _token MiniMeToken Address that will be used as governance token * @param _supportRequiredPct Percentage of yeas in casted votes for a vote to succeed (expressed as a percentage of 10^18; eg. 10^16 = 1%, 10^18 = 100%) * @param _minAcceptQuorumPct Percentage of yeas in total possible votes for a vote to succeed (expressed as a percentage of 10^18; eg. 10^16 = 1%, 10^18 = 100%) * @param _voteTime Seconds that a vote will be open for token holders to vote (unless enough yeas or nays have been cast to make an early decision) */ function initialize( MiniMeToken _token, uint64 _supportRequiredPct, uint64 _minAcceptQuorumPct, uint64 _voteTime ) external onlyInit { initialized(); require(_minAcceptQuorumPct <= _supportRequiredPct, ERROR_INIT_PCTS); require(_supportRequiredPct < PCT_BASE, ERROR_INIT_SUPPORT_TOO_BIG); token = _token; supportRequiredPct = _supportRequiredPct; minAcceptQuorumPct = _minAcceptQuorumPct; voteTime = _voteTime; } /** * @notice Change required support to `@formatPct(_supportRequiredPct)`% * @param _supportRequiredPct New required support */ function changeSupportRequiredPct(uint64 _supportRequiredPct) external authP(MODIFY_SUPPORT_ROLE, arr(uint256(_supportRequiredPct), uint256(supportRequiredPct))) { require(minAcceptQuorumPct <= _supportRequiredPct, ERROR_CHANGE_SUPPORT_PCTS); require(_supportRequiredPct < PCT_BASE, ERROR_CHANGE_SUPPORT_TOO_BIG); supportRequiredPct = _supportRequiredPct; emit ChangeSupportRequired(_supportRequiredPct); } /** * @notice Change minimum acceptance quorum to `@formatPct(_minAcceptQuorumPct)`% * @param _minAcceptQuorumPct New acceptance quorum */ function changeMinAcceptQuorumPct(uint64 _minAcceptQuorumPct) external authP(MODIFY_QUORUM_ROLE, arr(uint256(_minAcceptQuorumPct), uint256(minAcceptQuorumPct))) { require(_minAcceptQuorumPct <= supportRequiredPct, ERROR_CHANGE_QUORUM_PCTS); minAcceptQuorumPct = _minAcceptQuorumPct; emit ChangeMinQuorum(_minAcceptQuorumPct); } /** * @notice Create a new vote about "`_metadata`" * @param _executionScript EVM script to be executed on approval * @param _metadata Vote metadata * @return voteId Id for newly created vote */ function newVote(bytes _executionScript, string _metadata) external auth(CREATE_VOTES_ROLE) returns (uint256 voteId) { return _newVote(_executionScript, _metadata, true, true); } /** * @notice Create a new vote about "`_metadata`" * @param _executionScript EVM script to be executed on approval * @param _metadata Vote metadata * @param _castVote Whether to also cast newly created vote * @param _executesIfDecided Whether to also immediately execute newly created vote if decided * @return voteId id for newly created vote */ function newVote(bytes _executionScript, string _metadata, bool _castVote, bool _executesIfDecided) external auth(CREATE_VOTES_ROLE) returns (uint256 voteId) { return _newVote(_executionScript, _metadata, _castVote, _executesIfDecided); } /** * @notice Vote `_supports ? 'yes' : 'no'` in vote #`_voteId` * @dev Initialization check is implicitly provided by `voteExists()` as new votes can only be * created via `newVote(),` which requires initialization * @param _voteId Id for vote * @param _supports Whether voter supports the vote * @param _executesIfDecided Whether the vote should execute its action if it becomes decided */ function vote(uint256 _voteId, bool _supports, bool _executesIfDecided) external voteExists(_voteId) { require(_canVote(_voteId, msg.sender), ERROR_CAN_NOT_VOTE); _vote(_voteId, _supports, msg.sender, _executesIfDecided); } /** * @notice Execute vote #`_voteId` * @dev Initialization check is implicitly provided by `voteExists()` as new votes can only be * created via `newVote(),` which requires initialization * @param _voteId Id for vote */ function executeVote(uint256 _voteId) external voteExists(_voteId) { _executeVote(_voteId); } // Forwarding fns function isForwarder() external pure returns (bool) { return true; } /** * @notice Creates a vote to execute the desired action, and casts a support vote if possible * @dev IForwarder interface conformance * @param _evmScript Start vote with script */ function forward(bytes _evmScript) public { require(canForward(msg.sender, _evmScript), ERROR_CAN_NOT_FORWARD); _newVote(_evmScript, "", true, true); } function canForward(address _sender, bytes) public view returns (bool) { // Note that `canPerform()` implicitly does an initialization check itself return canPerform(_sender, CREATE_VOTES_ROLE, arr()); } // Getter fns /** * @dev Initialization check is implicitly provided by `voteExists()` as new votes can only be * created via `newVote(),` which requires initialization */ function canExecute(uint256 _voteId) public view voteExists(_voteId) returns (bool) { return _canExecute(_voteId); } /** * @dev Initialization check is implicitly provided by `voteExists()` as new votes can only be * created via `newVote(),` which requires initialization */ function canVote(uint256 _voteId, address _voter) public view voteExists(_voteId) returns (bool) { return _canVote(_voteId, _voter); } function getVote(uint256 _voteId) public view voteExists(_voteId) returns ( bool open, bool executed, uint64 startDate, uint64 snapshotBlock, uint64 supportRequired, uint64 minAcceptQuorum, uint256 yea, uint256 nay, uint256 votingPower, bytes script ) { Vote storage vote_ = votes[_voteId]; open = _isVoteOpen(vote_); executed = vote_.executed; startDate = vote_.startDate; snapshotBlock = vote_.snapshotBlock; supportRequired = vote_.supportRequiredPct; minAcceptQuorum = vote_.minAcceptQuorumPct; yea = vote_.yea; nay = vote_.nay; votingPower = vote_.votingPower; script = vote_.executionScript; } function getVoterState(uint256 _voteId, address _voter) public view voteExists(_voteId) returns (VoterState) { return votes[_voteId].voters[_voter]; } // Internal fns function _newVote(bytes _executionScript, string _metadata, bool _castVote, bool _executesIfDecided) internal returns (uint256 voteId) { uint64 snapshotBlock = getBlockNumber64() - 1; // avoid double voting in this very block uint256 votingPower = token.totalSupplyAt(snapshotBlock); require(votingPower > 0, ERROR_NO_VOTING_POWER); voteId = votesLength++; Vote storage vote_ = votes[voteId]; vote_.startDate = getTimestamp64(); vote_.snapshotBlock = snapshotBlock; vote_.supportRequiredPct = supportRequiredPct; vote_.minAcceptQuorumPct = minAcceptQuorumPct; vote_.votingPower = votingPower; vote_.executionScript = _executionScript; emit StartVote(voteId, msg.sender, _metadata); if (_castVote && _canVote(voteId, msg.sender)) { _vote(voteId, true, msg.sender, _executesIfDecided); } } function _vote( uint256 _voteId, bool _supports, address _voter, bool _executesIfDecided ) internal { Vote storage vote_ = votes[_voteId]; // This could re-enter, though we can assume the governance token is not malicious uint256 voterStake = token.balanceOfAt(_voter, vote_.snapshotBlock); VoterState state = vote_.voters[_voter]; // If voter had previously voted, decrease count if (state == VoterState.Yea) { vote_.yea = vote_.yea.sub(voterStake); } else if (state == VoterState.Nay) { vote_.nay = vote_.nay.sub(voterStake); } if (_supports) { vote_.yea = vote_.yea.add(voterStake); } else { vote_.nay = vote_.nay.add(voterStake); } vote_.voters[_voter] = _supports ? VoterState.Yea : VoterState.Nay; emit CastVote(_voteId, _voter, _supports, voterStake); if (_executesIfDecided && _canExecute(_voteId)) { // We've already checked if the vote can be executed with `_canExecute()` _unsafeExecuteVote(_voteId); } } function _executeVote(uint256 _voteId) internal { require(_canExecute(_voteId), ERROR_CAN_NOT_EXECUTE); _unsafeExecuteVote(_voteId); } /** * @dev Unsafe version of _executeVote that assumes you have already checked if the vote can be executed */ function _unsafeExecuteVote(uint256 _voteId) internal { Vote storage vote_ = votes[_voteId]; vote_.executed = true; bytes memory input = new bytes(0); // TODO: Consider input for voting scripts runScript(vote_.executionScript, input, new address[](0)); emit ExecuteVote(_voteId); } function _canExecute(uint256 _voteId) internal view returns (bool) { Vote storage vote_ = votes[_voteId]; if (vote_.executed) { return false; } // Voting is already decided if (_isValuePct(vote_.yea, vote_.votingPower, vote_.supportRequiredPct)) { return true; } // Vote ended? if (_isVoteOpen(vote_)) { return false; } // Has enough support? uint256 totalVotes = vote_.yea.add(vote_.nay); if (!_isValuePct(vote_.yea, totalVotes, vote_.supportRequiredPct)) { return false; } // Has min quorum? if (!_isValuePct(vote_.yea, vote_.votingPower, vote_.minAcceptQuorumPct)) { return false; } return true; } function _canVote(uint256 _voteId, address _voter) internal view returns (bool) { Vote storage vote_ = votes[_voteId]; return _isVoteOpen(vote_) && token.balanceOfAt(_voter, vote_.snapshotBlock) > 0; } function _isVoteOpen(Vote storage vote_) internal view returns (bool) { return getTimestamp64() < vote_.startDate.add(voteTime) && !vote_.executed; } /** * @dev Calculates whether `_value` is more than a percentage `_pct` of `_total` */ function _isValuePct(uint256 _value, uint256 _total, uint256 _pct) internal pure returns (bool) { if (_total == 0) { return false; } uint256 computedPct = _value.mul(PCT_BASE) / _total; return computedPct > _pct; } } // File: @aragon/ppf-contracts/contracts/IFeed.sol pragma solidity ^0.4.18; interface IFeed { function ratePrecision() external pure returns (uint256); function get(address base, address quote) external view returns (uint128 xrt, uint64 when); } // File: @aragon/apps-finance/contracts/Finance.sol /* * SPDX-License-Identitifer: GPL-3.0-or-later */ pragma solidity 0.4.24; contract Finance is EtherTokenConstant, IsContract, AragonApp { using SafeMath for uint256; using SafeMath64 for uint64; using SafeERC20 for ERC20; bytes32 public constant CREATE_PAYMENTS_ROLE = keccak256("CREATE_PAYMENTS_ROLE"); bytes32 public constant CHANGE_PERIOD_ROLE = keccak256("CHANGE_PERIOD_ROLE"); bytes32 public constant CHANGE_BUDGETS_ROLE = keccak256("CHANGE_BUDGETS_ROLE"); bytes32 public constant EXECUTE_PAYMENTS_ROLE = keccak256("EXECUTE_PAYMENTS_ROLE"); bytes32 public constant MANAGE_PAYMENTS_ROLE = keccak256("MANAGE_PAYMENTS_ROLE"); uint256 internal constant NO_SCHEDULED_PAYMENT = 0; uint256 internal constant NO_TRANSACTION = 0; uint256 internal constant MAX_SCHEDULED_PAYMENTS_PER_TX = 20; uint256 internal constant MAX_UINT256 = uint256(-1); uint64 internal constant MAX_UINT64 = uint64(-1); uint64 internal constant MINIMUM_PERIOD = uint64(1 days); string private constant ERROR_COMPLETE_TRANSITION = "FINANCE_COMPLETE_TRANSITION"; string private constant ERROR_NO_SCHEDULED_PAYMENT = "FINANCE_NO_SCHEDULED_PAYMENT"; string private constant ERROR_NO_TRANSACTION = "FINANCE_NO_TRANSACTION"; string private constant ERROR_NO_PERIOD = "FINANCE_NO_PERIOD"; string private constant ERROR_VAULT_NOT_CONTRACT = "FINANCE_VAULT_NOT_CONTRACT"; string private constant ERROR_SET_PERIOD_TOO_SHORT = "FINANCE_SET_PERIOD_TOO_SHORT"; string private constant ERROR_NEW_PAYMENT_AMOUNT_ZERO = "FINANCE_NEW_PAYMENT_AMOUNT_ZERO"; string private constant ERROR_NEW_PAYMENT_INTERVAL_ZERO = "FINANCE_NEW_PAYMENT_INTRVL_ZERO"; string private constant ERROR_NEW_PAYMENT_EXECS_ZERO = "FINANCE_NEW_PAYMENT_EXECS_ZERO"; string private constant ERROR_NEW_PAYMENT_IMMEDIATE = "FINANCE_NEW_PAYMENT_IMMEDIATE"; string private constant ERROR_RECOVER_AMOUNT_ZERO = "FINANCE_RECOVER_AMOUNT_ZERO"; string private constant ERROR_DEPOSIT_AMOUNT_ZERO = "FINANCE_DEPOSIT_AMOUNT_ZERO"; string private constant ERROR_ETH_VALUE_MISMATCH = "FINANCE_ETH_VALUE_MISMATCH"; string private constant ERROR_BUDGET = "FINANCE_BUDGET"; string private constant ERROR_EXECUTE_PAYMENT_NUM = "FINANCE_EXECUTE_PAYMENT_NUM"; string private constant ERROR_EXECUTE_PAYMENT_TIME = "FINANCE_EXECUTE_PAYMENT_TIME"; string private constant ERROR_PAYMENT_RECEIVER = "FINANCE_PAYMENT_RECEIVER"; string private constant ERROR_TOKEN_TRANSFER_FROM_REVERTED = "FINANCE_TKN_TRANSFER_FROM_REVERT"; string private constant ERROR_TOKEN_APPROVE_FAILED = "FINANCE_TKN_APPROVE_FAILED"; string private constant ERROR_PAYMENT_INACTIVE = "FINANCE_PAYMENT_INACTIVE"; string private constant ERROR_REMAINING_BUDGET = "FINANCE_REMAINING_BUDGET"; // Order optimized for storage struct ScheduledPayment { address token; address receiver; address createdBy; bool inactive; uint256 amount; uint64 initialPaymentTime; uint64 interval; uint64 maxExecutions; uint64 executions; } // Order optimized for storage struct Transaction { address token; address entity; bool isIncoming; uint256 amount; uint256 paymentId; uint64 paymentExecutionNumber; uint64 date; uint64 periodId; } struct TokenStatement { uint256 expenses; uint256 income; } struct Period { uint64 startTime; uint64 endTime; uint256 firstTransactionId; uint256 lastTransactionId; mapping (address => TokenStatement) tokenStatement; } struct Settings { uint64 periodDuration; mapping (address => uint256) budgets; mapping (address => bool) hasBudget; } Vault public vault; Settings internal settings; // We are mimicing arrays, we use mappings instead to make app upgrade more graceful mapping (uint256 => ScheduledPayment) internal scheduledPayments; // Payments start at index 1, to allow us to use scheduledPayments[0] for transactions that are not // linked to a scheduled payment uint256 public paymentsNextIndex; mapping (uint256 => Transaction) internal transactions; uint256 public transactionsNextIndex; mapping (uint64 => Period) internal periods; uint64 public periodsLength; event NewPeriod(uint64 indexed periodId, uint64 periodStarts, uint64 periodEnds); event SetBudget(address indexed token, uint256 amount, bool hasBudget); event NewPayment(uint256 indexed paymentId, address indexed recipient, uint64 maxExecutions, string reference); event NewTransaction(uint256 indexed transactionId, bool incoming, address indexed entity, uint256 amount, string reference); event ChangePaymentState(uint256 indexed paymentId, bool active); event ChangePeriodDuration(uint64 newDuration); event PaymentFailure(uint256 paymentId); // Modifier used by all methods that impact accounting to make sure accounting period // is changed before the operation if needed // NOTE: its use **MUST** be accompanied by an initialization check modifier transitionsPeriod { bool completeTransition = _tryTransitionAccountingPeriod(getMaxPeriodTransitions()); require(completeTransition, ERROR_COMPLETE_TRANSITION); _; } modifier scheduledPaymentExists(uint256 _paymentId) { require(_paymentId > 0 && _paymentId < paymentsNextIndex, ERROR_NO_SCHEDULED_PAYMENT); _; } modifier transactionExists(uint256 _transactionId) { require(_transactionId > 0 && _transactionId < transactionsNextIndex, ERROR_NO_TRANSACTION); _; } modifier periodExists(uint64 _periodId) { require(_periodId < periodsLength, ERROR_NO_PERIOD); _; } /** * @notice Deposit ETH to the Vault, to avoid locking them in this Finance app forever * @dev Send ETH to Vault. Send all the available balance. */ function () external payable isInitialized transitionsPeriod { require(msg.value > 0, ERROR_DEPOSIT_AMOUNT_ZERO); _deposit( ETH, msg.value, "Ether transfer to Finance app", msg.sender, true ); } /** * @notice Initialize Finance app for Vault at `_vault` with period length of `@transformTime(_periodDuration)` * @param _vault Address of the vault Finance will rely on (non changeable) * @param _periodDuration Duration in seconds of each period */ function initialize(Vault _vault, uint64 _periodDuration) external onlyInit { initialized(); require(isContract(_vault), ERROR_VAULT_NOT_CONTRACT); vault = _vault; require(_periodDuration >= MINIMUM_PERIOD, ERROR_SET_PERIOD_TOO_SHORT); settings.periodDuration = _periodDuration; // Reserve the first scheduled payment index as an unused index for transactions not linked // to a scheduled payment scheduledPayments[0].inactive = true; paymentsNextIndex = 1; // Reserve the first transaction index as an unused index for periods with no transactions transactionsNextIndex = 1; // Start the first period _newPeriod(getTimestamp64()); } /** * @notice Deposit `@tokenAmount(_token, _amount)` * @dev Deposit for approved ERC20 tokens or ETH * @param _token Address of deposited token * @param _amount Amount of tokens sent * @param _reference Reason for payment */ function deposit(address _token, uint256 _amount, string _reference) external payable isInitialized transitionsPeriod { require(_amount > 0, ERROR_DEPOSIT_AMOUNT_ZERO); if (_token == ETH) { // Ensure that the ETH sent with the transaction equals the amount in the deposit require(msg.value == _amount, ERROR_ETH_VALUE_MISMATCH); } _deposit( _token, _amount, _reference, msg.sender, true ); } /** * @notice Create a new payment of `@tokenAmount(_token, _amount)` to `_receiver` for '`_reference`' * @dev Note that this function is protected by the `CREATE_PAYMENTS_ROLE` but uses `MAX_UINT256` * as its interval auth parameter (as a sentinel value for "never repeating"). * While this protects against most cases (you typically want to set a baseline requirement * for interval time), it does mean users will have to explicitly check for this case when * granting a permission that includes a upperbound requirement on the interval time. * @param _token Address of token for payment * @param _receiver Address that will receive payment * @param _amount Tokens that are paid every time the payment is due * @param _reference String detailing payment reason */ function newImmediatePayment(address _token, address _receiver, uint256 _amount, string _reference) external // Use MAX_UINT256 as the interval parameter, as this payment will never repeat // Payment time parameter is left as the last param as it was added later authP(CREATE_PAYMENTS_ROLE, _arr(_token, _receiver, _amount, MAX_UINT256, uint256(1), getTimestamp())) transitionsPeriod { require(_amount > 0, ERROR_NEW_PAYMENT_AMOUNT_ZERO); _makePaymentTransaction( _token, _receiver, _amount, NO_SCHEDULED_PAYMENT, // unrelated to any payment id; it isn't created 0, // also unrelated to any payment executions _reference ); } /** * @notice Create a new payment of `@tokenAmount(_token, _amount)` to `_receiver` for `_reference`, executing `_maxExecutions` times at intervals of `@transformTime(_interval)` * @dev See `newImmediatePayment()` for limitations on how the interval auth parameter can be used * @param _token Address of token for payment * @param _receiver Address that will receive payment * @param _amount Tokens that are paid every time the payment is due * @param _initialPaymentTime Timestamp for when the first payment is done * @param _interval Number of seconds that need to pass between payment transactions * @param _maxExecutions Maximum instances a payment can be executed * @param _reference String detailing payment reason */ function newScheduledPayment( address _token, address _receiver, uint256 _amount, uint64 _initialPaymentTime, uint64 _interval, uint64 _maxExecutions, string _reference ) external // Payment time parameter is left as the last param as it was added later authP(CREATE_PAYMENTS_ROLE, _arr(_token, _receiver, _amount, uint256(_interval), uint256(_maxExecutions), uint256(_initialPaymentTime))) transitionsPeriod returns (uint256 paymentId) { require(_amount > 0, ERROR_NEW_PAYMENT_AMOUNT_ZERO); require(_interval > 0, ERROR_NEW_PAYMENT_INTERVAL_ZERO); require(_maxExecutions > 0, ERROR_NEW_PAYMENT_EXECS_ZERO); // Token budget must not be set at all or allow at least one instance of this payment each period require(!settings.hasBudget[_token] || settings.budgets[_token] >= _amount, ERROR_BUDGET); // Don't allow creating single payments that are immediately executable, use `newImmediatePayment()` instead if (_maxExecutions == 1) { require(_initialPaymentTime > getTimestamp64(), ERROR_NEW_PAYMENT_IMMEDIATE); } paymentId = paymentsNextIndex++; emit NewPayment(paymentId, _receiver, _maxExecutions, _reference); ScheduledPayment storage payment = scheduledPayments[paymentId]; payment.token = _token; payment.receiver = _receiver; payment.amount = _amount; payment.initialPaymentTime = _initialPaymentTime; payment.interval = _interval; payment.maxExecutions = _maxExecutions; payment.createdBy = msg.sender; // We skip checking how many times the new payment was executed to allow creating new // scheduled payments before having enough vault balance _executePayment(paymentId); } /** * @notice Change period duration to `@transformTime(_periodDuration)`, effective for next accounting period * @param _periodDuration Duration in seconds for accounting periods */ function setPeriodDuration(uint64 _periodDuration) external authP(CHANGE_PERIOD_ROLE, arr(uint256(_periodDuration), uint256(settings.periodDuration))) transitionsPeriod { require(_periodDuration >= MINIMUM_PERIOD, ERROR_SET_PERIOD_TOO_SHORT); settings.periodDuration = _periodDuration; emit ChangePeriodDuration(_periodDuration); } /** * @notice Set budget for `_token.symbol(): string` to `@tokenAmount(_token, _amount, false)`, effective immediately * @param _token Address for token * @param _amount New budget amount */ function setBudget( address _token, uint256 _amount ) external authP(CHANGE_BUDGETS_ROLE, arr(_token, _amount, settings.budgets[_token], uint256(settings.hasBudget[_token] ? 1 : 0))) transitionsPeriod { settings.budgets[_token] = _amount; if (!settings.hasBudget[_token]) { settings.hasBudget[_token] = true; } emit SetBudget(_token, _amount, true); } /** * @notice Remove spending limit for `_token.symbol(): string`, effective immediately * @param _token Address for token */ function removeBudget(address _token) external authP(CHANGE_BUDGETS_ROLE, arr(_token, uint256(0), settings.budgets[_token], uint256(settings.hasBudget[_token] ? 1 : 0))) transitionsPeriod { settings.budgets[_token] = 0; settings.hasBudget[_token] = false; emit SetBudget(_token, 0, false); } /** * @notice Execute pending payment #`_paymentId` * @dev Executes any payment (requires role) * @param _paymentId Identifier for payment */ function executePayment(uint256 _paymentId) external authP(EXECUTE_PAYMENTS_ROLE, arr(_paymentId, scheduledPayments[_paymentId].amount)) scheduledPaymentExists(_paymentId) transitionsPeriod { _executePaymentAtLeastOnce(_paymentId); } /** * @notice Execute pending payment #`_paymentId` * @dev Always allow receiver of a payment to trigger execution * Initialization check is implicitly provided by `scheduledPaymentExists()` as new * scheduled payments can only be created via `newScheduledPayment(),` which requires initialization * @param _paymentId Identifier for payment */ function receiverExecutePayment(uint256 _paymentId) external scheduledPaymentExists(_paymentId) transitionsPeriod { require(scheduledPayments[_paymentId].receiver == msg.sender, ERROR_PAYMENT_RECEIVER); _executePaymentAtLeastOnce(_paymentId); } /** * @notice `_active ? 'Activate' : 'Disable'` payment #`_paymentId` * @dev Note that we do not require this action to transition periods, as it doesn't directly * impact any accounting periods. * Not having to transition periods also makes disabling payments easier to prevent funds * from being pulled out in the event of a breach. * @param _paymentId Identifier for payment * @param _active Whether it will be active or inactive */ function setPaymentStatus(uint256 _paymentId, bool _active) external authP(MANAGE_PAYMENTS_ROLE, arr(_paymentId, uint256(_active ? 1 : 0))) scheduledPaymentExists(_paymentId) { scheduledPayments[_paymentId].inactive = !_active; emit ChangePaymentState(_paymentId, _active); } /** * @notice Send tokens held in this contract to the Vault * @dev Allows making a simple payment from this contract to the Vault, to avoid locked tokens. * This contract should never receive tokens with a simple transfer call, but in case it * happens, this function allows for their recovery. * @param _token Token whose balance is going to be transferred. */ function recoverToVault(address _token) external isInitialized transitionsPeriod { uint256 amount = _token == ETH ? address(this).balance : ERC20(_token).staticBalanceOf(address(this)); require(amount > 0, ERROR_RECOVER_AMOUNT_ZERO); _deposit( _token, amount, "Recover to Vault", address(this), false ); } /** * @notice Transition accounting period if needed * @dev Transitions accounting periods if needed. For preventing OOG attacks, a maxTransitions * param is provided. If more than the specified number of periods need to be transitioned, * it will return false. * @param _maxTransitions Maximum periods that can be transitioned * @return success Boolean indicating whether the accounting period is the correct one (if false, * maxTransitions was surpased and another call is needed) */ function tryTransitionAccountingPeriod(uint64 _maxTransitions) external isInitialized returns (bool success) { return _tryTransitionAccountingPeriod(_maxTransitions); } // Getter fns /** * @dev Disable recovery escape hatch if the app has been initialized, as it could be used * maliciously to transfer funds in the Finance app to another Vault * finance#recoverToVault() should be used to recover funds to the Finance's vault */ function allowRecoverability(address) public view returns (bool) { return !hasInitialized(); } function getPayment(uint256 _paymentId) public view scheduledPaymentExists(_paymentId) returns ( address token, address receiver, uint256 amount, uint64 initialPaymentTime, uint64 interval, uint64 maxExecutions, bool inactive, uint64 executions, address createdBy ) { ScheduledPayment storage payment = scheduledPayments[_paymentId]; token = payment.token; receiver = payment.receiver; amount = payment.amount; initialPaymentTime = payment.initialPaymentTime; interval = payment.interval; maxExecutions = payment.maxExecutions; executions = payment.executions; inactive = payment.inactive; createdBy = payment.createdBy; } function getTransaction(uint256 _transactionId) public view transactionExists(_transactionId) returns ( uint64 periodId, uint256 amount, uint256 paymentId, uint64 paymentExecutionNumber, address token, address entity, bool isIncoming, uint64 date ) { Transaction storage transaction = transactions[_transactionId]; token = transaction.token; entity = transaction.entity; isIncoming = transaction.isIncoming; date = transaction.date; periodId = transaction.periodId; amount = transaction.amount; paymentId = transaction.paymentId; paymentExecutionNumber = transaction.paymentExecutionNumber; } function getPeriod(uint64 _periodId) public view periodExists(_periodId) returns ( bool isCurrent, uint64 startTime, uint64 endTime, uint256 firstTransactionId, uint256 lastTransactionId ) { Period storage period = periods[_periodId]; isCurrent = _currentPeriodId() == _periodId; startTime = period.startTime; endTime = period.endTime; firstTransactionId = period.firstTransactionId; lastTransactionId = period.lastTransactionId; } function getPeriodTokenStatement(uint64 _periodId, address _token) public view periodExists(_periodId) returns (uint256 expenses, uint256 income) { TokenStatement storage tokenStatement = periods[_periodId].tokenStatement[_token]; expenses = tokenStatement.expenses; income = tokenStatement.income; } /** * @dev We have to check for initialization as periods are only valid after initializing */ function currentPeriodId() public view isInitialized returns (uint64) { return _currentPeriodId(); } /** * @dev We have to check for initialization as periods are only valid after initializing */ function getPeriodDuration() public view isInitialized returns (uint64) { return settings.periodDuration; } /** * @dev We have to check for initialization as budgets are only valid after initializing */ function getBudget(address _token) public view isInitialized returns (uint256 budget, bool hasBudget) { budget = settings.budgets[_token]; hasBudget = settings.hasBudget[_token]; } /** * @dev We have to check for initialization as budgets are only valid after initializing */ function getRemainingBudget(address _token) public view isInitialized returns (uint256) { return _getRemainingBudget(_token); } /** * @dev We have to check for initialization as budgets are only valid after initializing */ function canMakePayment(address _token, uint256 _amount) public view isInitialized returns (bool) { return _canMakePayment(_token, _amount); } /** * @dev Initialization check is implicitly provided by `scheduledPaymentExists()` as new * scheduled payments can only be created via `newScheduledPayment(),` which requires initialization */ function nextPaymentTime(uint256 _paymentId) public view scheduledPaymentExists(_paymentId) returns (uint64) { return _nextPaymentTime(_paymentId); } // Internal fns function _deposit(address _token, uint256 _amount, string _reference, address _sender, bool _isExternalDeposit) internal { _recordIncomingTransaction( _token, _sender, _amount, _reference ); if (_token == ETH) { vault.deposit.value(_amount)(ETH, _amount); } else { // First, transfer the tokens to Finance if necessary // External deposit will be false when the assets were already in the Finance app // and just need to be transferred to the Vault if (_isExternalDeposit) { // This assumes the sender has approved the tokens for Finance require( ERC20(_token).safeTransferFrom(msg.sender, address(this), _amount), ERROR_TOKEN_TRANSFER_FROM_REVERTED ); } // Approve the tokens for the Vault (it does the actual transferring) require(ERC20(_token).safeApprove(vault, _amount), ERROR_TOKEN_APPROVE_FAILED); // Finally, initiate the deposit vault.deposit(_token, _amount); } } function _executePayment(uint256 _paymentId) internal returns (uint256) { ScheduledPayment storage payment = scheduledPayments[_paymentId]; require(!payment.inactive, ERROR_PAYMENT_INACTIVE); uint64 paid = 0; while (_nextPaymentTime(_paymentId) <= getTimestamp64() && paid < MAX_SCHEDULED_PAYMENTS_PER_TX) { if (!_canMakePayment(payment.token, payment.amount)) { emit PaymentFailure(_paymentId); break; } // The while() predicate prevents these two from ever overflowing payment.executions += 1; paid += 1; // We've already checked the remaining budget with `_canMakePayment()` _unsafeMakePaymentTransaction( payment.token, payment.receiver, payment.amount, _paymentId, payment.executions, "" ); } return paid; } function _executePaymentAtLeastOnce(uint256 _paymentId) internal { uint256 paid = _executePayment(_paymentId); if (paid == 0) { if (_nextPaymentTime(_paymentId) <= getTimestamp64()) { revert(ERROR_EXECUTE_PAYMENT_NUM); } else { revert(ERROR_EXECUTE_PAYMENT_TIME); } } } function _makePaymentTransaction( address _token, address _receiver, uint256 _amount, uint256 _paymentId, uint64 _paymentExecutionNumber, string _reference ) internal { require(_getRemainingBudget(_token) >= _amount, ERROR_REMAINING_BUDGET); _unsafeMakePaymentTransaction(_token, _receiver, _amount, _paymentId, _paymentExecutionNumber, _reference); } /** * @dev Unsafe version of _makePaymentTransaction that assumes you have already checked the * remaining budget */ function _unsafeMakePaymentTransaction( address _token, address _receiver, uint256 _amount, uint256 _paymentId, uint64 _paymentExecutionNumber, string _reference ) internal { _recordTransaction( false, _token, _receiver, _amount, _paymentId, _paymentExecutionNumber, _reference ); vault.transfer(_token, _receiver, _amount); } function _newPeriod(uint64 _startTime) internal returns (Period storage) { // There should be no way for this to overflow since each period is at least one day uint64 newPeriodId = periodsLength++; Period storage period = periods[newPeriodId]; period.startTime = _startTime; // Be careful here to not overflow; if startTime + periodDuration overflows, we set endTime // to MAX_UINT64 (let's assume that's the end of time for now). uint64 endTime = _startTime + settings.periodDuration - 1; if (endTime < _startTime) { // overflowed endTime = MAX_UINT64; } period.endTime = endTime; emit NewPeriod(newPeriodId, period.startTime, period.endTime); return period; } function _recordIncomingTransaction( address _token, address _sender, uint256 _amount, string _reference ) internal { _recordTransaction( true, // incoming transaction _token, _sender, _amount, NO_SCHEDULED_PAYMENT, // unrelated to any existing payment 0, // and no payment executions _reference ); } function _recordTransaction( bool _incoming, address _token, address _entity, uint256 _amount, uint256 _paymentId, uint64 _paymentExecutionNumber, string _reference ) internal { uint64 periodId = _currentPeriodId(); TokenStatement storage tokenStatement = periods[periodId].tokenStatement[_token]; if (_incoming) { tokenStatement.income = tokenStatement.income.add(_amount); } else { tokenStatement.expenses = tokenStatement.expenses.add(_amount); } uint256 transactionId = transactionsNextIndex++; Transaction storage transaction = transactions[transactionId]; transaction.token = _token; transaction.entity = _entity; transaction.isIncoming = _incoming; transaction.amount = _amount; transaction.paymentId = _paymentId; transaction.paymentExecutionNumber = _paymentExecutionNumber; transaction.date = getTimestamp64(); transaction.periodId = periodId; Period storage period = periods[periodId]; if (period.firstTransactionId == NO_TRANSACTION) { period.firstTransactionId = transactionId; } emit NewTransaction(transactionId, _incoming, _entity, _amount, _reference); } function _tryTransitionAccountingPeriod(uint64 _maxTransitions) internal returns (bool success) { Period storage currentPeriod = periods[_currentPeriodId()]; uint64 timestamp = getTimestamp64(); // Transition periods if necessary while (timestamp > currentPeriod.endTime) { if (_maxTransitions == 0) { // Required number of transitions is over allowed number, return false indicating // it didn't fully transition return false; } // We're already protected from underflowing above _maxTransitions -= 1; // If there were any transactions in period, record which was the last // In case 0 transactions occured, first and last tx id will be 0 if (currentPeriod.firstTransactionId != NO_TRANSACTION) { currentPeriod.lastTransactionId = transactionsNextIndex.sub(1); } // New period starts at end time + 1 currentPeriod = _newPeriod(currentPeriod.endTime.add(1)); } return true; } function _canMakePayment(address _token, uint256 _amount) internal view returns (bool) { return _getRemainingBudget(_token) >= _amount && vault.balance(_token) >= _amount; } function _currentPeriodId() internal view returns (uint64) { // There is no way for this to overflow if protected by an initialization check return periodsLength - 1; } function _getRemainingBudget(address _token) internal view returns (uint256) { if (!settings.hasBudget[_token]) { return MAX_UINT256; } uint256 budget = settings.budgets[_token]; uint256 spent = periods[_currentPeriodId()].tokenStatement[_token].expenses; // A budget decrease can cause the spent amount to be greater than period budget // If so, return 0 to not allow more spending during period if (spent >= budget) { return 0; } // We're already protected from the overflow above return budget - spent; } function _nextPaymentTime(uint256 _paymentId) internal view returns (uint64) { ScheduledPayment storage payment = scheduledPayments[_paymentId]; if (payment.executions >= payment.maxExecutions) { return MAX_UINT64; // re-executes in some billions of years time... should not need to worry } // Split in multiple lines to circumvent linter warning uint64 increase = payment.executions.mul(payment.interval); uint64 nextPayment = payment.initialPaymentTime.add(increase); return nextPayment; } // Syntax sugar function _arr(address _a, address _b, uint256 _c, uint256 _d, uint256 _e, uint256 _f) internal pure returns (uint256[] r) { r = new uint256[](6); r[0] = uint256(_a); r[1] = uint256(_b); r[2] = _c; r[3] = _d; r[4] = _e; r[5] = _f; } // Mocked fns (overrided during testing) // Must be view for mocking purposes function getMaxPeriodTransitions() internal view returns (uint64) { return MAX_UINT64; } } // File: @aragon/apps-payroll/contracts/Payroll.sol pragma solidity 0.4.24; /** * @title Payroll in multiple currencies */ contract Payroll is EtherTokenConstant, IForwarder, IsContract, AragonApp { using SafeMath for uint256; using SafeMath64 for uint64; /* Hardcoded constants to save gas * bytes32 constant public ADD_EMPLOYEE_ROLE = keccak256("ADD_EMPLOYEE_ROLE"); * bytes32 constant public TERMINATE_EMPLOYEE_ROLE = keccak256("TERMINATE_EMPLOYEE_ROLE"); * bytes32 constant public SET_EMPLOYEE_SALARY_ROLE = keccak256("SET_EMPLOYEE_SALARY_ROLE"); * bytes32 constant public ADD_BONUS_ROLE = keccak256("ADD_BONUS_ROLE"); * bytes32 constant public ADD_REIMBURSEMENT_ROLE = keccak256("ADD_REIMBURSEMENT_ROLE"); * bytes32 constant public MANAGE_ALLOWED_TOKENS_ROLE = keccak256("MANAGE_ALLOWED_TOKENS_ROLE"); * bytes32 constant public MODIFY_PRICE_FEED_ROLE = keccak256("MODIFY_PRICE_FEED_ROLE"); * bytes32 constant public MODIFY_RATE_EXPIRY_ROLE = keccak256("MODIFY_RATE_EXPIRY_ROLE"); */ bytes32 constant public ADD_EMPLOYEE_ROLE = 0x9ecdc3c63716b45d0756eece5fe1614cae1889ec5a1ce62b3127c1f1f1615d6e; bytes32 constant public TERMINATE_EMPLOYEE_ROLE = 0x69c67f914d12b6440e7ddf01961214818d9158fbcb19211e0ff42800fdea9242; bytes32 constant public SET_EMPLOYEE_SALARY_ROLE = 0xea9ac65018da2421cf419ee2152371440c08267a193a33ccc1e39545d197e44d; bytes32 constant public ADD_BONUS_ROLE = 0xceca7e2f5eb749a87aaf68f3f76d6b9251aa2f4600f13f93c5a4adf7a72df4ae; bytes32 constant public ADD_REIMBURSEMENT_ROLE = 0x90698b9d54427f1e41636025017309bdb1b55320da960c8845bab0a504b01a16; bytes32 constant public MANAGE_ALLOWED_TOKENS_ROLE = 0x0be34987c45700ee3fae8c55e270418ba903337decc6bacb1879504be9331c06; bytes32 constant public MODIFY_PRICE_FEED_ROLE = 0x74350efbcba8b85341c5bbf70cc34e2a585fc1463524773a12fa0a71d4eb9302; bytes32 constant public MODIFY_RATE_EXPIRY_ROLE = 0x79fe989a8899060dfbdabb174ebb96616fa9f1d9dadd739f8d814cbab452404e; uint256 internal constant MAX_ALLOWED_TOKENS = 20; // prevent OOG issues with `payday()` uint64 internal constant MIN_RATE_EXPIRY = uint64(1 minutes); // 1 min == ~4 block window to mine both a price feed update and a payout uint256 internal constant MAX_UINT256 = uint256(-1); uint64 internal constant MAX_UINT64 = uint64(-1); string private constant ERROR_EMPLOYEE_DOESNT_EXIST = "PAYROLL_EMPLOYEE_DOESNT_EXIST"; string private constant ERROR_NON_ACTIVE_EMPLOYEE = "PAYROLL_NON_ACTIVE_EMPLOYEE"; string private constant ERROR_SENDER_DOES_NOT_MATCH = "PAYROLL_SENDER_DOES_NOT_MATCH"; string private constant ERROR_FINANCE_NOT_CONTRACT = "PAYROLL_FINANCE_NOT_CONTRACT"; string private constant ERROR_TOKEN_ALREADY_SET = "PAYROLL_TOKEN_ALREADY_SET"; string private constant ERROR_MAX_ALLOWED_TOKENS = "PAYROLL_MAX_ALLOWED_TOKENS"; string private constant ERROR_MIN_RATES_MISMATCH = "PAYROLL_MIN_RATES_MISMATCH"; string private constant ERROR_TOKEN_ALLOCATION_MISMATCH = "PAYROLL_TOKEN_ALLOCATION_MISMATCH"; string private constant ERROR_NOT_ALLOWED_TOKEN = "PAYROLL_NOT_ALLOWED_TOKEN"; string private constant ERROR_DISTRIBUTION_NOT_FULL = "PAYROLL_DISTRIBUTION_NOT_FULL"; string private constant ERROR_INVALID_PAYMENT_TYPE = "PAYROLL_INVALID_PAYMENT_TYPE"; string private constant ERROR_NOTHING_PAID = "PAYROLL_NOTHING_PAID"; string private constant ERROR_CAN_NOT_FORWARD = "PAYROLL_CAN_NOT_FORWARD"; string private constant ERROR_EMPLOYEE_NULL_ADDRESS = "PAYROLL_EMPLOYEE_NULL_ADDRESS"; string private constant ERROR_EMPLOYEE_ALREADY_EXIST = "PAYROLL_EMPLOYEE_ALREADY_EXIST"; string private constant ERROR_FEED_NOT_CONTRACT = "PAYROLL_FEED_NOT_CONTRACT"; string private constant ERROR_EXPIRY_TIME_TOO_SHORT = "PAYROLL_EXPIRY_TIME_TOO_SHORT"; string private constant ERROR_PAST_TERMINATION_DATE = "PAYROLL_PAST_TERMINATION_DATE"; string private constant ERROR_EXCHANGE_RATE_TOO_LOW = "PAYROLL_EXCHANGE_RATE_TOO_LOW"; string private constant ERROR_LAST_PAYROLL_DATE_TOO_BIG = "PAYROLL_LAST_DATE_TOO_BIG"; string private constant ERROR_INVALID_REQUESTED_AMOUNT = "PAYROLL_INVALID_REQUESTED_AMT"; enum PaymentType { Payroll, Reimbursement, Bonus } struct Employee { address accountAddress; // unique, but can be changed over time uint256 denominationTokenSalary; // salary per second in denomination Token uint256 accruedSalary; // keep track of any leftover accrued salary when changing salaries uint256 bonus; uint256 reimbursements; uint64 lastPayroll; uint64 endDate; address[] allocationTokenAddresses; mapping(address => uint256) allocationTokens; } Finance public finance; address public denominationToken; IFeed public feed; uint64 public rateExpiryTime; // Employees start at index 1, to allow us to use employees[0] to check for non-existent employees uint256 public nextEmployee; mapping(uint256 => Employee) internal employees; // employee ID -> employee mapping(address => uint256) internal employeeIds; // employee address -> employee ID mapping(address => bool) internal allowedTokens; event AddEmployee( uint256 indexed employeeId, address indexed accountAddress, uint256 initialDenominationSalary, uint64 startDate, string role ); event TerminateEmployee(uint256 indexed employeeId, uint64 endDate); event SetEmployeeSalary(uint256 indexed employeeId, uint256 denominationSalary); event AddEmployeeAccruedSalary(uint256 indexed employeeId, uint256 amount); event AddEmployeeBonus(uint256 indexed employeeId, uint256 amount); event AddEmployeeReimbursement(uint256 indexed employeeId, uint256 amount); event ChangeAddressByEmployee(uint256 indexed employeeId, address indexed newAccountAddress, address indexed oldAccountAddress); event DetermineAllocation(uint256 indexed employeeId); event SendPayment( uint256 indexed employeeId, address indexed accountAddress, address indexed token, uint256 amount, uint256 exchangeRate, string paymentReference ); event SetAllowedToken(address indexed token, bool allowed); event SetPriceFeed(address indexed feed); event SetRateExpiryTime(uint64 time); // Check employee exists by ID modifier employeeIdExists(uint256 _employeeId) { require(_employeeExists(_employeeId), ERROR_EMPLOYEE_DOESNT_EXIST); _; } // Check employee exists and is still active modifier employeeActive(uint256 _employeeId) { // No need to check for existence as _isEmployeeIdActive() is false for non-existent employees require(_isEmployeeIdActive(_employeeId), ERROR_NON_ACTIVE_EMPLOYEE); _; } // Check sender matches an existing employee modifier employeeMatches { require(employees[employeeIds[msg.sender]].accountAddress == msg.sender, ERROR_SENDER_DOES_NOT_MATCH); _; } /** * @notice Initialize Payroll app for Finance at `_finance` and price feed at `_priceFeed`, setting denomination token to `_token` and exchange rate expiry time to `@transformTime(_rateExpiryTime)` * @dev Note that we do not require _denominationToken to be a contract, as it may be a "fake" * address used by the price feed to denominate fiat currencies * @param _finance Address of the Finance app this Payroll app will rely on for payments (non-changeable) * @param _denominationToken Address of the denomination token used for salary accounting * @param _priceFeed Address of the price feed * @param _rateExpiryTime Acceptable expiry time in seconds for the price feed's exchange rates */ function initialize(Finance _finance, address _denominationToken, IFeed _priceFeed, uint64 _rateExpiryTime) external onlyInit { initialized(); require(isContract(_finance), ERROR_FINANCE_NOT_CONTRACT); finance = _finance; denominationToken = _denominationToken; _setPriceFeed(_priceFeed); _setRateExpiryTime(_rateExpiryTime); // Employees start at index 1, to allow us to use employees[0] to check for non-existent employees nextEmployee = 1; } /** * @notice `_allowed ? 'Add' : 'Remove'` `_token.symbol(): string` `_allowed ? 'to' : 'from'` the set of allowed tokens * @param _token Address of the token to be added or removed from the list of allowed tokens for payments * @param _allowed Boolean to tell whether the given token should be added or removed from the list */ function setAllowedToken(address _token, bool _allowed) external authP(MANAGE_ALLOWED_TOKENS_ROLE, arr(_token)) { require(allowedTokens[_token] != _allowed, ERROR_TOKEN_ALREADY_SET); allowedTokens[_token] = _allowed; emit SetAllowedToken(_token, _allowed); } /** * @notice Set the price feed for exchange rates to `_feed` * @param _feed Address of the new price feed instance */ function setPriceFeed(IFeed _feed) external authP(MODIFY_PRICE_FEED_ROLE, arr(_feed, feed)) { _setPriceFeed(_feed); } /** * @notice Set the acceptable expiry time for the price feed's exchange rates to `@transformTime(_time)` * @dev Exchange rates older than the given value won't be accepted for payments and will cause payouts to revert * @param _time The expiration time in seconds for exchange rates */ function setRateExpiryTime(uint64 _time) external authP(MODIFY_RATE_EXPIRY_ROLE, arr(uint256(_time), uint256(rateExpiryTime))) { _setRateExpiryTime(_time); } /** * @notice Add employee with address `_accountAddress` to payroll with an salary of `_initialDenominationSalary` per second, starting on `@formatDate(_startDate)` * @param _accountAddress Employee's address to receive payroll * @param _initialDenominationSalary Employee's salary, per second in denomination token * @param _startDate Employee's starting timestamp in seconds (it actually sets their initial lastPayroll value) * @param _role Employee's role */ function addEmployee(address _accountAddress, uint256 _initialDenominationSalary, uint64 _startDate, string _role) external authP(ADD_EMPLOYEE_ROLE, arr(_accountAddress, _initialDenominationSalary, uint256(_startDate))) { _addEmployee(_accountAddress, _initialDenominationSalary, _startDate, _role); } /** * @notice Add `_amount` to bonus for employee #`_employeeId` * @param _employeeId Employee's identifier * @param _amount Amount to be added to the employee's bonuses in denomination token */ function addBonus(uint256 _employeeId, uint256 _amount) external authP(ADD_BONUS_ROLE, arr(_employeeId, _amount)) employeeActive(_employeeId) { _addBonus(_employeeId, _amount); } /** * @notice Add `_amount` to reimbursements for employee #`_employeeId` * @param _employeeId Employee's identifier * @param _amount Amount to be added to the employee's reimbursements in denomination token */ function addReimbursement(uint256 _employeeId, uint256 _amount) external authP(ADD_REIMBURSEMENT_ROLE, arr(_employeeId, _amount)) employeeActive(_employeeId) { _addReimbursement(_employeeId, _amount); } /** * @notice Set employee #`_employeeId`'s salary to `_denominationSalary` per second * @dev This reverts if either the employee's owed salary or accrued salary overflows, to avoid * losing any accrued salary for an employee due to the employer changing their salary. * @param _employeeId Employee's identifier * @param _denominationSalary Employee's new salary, per second in denomination token */ function setEmployeeSalary(uint256 _employeeId, uint256 _denominationSalary) external authP(SET_EMPLOYEE_SALARY_ROLE, arr(_employeeId, _denominationSalary, employees[_employeeId].denominationTokenSalary)) employeeActive(_employeeId) { Employee storage employee = employees[_employeeId]; // Accrue employee's owed salary; don't cap to revert on overflow uint256 owed = _getOwedSalarySinceLastPayroll(employee, false); _addAccruedSalary(_employeeId, owed); // Update employee to track the new salary and payment date employee.lastPayroll = getTimestamp64(); employee.denominationTokenSalary = _denominationSalary; emit SetEmployeeSalary(_employeeId, _denominationSalary); } /** * @notice Terminate employee #`_employeeId` on `@formatDate(_endDate)` * @param _employeeId Employee's identifier * @param _endDate Termination timestamp in seconds */ function terminateEmployee(uint256 _employeeId, uint64 _endDate) external authP(TERMINATE_EMPLOYEE_ROLE, arr(_employeeId, uint256(_endDate))) employeeActive(_employeeId) { _terminateEmployee(_employeeId, _endDate); } /** * @notice Change your employee account address to `_newAccountAddress` * @dev Initialization check is implicitly provided by `employeeMatches` as new employees can * only be added via `addEmployee(),` which requires initialization. * As the employee is allowed to call this, we enforce non-reentrancy. * @param _newAccountAddress New address to receive payments for the requesting employee */ function changeAddressByEmployee(address _newAccountAddress) external employeeMatches nonReentrant { uint256 employeeId = employeeIds[msg.sender]; address oldAddress = employees[employeeId].accountAddress; _setEmployeeAddress(employeeId, _newAccountAddress); // Don't delete the old address until after setting the new address to check that the // employee specified a new address delete employeeIds[oldAddress]; emit ChangeAddressByEmployee(employeeId, _newAccountAddress, oldAddress); } /** * @notice Set the token distribution for your payments * @dev Initialization check is implicitly provided by `employeeMatches` as new employees can * only be added via `addEmployee(),` which requires initialization. * As the employee is allowed to call this, we enforce non-reentrancy. * @param _tokens Array of token addresses; they must belong to the list of allowed tokens * @param _distribution Array with each token's corresponding proportions (must be integers summing to 100) */ function determineAllocation(address[] _tokens, uint256[] _distribution) external employeeMatches nonReentrant { // Check array lengthes match require(_tokens.length <= MAX_ALLOWED_TOKENS, ERROR_MAX_ALLOWED_TOKENS); require(_tokens.length == _distribution.length, ERROR_TOKEN_ALLOCATION_MISMATCH); uint256 employeeId = employeeIds[msg.sender]; Employee storage employee = employees[employeeId]; // Delete previous token allocations address[] memory previousAllowedTokenAddresses = employee.allocationTokenAddresses; for (uint256 j = 0; j < previousAllowedTokenAddresses.length; j++) { delete employee.allocationTokens[previousAllowedTokenAddresses[j]]; } delete employee.allocationTokenAddresses; // Set distributions only if given tokens are allowed for (uint256 i = 0; i < _tokens.length; i++) { employee.allocationTokenAddresses.push(_tokens[i]); employee.allocationTokens[_tokens[i]] = _distribution[i]; } _ensureEmployeeTokenAllocationsIsValid(employee); emit DetermineAllocation(employeeId); } /** * @notice Request your `_type == 0 ? 'salary' : _type == 1 ? 'reimbursements' : 'bonus'` * @dev Reverts if no payments were made. * Initialization check is implicitly provided by `employeeMatches` as new employees can * only be added via `addEmployee(),` which requires initialization. * As the employee is allowed to call this, we enforce non-reentrancy. * @param _type Payment type being requested (Payroll, Reimbursement or Bonus) * @param _requestedAmount Requested amount to pay for the payment type. Must be less than or equal to total owed amount for the payment type, or zero to request all. * @param _minRates Array of employee's minimum acceptable rates for their allowed payment tokens */ function payday(PaymentType _type, uint256 _requestedAmount, uint256[] _minRates) external employeeMatches nonReentrant { uint256 paymentAmount; uint256 employeeId = employeeIds[msg.sender]; Employee storage employee = employees[employeeId]; _ensureEmployeeTokenAllocationsIsValid(employee); require(_minRates.length == 0 || _minRates.length == employee.allocationTokenAddresses.length, ERROR_MIN_RATES_MISMATCH); // Do internal employee accounting if (_type == PaymentType.Payroll) { // Salary is capped here to avoid reverting at this point if it becomes too big // (so employees aren't DDOSed if their salaries get too large) // If we do use a capped value, the employee's lastPayroll date will be adjusted accordingly uint256 totalOwedSalary = _getTotalOwedCappedSalary(employee); paymentAmount = _ensurePaymentAmount(totalOwedSalary, _requestedAmount); _updateEmployeeAccountingBasedOnPaidSalary(employee, paymentAmount); } else if (_type == PaymentType.Reimbursement) { uint256 owedReimbursements = employee.reimbursements; paymentAmount = _ensurePaymentAmount(owedReimbursements, _requestedAmount); employee.reimbursements = owedReimbursements.sub(paymentAmount); } else if (_type == PaymentType.Bonus) { uint256 owedBonusAmount = employee.bonus; paymentAmount = _ensurePaymentAmount(owedBonusAmount, _requestedAmount); employee.bonus = owedBonusAmount.sub(paymentAmount); } else { revert(ERROR_INVALID_PAYMENT_TYPE); } // Actually transfer the owed funds require(_transferTokensAmount(employeeId, _type, paymentAmount, _minRates), ERROR_NOTHING_PAID); _removeEmployeeIfTerminatedAndPaidOut(employeeId); } // Forwarding fns /** * @dev IForwarder interface conformance. Tells whether the Payroll app is a forwarder or not. * @return Always true */ function isForwarder() external pure returns (bool) { return true; } /** * @notice Execute desired action as an active employee * @dev IForwarder interface conformance. Allows active employees to run EVMScripts in the context of the Payroll app. * @param _evmScript Script being executed */ function forward(bytes _evmScript) public { require(canForward(msg.sender, _evmScript), ERROR_CAN_NOT_FORWARD); bytes memory input = new bytes(0); // TODO: Consider input for this // Add the Finance app to the blacklist to disallow employees from executing actions on the // Finance app from Payroll's context (since Payroll requires permissions on Finance) address[] memory blacklist = new address[](1); blacklist[0] = address(finance); runScript(_evmScript, input, blacklist); } /** * @dev IForwarder interface conformance. Tells whether a given address can forward actions or not. * @param _sender Address of the account intending to forward an action * @return True if the given address is an active employee, false otherwise */ function canForward(address _sender, bytes) public view returns (bool) { return _isEmployeeIdActive(employeeIds[_sender]); } // Getter fns /** * @dev Return employee's identifier by their account address * @param _accountAddress Employee's address to receive payments * @return Employee's identifier */ function getEmployeeIdByAddress(address _accountAddress) public view returns (uint256) { require(employeeIds[_accountAddress] != uint256(0), ERROR_EMPLOYEE_DOESNT_EXIST); return employeeIds[_accountAddress]; } /** * @dev Return all information for employee by their ID * @param _employeeId Employee's identifier * @return Employee's address to receive payments * @return Employee's salary, per second in denomination token * @return Employee's accrued salary * @return Employee's bonus amount * @return Employee's reimbursements amount * @return Employee's last payment date * @return Employee's termination date (max uint64 if none) * @return Employee's allowed payment tokens */ function getEmployee(uint256 _employeeId) public view employeeIdExists(_employeeId) returns ( address accountAddress, uint256 denominationSalary, uint256 accruedSalary, uint256 bonus, uint256 reimbursements, uint64 lastPayroll, uint64 endDate, address[] allocationTokens ) { Employee storage employee = employees[_employeeId]; accountAddress = employee.accountAddress; denominationSalary = employee.denominationTokenSalary; accruedSalary = employee.accruedSalary; bonus = employee.bonus; reimbursements = employee.reimbursements; lastPayroll = employee.lastPayroll; endDate = employee.endDate; allocationTokens = employee.allocationTokenAddresses; } /** * @dev Get owed salary since last payroll for an employee. It will take into account the accrued salary as well. * The result will be capped to max uint256 to avoid having an overflow. * @return Employee's total owed salary: current owed payroll since the last payroll date, plus the accrued salary. */ function getTotalOwedSalary(uint256 _employeeId) public view employeeIdExists(_employeeId) returns (uint256) { return _getTotalOwedCappedSalary(employees[_employeeId]); } /** * @dev Get an employee's payment allocation for a token * @param _employeeId Employee's identifier * @param _token Token to query the payment allocation for * @return Employee's payment allocation for the token being queried */ function getAllocation(uint256 _employeeId, address _token) public view employeeIdExists(_employeeId) returns (uint256) { return employees[_employeeId].allocationTokens[_token]; } /** * @dev Check if a token is allowed to be used for payments * @param _token Address of the token to be checked * @return True if the given token is allowed, false otherwise */ function isTokenAllowed(address _token) public view isInitialized returns (bool) { return allowedTokens[_token]; } // Internal fns /** * @dev Set the price feed used for exchange rates * @param _feed Address of the new price feed instance */ function _setPriceFeed(IFeed _feed) internal { require(isContract(_feed), ERROR_FEED_NOT_CONTRACT); feed = _feed; emit SetPriceFeed(feed); } /** * @dev Set the exchange rate expiry time in seconds. * Exchange rates older than the given value won't be accepted for payments and will cause * payouts to revert. * @param _time The expiration time in seconds for exchange rates */ function _setRateExpiryTime(uint64 _time) internal { // Require a sane minimum for the rate expiry time require(_time >= MIN_RATE_EXPIRY, ERROR_EXPIRY_TIME_TOO_SHORT); rateExpiryTime = _time; emit SetRateExpiryTime(rateExpiryTime); } /** * @dev Add a new employee to Payroll * @param _accountAddress Employee's address to receive payroll * @param _initialDenominationSalary Employee's salary, per second in denomination token * @param _startDate Employee's starting timestamp in seconds * @param _role Employee's role */ function _addEmployee(address _accountAddress, uint256 _initialDenominationSalary, uint64 _startDate, string _role) internal { uint256 employeeId = nextEmployee++; _setEmployeeAddress(employeeId, _accountAddress); Employee storage employee = employees[employeeId]; employee.denominationTokenSalary = _initialDenominationSalary; employee.lastPayroll = _startDate; employee.endDate = MAX_UINT64; emit AddEmployee(employeeId, _accountAddress, _initialDenominationSalary, _startDate, _role); } /** * @dev Add amount to an employee's bonuses * @param _employeeId Employee's identifier * @param _amount Amount be added to the employee's bonuses in denomination token */ function _addBonus(uint256 _employeeId, uint256 _amount) internal { Employee storage employee = employees[_employeeId]; employee.bonus = employee.bonus.add(_amount); emit AddEmployeeBonus(_employeeId, _amount); } /** * @dev Add amount to an employee's reimbursements * @param _employeeId Employee's identifier * @param _amount Amount be added to the employee's reimbursements in denomination token */ function _addReimbursement(uint256 _employeeId, uint256 _amount) internal { Employee storage employee = employees[_employeeId]; employee.reimbursements = employee.reimbursements.add(_amount); emit AddEmployeeReimbursement(_employeeId, _amount); } /** * @dev Add amount to an employee's accrued salary * @param _employeeId Employee's identifier * @param _amount Amount be added to the employee's accrued salary in denomination token */ function _addAccruedSalary(uint256 _employeeId, uint256 _amount) internal { Employee storage employee = employees[_employeeId]; employee.accruedSalary = employee.accruedSalary.add(_amount); emit AddEmployeeAccruedSalary(_employeeId, _amount); } /** * @dev Set an employee's account address * @param _employeeId Employee's identifier * @param _accountAddress Employee's address to receive payroll */ function _setEmployeeAddress(uint256 _employeeId, address _accountAddress) internal { // Check address is non-null require(_accountAddress != address(0), ERROR_EMPLOYEE_NULL_ADDRESS); // Check address isn't already being used require(employeeIds[_accountAddress] == uint256(0), ERROR_EMPLOYEE_ALREADY_EXIST); employees[_employeeId].accountAddress = _accountAddress; // Create IDs mapping employeeIds[_accountAddress] = _employeeId; } /** * @dev Terminate employee on end date * @param _employeeId Employee's identifier * @param _endDate Termination timestamp in seconds */ function _terminateEmployee(uint256 _employeeId, uint64 _endDate) internal { // Prevent past termination dates require(_endDate >= getTimestamp64(), ERROR_PAST_TERMINATION_DATE); employees[_employeeId].endDate = _endDate; emit TerminateEmployee(_employeeId, _endDate); } /** * @dev Loop over allowed tokens to send requested amount to the employee in their desired allocation * @param _employeeId Employee's identifier * @param _totalAmount Total amount to be transferred to the employee distributed in accordance to the employee's token allocation. * @param _type Payment type being transferred (Payroll, Reimbursement or Bonus) * @param _minRates Array of employee's minimum acceptable rates for their allowed payment tokens * @return True if there was at least one token transfer */ function _transferTokensAmount(uint256 _employeeId, PaymentType _type, uint256 _totalAmount, uint256[] _minRates) internal returns (bool somethingPaid) { if (_totalAmount == 0) { return false; } Employee storage employee = employees[_employeeId]; address employeeAddress = employee.accountAddress; string memory paymentReference = _paymentReferenceFor(_type); address[] storage allocationTokenAddresses = employee.allocationTokenAddresses; for (uint256 i = 0; i < allocationTokenAddresses.length; i++) { address token = allocationTokenAddresses[i]; uint256 tokenAllocation = employee.allocationTokens[token]; if (tokenAllocation != uint256(0)) { // Get the exchange rate for the payout token in denomination token, // as we do accounting in denomination tokens uint256 exchangeRate = _getExchangeRateInDenominationToken(token); require(_minRates.length > 0 ? exchangeRate >= _minRates[i] : exchangeRate > 0, ERROR_EXCHANGE_RATE_TOO_LOW); // Convert amount (in denomination tokens) to payout token and apply allocation uint256 tokenAmount = _totalAmount.mul(exchangeRate).mul(tokenAllocation); // Divide by 100 for the allocation percentage and by the exchange rate precision tokenAmount = tokenAmount.div(100).div(feed.ratePrecision()); // Finance reverts if the payment wasn't possible finance.newImmediatePayment(token, employeeAddress, tokenAmount, paymentReference); emit SendPayment(_employeeId, employeeAddress, token, tokenAmount, exchangeRate, paymentReference); somethingPaid = true; } } } /** * @dev Remove employee if there are no owed funds and employee's end date has been reached * @param _employeeId Employee's identifier */ function _removeEmployeeIfTerminatedAndPaidOut(uint256 _employeeId) internal { Employee storage employee = employees[_employeeId]; if ( employee.lastPayroll == employee.endDate && (employee.accruedSalary == 0 && employee.bonus == 0 && employee.reimbursements == 0) ) { delete employeeIds[employee.accountAddress]; delete employees[_employeeId]; } } /** * @dev Updates the accrued salary and payroll date of an employee based on a payment amount and * their currently owed salary since last payroll date * @param _employee Employee struct in storage * @param _paymentAmount Amount being paid to the employee */ function _updateEmployeeAccountingBasedOnPaidSalary(Employee storage _employee, uint256 _paymentAmount) internal { uint256 accruedSalary = _employee.accruedSalary; if (_paymentAmount <= accruedSalary) { // Employee is only cashing out some previously owed salary so we don't need to update // their last payroll date // No need to use SafeMath as we already know _paymentAmount <= accruedSalary _employee.accruedSalary = accruedSalary - _paymentAmount; return; } // Employee is cashing out some of their currently owed salary so their last payroll date // needs to be modified based on the amount of salary paid uint256 currentSalaryPaid = _paymentAmount; if (accruedSalary > 0) { // Employee is cashing out a mixed amount between previous and current owed salaries; // first use up their accrued salary // No need to use SafeMath here as we already know _paymentAmount > accruedSalary currentSalaryPaid = _paymentAmount - accruedSalary; // We finally need to clear their accrued salary _employee.accruedSalary = 0; } uint256 salary = _employee.denominationTokenSalary; uint256 timeDiff = currentSalaryPaid.div(salary); // If they're being paid an amount that doesn't match perfectly with the adjusted time // (up to a seconds' worth of salary), add the second and put the extra remaining salary // into their accrued salary uint256 extraSalary = currentSalaryPaid % salary; if (extraSalary > 0) { timeDiff = timeDiff.add(1); _employee.accruedSalary = salary - extraSalary; } uint256 lastPayrollDate = uint256(_employee.lastPayroll).add(timeDiff); // Even though this function should never receive a currentSalaryPaid value that would // result in the lastPayrollDate being higher than the current time, // let's double check to be safe require(lastPayrollDate <= uint256(getTimestamp64()), ERROR_LAST_PAYROLL_DATE_TOO_BIG); // Already know lastPayrollDate must fit in uint64 from above _employee.lastPayroll = uint64(lastPayrollDate); } /** * @dev Tell whether an employee is registered in this Payroll or not * @param _employeeId Employee's identifier * @return True if the given employee ID belongs to an registered employee, false otherwise */ function _employeeExists(uint256 _employeeId) internal view returns (bool) { return employees[_employeeId].accountAddress != address(0); } /** * @dev Tell whether an employee has a valid token allocation or not. * A valid allocation is one that sums to 100 and only includes allowed tokens. * @param _employee Employee struct in storage * @return Reverts if employee's allocation is invalid */ function _ensureEmployeeTokenAllocationsIsValid(Employee storage _employee) internal view { uint256 sum = 0; address[] memory allocationTokenAddresses = _employee.allocationTokenAddresses; for (uint256 i = 0; i < allocationTokenAddresses.length; i++) { address token = allocationTokenAddresses[i]; require(allowedTokens[token], ERROR_NOT_ALLOWED_TOKEN); sum = sum.add(_employee.allocationTokens[token]); } require(sum == 100, ERROR_DISTRIBUTION_NOT_FULL); } /** * @dev Tell whether an employee is still active or not * @param _employee Employee struct in storage * @return True if the employee exists and has an end date that has not been reached yet, false otherwise */ function _isEmployeeActive(Employee storage _employee) internal view returns (bool) { return _employee.endDate >= getTimestamp64(); } /** * @dev Tell whether an employee id is still active or not * @param _employeeId Employee's identifier * @return True if the employee exists and has an end date that has not been reached yet, false otherwise */ function _isEmployeeIdActive(uint256 _employeeId) internal view returns (bool) { return _isEmployeeActive(employees[_employeeId]); } /** * @dev Get exchange rate for a token based on the denomination token. * As an example, if the denomination token was USD and ETH's price was 100USD, * this would return 0.01 * precision rate for ETH. * @param _token Token to get price of in denomination tokens * @return Exchange rate (multiplied by the PPF rate precision) */ function _getExchangeRateInDenominationToken(address _token) internal view returns (uint256) { // xrt is the number of `_token` that can be exchanged for one `denominationToken` (uint128 xrt, uint64 when) = feed.get( denominationToken, // Base (e.g. USD) _token // Quote (e.g. ETH) ); // Check the price feed is recent enough if (getTimestamp64().sub(when) >= rateExpiryTime) { return 0; } return uint256(xrt); } /** * @dev Get owed salary since last payroll for an employee * @param _employee Employee struct in storage * @param _capped Safely cap the owed salary at max uint * @return Owed salary in denomination tokens since last payroll for the employee. * If _capped is false, it reverts in case of an overflow. */ function _getOwedSalarySinceLastPayroll(Employee storage _employee, bool _capped) internal view returns (uint256) { uint256 timeDiff = _getOwedPayrollPeriod(_employee); if (timeDiff == 0) { return 0; } uint256 salary = _employee.denominationTokenSalary; if (_capped) { // Return max uint if the result overflows uint256 result = salary * timeDiff; return (result / timeDiff != salary) ? MAX_UINT256 : result; } else { return salary.mul(timeDiff); } } /** * @dev Get owed payroll period for an employee * @param _employee Employee struct in storage * @return Owed time in seconds since the employee's last payroll date */ function _getOwedPayrollPeriod(Employee storage _employee) internal view returns (uint256) { // Get the min of current date and termination date uint64 date = _isEmployeeActive(_employee) ? getTimestamp64() : _employee.endDate; // Make sure we don't revert if we try to get the owed salary for an employee whose last // payroll date is now or in the future // This can happen either by adding new employees with start dates in the future, to allow // us to change their salary before their start date, or by terminating an employee and // paying out their full owed salary if (date <= _employee.lastPayroll) { return 0; } // Return time diff in seconds, no need to use SafeMath as the underflow was covered by the previous check return uint256(date - _employee.lastPayroll); } /** * @dev Get owed salary since last payroll for an employee. It will take into account the accrued salary as well. * The result will be capped to max uint256 to avoid having an overflow. * @param _employee Employee struct in storage * @return Employee's total owed salary: current owed payroll since the last payroll date, plus the accrued salary. */ function _getTotalOwedCappedSalary(Employee storage _employee) internal view returns (uint256) { uint256 currentOwedSalary = _getOwedSalarySinceLastPayroll(_employee, true); // cap amount uint256 totalOwedSalary = currentOwedSalary + _employee.accruedSalary; if (totalOwedSalary < currentOwedSalary) { totalOwedSalary = MAX_UINT256; } return totalOwedSalary; } /** * @dev Get payment reference for a given payment type * @param _type Payment type to query the reference of * @return Payment reference for the given payment type */ function _paymentReferenceFor(PaymentType _type) internal pure returns (string memory) { if (_type == PaymentType.Payroll) { return "Employee salary"; } else if (_type == PaymentType.Reimbursement) { return "Employee reimbursement"; } if (_type == PaymentType.Bonus) { return "Employee bonus"; } revert(ERROR_INVALID_PAYMENT_TYPE); } function _ensurePaymentAmount(uint256 _owedAmount, uint256 _requestedAmount) private pure returns (uint256) { require(_owedAmount > 0, ERROR_NOTHING_PAID); require(_owedAmount >= _requestedAmount, ERROR_INVALID_REQUESTED_AMOUNT); return _requestedAmount > 0 ? _requestedAmount : _owedAmount; } } // File: @aragon/apps-token-manager/contracts/TokenManager.sol /* * SPDX-License-Identitifer: GPL-3.0-or-later */ /* solium-disable function-order */ pragma solidity 0.4.24; contract TokenManager is ITokenController, IForwarder, AragonApp { using SafeMath for uint256; bytes32 public constant MINT_ROLE = keccak256("MINT_ROLE"); bytes32 public constant ISSUE_ROLE = keccak256("ISSUE_ROLE"); bytes32 public constant ASSIGN_ROLE = keccak256("ASSIGN_ROLE"); bytes32 public constant REVOKE_VESTINGS_ROLE = keccak256("REVOKE_VESTINGS_ROLE"); bytes32 public constant BURN_ROLE = keccak256("BURN_ROLE"); uint256 public constant MAX_VESTINGS_PER_ADDRESS = 50; string private constant ERROR_CALLER_NOT_TOKEN = "TM_CALLER_NOT_TOKEN"; string private constant ERROR_NO_VESTING = "TM_NO_VESTING"; string private constant ERROR_TOKEN_CONTROLLER = "TM_TOKEN_CONTROLLER"; string private constant ERROR_MINT_RECEIVER_IS_TM = "TM_MINT_RECEIVER_IS_TM"; string private constant ERROR_VESTING_TO_TM = "TM_VESTING_TO_TM"; string private constant ERROR_TOO_MANY_VESTINGS = "TM_TOO_MANY_VESTINGS"; string private constant ERROR_WRONG_CLIFF_DATE = "TM_WRONG_CLIFF_DATE"; string private constant ERROR_VESTING_NOT_REVOKABLE = "TM_VESTING_NOT_REVOKABLE"; string private constant ERROR_REVOKE_TRANSFER_FROM_REVERTED = "TM_REVOKE_TRANSFER_FROM_REVERTED"; string private constant ERROR_CAN_NOT_FORWARD = "TM_CAN_NOT_FORWARD"; string private constant ERROR_BALANCE_INCREASE_NOT_ALLOWED = "TM_BALANCE_INC_NOT_ALLOWED"; string private constant ERROR_ASSIGN_TRANSFER_FROM_REVERTED = "TM_ASSIGN_TRANSFER_FROM_REVERTED"; struct TokenVesting { uint256 amount; uint64 start; uint64 cliff; uint64 vesting; bool revokable; } // Note that we COMPLETELY trust this MiniMeToken to not be malicious for proper operation of this contract MiniMeToken public token; uint256 public maxAccountTokens; // We are mimicing an array in the inner mapping, we use a mapping instead to make app upgrade more graceful mapping (address => mapping (uint256 => TokenVesting)) internal vestings; mapping (address => uint256) public vestingsLengths; // Other token specific events can be watched on the token address directly (avoids duplication) event NewVesting(address indexed receiver, uint256 vestingId, uint256 amount); event RevokeVesting(address indexed receiver, uint256 vestingId, uint256 nonVestedAmount); modifier onlyToken() { require(msg.sender == address(token), ERROR_CALLER_NOT_TOKEN); _; } modifier vestingExists(address _holder, uint256 _vestingId) { // TODO: it's not checking for gaps that may appear because of deletes in revokeVesting function require(_vestingId < vestingsLengths[_holder], ERROR_NO_VESTING); _; } /** * @notice Initialize Token Manager for `_token.symbol(): string`, whose tokens are `transferable ? 'not' : ''` transferable`_maxAccountTokens > 0 ? ' and limited to a maximum of ' + @tokenAmount(_token, _maxAccountTokens, false) + ' per account' : ''` * @param _token MiniMeToken address for the managed token (Token Manager instance must be already set as the token controller) * @param _transferable whether the token can be transferred by holders * @param _maxAccountTokens Maximum amount of tokens an account can have (0 for infinite tokens) */ function initialize( MiniMeToken _token, bool _transferable, uint256 _maxAccountTokens ) external onlyInit { initialized(); require(_token.controller() == address(this), ERROR_TOKEN_CONTROLLER); token = _token; maxAccountTokens = _maxAccountTokens == 0 ? uint256(-1) : _maxAccountTokens; if (token.transfersEnabled() != _transferable) { token.enableTransfers(_transferable); } } /** * @notice Mint `@tokenAmount(self.token(): address, _amount, false)` tokens for `_receiver` * @param _receiver The address receiving the tokens, cannot be the Token Manager itself (use `issue()` instead) * @param _amount Number of tokens minted */ function mint(address _receiver, uint256 _amount) external authP(MINT_ROLE, arr(_receiver, _amount)) { require(_receiver != address(this), ERROR_MINT_RECEIVER_IS_TM); _mint(_receiver, _amount); } /** * @notice Mint `@tokenAmount(self.token(): address, _amount, false)` tokens for the Token Manager * @param _amount Number of tokens minted */ function issue(uint256 _amount) external authP(ISSUE_ROLE, arr(_amount)) { _mint(address(this), _amount); } /** * @notice Assign `@tokenAmount(self.token(): address, _amount, false)` tokens to `_receiver` from the Token Manager's holdings * @param _receiver The address receiving the tokens * @param _amount Number of tokens transferred */ function assign(address _receiver, uint256 _amount) external authP(ASSIGN_ROLE, arr(_receiver, _amount)) { _assign(_receiver, _amount); } /** * @notice Burn `@tokenAmount(self.token(): address, _amount, false)` tokens from `_holder` * @param _holder Holder of tokens being burned * @param _amount Number of tokens being burned */ function burn(address _holder, uint256 _amount) external authP(BURN_ROLE, arr(_holder, _amount)) { // minime.destroyTokens() never returns false, only reverts on failure token.destroyTokens(_holder, _amount); } /** * @notice Assign `@tokenAmount(self.token(): address, _amount, false)` tokens to `_receiver` from the Token Manager's holdings with a `_revokable : 'revokable' : ''` vesting starting at `@formatDate(_start)`, cliff at `@formatDate(_cliff)` (first portion of tokens transferable), and completed vesting at `@formatDate(_vested)` (all tokens transferable) * @param _receiver The address receiving the tokens, cannot be Token Manager itself * @param _amount Number of tokens vested * @param _start Date the vesting calculations start * @param _cliff Date when the initial portion of tokens are transferable * @param _vested Date when all tokens are transferable * @param _revokable Whether the vesting can be revoked by the Token Manager */ function assignVested( address _receiver, uint256 _amount, uint64 _start, uint64 _cliff, uint64 _vested, bool _revokable ) external authP(ASSIGN_ROLE, arr(_receiver, _amount)) returns (uint256) { require(_receiver != address(this), ERROR_VESTING_TO_TM); require(vestingsLengths[_receiver] < MAX_VESTINGS_PER_ADDRESS, ERROR_TOO_MANY_VESTINGS); require(_start <= _cliff && _cliff <= _vested, ERROR_WRONG_CLIFF_DATE); uint256 vestingId = vestingsLengths[_receiver]++; vestings[_receiver][vestingId] = TokenVesting( _amount, _start, _cliff, _vested, _revokable ); _assign(_receiver, _amount); emit NewVesting(_receiver, vestingId, _amount); return vestingId; } /** * @notice Revoke vesting #`_vestingId` from `_holder`, returning unvested tokens to the Token Manager * @param _holder Address whose vesting to revoke * @param _vestingId Numeric id of the vesting */ function revokeVesting(address _holder, uint256 _vestingId) external authP(REVOKE_VESTINGS_ROLE, arr(_holder)) vestingExists(_holder, _vestingId) { TokenVesting storage v = vestings[_holder][_vestingId]; require(v.revokable, ERROR_VESTING_NOT_REVOKABLE); uint256 nonVested = _calculateNonVestedTokens( v.amount, getTimestamp(), v.start, v.cliff, v.vesting ); // To make vestingIds immutable over time, we just zero out the revoked vesting // Clearing this out also allows the token transfer back to the Token Manager to succeed delete vestings[_holder][_vestingId]; // transferFrom always works as controller // onTransfer hook always allows if transfering to token controller require(token.transferFrom(_holder, address(this), nonVested), ERROR_REVOKE_TRANSFER_FROM_REVERTED); emit RevokeVesting(_holder, _vestingId, nonVested); } // ITokenController fns // `onTransfer()`, `onApprove()`, and `proxyPayment()` are callbacks from the MiniMe token // contract and are only meant to be called through the managed MiniMe token that gets assigned // during initialization. /* * @dev Notifies the controller about a token transfer allowing the controller to decide whether * to allow it or react if desired (only callable from the token). * Initialization check is implicitly provided by `onlyToken()`. * @param _from The origin of the transfer * @param _to The destination of the transfer * @param _amount The amount of the transfer * @return False if the controller does not authorize the transfer */ function onTransfer(address _from, address _to, uint256 _amount) external onlyToken returns (bool) { return _isBalanceIncreaseAllowed(_to, _amount) && _transferableBalance(_from, getTimestamp()) >= _amount; } /** * @dev Notifies the controller about an approval allowing the controller to react if desired * Initialization check is implicitly provided by `onlyToken()`. * @return False if the controller does not authorize the approval */ function onApprove(address, address, uint) external onlyToken returns (bool) { return true; } /** * @dev Called when ether is sent to the MiniMe Token contract * Initialization check is implicitly provided by `onlyToken()`. * @return True if the ether is accepted, false for it to throw */ function proxyPayment(address) external payable onlyToken returns (bool) { return false; } // Forwarding fns function isForwarder() external pure returns (bool) { return true; } /** * @notice Execute desired action as a token holder * @dev IForwarder interface conformance. Forwards any token holder action. * @param _evmScript Script being executed */ function forward(bytes _evmScript) public { require(canForward(msg.sender, _evmScript), ERROR_CAN_NOT_FORWARD); bytes memory input = new bytes(0); // TODO: Consider input for this // Add the managed token to the blacklist to disallow a token holder from executing actions // on the token controller's (this contract) behalf address[] memory blacklist = new address[](1); blacklist[0] = address(token); runScript(_evmScript, input, blacklist); } function canForward(address _sender, bytes) public view returns (bool) { return hasInitialized() && token.balanceOf(_sender) > 0; } // Getter fns function getVesting( address _recipient, uint256 _vestingId ) public view vestingExists(_recipient, _vestingId) returns ( uint256 amount, uint64 start, uint64 cliff, uint64 vesting, bool revokable ) { TokenVesting storage tokenVesting = vestings[_recipient][_vestingId]; amount = tokenVesting.amount; start = tokenVesting.start; cliff = tokenVesting.cliff; vesting = tokenVesting.vesting; revokable = tokenVesting.revokable; } function spendableBalanceOf(address _holder) public view isInitialized returns (uint256) { return _transferableBalance(_holder, getTimestamp()); } function transferableBalance(address _holder, uint256 _time) public view isInitialized returns (uint256) { return _transferableBalance(_holder, _time); } /** * @dev Disable recovery escape hatch for own token, * as the it has the concept of issuing tokens without assigning them */ function allowRecoverability(address _token) public view returns (bool) { return _token != address(token); } // Internal fns function _assign(address _receiver, uint256 _amount) internal { require(_isBalanceIncreaseAllowed(_receiver, _amount), ERROR_BALANCE_INCREASE_NOT_ALLOWED); // Must use transferFrom() as transfer() does not give the token controller full control require(token.transferFrom(address(this), _receiver, _amount), ERROR_ASSIGN_TRANSFER_FROM_REVERTED); } function _mint(address _receiver, uint256 _amount) internal { require(_isBalanceIncreaseAllowed(_receiver, _amount), ERROR_BALANCE_INCREASE_NOT_ALLOWED); token.generateTokens(_receiver, _amount); // minime.generateTokens() never returns false } function _isBalanceIncreaseAllowed(address _receiver, uint256 _inc) internal view returns (bool) { // Max balance doesn't apply to the token manager itself if (_receiver == address(this)) { return true; } return token.balanceOf(_receiver).add(_inc) <= maxAccountTokens; } /** * @dev Calculate amount of non-vested tokens at a specifc time * @param tokens The total amount of tokens vested * @param time The time at which to check * @param start The date vesting started * @param cliff The cliff period * @param vested The fully vested date * @return The amount of non-vested tokens of a specific grant * transferableTokens * | _/-------- vestedTokens rect * | _/ * | _/ * | _/ * | _/ * | / * | .| * | . | * | . | * | . | * | . | * | . | * +===+===========+---------+----------> time * Start Cliff Vested */ function _calculateNonVestedTokens( uint256 tokens, uint256 time, uint256 start, uint256 cliff, uint256 vested ) private pure returns (uint256) { // Shortcuts for before cliff and after vested cases. if (time >= vested) { return 0; } if (time < cliff) { return tokens; } // Interpolate all vested tokens. // As before cliff the shortcut returns 0, we can just calculate a value // in the vesting rect (as shown in above's figure) // vestedTokens = tokens * (time - start) / (vested - start) // In assignVesting we enforce start <= cliff <= vested // Here we shortcut time >= vested and time < cliff, // so no division by 0 is possible uint256 vestedTokens = tokens.mul(time.sub(start)) / vested.sub(start); // tokens - vestedTokens return tokens.sub(vestedTokens); } function _transferableBalance(address _holder, uint256 _time) internal view returns (uint256) { uint256 transferable = token.balanceOf(_holder); // This check is not strictly necessary for the current version of this contract, as // Token Managers now cannot assign vestings to themselves. // However, this was a possibility in the past, so in case there were vestings assigned to // themselves, this will still return the correct value (entire balance, as the Token // Manager does not have a spending limit on its own balance). if (_holder != address(this)) { uint256 vestingsCount = vestingsLengths[_holder]; for (uint256 i = 0; i < vestingsCount; i++) { TokenVesting storage v = vestings[_holder][i]; uint256 nonTransferable = _calculateNonVestedTokens( v.amount, _time, v.start, v.cliff, v.vesting ); transferable = transferable.sub(nonTransferable); } } return transferable; } } // File: @aragon/apps-survey/contracts/Survey.sol /* * SPDX-License-Identitifer: GPL-3.0-or-later */ pragma solidity 0.4.24; contract Survey is AragonApp { using SafeMath for uint256; using SafeMath64 for uint64; bytes32 public constant CREATE_SURVEYS_ROLE = keccak256("CREATE_SURVEYS_ROLE"); bytes32 public constant MODIFY_PARTICIPATION_ROLE = keccak256("MODIFY_PARTICIPATION_ROLE"); uint64 public constant PCT_BASE = 10 ** 18; // 0% = 0; 1% = 10^16; 100% = 10^18 uint256 public constant ABSTAIN_VOTE = 0; string private constant ERROR_MIN_PARTICIPATION = "SURVEY_MIN_PARTICIPATION"; string private constant ERROR_NO_SURVEY = "SURVEY_NO_SURVEY"; string private constant ERROR_NO_VOTING_POWER = "SURVEY_NO_VOTING_POWER"; string private constant ERROR_CAN_NOT_VOTE = "SURVEY_CAN_NOT_VOTE"; string private constant ERROR_VOTE_WRONG_INPUT = "SURVEY_VOTE_WRONG_INPUT"; string private constant ERROR_VOTE_WRONG_OPTION = "SURVEY_VOTE_WRONG_OPTION"; string private constant ERROR_NO_STAKE = "SURVEY_NO_STAKE"; string private constant ERROR_OPTIONS_NOT_ORDERED = "SURVEY_OPTIONS_NOT_ORDERED"; string private constant ERROR_NO_OPTION = "SURVEY_NO_OPTION"; struct OptionCast { uint256 optionId; uint256 stake; } /* Allows for multiple option votes. * Index 0 is always used for the ABSTAIN_VOTE option, that's calculated automatically by the * contract. */ struct MultiOptionVote { uint256 optionsCastedLength; // `castedVotes` simulates an array // Each OptionCast in `castedVotes` must be ordered by ascending option IDs mapping (uint256 => OptionCast) castedVotes; } struct SurveyStruct { uint64 startDate; uint64 snapshotBlock; uint64 minParticipationPct; uint256 options; uint256 votingPower; // total tokens that can cast a vote uint256 participation; // tokens that casted a vote // Note that option IDs are from 1 to `options`, due to ABSTAIN_VOTE taking 0 mapping (uint256 => uint256) optionPower; // option ID -> voting power for option mapping (address => MultiOptionVote) votes; // voter -> options voted, with its stakes } MiniMeToken public token; uint64 public minParticipationPct; uint64 public surveyTime; // We are mimicing an array, we use a mapping instead to make app upgrade more graceful mapping (uint256 => SurveyStruct) internal surveys; uint256 public surveysLength; event StartSurvey(uint256 indexed surveyId, address indexed creator, string metadata); event CastVote(uint256 indexed surveyId, address indexed voter, uint256 option, uint256 stake, uint256 optionPower); event ResetVote(uint256 indexed surveyId, address indexed voter, uint256 option, uint256 previousStake, uint256 optionPower); event ChangeMinParticipation(uint64 minParticipationPct); modifier acceptableMinParticipationPct(uint64 _minParticipationPct) { require(_minParticipationPct > 0 && _minParticipationPct <= PCT_BASE, ERROR_MIN_PARTICIPATION); _; } modifier surveyExists(uint256 _surveyId) { require(_surveyId < surveysLength, ERROR_NO_SURVEY); _; } /** * @notice Initialize Survey app with `_token.symbol(): string` for governance, minimum acceptance participation of `@formatPct(_minParticipationPct)`%, and a voting duration of `@transformTime(_surveyTime)` * @param _token MiniMeToken address that will be used as governance token * @param _minParticipationPct Percentage of total voting power that must participate in a survey for it to be taken into account (expressed as a 10^18 percentage, (eg 10^16 = 1%, 10^18 = 100%) * @param _surveyTime Seconds that a survey will be open for token holders to vote */ function initialize( MiniMeToken _token, uint64 _minParticipationPct, uint64 _surveyTime ) external onlyInit acceptableMinParticipationPct(_minParticipationPct) { initialized(); token = _token; minParticipationPct = _minParticipationPct; surveyTime = _surveyTime; } /** * @notice Change minimum acceptance participation to `@formatPct(_minParticipationPct)`% * @param _minParticipationPct New acceptance participation */ function changeMinAcceptParticipationPct(uint64 _minParticipationPct) external authP(MODIFY_PARTICIPATION_ROLE, arr(uint256(_minParticipationPct), uint256(minParticipationPct))) acceptableMinParticipationPct(_minParticipationPct) { minParticipationPct = _minParticipationPct; emit ChangeMinParticipation(_minParticipationPct); } /** * @notice Create a new non-binding survey about "`_metadata`" * @param _metadata Survey metadata * @param _options Number of options voters can decide between * @return surveyId id for newly created survey */ function newSurvey(string _metadata, uint256 _options) external auth(CREATE_SURVEYS_ROLE) returns (uint256 surveyId) { uint64 snapshotBlock = getBlockNumber64() - 1; // avoid double voting in this very block uint256 votingPower = token.totalSupplyAt(snapshotBlock); require(votingPower > 0, ERROR_NO_VOTING_POWER); surveyId = surveysLength++; SurveyStruct storage survey = surveys[surveyId]; survey.startDate = getTimestamp64(); survey.snapshotBlock = snapshotBlock; // avoid double voting in this very block survey.minParticipationPct = minParticipationPct; survey.options = _options; survey.votingPower = votingPower; emit StartSurvey(surveyId, msg.sender, _metadata); } /** * @notice Reset previously casted vote in survey #`_surveyId`, if any. * @dev Initialization check is implicitly provided by `surveyExists()` as new surveys can only * be created via `newSurvey(),` which requires initialization * @param _surveyId Id for survey */ function resetVote(uint256 _surveyId) external surveyExists(_surveyId) { require(canVote(_surveyId, msg.sender), ERROR_CAN_NOT_VOTE); _resetVote(_surveyId); } /** * @notice Vote for multiple options in survey #`_surveyId`. * @dev Initialization check is implicitly provided by `surveyExists()` as new surveys can only * be created via `newSurvey(),` which requires initialization * @param _surveyId Id for survey * @param _optionIds Array with indexes of supported options * @param _stakes Number of tokens assigned to each option */ function voteOptions(uint256 _surveyId, uint256[] _optionIds, uint256[] _stakes) external surveyExists(_surveyId) { require(_optionIds.length == _stakes.length && _optionIds.length > 0, ERROR_VOTE_WRONG_INPUT); require(canVote(_surveyId, msg.sender), ERROR_CAN_NOT_VOTE); _voteOptions(_surveyId, _optionIds, _stakes); } /** * @notice Vote option #`_optionId` in survey #`_surveyId`. * @dev Initialization check is implicitly provided by `surveyExists()` as new surveys can only * be created via `newSurvey(),` which requires initialization * @dev It will use the whole balance. * @param _surveyId Id for survey * @param _optionId Index of supported option */ function voteOption(uint256 _surveyId, uint256 _optionId) external surveyExists(_surveyId) { require(canVote(_surveyId, msg.sender), ERROR_CAN_NOT_VOTE); SurveyStruct storage survey = surveys[_surveyId]; // This could re-enter, though we can asume the governance token is not maliciuous uint256 voterStake = token.balanceOfAt(msg.sender, survey.snapshotBlock); uint256[] memory options = new uint256[](1); uint256[] memory stakes = new uint256[](1); options[0] = _optionId; stakes[0] = voterStake; _voteOptions(_surveyId, options, stakes); } // Getter fns function canVote(uint256 _surveyId, address _voter) public view surveyExists(_surveyId) returns (bool) { SurveyStruct storage survey = surveys[_surveyId]; return _isSurveyOpen(survey) && token.balanceOfAt(_voter, survey.snapshotBlock) > 0; } function getSurvey(uint256 _surveyId) public view surveyExists(_surveyId) returns ( bool open, uint64 startDate, uint64 snapshotBlock, uint64 minParticipation, uint256 votingPower, uint256 participation, uint256 options ) { SurveyStruct storage survey = surveys[_surveyId]; open = _isSurveyOpen(survey); startDate = survey.startDate; snapshotBlock = survey.snapshotBlock; minParticipation = survey.minParticipationPct; votingPower = survey.votingPower; participation = survey.participation; options = survey.options; } /** * @dev This is not meant to be used on-chain */ /* solium-disable-next-line function-order */ function getVoterState(uint256 _surveyId, address _voter) external view surveyExists(_surveyId) returns (uint256[] options, uint256[] stakes) { MultiOptionVote storage vote = surveys[_surveyId].votes[_voter]; if (vote.optionsCastedLength == 0) { return (new uint256[](0), new uint256[](0)); } options = new uint256[](vote.optionsCastedLength + 1); stakes = new uint256[](vote.optionsCastedLength + 1); for (uint256 i = 0; i <= vote.optionsCastedLength; i++) { options[i] = vote.castedVotes[i].optionId; stakes[i] = vote.castedVotes[i].stake; } } function getOptionPower(uint256 _surveyId, uint256 _optionId) public view surveyExists(_surveyId) returns (uint256) { SurveyStruct storage survey = surveys[_surveyId]; require(_optionId <= survey.options, ERROR_NO_OPTION); return survey.optionPower[_optionId]; } function isParticipationAchieved(uint256 _surveyId) public view surveyExists(_surveyId) returns (bool) { SurveyStruct storage survey = surveys[_surveyId]; // votingPower is always > 0 uint256 participationPct = survey.participation.mul(PCT_BASE) / survey.votingPower; return participationPct >= survey.minParticipationPct; } // Internal fns /* * @dev Assumes the survey exists and that msg.sender can vote */ function _resetVote(uint256 _surveyId) internal { SurveyStruct storage survey = surveys[_surveyId]; MultiOptionVote storage previousVote = survey.votes[msg.sender]; if (previousVote.optionsCastedLength > 0) { // Voter removes their vote (index 0 is the abstain vote) for (uint256 i = 1; i <= previousVote.optionsCastedLength; i++) { OptionCast storage previousOptionCast = previousVote.castedVotes[i]; uint256 previousOptionPower = survey.optionPower[previousOptionCast.optionId]; uint256 currentOptionPower = previousOptionPower.sub(previousOptionCast.stake); survey.optionPower[previousOptionCast.optionId] = currentOptionPower; emit ResetVote(_surveyId, msg.sender, previousOptionCast.optionId, previousOptionCast.stake, currentOptionPower); } // Compute previously casted votes (i.e. substract non-used tokens from stake) uint256 voterStake = token.balanceOfAt(msg.sender, survey.snapshotBlock); uint256 previousParticipation = voterStake.sub(previousVote.castedVotes[0].stake); // And remove it from total participation survey.participation = survey.participation.sub(previousParticipation); // Reset previously voted options delete survey.votes[msg.sender]; } } /* * @dev Assumes the survey exists and that msg.sender can vote */ function _voteOptions(uint256 _surveyId, uint256[] _optionIds, uint256[] _stakes) internal { SurveyStruct storage survey = surveys[_surveyId]; MultiOptionVote storage senderVotes = survey.votes[msg.sender]; // Revert previous votes, if any _resetVote(_surveyId); uint256 totalVoted = 0; // Reserve first index for ABSTAIN_VOTE senderVotes.castedVotes[0] = OptionCast({ optionId: ABSTAIN_VOTE, stake: 0 }); for (uint256 optionIndex = 1; optionIndex <= _optionIds.length; optionIndex++) { // Voters don't specify that they're abstaining, // but we still keep track of this by reserving the first index of a survey's votes. // We subtract 1 from the indexes of the arrays passed in by the voter to account for this. uint256 optionId = _optionIds[optionIndex - 1]; uint256 stake = _stakes[optionIndex - 1]; require(optionId != ABSTAIN_VOTE && optionId <= survey.options, ERROR_VOTE_WRONG_OPTION); require(stake > 0, ERROR_NO_STAKE); // Let's avoid repeating an option by making sure that ascending order is preserved in // the options array by checking that the current optionId is larger than the last one // we added require(senderVotes.castedVotes[optionIndex - 1].optionId < optionId, ERROR_OPTIONS_NOT_ORDERED); // Register voter amount senderVotes.castedVotes[optionIndex] = OptionCast({ optionId: optionId, stake: stake }); // Add to total option support survey.optionPower[optionId] = survey.optionPower[optionId].add(stake); // Keep track of stake used so far totalVoted = totalVoted.add(stake); emit CastVote(_surveyId, msg.sender, optionId, stake, survey.optionPower[optionId]); } // Compute and register non used tokens // Implictly we are doing require(totalVoted <= voterStake) too // (as stated before, index 0 is for ABSTAIN_VOTE option) uint256 voterStake = token.balanceOfAt(msg.sender, survey.snapshotBlock); senderVotes.castedVotes[0].stake = voterStake.sub(totalVoted); // Register number of options voted senderVotes.optionsCastedLength = _optionIds.length; // Add voter tokens to participation survey.participation = survey.participation.add(totalVoted); assert(survey.participation <= survey.votingPower); } function _isSurveyOpen(SurveyStruct storage _survey) internal view returns (bool) { return getTimestamp64() < _survey.startDate.add(surveyTime); } } // File: @aragon/os/contracts/acl/IACLOracle.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; interface IACLOracle { function canPerform(address who, address where, bytes32 what, uint256[] how) external view returns (bool); } // File: @aragon/os/contracts/acl/ACL.sol pragma solidity 0.4.24; /* solium-disable function-order */ // Allow public initialize() to be first contract ACL is IACL, TimeHelpers, AragonApp, ACLHelpers { /* Hardcoded constants to save gas bytes32 public constant CREATE_PERMISSIONS_ROLE = keccak256("CREATE_PERMISSIONS_ROLE"); */ bytes32 public constant CREATE_PERMISSIONS_ROLE = 0x0b719b33c83b8e5d300c521cb8b54ae9bd933996a14bef8c2f4e0285d2d2400a; enum Op { NONE, EQ, NEQ, GT, LT, GTE, LTE, RET, NOT, AND, OR, XOR, IF_ELSE } // op types struct Param { uint8 id; uint8 op; uint240 value; // even though value is an uint240 it can store addresses // in the case of 32 byte hashes losing 2 bytes precision isn't a huge deal // op and id take less than 1 byte each so it can be kept in 1 sstore } uint8 internal constant BLOCK_NUMBER_PARAM_ID = 200; uint8 internal constant TIMESTAMP_PARAM_ID = 201; // 202 is unused uint8 internal constant ORACLE_PARAM_ID = 203; uint8 internal constant LOGIC_OP_PARAM_ID = 204; uint8 internal constant PARAM_VALUE_PARAM_ID = 205; // TODO: Add execution times param type? /* Hardcoded constant to save gas bytes32 public constant EMPTY_PARAM_HASH = keccak256(uint256(0)); */ bytes32 public constant EMPTY_PARAM_HASH = 0x290decd9548b62a8d60345a988386fc84ba6bc95484008f6362f93160ef3e563; bytes32 public constant NO_PERMISSION = bytes32(0); address public constant ANY_ENTITY = address(-1); address public constant BURN_ENTITY = address(1); // address(0) is already used as "no permission manager" uint256 internal constant ORACLE_CHECK_GAS = 30000; string private constant ERROR_AUTH_INIT_KERNEL = "ACL_AUTH_INIT_KERNEL"; string private constant ERROR_AUTH_NO_MANAGER = "ACL_AUTH_NO_MANAGER"; string private constant ERROR_EXISTENT_MANAGER = "ACL_EXISTENT_MANAGER"; // Whether someone has a permission mapping (bytes32 => bytes32) internal permissions; // permissions hash => params hash mapping (bytes32 => Param[]) internal permissionParams; // params hash => params // Who is the manager of a permission mapping (bytes32 => address) internal permissionManager; event SetPermission(address indexed entity, address indexed app, bytes32 indexed role, bool allowed); event SetPermissionParams(address indexed entity, address indexed app, bytes32 indexed role, bytes32 paramsHash); event ChangePermissionManager(address indexed app, bytes32 indexed role, address indexed manager); modifier onlyPermissionManager(address _app, bytes32 _role) { require(msg.sender == getPermissionManager(_app, _role), ERROR_AUTH_NO_MANAGER); _; } modifier noPermissionManager(address _app, bytes32 _role) { // only allow permission creation (or re-creation) when there is no manager require(getPermissionManager(_app, _role) == address(0), ERROR_EXISTENT_MANAGER); _; } /** * @dev Initialize can only be called once. It saves the block number in which it was initialized. * @notice Initialize an ACL instance and set `_permissionsCreator` as the entity that can create other permissions * @param _permissionsCreator Entity that will be given permission over createPermission */ function initialize(address _permissionsCreator) public onlyInit { initialized(); require(msg.sender == address(kernel()), ERROR_AUTH_INIT_KERNEL); _createPermission(_permissionsCreator, this, CREATE_PERMISSIONS_ROLE, _permissionsCreator); } /** * @dev Creates a permission that wasn't previously set and managed. * If a created permission is removed it is possible to reset it with createPermission. * This is the **ONLY** way to create permissions and set managers to permissions that don't * have a manager. * In terms of the ACL being initialized, this function implicitly protects all the other * state-changing external functions, as they all require the sender to be a manager. * @notice Create a new permission granting `_entity` the ability to perform actions requiring `_role` on `_app`, setting `_manager` as the permission's manager * @param _entity Address of the whitelisted entity that will be able to perform the role * @param _app Address of the app in which the role will be allowed (requires app to depend on kernel for ACL) * @param _role Identifier for the group of actions in app given access to perform * @param _manager Address of the entity that will be able to grant and revoke the permission further. */ function createPermission(address _entity, address _app, bytes32 _role, address _manager) external auth(CREATE_PERMISSIONS_ROLE) noPermissionManager(_app, _role) { _createPermission(_entity, _app, _role, _manager); } /** * @dev Grants permission if allowed. This requires `msg.sender` to be the permission manager * @notice Grant `_entity` the ability to perform actions requiring `_role` on `_app` * @param _entity Address of the whitelisted entity that will be able to perform the role * @param _app Address of the app in which the role will be allowed (requires app to depend on kernel for ACL) * @param _role Identifier for the group of actions in app given access to perform */ function grantPermission(address _entity, address _app, bytes32 _role) external { grantPermissionP(_entity, _app, _role, new uint256[](0)); } /** * @dev Grants a permission with parameters if allowed. This requires `msg.sender` to be the permission manager * @notice Grant `_entity` the ability to perform actions requiring `_role` on `_app` * @param _entity Address of the whitelisted entity that will be able to perform the role * @param _app Address of the app in which the role will be allowed (requires app to depend on kernel for ACL) * @param _role Identifier for the group of actions in app given access to perform * @param _params Permission parameters */ function grantPermissionP(address _entity, address _app, bytes32 _role, uint256[] _params) public onlyPermissionManager(_app, _role) { bytes32 paramsHash = _params.length > 0 ? _saveParams(_params) : EMPTY_PARAM_HASH; _setPermission(_entity, _app, _role, paramsHash); } /** * @dev Revokes permission if allowed. This requires `msg.sender` to be the the permission manager * @notice Revoke from `_entity` the ability to perform actions requiring `_role` on `_app` * @param _entity Address of the whitelisted entity to revoke access from * @param _app Address of the app in which the role will be revoked * @param _role Identifier for the group of actions in app being revoked */ function revokePermission(address _entity, address _app, bytes32 _role) external onlyPermissionManager(_app, _role) { _setPermission(_entity, _app, _role, NO_PERMISSION); } /** * @notice Set `_newManager` as the manager of `_role` in `_app` * @param _newManager Address for the new manager * @param _app Address of the app in which the permission management is being transferred * @param _role Identifier for the group of actions being transferred */ function setPermissionManager(address _newManager, address _app, bytes32 _role) external onlyPermissionManager(_app, _role) { _setPermissionManager(_newManager, _app, _role); } /** * @notice Remove the manager of `_role` in `_app` * @param _app Address of the app in which the permission is being unmanaged * @param _role Identifier for the group of actions being unmanaged */ function removePermissionManager(address _app, bytes32 _role) external onlyPermissionManager(_app, _role) { _setPermissionManager(address(0), _app, _role); } /** * @notice Burn non-existent `_role` in `_app`, so no modification can be made to it (grant, revoke, permission manager) * @param _app Address of the app in which the permission is being burned * @param _role Identifier for the group of actions being burned */ function createBurnedPermission(address _app, bytes32 _role) external auth(CREATE_PERMISSIONS_ROLE) noPermissionManager(_app, _role) { _setPermissionManager(BURN_ENTITY, _app, _role); } /** * @notice Burn `_role` in `_app`, so no modification can be made to it (grant, revoke, permission manager) * @param _app Address of the app in which the permission is being burned * @param _role Identifier for the group of actions being burned */ function burnPermissionManager(address _app, bytes32 _role) external onlyPermissionManager(_app, _role) { _setPermissionManager(BURN_ENTITY, _app, _role); } /** * @notice Get parameters for permission array length * @param _entity Address of the whitelisted entity that will be able to perform the role * @param _app Address of the app * @param _role Identifier for a group of actions in app * @return Length of the array */ function getPermissionParamsLength(address _entity, address _app, bytes32 _role) external view returns (uint) { return permissionParams[permissions[permissionHash(_entity, _app, _role)]].length; } /** * @notice Get parameter for permission * @param _entity Address of the whitelisted entity that will be able to perform the role * @param _app Address of the app * @param _role Identifier for a group of actions in app * @param _index Index of parameter in the array * @return Parameter (id, op, value) */ function getPermissionParam(address _entity, address _app, bytes32 _role, uint _index) external view returns (uint8, uint8, uint240) { Param storage param = permissionParams[permissions[permissionHash(_entity, _app, _role)]][_index]; return (param.id, param.op, param.value); } /** * @dev Get manager for permission * @param _app Address of the app * @param _role Identifier for a group of actions in app * @return address of the manager for the permission */ function getPermissionManager(address _app, bytes32 _role) public view returns (address) { return permissionManager[roleHash(_app, _role)]; } /** * @dev Function called by apps to check ACL on kernel or to check permission statu * @param _who Sender of the original call * @param _where Address of the app * @param _where Identifier for a group of actions in app * @param _how Permission parameters * @return boolean indicating whether the ACL allows the role or not */ function hasPermission(address _who, address _where, bytes32 _what, bytes memory _how) public view returns (bool) { return hasPermission(_who, _where, _what, ConversionHelpers.dangerouslyCastBytesToUintArray(_how)); } function hasPermission(address _who, address _where, bytes32 _what, uint256[] memory _how) public view returns (bool) { bytes32 whoParams = permissions[permissionHash(_who, _where, _what)]; if (whoParams != NO_PERMISSION && evalParams(whoParams, _who, _where, _what, _how)) { return true; } bytes32 anyParams = permissions[permissionHash(ANY_ENTITY, _where, _what)]; if (anyParams != NO_PERMISSION && evalParams(anyParams, ANY_ENTITY, _where, _what, _how)) { return true; } return false; } function hasPermission(address _who, address _where, bytes32 _what) public view returns (bool) { uint256[] memory empty = new uint256[](0); return hasPermission(_who, _where, _what, empty); } function evalParams( bytes32 _paramsHash, address _who, address _where, bytes32 _what, uint256[] _how ) public view returns (bool) { if (_paramsHash == EMPTY_PARAM_HASH) { return true; } return _evalParam(_paramsHash, 0, _who, _where, _what, _how); } /** * @dev Internal createPermission for access inside the kernel (on instantiation) */ function _createPermission(address _entity, address _app, bytes32 _role, address _manager) internal { _setPermission(_entity, _app, _role, EMPTY_PARAM_HASH); _setPermissionManager(_manager, _app, _role); } /** * @dev Internal function called to actually save the permission */ function _setPermission(address _entity, address _app, bytes32 _role, bytes32 _paramsHash) internal { permissions[permissionHash(_entity, _app, _role)] = _paramsHash; bool entityHasPermission = _paramsHash != NO_PERMISSION; bool permissionHasParams = entityHasPermission && _paramsHash != EMPTY_PARAM_HASH; emit SetPermission(_entity, _app, _role, entityHasPermission); if (permissionHasParams) { emit SetPermissionParams(_entity, _app, _role, _paramsHash); } } function _saveParams(uint256[] _encodedParams) internal returns (bytes32) { bytes32 paramHash = keccak256(abi.encodePacked(_encodedParams)); Param[] storage params = permissionParams[paramHash]; if (params.length == 0) { // params not saved before for (uint256 i = 0; i < _encodedParams.length; i++) { uint256 encodedParam = _encodedParams[i]; Param memory param = Param(decodeParamId(encodedParam), decodeParamOp(encodedParam), uint240(encodedParam)); params.push(param); } } return paramHash; } function _evalParam( bytes32 _paramsHash, uint32 _paramId, address _who, address _where, bytes32 _what, uint256[] _how ) internal view returns (bool) { if (_paramId >= permissionParams[_paramsHash].length) { return false; // out of bounds } Param memory param = permissionParams[_paramsHash][_paramId]; if (param.id == LOGIC_OP_PARAM_ID) { return _evalLogic(param, _paramsHash, _who, _where, _what, _how); } uint256 value; uint256 comparedTo = uint256(param.value); // get value if (param.id == ORACLE_PARAM_ID) { value = checkOracle(IACLOracle(param.value), _who, _where, _what, _how) ? 1 : 0; comparedTo = 1; } else if (param.id == BLOCK_NUMBER_PARAM_ID) { value = getBlockNumber(); } else if (param.id == TIMESTAMP_PARAM_ID) { value = getTimestamp(); } else if (param.id == PARAM_VALUE_PARAM_ID) { value = uint256(param.value); } else { if (param.id >= _how.length) { return false; } value = uint256(uint240(_how[param.id])); // force lost precision } if (Op(param.op) == Op.RET) { return uint256(value) > 0; } return compare(value, Op(param.op), comparedTo); } function _evalLogic(Param _param, bytes32 _paramsHash, address _who, address _where, bytes32 _what, uint256[] _how) internal view returns (bool) { if (Op(_param.op) == Op.IF_ELSE) { uint32 conditionParam; uint32 successParam; uint32 failureParam; (conditionParam, successParam, failureParam) = decodeParamsList(uint256(_param.value)); bool result = _evalParam(_paramsHash, conditionParam, _who, _where, _what, _how); return _evalParam(_paramsHash, result ? successParam : failureParam, _who, _where, _what, _how); } uint32 param1; uint32 param2; (param1, param2,) = decodeParamsList(uint256(_param.value)); bool r1 = _evalParam(_paramsHash, param1, _who, _where, _what, _how); if (Op(_param.op) == Op.NOT) { return !r1; } if (r1 && Op(_param.op) == Op.OR) { return true; } if (!r1 && Op(_param.op) == Op.AND) { return false; } bool r2 = _evalParam(_paramsHash, param2, _who, _where, _what, _how); if (Op(_param.op) == Op.XOR) { return r1 != r2; } return r2; // both or and and depend on result of r2 after checks } function compare(uint256 _a, Op _op, uint256 _b) internal pure returns (bool) { if (_op == Op.EQ) return _a == _b; // solium-disable-line lbrace if (_op == Op.NEQ) return _a != _b; // solium-disable-line lbrace if (_op == Op.GT) return _a > _b; // solium-disable-line lbrace if (_op == Op.LT) return _a < _b; // solium-disable-line lbrace if (_op == Op.GTE) return _a >= _b; // solium-disable-line lbrace if (_op == Op.LTE) return _a <= _b; // solium-disable-line lbrace return false; } function checkOracle(IACLOracle _oracleAddr, address _who, address _where, bytes32 _what, uint256[] _how) internal view returns (bool) { bytes4 sig = _oracleAddr.canPerform.selector; // a raw call is required so we can return false if the call reverts, rather than reverting bytes memory checkCalldata = abi.encodeWithSelector(sig, _who, _where, _what, _how); uint256 oracleCheckGas = ORACLE_CHECK_GAS; bool ok; assembly { ok := staticcall(oracleCheckGas, _oracleAddr, add(checkCalldata, 0x20), mload(checkCalldata), 0, 0) } if (!ok) { return false; } uint256 size; assembly { size := returndatasize } if (size != 32) { return false; } bool result; assembly { let ptr := mload(0x40) // get next free memory ptr returndatacopy(ptr, 0, size) // copy return from above `staticcall` result := mload(ptr) // read data at ptr and set it to result mstore(ptr, 0) // set pointer memory to 0 so it still is the next free ptr } return result; } /** * @dev Internal function that sets management */ function _setPermissionManager(address _newManager, address _app, bytes32 _role) internal { permissionManager[roleHash(_app, _role)] = _newManager; emit ChangePermissionManager(_app, _role, _newManager); } function roleHash(address _where, bytes32 _what) internal pure returns (bytes32) { return keccak256(abi.encodePacked("ROLE", _where, _what)); } function permissionHash(address _who, address _where, bytes32 _what) internal pure returns (bytes32) { return keccak256(abi.encodePacked("PERMISSION", _who, _where, _what)); } } // File: @aragon/os/contracts/apm/Repo.sol pragma solidity 0.4.24; /* solium-disable function-order */ // Allow public initialize() to be first contract Repo is AragonApp { /* Hardcoded constants to save gas bytes32 public constant CREATE_VERSION_ROLE = keccak256("CREATE_VERSION_ROLE"); */ bytes32 public constant CREATE_VERSION_ROLE = 0x1f56cfecd3595a2e6cc1a7e6cb0b20df84cdbd92eff2fee554e70e4e45a9a7d8; string private constant ERROR_INVALID_BUMP = "REPO_INVALID_BUMP"; string private constant ERROR_INVALID_VERSION = "REPO_INVALID_VERSION"; string private constant ERROR_INEXISTENT_VERSION = "REPO_INEXISTENT_VERSION"; struct Version { uint16[3] semanticVersion; address contractAddress; bytes contentURI; } uint256 internal versionsNextIndex; mapping (uint256 => Version) internal versions; mapping (bytes32 => uint256) internal versionIdForSemantic; mapping (address => uint256) internal latestVersionIdForContract; event NewVersion(uint256 versionId, uint16[3] semanticVersion); /** * @dev Initialize can only be called once. It saves the block number in which it was initialized. * @notice Initialize this Repo */ function initialize() public onlyInit { initialized(); versionsNextIndex = 1; } /** * @notice Create new version with contract `_contractAddress` and content `@fromHex(_contentURI)` * @param _newSemanticVersion Semantic version for new repo version * @param _contractAddress address for smart contract logic for version (if set to 0, it uses last versions' contractAddress) * @param _contentURI External URI for fetching new version's content */ function newVersion( uint16[3] _newSemanticVersion, address _contractAddress, bytes _contentURI ) public auth(CREATE_VERSION_ROLE) { address contractAddress = _contractAddress; uint256 lastVersionIndex = versionsNextIndex - 1; uint16[3] memory lastSematicVersion; if (lastVersionIndex > 0) { Version storage lastVersion = versions[lastVersionIndex]; lastSematicVersion = lastVersion.semanticVersion; if (contractAddress == address(0)) { contractAddress = lastVersion.contractAddress; } // Only allows smart contract change on major version bumps require( lastVersion.contractAddress == contractAddress || _newSemanticVersion[0] > lastVersion.semanticVersion[0], ERROR_INVALID_VERSION ); } require(isValidBump(lastSematicVersion, _newSemanticVersion), ERROR_INVALID_BUMP); uint256 versionId = versionsNextIndex++; versions[versionId] = Version(_newSemanticVersion, contractAddress, _contentURI); versionIdForSemantic[semanticVersionHash(_newSemanticVersion)] = versionId; latestVersionIdForContract[contractAddress] = versionId; emit NewVersion(versionId, _newSemanticVersion); } function getLatest() public view returns (uint16[3] semanticVersion, address contractAddress, bytes contentURI) { return getByVersionId(versionsNextIndex - 1); } function getLatestForContractAddress(address _contractAddress) public view returns (uint16[3] semanticVersion, address contractAddress, bytes contentURI) { return getByVersionId(latestVersionIdForContract[_contractAddress]); } function getBySemanticVersion(uint16[3] _semanticVersion) public view returns (uint16[3] semanticVersion, address contractAddress, bytes contentURI) { return getByVersionId(versionIdForSemantic[semanticVersionHash(_semanticVersion)]); } function getByVersionId(uint _versionId) public view returns (uint16[3] semanticVersion, address contractAddress, bytes contentURI) { require(_versionId > 0 && _versionId < versionsNextIndex, ERROR_INEXISTENT_VERSION); Version storage version = versions[_versionId]; return (version.semanticVersion, version.contractAddress, version.contentURI); } function getVersionsCount() public view returns (uint256) { return versionsNextIndex - 1; } function isValidBump(uint16[3] _oldVersion, uint16[3] _newVersion) public pure returns (bool) { bool hasBumped; uint i = 0; while (i < 3) { if (hasBumped) { if (_newVersion[i] != 0) { return false; } } else if (_newVersion[i] != _oldVersion[i]) { if (_oldVersion[i] > _newVersion[i] || _newVersion[i] - _oldVersion[i] != 1) { return false; } hasBumped = true; } i++; } return hasBumped; } function semanticVersionHash(uint16[3] version) internal pure returns (bytes32) { return keccak256(abi.encodePacked(version[0], version[1], version[2])); } } // File: @aragon/os/contracts/apm/APMNamehash.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract APMNamehash { /* Hardcoded constants to save gas bytes32 internal constant APM_NODE = keccak256(abi.encodePacked(ETH_TLD_NODE, keccak256(abi.encodePacked("aragonpm")))); */ bytes32 internal constant APM_NODE = 0x9065c3e7f7b7ef1ef4e53d2d0b8e0cef02874ab020c1ece79d5f0d3d0111c0ba; function apmNamehash(string name) internal pure returns (bytes32) { return keccak256(abi.encodePacked(APM_NODE, keccak256(bytes(name)))); } } // File: @aragon/os/contracts/kernel/KernelStorage.sol pragma solidity 0.4.24; contract KernelStorage { // namespace => app id => address mapping (bytes32 => mapping (bytes32 => address)) public apps; bytes32 public recoveryVaultAppId; } // File: @aragon/os/contracts/lib/misc/ERCProxy.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract ERCProxy { uint256 internal constant FORWARDING = 1; uint256 internal constant UPGRADEABLE = 2; function proxyType() public pure returns (uint256 proxyTypeId); function implementation() public view returns (address codeAddr); } // File: @aragon/os/contracts/common/DelegateProxy.sol pragma solidity 0.4.24; contract DelegateProxy is ERCProxy, IsContract { uint256 internal constant FWD_GAS_LIMIT = 10000; /** * @dev Performs a delegatecall and returns whatever the delegatecall returned (entire context execution will return!) * @param _dst Destination address to perform the delegatecall * @param _calldata Calldata for the delegatecall */ function delegatedFwd(address _dst, bytes _calldata) internal { require(isContract(_dst)); uint256 fwdGasLimit = FWD_GAS_LIMIT; assembly { let result := delegatecall(sub(gas, fwdGasLimit), _dst, add(_calldata, 0x20), mload(_calldata), 0, 0) let size := returndatasize let ptr := mload(0x40) returndatacopy(ptr, 0, size) // revert instead of invalid() bc if the underlying call failed with invalid() it already wasted gas. // if the call returned error data, forward it switch result case 0 { revert(ptr, size) } default { return(ptr, size) } } } } // File: @aragon/os/contracts/common/DepositableDelegateProxy.sol pragma solidity 0.4.24; contract DepositableDelegateProxy is DepositableStorage, DelegateProxy { event ProxyDeposit(address sender, uint256 value); function () external payable { // send / transfer if (gasleft() < FWD_GAS_LIMIT) { require(msg.value > 0 && msg.data.length == 0); require(isDepositable()); emit ProxyDeposit(msg.sender, msg.value); } else { // all calls except for send or transfer address target = implementation(); delegatedFwd(target, msg.data); } } } // File: @aragon/os/contracts/apps/AppProxyBase.sol pragma solidity 0.4.24; contract AppProxyBase is AppStorage, DepositableDelegateProxy, KernelNamespaceConstants { /** * @dev Initialize AppProxy * @param _kernel Reference to organization kernel for the app * @param _appId Identifier for app * @param _initializePayload Payload for call to be made after setup to initialize */ constructor(IKernel _kernel, bytes32 _appId, bytes _initializePayload) public { setKernel(_kernel); setAppId(_appId); // Implicit check that kernel is actually a Kernel // The EVM doesn't actually provide a way for us to make sure, but we can force a revert to // occur if the kernel is set to 0x0 or a non-code address when we try to call a method on // it. address appCode = getAppBase(_appId); // If initialize payload is provided, it will be executed if (_initializePayload.length > 0) { require(isContract(appCode)); // Cannot make delegatecall as a delegateproxy.delegatedFwd as it // returns ending execution context and halts contract deployment require(appCode.delegatecall(_initializePayload)); } } function getAppBase(bytes32 _appId) internal view returns (address) { return kernel().getApp(KERNEL_APP_BASES_NAMESPACE, _appId); } } // File: @aragon/os/contracts/apps/AppProxyUpgradeable.sol pragma solidity 0.4.24; contract AppProxyUpgradeable is AppProxyBase { /** * @dev Initialize AppProxyUpgradeable (makes it an upgradeable Aragon app) * @param _kernel Reference to organization kernel for the app * @param _appId Identifier for app * @param _initializePayload Payload for call to be made after setup to initialize */ constructor(IKernel _kernel, bytes32 _appId, bytes _initializePayload) AppProxyBase(_kernel, _appId, _initializePayload) public // solium-disable-line visibility-first { // solium-disable-previous-line no-empty-blocks } /** * @dev ERC897, the address the proxy would delegate calls to */ function implementation() public view returns (address) { return getAppBase(appId()); } /** * @dev ERC897, whether it is a forwarding (1) or an upgradeable (2) proxy */ function proxyType() public pure returns (uint256 proxyTypeId) { return UPGRADEABLE; } } // File: @aragon/os/contracts/apps/AppProxyPinned.sol pragma solidity 0.4.24; contract AppProxyPinned is IsContract, AppProxyBase { using UnstructuredStorage for bytes32; // keccak256("aragonOS.appStorage.pinnedCode") bytes32 internal constant PINNED_CODE_POSITION = 0xdee64df20d65e53d7f51cb6ab6d921a0a6a638a91e942e1d8d02df28e31c038e; /** * @dev Initialize AppProxyPinned (makes it an un-upgradeable Aragon app) * @param _kernel Reference to organization kernel for the app * @param _appId Identifier for app * @param _initializePayload Payload for call to be made after setup to initialize */ constructor(IKernel _kernel, bytes32 _appId, bytes _initializePayload) AppProxyBase(_kernel, _appId, _initializePayload) public // solium-disable-line visibility-first { setPinnedCode(getAppBase(_appId)); require(isContract(pinnedCode())); } /** * @dev ERC897, the address the proxy would delegate calls to */ function implementation() public view returns (address) { return pinnedCode(); } /** * @dev ERC897, whether it is a forwarding (1) or an upgradeable (2) proxy */ function proxyType() public pure returns (uint256 proxyTypeId) { return FORWARDING; } function setPinnedCode(address _pinnedCode) internal { PINNED_CODE_POSITION.setStorageAddress(_pinnedCode); } function pinnedCode() internal view returns (address) { return PINNED_CODE_POSITION.getStorageAddress(); } } // File: @aragon/os/contracts/factory/AppProxyFactory.sol pragma solidity 0.4.24; contract AppProxyFactory { event NewAppProxy(address proxy, bool isUpgradeable, bytes32 appId); /** * @notice Create a new upgradeable app instance on `_kernel` with identifier `_appId` * @param _kernel App's Kernel reference * @param _appId Identifier for app * @return AppProxyUpgradeable */ function newAppProxy(IKernel _kernel, bytes32 _appId) public returns (AppProxyUpgradeable) { return newAppProxy(_kernel, _appId, new bytes(0)); } /** * @notice Create a new upgradeable app instance on `_kernel` with identifier `_appId` and initialization payload `_initializePayload` * @param _kernel App's Kernel reference * @param _appId Identifier for app * @return AppProxyUpgradeable */ function newAppProxy(IKernel _kernel, bytes32 _appId, bytes _initializePayload) public returns (AppProxyUpgradeable) { AppProxyUpgradeable proxy = new AppProxyUpgradeable(_kernel, _appId, _initializePayload); emit NewAppProxy(address(proxy), true, _appId); return proxy; } /** * @notice Create a new pinned app instance on `_kernel` with identifier `_appId` * @param _kernel App's Kernel reference * @param _appId Identifier for app * @return AppProxyPinned */ function newAppProxyPinned(IKernel _kernel, bytes32 _appId) public returns (AppProxyPinned) { return newAppProxyPinned(_kernel, _appId, new bytes(0)); } /** * @notice Create a new pinned app instance on `_kernel` with identifier `_appId` and initialization payload `_initializePayload` * @param _kernel App's Kernel reference * @param _appId Identifier for app * @param _initializePayload Proxy initialization payload * @return AppProxyPinned */ function newAppProxyPinned(IKernel _kernel, bytes32 _appId, bytes _initializePayload) public returns (AppProxyPinned) { AppProxyPinned proxy = new AppProxyPinned(_kernel, _appId, _initializePayload); emit NewAppProxy(address(proxy), false, _appId); return proxy; } } // File: @aragon/os/contracts/kernel/Kernel.sol pragma solidity 0.4.24; // solium-disable-next-line max-len contract Kernel is IKernel, KernelStorage, KernelAppIds, KernelNamespaceConstants, Petrifiable, IsContract, VaultRecoverable, AppProxyFactory, ACLSyntaxSugar { /* Hardcoded constants to save gas bytes32 public constant APP_MANAGER_ROLE = keccak256("APP_MANAGER_ROLE"); */ bytes32 public constant APP_MANAGER_ROLE = 0xb6d92708f3d4817afc106147d969e229ced5c46e65e0a5002a0d391287762bd0; string private constant ERROR_APP_NOT_CONTRACT = "KERNEL_APP_NOT_CONTRACT"; string private constant ERROR_INVALID_APP_CHANGE = "KERNEL_INVALID_APP_CHANGE"; string private constant ERROR_AUTH_FAILED = "KERNEL_AUTH_FAILED"; /** * @dev Constructor that allows the deployer to choose if the base instance should be petrified immediately. * @param _shouldPetrify Immediately petrify this instance so that it can never be initialized */ constructor(bool _shouldPetrify) public { if (_shouldPetrify) { petrify(); } } /** * @dev Initialize can only be called once. It saves the block number in which it was initialized. * @notice Initialize this kernel instance along with its ACL and set `_permissionsCreator` as the entity that can create other permissions * @param _baseAcl Address of base ACL app * @param _permissionsCreator Entity that will be given permission over createPermission */ function initialize(IACL _baseAcl, address _permissionsCreator) public onlyInit { initialized(); // Set ACL base _setApp(KERNEL_APP_BASES_NAMESPACE, KERNEL_DEFAULT_ACL_APP_ID, _baseAcl); // Create ACL instance and attach it as the default ACL app IACL acl = IACL(newAppProxy(this, KERNEL_DEFAULT_ACL_APP_ID)); acl.initialize(_permissionsCreator); _setApp(KERNEL_APP_ADDR_NAMESPACE, KERNEL_DEFAULT_ACL_APP_ID, acl); recoveryVaultAppId = KERNEL_DEFAULT_VAULT_APP_ID; } /** * @dev Create a new instance of an app linked to this kernel * @notice Create a new upgradeable instance of `_appId` app linked to the Kernel, setting its code to `_appBase` * @param _appId Identifier for app * @param _appBase Address of the app's base implementation * @return AppProxy instance */ function newAppInstance(bytes32 _appId, address _appBase) public auth(APP_MANAGER_ROLE, arr(KERNEL_APP_BASES_NAMESPACE, _appId)) returns (ERCProxy appProxy) { return newAppInstance(_appId, _appBase, new bytes(0), false); } /** * @dev Create a new instance of an app linked to this kernel and set its base * implementation if it was not already set * @notice Create a new upgradeable instance of `_appId` app linked to the Kernel, setting its code to `_appBase`. `_setDefault ? 'Also sets it as the default app instance.':''` * @param _appId Identifier for app * @param _appBase Address of the app's base implementation * @param _initializePayload Payload for call made by the proxy during its construction to initialize * @param _setDefault Whether the app proxy app is the default one. * Useful when the Kernel needs to know of an instance of a particular app, * like Vault for escape hatch mechanism. * @return AppProxy instance */ function newAppInstance(bytes32 _appId, address _appBase, bytes _initializePayload, bool _setDefault) public auth(APP_MANAGER_ROLE, arr(KERNEL_APP_BASES_NAMESPACE, _appId)) returns (ERCProxy appProxy) { _setAppIfNew(KERNEL_APP_BASES_NAMESPACE, _appId, _appBase); appProxy = newAppProxy(this, _appId, _initializePayload); // By calling setApp directly and not the internal functions, we make sure the params are checked // and it will only succeed if sender has permissions to set something to the namespace. if (_setDefault) { setApp(KERNEL_APP_ADDR_NAMESPACE, _appId, appProxy); } } /** * @dev Create a new pinned instance of an app linked to this kernel * @notice Create a new non-upgradeable instance of `_appId` app linked to the Kernel, setting its code to `_appBase`. * @param _appId Identifier for app * @param _appBase Address of the app's base implementation * @return AppProxy instance */ function newPinnedAppInstance(bytes32 _appId, address _appBase) public auth(APP_MANAGER_ROLE, arr(KERNEL_APP_BASES_NAMESPACE, _appId)) returns (ERCProxy appProxy) { return newPinnedAppInstance(_appId, _appBase, new bytes(0), false); } /** * @dev Create a new pinned instance of an app linked to this kernel and set * its base implementation if it was not already set * @notice Create a new non-upgradeable instance of `_appId` app linked to the Kernel, setting its code to `_appBase`. `_setDefault ? 'Also sets it as the default app instance.':''` * @param _appId Identifier for app * @param _appBase Address of the app's base implementation * @param _initializePayload Payload for call made by the proxy during its construction to initialize * @param _setDefault Whether the app proxy app is the default one. * Useful when the Kernel needs to know of an instance of a particular app, * like Vault for escape hatch mechanism. * @return AppProxy instance */ function newPinnedAppInstance(bytes32 _appId, address _appBase, bytes _initializePayload, bool _setDefault) public auth(APP_MANAGER_ROLE, arr(KERNEL_APP_BASES_NAMESPACE, _appId)) returns (ERCProxy appProxy) { _setAppIfNew(KERNEL_APP_BASES_NAMESPACE, _appId, _appBase); appProxy = newAppProxyPinned(this, _appId, _initializePayload); // By calling setApp directly and not the internal functions, we make sure the params are checked // and it will only succeed if sender has permissions to set something to the namespace. if (_setDefault) { setApp(KERNEL_APP_ADDR_NAMESPACE, _appId, appProxy); } } /** * @dev Set the resolving address of an app instance or base implementation * @notice Set the resolving address of `_appId` in namespace `_namespace` to `_app` * @param _namespace App namespace to use * @param _appId Identifier for app * @param _app Address of the app instance or base implementation * @return ID of app */ function setApp(bytes32 _namespace, bytes32 _appId, address _app) public auth(APP_MANAGER_ROLE, arr(_namespace, _appId)) { _setApp(_namespace, _appId, _app); } /** * @dev Set the default vault id for the escape hatch mechanism * @param _recoveryVaultAppId Identifier of the recovery vault app */ function setRecoveryVaultAppId(bytes32 _recoveryVaultAppId) public auth(APP_MANAGER_ROLE, arr(KERNEL_APP_ADDR_NAMESPACE, _recoveryVaultAppId)) { recoveryVaultAppId = _recoveryVaultAppId; } // External access to default app id and namespace constants to mimic default getters for constants /* solium-disable function-order, mixedcase */ function CORE_NAMESPACE() external pure returns (bytes32) { return KERNEL_CORE_NAMESPACE; } function APP_BASES_NAMESPACE() external pure returns (bytes32) { return KERNEL_APP_BASES_NAMESPACE; } function APP_ADDR_NAMESPACE() external pure returns (bytes32) { return KERNEL_APP_ADDR_NAMESPACE; } function KERNEL_APP_ID() external pure returns (bytes32) { return KERNEL_CORE_APP_ID; } function DEFAULT_ACL_APP_ID() external pure returns (bytes32) { return KERNEL_DEFAULT_ACL_APP_ID; } /* solium-enable function-order, mixedcase */ /** * @dev Get the address of an app instance or base implementation * @param _namespace App namespace to use * @param _appId Identifier for app * @return Address of the app */ function getApp(bytes32 _namespace, bytes32 _appId) public view returns (address) { return apps[_namespace][_appId]; } /** * @dev Get the address of the recovery Vault instance (to recover funds) * @return Address of the Vault */ function getRecoveryVault() public view returns (address) { return apps[KERNEL_APP_ADDR_NAMESPACE][recoveryVaultAppId]; } /** * @dev Get the installed ACL app * @return ACL app */ function acl() public view returns (IACL) { return IACL(getApp(KERNEL_APP_ADDR_NAMESPACE, KERNEL_DEFAULT_ACL_APP_ID)); } /** * @dev Function called by apps to check ACL on kernel or to check permission status * @param _who Sender of the original call * @param _where Address of the app * @param _what Identifier for a group of actions in app * @param _how Extra data for ACL auth * @return Boolean indicating whether the ACL allows the role or not. * Always returns false if the kernel hasn't been initialized yet. */ function hasPermission(address _who, address _where, bytes32 _what, bytes _how) public view returns (bool) { IACL defaultAcl = acl(); return address(defaultAcl) != address(0) && // Poor man's initialization check (saves gas) defaultAcl.hasPermission(_who, _where, _what, _how); } function _setApp(bytes32 _namespace, bytes32 _appId, address _app) internal { require(isContract(_app), ERROR_APP_NOT_CONTRACT); apps[_namespace][_appId] = _app; emit SetApp(_namespace, _appId, _app); } function _setAppIfNew(bytes32 _namespace, bytes32 _appId, address _app) internal { address app = getApp(_namespace, _appId); if (app != address(0)) { // The only way to set an app is if it passes the isContract check, so no need to check it again require(app == _app, ERROR_INVALID_APP_CHANGE); } else { _setApp(_namespace, _appId, _app); } } modifier auth(bytes32 _role, uint256[] memory _params) { require( hasPermission(msg.sender, address(this), _role, ConversionHelpers.dangerouslyCastUintArrayToBytes(_params)), ERROR_AUTH_FAILED ); _; } } // File: @aragon/os/contracts/lib/ens/AbstractENS.sol // See https://github.com/ensdomains/ens/blob/7e377df83f/contracts/AbstractENS.sol pragma solidity ^0.4.15; interface AbstractENS { function owner(bytes32 _node) public constant returns (address); function resolver(bytes32 _node) public constant returns (address); function ttl(bytes32 _node) public constant returns (uint64); function setOwner(bytes32 _node, address _owner) public; function setSubnodeOwner(bytes32 _node, bytes32 label, address _owner) public; function setResolver(bytes32 _node, address _resolver) public; function setTTL(bytes32 _node, uint64 _ttl) public; // Logged when the owner of a node assigns a new owner to a subnode. event NewOwner(bytes32 indexed _node, bytes32 indexed _label, address _owner); // Logged when the owner of a node transfers ownership to a new account. event Transfer(bytes32 indexed _node, address _owner); // Logged when the resolver for a node changes. event NewResolver(bytes32 indexed _node, address _resolver); // Logged when the TTL of a node changes event NewTTL(bytes32 indexed _node, uint64 _ttl); } // File: @aragon/os/contracts/lib/ens/ENS.sol // See https://github.com/ensdomains/ens/blob/7e377df83f/contracts/ENS.sol pragma solidity ^0.4.0; /** * The ENS registry contract. */ contract ENS is AbstractENS { struct Record { address owner; address resolver; uint64 ttl; } mapping(bytes32=>Record) records; // Permits modifications only by the owner of the specified node. modifier only_owner(bytes32 node) { if (records[node].owner != msg.sender) throw; _; } /** * Constructs a new ENS registrar. */ function ENS() public { records[0].owner = msg.sender; } /** * Returns the address that owns the specified node. */ function owner(bytes32 node) public constant returns (address) { return records[node].owner; } /** * Returns the address of the resolver for the specified node. */ function resolver(bytes32 node) public constant returns (address) { return records[node].resolver; } /** * Returns the TTL of a node, and any records associated with it. */ function ttl(bytes32 node) public constant returns (uint64) { return records[node].ttl; } /** * Transfers ownership of a node to a new address. May only be called by the current * owner of the node. * @param node The node to transfer ownership of. * @param owner The address of the new owner. */ function setOwner(bytes32 node, address owner) only_owner(node) public { Transfer(node, owner); records[node].owner = owner; } /** * Transfers ownership of a subnode keccak256(node, label) to a new address. May only be * called by the owner of the parent node. * @param node The parent node. * @param label The hash of the label specifying the subnode. * @param owner The address of the new owner. */ function setSubnodeOwner(bytes32 node, bytes32 label, address owner) only_owner(node) public { var subnode = keccak256(node, label); NewOwner(node, label, owner); records[subnode].owner = owner; } /** * Sets the resolver address for the specified node. * @param node The node to update. * @param resolver The address of the resolver. */ function setResolver(bytes32 node, address resolver) only_owner(node) public { NewResolver(node, resolver); records[node].resolver = resolver; } /** * Sets the TTL for the specified node. * @param node The node to update. * @param ttl The TTL in seconds. */ function setTTL(bytes32 node, uint64 ttl) only_owner(node) public { NewTTL(node, ttl); records[node].ttl = ttl; } } // File: @aragon/os/contracts/lib/ens/PublicResolver.sol // See https://github.com/ensdomains/ens/blob/7e377df83f/contracts/PublicResolver.sol pragma solidity ^0.4.0; /** * A simple resolver anyone can use; only allows the owner of a node to set its * address. */ contract PublicResolver { bytes4 constant INTERFACE_META_ID = 0x01ffc9a7; bytes4 constant ADDR_INTERFACE_ID = 0x3b3b57de; bytes4 constant CONTENT_INTERFACE_ID = 0xd8389dc5; bytes4 constant NAME_INTERFACE_ID = 0x691f3431; bytes4 constant ABI_INTERFACE_ID = 0x2203ab56; bytes4 constant PUBKEY_INTERFACE_ID = 0xc8690233; bytes4 constant TEXT_INTERFACE_ID = 0x59d1d43c; event AddrChanged(bytes32 indexed node, address a); event ContentChanged(bytes32 indexed node, bytes32 hash); event NameChanged(bytes32 indexed node, string name); event ABIChanged(bytes32 indexed node, uint256 indexed contentType); event PubkeyChanged(bytes32 indexed node, bytes32 x, bytes32 y); event TextChanged(bytes32 indexed node, string indexed indexedKey, string key); struct PublicKey { bytes32 x; bytes32 y; } struct Record { address addr; bytes32 content; string name; PublicKey pubkey; mapping(string=>string) text; mapping(uint256=>bytes) abis; } AbstractENS ens; mapping(bytes32=>Record) records; modifier only_owner(bytes32 node) { if (ens.owner(node) != msg.sender) throw; _; } /** * Constructor. * @param ensAddr The ENS registrar contract. */ function PublicResolver(AbstractENS ensAddr) public { ens = ensAddr; } /** * Returns true if the resolver implements the interface specified by the provided hash. * @param interfaceID The ID of the interface to check for. * @return True if the contract implements the requested interface. */ function supportsInterface(bytes4 interfaceID) public pure returns (bool) { return interfaceID == ADDR_INTERFACE_ID || interfaceID == CONTENT_INTERFACE_ID || interfaceID == NAME_INTERFACE_ID || interfaceID == ABI_INTERFACE_ID || interfaceID == PUBKEY_INTERFACE_ID || interfaceID == TEXT_INTERFACE_ID || interfaceID == INTERFACE_META_ID; } /** * Returns the address associated with an ENS node. * @param node The ENS node to query. * @return The associated address. */ function addr(bytes32 node) public constant returns (address ret) { ret = records[node].addr; } /** * Sets the address associated with an ENS node. * May only be called by the owner of that node in the ENS registry. * @param node The node to update. * @param addr The address to set. */ function setAddr(bytes32 node, address addr) only_owner(node) public { records[node].addr = addr; AddrChanged(node, addr); } /** * Returns the content hash associated with an ENS node. * Note that this resource type is not standardized, and will likely change * in future to a resource type based on multihash. * @param node The ENS node to query. * @return The associated content hash. */ function content(bytes32 node) public constant returns (bytes32 ret) { ret = records[node].content; } /** * Sets the content hash associated with an ENS node. * May only be called by the owner of that node in the ENS registry. * Note that this resource type is not standardized, and will likely change * in future to a resource type based on multihash. * @param node The node to update. * @param hash The content hash to set */ function setContent(bytes32 node, bytes32 hash) only_owner(node) public { records[node].content = hash; ContentChanged(node, hash); } /** * Returns the name associated with an ENS node, for reverse records. * Defined in EIP181. * @param node The ENS node to query. * @return The associated name. */ function name(bytes32 node) public constant returns (string ret) { ret = records[node].name; } /** * Sets the name associated with an ENS node, for reverse records. * May only be called by the owner of that node in the ENS registry. * @param node The node to update. * @param name The name to set. */ function setName(bytes32 node, string name) only_owner(node) public { records[node].name = name; NameChanged(node, name); } /** * Returns the ABI associated with an ENS node. * Defined in EIP205. * @param node The ENS node to query * @param contentTypes A bitwise OR of the ABI formats accepted by the caller. * @return contentType The content type of the return value * @return data The ABI data */ function ABI(bytes32 node, uint256 contentTypes) public constant returns (uint256 contentType, bytes data) { var record = records[node]; for(contentType = 1; contentType <= contentTypes; contentType <<= 1) { if ((contentType & contentTypes) != 0 && record.abis[contentType].length > 0) { data = record.abis[contentType]; return; } } contentType = 0; } /** * Sets the ABI associated with an ENS node. * Nodes may have one ABI of each content type. To remove an ABI, set it to * the empty string. * @param node The node to update. * @param contentType The content type of the ABI * @param data The ABI data. */ function setABI(bytes32 node, uint256 contentType, bytes data) only_owner(node) public { // Content types must be powers of 2 if (((contentType - 1) & contentType) != 0) throw; records[node].abis[contentType] = data; ABIChanged(node, contentType); } /** * Returns the SECP256k1 public key associated with an ENS node. * Defined in EIP 619. * @param node The ENS node to query * @return x, y the X and Y coordinates of the curve point for the public key. */ function pubkey(bytes32 node) public constant returns (bytes32 x, bytes32 y) { return (records[node].pubkey.x, records[node].pubkey.y); } /** * Sets the SECP256k1 public key associated with an ENS node. * @param node The ENS node to query * @param x the X coordinate of the curve point for the public key. * @param y the Y coordinate of the curve point for the public key. */ function setPubkey(bytes32 node, bytes32 x, bytes32 y) only_owner(node) public { records[node].pubkey = PublicKey(x, y); PubkeyChanged(node, x, y); } /** * Returns the text data associated with an ENS node and key. * @param node The ENS node to query. * @param key The text data key to query. * @return The associated text data. */ function text(bytes32 node, string key) public constant returns (string ret) { ret = records[node].text[key]; } /** * Sets the text data associated with an ENS node and key. * May only be called by the owner of that node in the ENS registry. * @param node The node to update. * @param key The key to set. * @param value The text data value to set. */ function setText(bytes32 node, string key, string value) only_owner(node) public { records[node].text[key] = value; TextChanged(node, key, key); } } // File: @aragon/os/contracts/kernel/KernelProxy.sol pragma solidity 0.4.24; contract KernelProxy is IKernelEvents, KernelStorage, KernelAppIds, KernelNamespaceConstants, IsContract, DepositableDelegateProxy { /** * @dev KernelProxy is a proxy contract to a kernel implementation. The implementation * can update the reference, which effectively upgrades the contract * @param _kernelImpl Address of the contract used as implementation for kernel */ constructor(IKernel _kernelImpl) public { require(isContract(address(_kernelImpl))); apps[KERNEL_CORE_NAMESPACE][KERNEL_CORE_APP_ID] = _kernelImpl; // Note that emitting this event is important for verifying that a KernelProxy instance // was never upgraded to a malicious Kernel logic contract over its lifespan. // This starts the "chain of trust", that can be followed through later SetApp() events // emitted during kernel upgrades. emit SetApp(KERNEL_CORE_NAMESPACE, KERNEL_CORE_APP_ID, _kernelImpl); } /** * @dev ERC897, whether it is a forwarding (1) or an upgradeable (2) proxy */ function proxyType() public pure returns (uint256 proxyTypeId) { return UPGRADEABLE; } /** * @dev ERC897, the address the proxy would delegate calls to */ function implementation() public view returns (address) { return apps[KERNEL_CORE_NAMESPACE][KERNEL_CORE_APP_ID]; } } // File: @aragon/os/contracts/evmscript/ScriptHelpers.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; library ScriptHelpers { function getSpecId(bytes _script) internal pure returns (uint32) { return uint32At(_script, 0); } function uint256At(bytes _data, uint256 _location) internal pure returns (uint256 result) { assembly { result := mload(add(_data, add(0x20, _location))) } } function addressAt(bytes _data, uint256 _location) internal pure returns (address result) { uint256 word = uint256At(_data, _location); assembly { result := div(and(word, 0xffffffffffffffffffffffffffffffffffffffff000000000000000000000000), 0x1000000000000000000000000) } } function uint32At(bytes _data, uint256 _location) internal pure returns (uint32 result) { uint256 word = uint256At(_data, _location); assembly { result := div(and(word, 0xffffffff00000000000000000000000000000000000000000000000000000000), 0x100000000000000000000000000000000000000000000000000000000) } } function locationOf(bytes _data, uint256 _location) internal pure returns (uint256 result) { assembly { result := add(_data, add(0x20, _location)) } } function toBytes(bytes4 _sig) internal pure returns (bytes) { bytes memory payload = new bytes(4); assembly { mstore(add(payload, 0x20), _sig) } return payload; } } // File: @aragon/os/contracts/evmscript/EVMScriptRegistry.sol pragma solidity 0.4.24; /* solium-disable function-order */ // Allow public initialize() to be first contract EVMScriptRegistry is IEVMScriptRegistry, EVMScriptRegistryConstants, AragonApp { using ScriptHelpers for bytes; /* Hardcoded constants to save gas bytes32 public constant REGISTRY_ADD_EXECUTOR_ROLE = keccak256("REGISTRY_ADD_EXECUTOR_ROLE"); bytes32 public constant REGISTRY_MANAGER_ROLE = keccak256("REGISTRY_MANAGER_ROLE"); */ bytes32 public constant REGISTRY_ADD_EXECUTOR_ROLE = 0xc4e90f38eea8c4212a009ca7b8947943ba4d4a58d19b683417f65291d1cd9ed2; // WARN: Manager can censor all votes and the like happening in an org bytes32 public constant REGISTRY_MANAGER_ROLE = 0xf7a450ef335e1892cb42c8ca72e7242359d7711924b75db5717410da3f614aa3; uint256 internal constant SCRIPT_START_LOCATION = 4; string private constant ERROR_INEXISTENT_EXECUTOR = "EVMREG_INEXISTENT_EXECUTOR"; string private constant ERROR_EXECUTOR_ENABLED = "EVMREG_EXECUTOR_ENABLED"; string private constant ERROR_EXECUTOR_DISABLED = "EVMREG_EXECUTOR_DISABLED"; string private constant ERROR_SCRIPT_LENGTH_TOO_SHORT = "EVMREG_SCRIPT_LENGTH_TOO_SHORT"; struct ExecutorEntry { IEVMScriptExecutor executor; bool enabled; } uint256 private executorsNextIndex; mapping (uint256 => ExecutorEntry) public executors; event EnableExecutor(uint256 indexed executorId, address indexed executorAddress); event DisableExecutor(uint256 indexed executorId, address indexed executorAddress); modifier executorExists(uint256 _executorId) { require(_executorId > 0 && _executorId < executorsNextIndex, ERROR_INEXISTENT_EXECUTOR); _; } /** * @notice Initialize the registry */ function initialize() public onlyInit { initialized(); // Create empty record to begin executor IDs at 1 executorsNextIndex = 1; } /** * @notice Add a new script executor with address `_executor` to the registry * @param _executor Address of the IEVMScriptExecutor that will be added to the registry * @return id Identifier of the executor in the registry */ function addScriptExecutor(IEVMScriptExecutor _executor) external auth(REGISTRY_ADD_EXECUTOR_ROLE) returns (uint256 id) { uint256 executorId = executorsNextIndex++; executors[executorId] = ExecutorEntry(_executor, true); emit EnableExecutor(executorId, _executor); return executorId; } /** * @notice Disable script executor with ID `_executorId` * @param _executorId Identifier of the executor in the registry */ function disableScriptExecutor(uint256 _executorId) external authP(REGISTRY_MANAGER_ROLE, arr(_executorId)) { // Note that we don't need to check for an executor's existence in this case, as only // existing executors can be enabled ExecutorEntry storage executorEntry = executors[_executorId]; require(executorEntry.enabled, ERROR_EXECUTOR_DISABLED); executorEntry.enabled = false; emit DisableExecutor(_executorId, executorEntry.executor); } /** * @notice Enable script executor with ID `_executorId` * @param _executorId Identifier of the executor in the registry */ function enableScriptExecutor(uint256 _executorId) external authP(REGISTRY_MANAGER_ROLE, arr(_executorId)) executorExists(_executorId) { ExecutorEntry storage executorEntry = executors[_executorId]; require(!executorEntry.enabled, ERROR_EXECUTOR_ENABLED); executorEntry.enabled = true; emit EnableExecutor(_executorId, executorEntry.executor); } /** * @dev Get the script executor that can execute a particular script based on its first 4 bytes * @param _script EVMScript being inspected */ function getScriptExecutor(bytes _script) public view returns (IEVMScriptExecutor) { require(_script.length >= SCRIPT_START_LOCATION, ERROR_SCRIPT_LENGTH_TOO_SHORT); uint256 id = _script.getSpecId(); // Note that we don't need to check for an executor's existence in this case, as only // existing executors can be enabled ExecutorEntry storage entry = executors[id]; return entry.enabled ? entry.executor : IEVMScriptExecutor(0); } } // File: @aragon/os/contracts/evmscript/executors/BaseEVMScriptExecutor.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract BaseEVMScriptExecutor is IEVMScriptExecutor, Autopetrified { uint256 internal constant SCRIPT_START_LOCATION = 4; } // File: @aragon/os/contracts/evmscript/executors/CallsScript.sol pragma solidity 0.4.24; // Inspired by https://github.com/reverendus/tx-manager contract CallsScript is BaseEVMScriptExecutor { using ScriptHelpers for bytes; /* Hardcoded constants to save gas bytes32 internal constant EXECUTOR_TYPE = keccak256("CALLS_SCRIPT"); */ bytes32 internal constant EXECUTOR_TYPE = 0x2dc858a00f3e417be1394b87c07158e989ec681ce8cc68a9093680ac1a870302; string private constant ERROR_BLACKLISTED_CALL = "EVMCALLS_BLACKLISTED_CALL"; string private constant ERROR_INVALID_LENGTH = "EVMCALLS_INVALID_LENGTH"; /* This is manually crafted in assembly string private constant ERROR_CALL_REVERTED = "EVMCALLS_CALL_REVERTED"; */ event LogScriptCall(address indexed sender, address indexed src, address indexed dst); /** * @notice Executes a number of call scripts * @param _script [ specId (uint32) ] many calls with this structure -> * [ to (address: 20 bytes) ] [ calldataLength (uint32: 4 bytes) ] [ calldata (calldataLength bytes) ] * @param _blacklist Addresses the script cannot call to, or will revert. * @return Always returns empty byte array */ function execScript(bytes _script, bytes, address[] _blacklist) external isInitialized returns (bytes) { uint256 location = SCRIPT_START_LOCATION; // first 32 bits are spec id while (location < _script.length) { // Check there's at least address + calldataLength available require(_script.length - location >= 0x18, ERROR_INVALID_LENGTH); address contractAddress = _script.addressAt(location); // Check address being called is not blacklist for (uint256 i = 0; i < _blacklist.length; i++) { require(contractAddress != _blacklist[i], ERROR_BLACKLISTED_CALL); } // logged before execution to ensure event ordering in receipt // if failed entire execution is reverted regardless emit LogScriptCall(msg.sender, address(this), contractAddress); uint256 calldataLength = uint256(_script.uint32At(location + 0x14)); uint256 startOffset = location + 0x14 + 0x04; uint256 calldataStart = _script.locationOf(startOffset); // compute end of script / next location location = startOffset + calldataLength; require(location <= _script.length, ERROR_INVALID_LENGTH); bool success; assembly { success := call( sub(gas, 5000), // forward gas left - 5000 contractAddress, // address 0, // no value calldataStart, // calldata start calldataLength, // calldata length 0, // don't write output 0 // don't write output ) switch success case 0 { let ptr := mload(0x40) switch returndatasize case 0 { // No error data was returned, revert with "EVMCALLS_CALL_REVERTED" // See remix: doing a `revert("EVMCALLS_CALL_REVERTED")` always results in // this memory layout mstore(ptr, 0x08c379a000000000000000000000000000000000000000000000000000000000) // error identifier mstore(add(ptr, 0x04), 0x0000000000000000000000000000000000000000000000000000000000000020) // starting offset mstore(add(ptr, 0x24), 0x0000000000000000000000000000000000000000000000000000000000000016) // reason length mstore(add(ptr, 0x44), 0x45564d43414c4c535f43414c4c5f524556455254454400000000000000000000) // reason revert(ptr, 100) // 100 = 4 + 3 * 32 (error identifier + 3 words for the ABI encoded error) } default { // Forward the full error data returndatacopy(ptr, 0, returndatasize) revert(ptr, returndatasize) } } default { } } } // No need to allocate empty bytes for the return as this can only be called via an delegatecall // (due to the isInitialized modifier) } function executorType() external pure returns (bytes32) { return EXECUTOR_TYPE; } } // File: @aragon/os/contracts/factory/EVMScriptRegistryFactory.sol pragma solidity 0.4.24; contract EVMScriptRegistryFactory is EVMScriptRegistryConstants { EVMScriptRegistry public baseReg; IEVMScriptExecutor public baseCallScript; /** * @notice Create a new EVMScriptRegistryFactory. */ constructor() public { baseReg = new EVMScriptRegistry(); baseCallScript = IEVMScriptExecutor(new CallsScript()); } /** * @notice Install a new pinned instance of EVMScriptRegistry on `_dao`. * @param _dao Kernel * @return Installed EVMScriptRegistry */ function newEVMScriptRegistry(Kernel _dao) public returns (EVMScriptRegistry reg) { bytes memory initPayload = abi.encodeWithSelector(reg.initialize.selector); reg = EVMScriptRegistry(_dao.newPinnedAppInstance(EVMSCRIPT_REGISTRY_APP_ID, baseReg, initPayload, true)); ACL acl = ACL(_dao.acl()); acl.createPermission(this, reg, reg.REGISTRY_ADD_EXECUTOR_ROLE(), this); reg.addScriptExecutor(baseCallScript); // spec 1 = CallsScript // Clean up the permissions acl.revokePermission(this, reg, reg.REGISTRY_ADD_EXECUTOR_ROLE()); acl.removePermissionManager(reg, reg.REGISTRY_ADD_EXECUTOR_ROLE()); return reg; } } // File: @aragon/os/contracts/factory/DAOFactory.sol pragma solidity 0.4.24; contract DAOFactory { IKernel public baseKernel; IACL public baseACL; EVMScriptRegistryFactory public regFactory; event DeployDAO(address dao); event DeployEVMScriptRegistry(address reg); /** * @notice Create a new DAOFactory, creating DAOs with Kernels proxied to `_baseKernel`, ACLs proxied to `_baseACL`, and new EVMScriptRegistries created from `_regFactory`. * @param _baseKernel Base Kernel * @param _baseACL Base ACL * @param _regFactory EVMScriptRegistry factory */ constructor(IKernel _baseKernel, IACL _baseACL, EVMScriptRegistryFactory _regFactory) public { // No need to init as it cannot be killed by devops199 if (address(_regFactory) != address(0)) { regFactory = _regFactory; } baseKernel = _baseKernel; baseACL = _baseACL; } /** * @notice Create a new DAO with `_root` set as the initial admin * @param _root Address that will be granted control to setup DAO permissions * @return Newly created DAO */ function newDAO(address _root) public returns (Kernel) { Kernel dao = Kernel(new KernelProxy(baseKernel)); if (address(regFactory) == address(0)) { dao.initialize(baseACL, _root); } else { dao.initialize(baseACL, this); ACL acl = ACL(dao.acl()); bytes32 permRole = acl.CREATE_PERMISSIONS_ROLE(); bytes32 appManagerRole = dao.APP_MANAGER_ROLE(); acl.grantPermission(regFactory, acl, permRole); acl.createPermission(regFactory, dao, appManagerRole, this); EVMScriptRegistry reg = regFactory.newEVMScriptRegistry(dao); emit DeployEVMScriptRegistry(address(reg)); // Clean up permissions // First, completely reset the APP_MANAGER_ROLE acl.revokePermission(regFactory, dao, appManagerRole); acl.removePermissionManager(dao, appManagerRole); // Then, make root the only holder and manager of CREATE_PERMISSIONS_ROLE acl.revokePermission(regFactory, acl, permRole); acl.revokePermission(this, acl, permRole); acl.grantPermission(_root, acl, permRole); acl.setPermissionManager(_root, acl, permRole); } emit DeployDAO(address(dao)); return dao; } } // File: @aragon/id/contracts/ens/IPublicResolver.sol pragma solidity ^0.4.0; interface IPublicResolver { function supportsInterface(bytes4 interfaceID) constant returns (bool); function addr(bytes32 node) constant returns (address ret); function setAddr(bytes32 node, address addr); function hash(bytes32 node) constant returns (bytes32 ret); function setHash(bytes32 node, bytes32 hash); } // File: @aragon/id/contracts/IFIFSResolvingRegistrar.sol pragma solidity 0.4.24; interface IFIFSResolvingRegistrar { function register(bytes32 _subnode, address _owner) external; function registerWithResolver(bytes32 _subnode, address _owner, IPublicResolver _resolver) public; } // File: @aragon/templates-shared/contracts/BaseTemplate.sol pragma solidity 0.4.24; contract BaseTemplate is APMNamehash, IsContract { using Uint256Helpers for uint256; /* Hardcoded constant to save gas * bytes32 constant internal AGENT_APP_ID = apmNamehash("agent"); // agent.aragonpm.eth * bytes32 constant internal VAULT_APP_ID = apmNamehash("vault"); // vault.aragonpm.eth * bytes32 constant internal VOTING_APP_ID = apmNamehash("voting"); // voting.aragonpm.eth * bytes32 constant internal SURVEY_APP_ID = apmNamehash("survey"); // survey.aragonpm.eth * bytes32 constant internal PAYROLL_APP_ID = apmNamehash("payroll"); // payroll.aragonpm.eth * bytes32 constant internal FINANCE_APP_ID = apmNamehash("finance"); // finance.aragonpm.eth * bytes32 constant internal TOKEN_MANAGER_APP_ID = apmNamehash("token-manager"); // token-manager.aragonpm.eth */ bytes32 constant internal AGENT_APP_ID = 0x9ac98dc5f995bf0211ed589ef022719d1487e5cb2bab505676f0d084c07cf89a; bytes32 constant internal VAULT_APP_ID = 0x7e852e0fcfce6551c13800f1e7476f982525c2b5277ba14b24339c68416336d1; bytes32 constant internal VOTING_APP_ID = 0x9fa3927f639745e587912d4b0fea7ef9013bf93fb907d29faeab57417ba6e1d4; bytes32 constant internal PAYROLL_APP_ID = 0x463f596a96d808cb28b5d080181e4a398bc793df2c222f6445189eb801001991; bytes32 constant internal FINANCE_APP_ID = 0xbf8491150dafc5dcaee5b861414dca922de09ccffa344964ae167212e8c673ae; bytes32 constant internal TOKEN_MANAGER_APP_ID = 0x6b20a3010614eeebf2138ccec99f028a61c811b3b1a3343b6ff635985c75c91f; bytes32 constant internal SURVEY_APP_ID = 0x030b2ab880b88e228f2da5a3d19a2a31bc10dbf91fb1143776a6de489389471e; string constant private ERROR_ENS_NOT_CONTRACT = "TEMPLATE_ENS_NOT_CONTRACT"; string constant private ERROR_DAO_FACTORY_NOT_CONTRACT = "TEMPLATE_DAO_FAC_NOT_CONTRACT"; string constant private ERROR_ARAGON_ID_NOT_PROVIDED = "TEMPLATE_ARAGON_ID_NOT_PROVIDED"; string constant private ERROR_ARAGON_ID_NOT_CONTRACT = "TEMPLATE_ARAGON_ID_NOT_CONTRACT"; string constant private ERROR_MINIME_FACTORY_NOT_PROVIDED = "TEMPLATE_MINIME_FAC_NOT_PROVIDED"; string constant private ERROR_MINIME_FACTORY_NOT_CONTRACT = "TEMPLATE_MINIME_FAC_NOT_CONTRACT"; string constant private ERROR_CANNOT_CAST_VALUE_TO_ADDRESS = "TEMPLATE_CANNOT_CAST_VALUE_TO_ADDRESS"; string constant private ERROR_INVALID_ID = "TEMPLATE_INVALID_ID"; ENS internal ens; DAOFactory internal daoFactory; MiniMeTokenFactory internal miniMeFactory; IFIFSResolvingRegistrar internal aragonID; event DeployDao(address dao); event SetupDao(address dao); event DeployToken(address token); event InstalledApp(address appProxy, bytes32 appId); constructor(DAOFactory _daoFactory, ENS _ens, MiniMeTokenFactory _miniMeFactory, IFIFSResolvingRegistrar _aragonID) public { require(isContract(address(_ens)), ERROR_ENS_NOT_CONTRACT); require(isContract(address(_daoFactory)), ERROR_DAO_FACTORY_NOT_CONTRACT); ens = _ens; aragonID = _aragonID; daoFactory = _daoFactory; miniMeFactory = _miniMeFactory; } /** * @dev Create a DAO using the DAO Factory and grant the template root permissions so it has full * control during setup. Once the DAO setup has finished, it is recommended to call the * `_transferRootPermissionsFromTemplateAndFinalizeDAO()` helper to transfer the root * permissions to the end entity in control of the organization. */ function _createDAO() internal returns (Kernel dao, ACL acl) { dao = daoFactory.newDAO(this); emit DeployDao(address(dao)); acl = ACL(dao.acl()); _createPermissionForTemplate(acl, dao, dao.APP_MANAGER_ROLE()); } /* ACL */ function _createPermissions(ACL _acl, address[] memory _grantees, address _app, bytes32 _permission, address _manager) internal { _acl.createPermission(_grantees[0], _app, _permission, address(this)); for (uint256 i = 1; i < _grantees.length; i++) { _acl.grantPermission(_grantees[i], _app, _permission); } _acl.revokePermission(address(this), _app, _permission); _acl.setPermissionManager(_manager, _app, _permission); } function _createPermissionForTemplate(ACL _acl, address _app, bytes32 _permission) internal { _acl.createPermission(address(this), _app, _permission, address(this)); } function _removePermissionFromTemplate(ACL _acl, address _app, bytes32 _permission) internal { _acl.revokePermission(address(this), _app, _permission); _acl.removePermissionManager(_app, _permission); } function _transferRootPermissionsFromTemplateAndFinalizeDAO(Kernel _dao, address _to) internal { _transferRootPermissionsFromTemplateAndFinalizeDAO(_dao, _to, _to); } function _transferRootPermissionsFromTemplateAndFinalizeDAO(Kernel _dao, address _to, address _manager) internal { ACL _acl = ACL(_dao.acl()); _transferPermissionFromTemplate(_acl, _dao, _to, _dao.APP_MANAGER_ROLE(), _manager); _transferPermissionFromTemplate(_acl, _acl, _to, _acl.CREATE_PERMISSIONS_ROLE(), _manager); emit SetupDao(_dao); } function _transferPermissionFromTemplate(ACL _acl, address _app, address _to, bytes32 _permission, address _manager) internal { _acl.grantPermission(_to, _app, _permission); _acl.revokePermission(address(this), _app, _permission); _acl.setPermissionManager(_manager, _app, _permission); } /* AGENT */ function _installDefaultAgentApp(Kernel _dao) internal returns (Agent) { bytes memory initializeData = abi.encodeWithSelector(Agent(0).initialize.selector); Agent agent = Agent(_installDefaultApp(_dao, AGENT_APP_ID, initializeData)); // We assume that installing the Agent app as a default app means the DAO should have its // Vault replaced by the Agent. Thus, we also set the DAO's recovery app to the Agent. _dao.setRecoveryVaultAppId(AGENT_APP_ID); return agent; } function _installNonDefaultAgentApp(Kernel _dao) internal returns (Agent) { bytes memory initializeData = abi.encodeWithSelector(Agent(0).initialize.selector); return Agent(_installNonDefaultApp(_dao, AGENT_APP_ID, initializeData)); } function _createAgentPermissions(ACL _acl, Agent _agent, address _grantee, address _manager) internal { _acl.createPermission(_grantee, _agent, _agent.EXECUTE_ROLE(), _manager); _acl.createPermission(_grantee, _agent, _agent.RUN_SCRIPT_ROLE(), _manager); } /* VAULT */ function _installVaultApp(Kernel _dao) internal returns (Vault) { bytes memory initializeData = abi.encodeWithSelector(Vault(0).initialize.selector); return Vault(_installDefaultApp(_dao, VAULT_APP_ID, initializeData)); } function _createVaultPermissions(ACL _acl, Vault _vault, address _grantee, address _manager) internal { _acl.createPermission(_grantee, _vault, _vault.TRANSFER_ROLE(), _manager); } /* VOTING */ function _installVotingApp(Kernel _dao, MiniMeToken _token, uint64[3] memory _votingSettings) internal returns (Voting) { return _installVotingApp(_dao, _token, _votingSettings[0], _votingSettings[1], _votingSettings[2]); } function _installVotingApp( Kernel _dao, MiniMeToken _token, uint64 _support, uint64 _acceptance, uint64 _duration ) internal returns (Voting) { bytes memory initializeData = abi.encodeWithSelector(Voting(0).initialize.selector, _token, _support, _acceptance, _duration); return Voting(_installNonDefaultApp(_dao, VOTING_APP_ID, initializeData)); } function _createVotingPermissions( ACL _acl, Voting _voting, address _settingsGrantee, address _createVotesGrantee, address _manager ) internal { _acl.createPermission(_settingsGrantee, _voting, _voting.MODIFY_QUORUM_ROLE(), _manager); _acl.createPermission(_settingsGrantee, _voting, _voting.MODIFY_SUPPORT_ROLE(), _manager); _acl.createPermission(_createVotesGrantee, _voting, _voting.CREATE_VOTES_ROLE(), _manager); } /* SURVEY */ function _installSurveyApp(Kernel _dao, MiniMeToken _token, uint64 _minParticipationPct, uint64 _surveyTime) internal returns (Survey) { bytes memory initializeData = abi.encodeWithSelector(Survey(0).initialize.selector, _token, _minParticipationPct, _surveyTime); return Survey(_installNonDefaultApp(_dao, SURVEY_APP_ID, initializeData)); } function _createSurveyPermissions(ACL _acl, Survey _survey, address _grantee, address _manager) internal { _acl.createPermission(_grantee, _survey, _survey.CREATE_SURVEYS_ROLE(), _manager); _acl.createPermission(_grantee, _survey, _survey.MODIFY_PARTICIPATION_ROLE(), _manager); } /* PAYROLL */ function _installPayrollApp( Kernel _dao, Finance _finance, address _denominationToken, IFeed _priceFeed, uint64 _rateExpiryTime ) internal returns (Payroll) { bytes memory initializeData = abi.encodeWithSelector( Payroll(0).initialize.selector, _finance, _denominationToken, _priceFeed, _rateExpiryTime ); return Payroll(_installNonDefaultApp(_dao, PAYROLL_APP_ID, initializeData)); } /** * @dev Internal function to configure payroll permissions. Note that we allow defining different managers for * payroll since it may be useful to have one control the payroll settings (rate expiration, price feed, * and allowed tokens), and another one to control the employee functionality (bonuses, salaries, * reimbursements, employees, etc). * @param _acl ACL instance being configured * @param _acl Payroll app being configured * @param _employeeManager Address that will receive permissions to handle employee payroll functionality * @param _settingsManager Address that will receive permissions to manage payroll settings * @param _permissionsManager Address that will be the ACL manager for the payroll permissions */ function _createPayrollPermissions( ACL _acl, Payroll _payroll, address _employeeManager, address _settingsManager, address _permissionsManager ) internal { _acl.createPermission(_employeeManager, _payroll, _payroll.ADD_BONUS_ROLE(), _permissionsManager); _acl.createPermission(_employeeManager, _payroll, _payroll.ADD_EMPLOYEE_ROLE(), _permissionsManager); _acl.createPermission(_employeeManager, _payroll, _payroll.ADD_REIMBURSEMENT_ROLE(), _permissionsManager); _acl.createPermission(_employeeManager, _payroll, _payroll.TERMINATE_EMPLOYEE_ROLE(), _permissionsManager); _acl.createPermission(_employeeManager, _payroll, _payroll.SET_EMPLOYEE_SALARY_ROLE(), _permissionsManager); _acl.createPermission(_settingsManager, _payroll, _payroll.MODIFY_PRICE_FEED_ROLE(), _permissionsManager); _acl.createPermission(_settingsManager, _payroll, _payroll.MODIFY_RATE_EXPIRY_ROLE(), _permissionsManager); _acl.createPermission(_settingsManager, _payroll, _payroll.MANAGE_ALLOWED_TOKENS_ROLE(), _permissionsManager); } function _unwrapPayrollSettings( uint256[4] memory _payrollSettings ) internal pure returns (address denominationToken, IFeed priceFeed, uint64 rateExpiryTime, address employeeManager) { denominationToken = _toAddress(_payrollSettings[0]); priceFeed = IFeed(_toAddress(_payrollSettings[1])); rateExpiryTime = _payrollSettings[2].toUint64(); employeeManager = _toAddress(_payrollSettings[3]); } /* FINANCE */ function _installFinanceApp(Kernel _dao, Vault _vault, uint64 _periodDuration) internal returns (Finance) { bytes memory initializeData = abi.encodeWithSelector(Finance(0).initialize.selector, _vault, _periodDuration); return Finance(_installNonDefaultApp(_dao, FINANCE_APP_ID, initializeData)); } function _createFinancePermissions(ACL _acl, Finance _finance, address _grantee, address _manager) internal { _acl.createPermission(_grantee, _finance, _finance.EXECUTE_PAYMENTS_ROLE(), _manager); _acl.createPermission(_grantee, _finance, _finance.MANAGE_PAYMENTS_ROLE(), _manager); } function _createFinanceCreatePaymentsPermission(ACL _acl, Finance _finance, address _grantee, address _manager) internal { _acl.createPermission(_grantee, _finance, _finance.CREATE_PAYMENTS_ROLE(), _manager); } function _grantCreatePaymentPermission(ACL _acl, Finance _finance, address _to) internal { _acl.grantPermission(_to, _finance, _finance.CREATE_PAYMENTS_ROLE()); } function _transferCreatePaymentManagerFromTemplate(ACL _acl, Finance _finance, address _manager) internal { _acl.setPermissionManager(_manager, _finance, _finance.CREATE_PAYMENTS_ROLE()); } /* TOKEN MANAGER */ function _installTokenManagerApp( Kernel _dao, MiniMeToken _token, bool _transferable, uint256 _maxAccountTokens ) internal returns (TokenManager) { TokenManager tokenManager = TokenManager(_installNonDefaultApp(_dao, TOKEN_MANAGER_APP_ID)); _token.changeController(tokenManager); tokenManager.initialize(_token, _transferable, _maxAccountTokens); return tokenManager; } function _createTokenManagerPermissions(ACL _acl, TokenManager _tokenManager, address _grantee, address _manager) internal { _acl.createPermission(_grantee, _tokenManager, _tokenManager.MINT_ROLE(), _manager); _acl.createPermission(_grantee, _tokenManager, _tokenManager.BURN_ROLE(), _manager); } function _mintTokens(ACL _acl, TokenManager _tokenManager, address[] memory _holders, uint256[] memory _stakes) internal { _createPermissionForTemplate(_acl, _tokenManager, _tokenManager.MINT_ROLE()); for (uint256 i = 0; i < _holders.length; i++) { _tokenManager.mint(_holders[i], _stakes[i]); } _removePermissionFromTemplate(_acl, _tokenManager, _tokenManager.MINT_ROLE()); } function _mintTokens(ACL _acl, TokenManager _tokenManager, address[] memory _holders, uint256 _stake) internal { _createPermissionForTemplate(_acl, _tokenManager, _tokenManager.MINT_ROLE()); for (uint256 i = 0; i < _holders.length; i++) { _tokenManager.mint(_holders[i], _stake); } _removePermissionFromTemplate(_acl, _tokenManager, _tokenManager.MINT_ROLE()); } function _mintTokens(ACL _acl, TokenManager _tokenManager, address _holder, uint256 _stake) internal { _createPermissionForTemplate(_acl, _tokenManager, _tokenManager.MINT_ROLE()); _tokenManager.mint(_holder, _stake); _removePermissionFromTemplate(_acl, _tokenManager, _tokenManager.MINT_ROLE()); } /* EVM SCRIPTS */ function _createEvmScriptsRegistryPermissions(ACL _acl, address _grantee, address _manager) internal { EVMScriptRegistry registry = EVMScriptRegistry(_acl.getEVMScriptRegistry()); _acl.createPermission(_grantee, registry, registry.REGISTRY_MANAGER_ROLE(), _manager); _acl.createPermission(_grantee, registry, registry.REGISTRY_ADD_EXECUTOR_ROLE(), _manager); } /* APPS */ function _installNonDefaultApp(Kernel _dao, bytes32 _appId) internal returns (address) { return _installNonDefaultApp(_dao, _appId, new bytes(0)); } function _installNonDefaultApp(Kernel _dao, bytes32 _appId, bytes memory _initializeData) internal returns (address) { return _installApp(_dao, _appId, _initializeData, false); } function _installDefaultApp(Kernel _dao, bytes32 _appId) internal returns (address) { return _installDefaultApp(_dao, _appId, new bytes(0)); } function _installDefaultApp(Kernel _dao, bytes32 _appId, bytes memory _initializeData) internal returns (address) { return _installApp(_dao, _appId, _initializeData, true); } function _installApp(Kernel _dao, bytes32 _appId, bytes memory _initializeData, bool _setDefault) internal returns (address) { address latestBaseAppAddress = _latestVersionAppBase(_appId); address instance = address(_dao.newAppInstance(_appId, latestBaseAppAddress, _initializeData, _setDefault)); emit InstalledApp(instance, _appId); return instance; } function _latestVersionAppBase(bytes32 _appId) internal view returns (address base) { Repo repo = Repo(PublicResolver(ens.resolver(_appId)).addr(_appId)); (,base,) = repo.getLatest(); } /* TOKEN */ function _createToken(string memory _name, string memory _symbol, uint8 _decimals) internal returns (MiniMeToken) { require(address(miniMeFactory) != address(0), ERROR_MINIME_FACTORY_NOT_PROVIDED); MiniMeToken token = miniMeFactory.createCloneToken(MiniMeToken(address(0)), 0, _name, _decimals, _symbol, true); emit DeployToken(address(token)); return token; } function _ensureMiniMeFactoryIsValid(address _miniMeFactory) internal view { require(isContract(address(_miniMeFactory)), ERROR_MINIME_FACTORY_NOT_CONTRACT); } /* IDS */ function _validateId(string memory _id) internal pure { require(bytes(_id).length > 0, ERROR_INVALID_ID); } function _registerID(string memory _name, address _owner) internal { require(address(aragonID) != address(0), ERROR_ARAGON_ID_NOT_PROVIDED); aragonID.register(keccak256(abi.encodePacked(_name)), _owner); } function _ensureAragonIdIsValid(address _aragonID) internal view { require(isContract(address(_aragonID)), ERROR_ARAGON_ID_NOT_CONTRACT); } /* HELPERS */ function _toAddress(uint256 _value) private pure returns (address) { require(_value <= uint160(-1), ERROR_CANNOT_CAST_VALUE_TO_ADDRESS); return address(_value); } } // File: @ablack/fundraising-bancor-formula/contracts/interfaces/IBancorFormula.sol pragma solidity 0.4.24; /* Bancor Formula interface */ contract IBancorFormula { function calculatePurchaseReturn(uint256 _supply, uint256 _connectorBalance, uint32 _connectorWeight, uint256 _depositAmount) public view returns (uint256); function calculateSaleReturn(uint256 _supply, uint256 _connectorBalance, uint32 _connectorWeight, uint256 _sellAmount) public view returns (uint256); function calculateCrossConnectorReturn(uint256 _fromConnectorBalance, uint32 _fromConnectorWeight, uint256 _toConnectorBalance, uint32 _toConnectorWeight, uint256 _amount) public view returns (uint256); } // File: @ablack/fundraising-bancor-formula/contracts/utility/Utils.sol pragma solidity 0.4.24; /* Utilities & Common Modifiers */ contract Utils { /** constructor */ constructor() public { } // verifies that an amount is greater than zero modifier greaterThanZero(uint256 _amount) { require(_amount > 0); _; } // validates an address - currently only checks that it isn't null modifier validAddress(address _address) { require(_address != address(0)); _; } // verifies that the address is different than this contract address modifier notThis(address _address) { require(_address != address(this)); _; } } // File: @ablack/fundraising-bancor-formula/contracts/BancorFormula.sol pragma solidity 0.4.24; contract BancorFormula is IBancorFormula, Utils { using SafeMath for uint256; string public version = '0.3'; uint256 private constant ONE = 1; uint32 private constant MAX_WEIGHT = 1000000; uint8 private constant MIN_PRECISION = 32; uint8 private constant MAX_PRECISION = 127; /** Auto-generated via 'PrintIntScalingFactors.py' */ uint256 private constant FIXED_1 = 0x080000000000000000000000000000000; uint256 private constant FIXED_2 = 0x100000000000000000000000000000000; uint256 private constant MAX_NUM = 0x200000000000000000000000000000000; /** Auto-generated via 'PrintLn2ScalingFactors.py' */ uint256 private constant LN2_NUMERATOR = 0x3f80fe03f80fe03f80fe03f80fe03f8; uint256 private constant LN2_DENOMINATOR = 0x5b9de1d10bf4103d647b0955897ba80; /** Auto-generated via 'PrintFunctionOptimalLog.py' and 'PrintFunctionOptimalExp.py' */ uint256 private constant OPT_LOG_MAX_VAL = 0x15bf0a8b1457695355fb8ac404e7a79e3; uint256 private constant OPT_EXP_MAX_VAL = 0x800000000000000000000000000000000; /** Auto-generated via 'PrintFunctionConstructor.py' */ uint256[128] private maxExpArray; constructor() public { // maxExpArray[ 0] = 0x6bffffffffffffffffffffffffffffffff; // maxExpArray[ 1] = 0x67ffffffffffffffffffffffffffffffff; // maxExpArray[ 2] = 0x637fffffffffffffffffffffffffffffff; // maxExpArray[ 3] = 0x5f6fffffffffffffffffffffffffffffff; // maxExpArray[ 4] = 0x5b77ffffffffffffffffffffffffffffff; // maxExpArray[ 5] = 0x57b3ffffffffffffffffffffffffffffff; // maxExpArray[ 6] = 0x5419ffffffffffffffffffffffffffffff; // maxExpArray[ 7] = 0x50a2ffffffffffffffffffffffffffffff; // maxExpArray[ 8] = 0x4d517fffffffffffffffffffffffffffff; // maxExpArray[ 9] = 0x4a233fffffffffffffffffffffffffffff; // maxExpArray[ 10] = 0x47165fffffffffffffffffffffffffffff; // maxExpArray[ 11] = 0x4429afffffffffffffffffffffffffffff; // maxExpArray[ 12] = 0x415bc7ffffffffffffffffffffffffffff; // maxExpArray[ 13] = 0x3eab73ffffffffffffffffffffffffffff; // maxExpArray[ 14] = 0x3c1771ffffffffffffffffffffffffffff; // maxExpArray[ 15] = 0x399e96ffffffffffffffffffffffffffff; // maxExpArray[ 16] = 0x373fc47fffffffffffffffffffffffffff; // maxExpArray[ 17] = 0x34f9e8ffffffffffffffffffffffffffff; // maxExpArray[ 18] = 0x32cbfd5fffffffffffffffffffffffffff; // maxExpArray[ 19] = 0x30b5057fffffffffffffffffffffffffff; // maxExpArray[ 20] = 0x2eb40f9fffffffffffffffffffffffffff; // maxExpArray[ 21] = 0x2cc8340fffffffffffffffffffffffffff; // maxExpArray[ 22] = 0x2af09481ffffffffffffffffffffffffff; // maxExpArray[ 23] = 0x292c5bddffffffffffffffffffffffffff; // maxExpArray[ 24] = 0x277abdcdffffffffffffffffffffffffff; // maxExpArray[ 25] = 0x25daf6657fffffffffffffffffffffffff; // maxExpArray[ 26] = 0x244c49c65fffffffffffffffffffffffff; // maxExpArray[ 27] = 0x22ce03cd5fffffffffffffffffffffffff; // maxExpArray[ 28] = 0x215f77c047ffffffffffffffffffffffff; // maxExpArray[ 29] = 0x1fffffffffffffffffffffffffffffffff; // maxExpArray[ 30] = 0x1eaefdbdabffffffffffffffffffffffff; // maxExpArray[ 31] = 0x1d6bd8b2ebffffffffffffffffffffffff; maxExpArray[ 32] = 0x1c35fedd14ffffffffffffffffffffffff; maxExpArray[ 33] = 0x1b0ce43b323fffffffffffffffffffffff; maxExpArray[ 34] = 0x19f0028ec1ffffffffffffffffffffffff; maxExpArray[ 35] = 0x18ded91f0e7fffffffffffffffffffffff; maxExpArray[ 36] = 0x17d8ec7f0417ffffffffffffffffffffff; maxExpArray[ 37] = 0x16ddc6556cdbffffffffffffffffffffff; maxExpArray[ 38] = 0x15ecf52776a1ffffffffffffffffffffff; maxExpArray[ 39] = 0x15060c256cb2ffffffffffffffffffffff; maxExpArray[ 40] = 0x1428a2f98d72ffffffffffffffffffffff; maxExpArray[ 41] = 0x13545598e5c23fffffffffffffffffffff; maxExpArray[ 42] = 0x1288c4161ce1dfffffffffffffffffffff; maxExpArray[ 43] = 0x11c592761c666fffffffffffffffffffff; maxExpArray[ 44] = 0x110a688680a757ffffffffffffffffffff; maxExpArray[ 45] = 0x1056f1b5bedf77ffffffffffffffffffff; maxExpArray[ 46] = 0x0faadceceeff8bffffffffffffffffffff; maxExpArray[ 47] = 0x0f05dc6b27edadffffffffffffffffffff; maxExpArray[ 48] = 0x0e67a5a25da4107fffffffffffffffffff; maxExpArray[ 49] = 0x0dcff115b14eedffffffffffffffffffff; maxExpArray[ 50] = 0x0d3e7a392431239fffffffffffffffffff; maxExpArray[ 51] = 0x0cb2ff529eb71e4fffffffffffffffffff; maxExpArray[ 52] = 0x0c2d415c3db974afffffffffffffffffff; maxExpArray[ 53] = 0x0bad03e7d883f69bffffffffffffffffff; maxExpArray[ 54] = 0x0b320d03b2c343d5ffffffffffffffffff; maxExpArray[ 55] = 0x0abc25204e02828dffffffffffffffffff; maxExpArray[ 56] = 0x0a4b16f74ee4bb207fffffffffffffffff; maxExpArray[ 57] = 0x09deaf736ac1f569ffffffffffffffffff; maxExpArray[ 58] = 0x0976bd9952c7aa957fffffffffffffffff; maxExpArray[ 59] = 0x09131271922eaa606fffffffffffffffff; maxExpArray[ 60] = 0x08b380f3558668c46fffffffffffffffff; maxExpArray[ 61] = 0x0857ddf0117efa215bffffffffffffffff; maxExpArray[ 62] = 0x07ffffffffffffffffffffffffffffffff; maxExpArray[ 63] = 0x07abbf6f6abb9d087fffffffffffffffff; maxExpArray[ 64] = 0x075af62cbac95f7dfa7fffffffffffffff; maxExpArray[ 65] = 0x070d7fb7452e187ac13fffffffffffffff; maxExpArray[ 66] = 0x06c3390ecc8af379295fffffffffffffff; maxExpArray[ 67] = 0x067c00a3b07ffc01fd6fffffffffffffff; maxExpArray[ 68] = 0x0637b647c39cbb9d3d27ffffffffffffff; maxExpArray[ 69] = 0x05f63b1fc104dbd39587ffffffffffffff; maxExpArray[ 70] = 0x05b771955b36e12f7235ffffffffffffff; maxExpArray[ 71] = 0x057b3d49dda84556d6f6ffffffffffffff; maxExpArray[ 72] = 0x054183095b2c8ececf30ffffffffffffff; maxExpArray[ 73] = 0x050a28be635ca2b888f77fffffffffffff; maxExpArray[ 74] = 0x04d5156639708c9db33c3fffffffffffff; maxExpArray[ 75] = 0x04a23105873875bd52dfdfffffffffffff; maxExpArray[ 76] = 0x0471649d87199aa990756fffffffffffff; maxExpArray[ 77] = 0x04429a21a029d4c1457cfbffffffffffff; maxExpArray[ 78] = 0x0415bc6d6fb7dd71af2cb3ffffffffffff; maxExpArray[ 79] = 0x03eab73b3bbfe282243ce1ffffffffffff; maxExpArray[ 80] = 0x03c1771ac9fb6b4c18e229ffffffffffff; maxExpArray[ 81] = 0x0399e96897690418f785257fffffffffff; maxExpArray[ 82] = 0x0373fc456c53bb779bf0ea9fffffffffff; maxExpArray[ 83] = 0x034f9e8e490c48e67e6ab8bfffffffffff; maxExpArray[ 84] = 0x032cbfd4a7adc790560b3337ffffffffff; maxExpArray[ 85] = 0x030b50570f6e5d2acca94613ffffffffff; maxExpArray[ 86] = 0x02eb40f9f620fda6b56c2861ffffffffff; maxExpArray[ 87] = 0x02cc8340ecb0d0f520a6af58ffffffffff; maxExpArray[ 88] = 0x02af09481380a0a35cf1ba02ffffffffff; maxExpArray[ 89] = 0x0292c5bdd3b92ec810287b1b3fffffffff; maxExpArray[ 90] = 0x0277abdcdab07d5a77ac6d6b9fffffffff; maxExpArray[ 91] = 0x025daf6654b1eaa55fd64df5efffffffff; maxExpArray[ 92] = 0x0244c49c648baa98192dce88b7ffffffff; maxExpArray[ 93] = 0x022ce03cd5619a311b2471268bffffffff; maxExpArray[ 94] = 0x0215f77c045fbe885654a44a0fffffffff; maxExpArray[ 95] = 0x01ffffffffffffffffffffffffffffffff; maxExpArray[ 96] = 0x01eaefdbdaaee7421fc4d3ede5ffffffff; maxExpArray[ 97] = 0x01d6bd8b2eb257df7e8ca57b09bfffffff; maxExpArray[ 98] = 0x01c35fedd14b861eb0443f7f133fffffff; maxExpArray[ 99] = 0x01b0ce43b322bcde4a56e8ada5afffffff; maxExpArray[100] = 0x019f0028ec1fff007f5a195a39dfffffff; maxExpArray[101] = 0x018ded91f0e72ee74f49b15ba527ffffff; maxExpArray[102] = 0x017d8ec7f04136f4e5615fd41a63ffffff; maxExpArray[103] = 0x016ddc6556cdb84bdc8d12d22e6fffffff; maxExpArray[104] = 0x015ecf52776a1155b5bd8395814f7fffff; maxExpArray[105] = 0x015060c256cb23b3b3cc3754cf40ffffff; maxExpArray[106] = 0x01428a2f98d728ae223ddab715be3fffff; maxExpArray[107] = 0x013545598e5c23276ccf0ede68034fffff; maxExpArray[108] = 0x01288c4161ce1d6f54b7f61081194fffff; maxExpArray[109] = 0x011c592761c666aa641d5a01a40f17ffff; maxExpArray[110] = 0x0110a688680a7530515f3e6e6cfdcdffff; maxExpArray[111] = 0x01056f1b5bedf75c6bcb2ce8aed428ffff; maxExpArray[112] = 0x00faadceceeff8a0890f3875f008277fff; maxExpArray[113] = 0x00f05dc6b27edad306388a600f6ba0bfff; maxExpArray[114] = 0x00e67a5a25da41063de1495d5b18cdbfff; maxExpArray[115] = 0x00dcff115b14eedde6fc3aa5353f2e4fff; maxExpArray[116] = 0x00d3e7a3924312399f9aae2e0f868f8fff; maxExpArray[117] = 0x00cb2ff529eb71e41582cccd5a1ee26fff; maxExpArray[118] = 0x00c2d415c3db974ab32a51840c0b67edff; maxExpArray[119] = 0x00bad03e7d883f69ad5b0a186184e06bff; maxExpArray[120] = 0x00b320d03b2c343d4829abd6075f0cc5ff; maxExpArray[121] = 0x00abc25204e02828d73c6e80bcdb1a95bf; maxExpArray[122] = 0x00a4b16f74ee4bb2040a1ec6c15fbbf2df; maxExpArray[123] = 0x009deaf736ac1f569deb1b5ae3f36c130f; maxExpArray[124] = 0x00976bd9952c7aa957f5937d790ef65037; maxExpArray[125] = 0x009131271922eaa6064b73a22d0bd4f2bf; maxExpArray[126] = 0x008b380f3558668c46c91c49a2f8e967b9; maxExpArray[127] = 0x00857ddf0117efa215952912839f6473e6; } /** @dev given a token supply, connector balance, weight and a deposit amount (in the connector token), calculates the return for a given conversion (in the main token) Formula: Return = _supply * ((1 + _depositAmount / _connectorBalance) ^ (_connectorWeight / 1000000) - 1) @param _supply token total supply @param _connectorBalance total connector balance @param _connectorWeight connector weight, represented in ppm, 1-1000000 @param _depositAmount deposit amount, in connector token @return purchase return amount */ function calculatePurchaseReturn(uint256 _supply, uint256 _connectorBalance, uint32 _connectorWeight, uint256 _depositAmount) public view returns (uint256) { // validate input require(_supply > 0 && _connectorBalance > 0 && _connectorWeight > 0 && _connectorWeight <= MAX_WEIGHT); // special case for 0 deposit amount if (_depositAmount == 0) return 0; // special case if the weight = 100% if (_connectorWeight == MAX_WEIGHT) return _supply.mul(_depositAmount) / _connectorBalance; uint256 result; uint8 precision; uint256 baseN = _depositAmount.add(_connectorBalance); (result, precision) = power(baseN, _connectorBalance, _connectorWeight, MAX_WEIGHT); uint256 temp = _supply.mul(result) >> precision; return temp - _supply; } /** @dev given a token supply, connector balance, weight and a sell amount (in the main token), calculates the return for a given conversion (in the connector token) Formula: Return = _connectorBalance * (1 - (1 - _sellAmount / _supply) ^ (1 / (_connectorWeight / 1000000))) @param _supply token total supply @param _connectorBalance total connector @param _connectorWeight constant connector Weight, represented in ppm, 1-1000000 @param _sellAmount sell amount, in the token itself @return sale return amount */ function calculateSaleReturn(uint256 _supply, uint256 _connectorBalance, uint32 _connectorWeight, uint256 _sellAmount) public view returns (uint256) { // validate input require(_supply > 0 && _connectorBalance > 0 && _connectorWeight > 0 && _connectorWeight <= MAX_WEIGHT && _sellAmount <= _supply); // special case for 0 sell amount if (_sellAmount == 0) return 0; // special case for selling the entire supply if (_sellAmount == _supply) return _connectorBalance; // special case if the weight = 100% if (_connectorWeight == MAX_WEIGHT) return _connectorBalance.mul(_sellAmount) / _supply; uint256 result; uint8 precision; uint256 baseD = _supply - _sellAmount; (result, precision) = power(_supply, baseD, MAX_WEIGHT, _connectorWeight); uint256 temp1 = _connectorBalance.mul(result); uint256 temp2 = _connectorBalance << precision; return (temp1 - temp2) / result; } /** @dev given two connector balances/weights and a sell amount (in the first connector token), calculates the return for a conversion from the first connector token to the second connector token (in the second connector token) Formula: Return = _toConnectorBalance * (1 - (_fromConnectorBalance / (_fromConnectorBalance + _amount)) ^ (_fromConnectorWeight / _toConnectorWeight)) @param _fromConnectorBalance input connector balance @param _fromConnectorWeight input connector weight, represented in ppm, 1-1000000 @param _toConnectorBalance output connector balance @param _toConnectorWeight output connector weight, represented in ppm, 1-1000000 @param _amount input connector amount @return second connector amount */ function calculateCrossConnectorReturn(uint256 _fromConnectorBalance, uint32 _fromConnectorWeight, uint256 _toConnectorBalance, uint32 _toConnectorWeight, uint256 _amount) public view returns (uint256) { // validate input require(_fromConnectorBalance > 0 && _fromConnectorWeight > 0 && _fromConnectorWeight <= MAX_WEIGHT && _toConnectorBalance > 0 && _toConnectorWeight > 0 && _toConnectorWeight <= MAX_WEIGHT); // special case for equal weights if (_fromConnectorWeight == _toConnectorWeight) return _toConnectorBalance.mul(_amount) / _fromConnectorBalance.add(_amount); uint256 result; uint8 precision; uint256 baseN = _fromConnectorBalance.add(_amount); (result, precision) = power(baseN, _fromConnectorBalance, _fromConnectorWeight, _toConnectorWeight); uint256 temp1 = _toConnectorBalance.mul(result); uint256 temp2 = _toConnectorBalance << precision; return (temp1 - temp2) / result; } /** General Description: Determine a value of precision. Calculate an integer approximation of (_baseN / _baseD) ^ (_expN / _expD) * 2 ^ precision. Return the result along with the precision used. Detailed Description: Instead of calculating "base ^ exp", we calculate "e ^ (log(base) * exp)". The value of "log(base)" is represented with an integer slightly smaller than "log(base) * 2 ^ precision". The larger "precision" is, the more accurately this value represents the real value. However, the larger "precision" is, the more bits are required in order to store this value. And the exponentiation function, which takes "x" and calculates "e ^ x", is limited to a maximum exponent (maximum value of "x"). This maximum exponent depends on the "precision" used, and it is given by "maxExpArray[precision] >> (MAX_PRECISION - precision)". Hence we need to determine the highest precision which can be used for the given input, before calling the exponentiation function. This allows us to compute "base ^ exp" with maximum accuracy and without exceeding 256 bits in any of the intermediate computations. This functions assumes that "_expN < 2 ^ 256 / log(MAX_NUM - 1)", otherwise the multiplication should be replaced with a "safeMul". */ function power(uint256 _baseN, uint256 _baseD, uint32 _expN, uint32 _expD) internal view returns (uint256, uint8) { require(_baseN < MAX_NUM); uint256 baseLog; uint256 base = _baseN * FIXED_1 / _baseD; if (base < OPT_LOG_MAX_VAL) { baseLog = optimalLog(base); } else { baseLog = generalLog(base); } uint256 baseLogTimesExp = baseLog * _expN / _expD; if (baseLogTimesExp < OPT_EXP_MAX_VAL) { return (optimalExp(baseLogTimesExp), MAX_PRECISION); } else { uint8 precision = findPositionInMaxExpArray(baseLogTimesExp); return (generalExp(baseLogTimesExp >> (MAX_PRECISION - precision), precision), precision); } } /** Compute log(x / FIXED_1) * FIXED_1. This functions assumes that "x >= FIXED_1", because the output would be negative otherwise. */ function generalLog(uint256 x) internal pure returns (uint256) { uint256 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 = MAX_PRECISION; i > 0; --i) { x = (x * x) / FIXED_1; // now 1 < x < 4 if (x >= FIXED_2) { x >>= 1; // now 1 < x < 2 res += ONE << (i - 1); } } } return res * LN2_NUMERATOR / LN2_DENOMINATOR; } /** Compute the largest integer smaller than or equal to the binary logarithm of the input. */ 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 >= (ONE << s)) { _n >>= s; res |= s; } } } return res; } /** The global "maxExpArray" is sorted in descending order, and therefore the following statements are equivalent: - This function finds the position of [the smallest value in "maxExpArray" larger than or equal to "x"] - This function finds the highest position of [a value in "maxExpArray" larger than or equal to "x"] */ function findPositionInMaxExpArray(uint256 _x) internal view returns (uint8) { uint8 lo = MIN_PRECISION; uint8 hi = MAX_PRECISION; while (lo + 1 < hi) { uint8 mid = (lo + hi) / 2; if (maxExpArray[mid] >= _x) lo = mid; else hi = mid; } if (maxExpArray[hi] >= _x) return hi; if (maxExpArray[lo] >= _x) return lo; require(false); return 0; } /** This function can be auto-generated by the script 'PrintFunctionGeneralExp.py'. It approximates "e ^ x" via maclaurin summation: "(x^0)/0! + (x^1)/1! + ... + (x^n)/n!". It returns "e ^ (x / 2 ^ precision) * 2 ^ precision", that is, the result is upshifted for accuracy. The global "maxExpArray" maps each "precision" to "((maximumExponent + 1) << (MAX_PRECISION - precision)) - 1". The maximum permitted value for "x" is therefore given by "maxExpArray[precision] >> (MAX_PRECISION - precision)". */ function generalExp(uint256 _x, uint8 _precision) internal pure returns (uint256) { uint256 xi = _x; uint256 res = 0; xi = (xi * _x) >> _precision; res += xi * 0x3442c4e6074a82f1797f72ac0000000; // add x^02 * (33! / 02!) xi = (xi * _x) >> _precision; res += xi * 0x116b96f757c380fb287fd0e40000000; // add x^03 * (33! / 03!) xi = (xi * _x) >> _precision; res += xi * 0x045ae5bdd5f0e03eca1ff4390000000; // add x^04 * (33! / 04!) xi = (xi * _x) >> _precision; res += xi * 0x00defabf91302cd95b9ffda50000000; // add x^05 * (33! / 05!) xi = (xi * _x) >> _precision; res += xi * 0x002529ca9832b22439efff9b8000000; // add x^06 * (33! / 06!) xi = (xi * _x) >> _precision; res += xi * 0x00054f1cf12bd04e516b6da88000000; // add x^07 * (33! / 07!) xi = (xi * _x) >> _precision; res += xi * 0x0000a9e39e257a09ca2d6db51000000; // add x^08 * (33! / 08!) xi = (xi * _x) >> _precision; res += xi * 0x000012e066e7b839fa050c309000000; // add x^09 * (33! / 09!) xi = (xi * _x) >> _precision; res += xi * 0x000001e33d7d926c329a1ad1a800000; // add x^10 * (33! / 10!) xi = (xi * _x) >> _precision; res += xi * 0x0000002bee513bdb4a6b19b5f800000; // add x^11 * (33! / 11!) xi = (xi * _x) >> _precision; res += xi * 0x00000003a9316fa79b88eccf2a00000; // add x^12 * (33! / 12!) xi = (xi * _x) >> _precision; res += xi * 0x0000000048177ebe1fa812375200000; // add x^13 * (33! / 13!) xi = (xi * _x) >> _precision; res += xi * 0x0000000005263fe90242dcbacf00000; // add x^14 * (33! / 14!) xi = (xi * _x) >> _precision; res += xi * 0x000000000057e22099c030d94100000; // add x^15 * (33! / 15!) xi = (xi * _x) >> _precision; res += xi * 0x0000000000057e22099c030d9410000; // add x^16 * (33! / 16!) xi = (xi * _x) >> _precision; res += xi * 0x00000000000052b6b54569976310000; // add x^17 * (33! / 17!) xi = (xi * _x) >> _precision; res += xi * 0x00000000000004985f67696bf748000; // add x^18 * (33! / 18!) xi = (xi * _x) >> _precision; res += xi * 0x000000000000003dea12ea99e498000; // add x^19 * (33! / 19!) xi = (xi * _x) >> _precision; res += xi * 0x00000000000000031880f2214b6e000; // add x^20 * (33! / 20!) xi = (xi * _x) >> _precision; res += xi * 0x000000000000000025bcff56eb36000; // add x^21 * (33! / 21!) xi = (xi * _x) >> _precision; res += xi * 0x000000000000000001b722e10ab1000; // add x^22 * (33! / 22!) xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000001317c70077000; // add x^23 * (33! / 23!) xi = (xi * _x) >> _precision; res += xi * 0x00000000000000000000cba84aafa00; // add x^24 * (33! / 24!) xi = (xi * _x) >> _precision; res += xi * 0x00000000000000000000082573a0a00; // add x^25 * (33! / 25!) xi = (xi * _x) >> _precision; res += xi * 0x00000000000000000000005035ad900; // add x^26 * (33! / 26!) xi = (xi * _x) >> _precision; res += xi * 0x000000000000000000000002f881b00; // add x^27 * (33! / 27!) xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000000000001b29340; // add x^28 * (33! / 28!) xi = (xi * _x) >> _precision; res += xi * 0x00000000000000000000000000efc40; // add x^29 * (33! / 29!) xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000000000000007fe0; // add x^30 * (33! / 30!) xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000000000000000420; // add x^31 * (33! / 31!) xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000000000000000021; // add x^32 * (33! / 32!) xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000000000000000001; // add x^33 * (33! / 33!) return res / 0x688589cc0e9505e2f2fee5580000000 + _x + (ONE << _precision); // divide by 33! and then add x^1 / 1! + x^0 / 0! } /** Return log(x / FIXED_1) * FIXED_1 Input range: FIXED_1 <= x <= LOG_EXP_MAX_VAL - 1 Auto-generated via 'PrintFunctionOptimalLog.py' Detailed description: - Rewrite the input as a product of natural exponents and a single residual r, such that 1 < r < 2 - The natural logarithm of each (pre-calculated) exponent is the degree of the exponent - The natural logarithm of r is calculated via Taylor series for log(1 + x), where x = r - 1 - The natural logarithm of the input is calculated by summing up the intermediate results above - For example: log(250) = log(e^4 * e^1 * e^0.5 * 1.021692859) = 4 + 1 + 0.5 + log(1 + 0.021692859) */ function optimalLog(uint256 x) internal pure returns (uint256) { uint256 res = 0; uint256 y; uint256 z; uint256 w; if (x >= 0xd3094c70f034de4b96ff7d5b6f99fcd8) {res += 0x40000000000000000000000000000000; x = x * FIXED_1 / 0xd3094c70f034de4b96ff7d5b6f99fcd8;} // add 1 / 2^1 if (x >= 0xa45af1e1f40c333b3de1db4dd55f29a7) {res += 0x20000000000000000000000000000000; x = x * FIXED_1 / 0xa45af1e1f40c333b3de1db4dd55f29a7;} // add 1 / 2^2 if (x >= 0x910b022db7ae67ce76b441c27035c6a1) {res += 0x10000000000000000000000000000000; x = x * FIXED_1 / 0x910b022db7ae67ce76b441c27035c6a1;} // add 1 / 2^3 if (x >= 0x88415abbe9a76bead8d00cf112e4d4a8) {res += 0x08000000000000000000000000000000; x = x * FIXED_1 / 0x88415abbe9a76bead8d00cf112e4d4a8;} // add 1 / 2^4 if (x >= 0x84102b00893f64c705e841d5d4064bd3) {res += 0x04000000000000000000000000000000; x = x * FIXED_1 / 0x84102b00893f64c705e841d5d4064bd3;} // add 1 / 2^5 if (x >= 0x8204055aaef1c8bd5c3259f4822735a2) {res += 0x02000000000000000000000000000000; x = x * FIXED_1 / 0x8204055aaef1c8bd5c3259f4822735a2;} // add 1 / 2^6 if (x >= 0x810100ab00222d861931c15e39b44e99) {res += 0x01000000000000000000000000000000; x = x * FIXED_1 / 0x810100ab00222d861931c15e39b44e99;} // add 1 / 2^7 if (x >= 0x808040155aabbbe9451521693554f733) {res += 0x00800000000000000000000000000000; x = x * FIXED_1 / 0x808040155aabbbe9451521693554f733;} // add 1 / 2^8 z = y = x - FIXED_1; w = y * y / FIXED_1; res += z * (0x100000000000000000000000000000000 - y) / 0x100000000000000000000000000000000; z = z * w / FIXED_1; // add y^01 / 01 - y^02 / 02 res += z * (0x0aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa - y) / 0x200000000000000000000000000000000; z = z * w / FIXED_1; // add y^03 / 03 - y^04 / 04 res += z * (0x099999999999999999999999999999999 - y) / 0x300000000000000000000000000000000; z = z * w / FIXED_1; // add y^05 / 05 - y^06 / 06 res += z * (0x092492492492492492492492492492492 - y) / 0x400000000000000000000000000000000; z = z * w / FIXED_1; // add y^07 / 07 - y^08 / 08 res += z * (0x08e38e38e38e38e38e38e38e38e38e38e - y) / 0x500000000000000000000000000000000; z = z * w / FIXED_1; // add y^09 / 09 - y^10 / 10 res += z * (0x08ba2e8ba2e8ba2e8ba2e8ba2e8ba2e8b - y) / 0x600000000000000000000000000000000; z = z * w / FIXED_1; // add y^11 / 11 - y^12 / 12 res += z * (0x089d89d89d89d89d89d89d89d89d89d89 - y) / 0x700000000000000000000000000000000; z = z * w / FIXED_1; // add y^13 / 13 - y^14 / 14 res += z * (0x088888888888888888888888888888888 - y) / 0x800000000000000000000000000000000; // add y^15 / 15 - y^16 / 16 return res; } /** Return 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; } } // File: @ablack/fundraising-shared-interfaces/contracts/IAragonFundraisingController.sol pragma solidity 0.4.24; contract IAragonFundraisingController { function openTrading() external; function updateTappedAmount(address _token) external; function collateralsToBeClaimed(address _collateral) public view returns (uint256); function balanceOf(address _who, address _token) public view returns (uint256); } // File: @ablack/fundraising-batched-bancor-market-maker/contracts/BatchedBancorMarketMaker.sol pragma solidity 0.4.24; contract BatchedBancorMarketMaker is EtherTokenConstant, IsContract, AragonApp { using SafeERC20 for ERC20; using SafeMath for uint256; /** Hardcoded constants to save gas bytes32 public constant OPEN_ROLE = keccak256("OPEN_ROLE"); bytes32 public constant UPDATE_FORMULA_ROLE = keccak256("UPDATE_FORMULA_ROLE"); bytes32 public constant UPDATE_BENEFICIARY_ROLE = keccak256("UPDATE_BENEFICIARY_ROLE"); bytes32 public constant UPDATE_FEES_ROLE = keccak256("UPDATE_FEES_ROLE"); bytes32 public constant ADD_COLLATERAL_TOKEN_ROLE = keccak256("ADD_COLLATERAL_TOKEN_ROLE"); bytes32 public constant REMOVE_COLLATERAL_TOKEN_ROLE = keccak256("REMOVE_COLLATERAL_TOKEN_ROLE"); bytes32 public constant UPDATE_COLLATERAL_TOKEN_ROLE = keccak256("UPDATE_COLLATERAL_TOKEN_ROLE"); bytes32 public constant OPEN_BUY_ORDER_ROLE = keccak256("OPEN_BUY_ORDER_ROLE"); bytes32 public constant OPEN_SELL_ORDER_ROLE = keccak256("OPEN_SELL_ORDER_ROLE"); */ bytes32 public constant OPEN_ROLE = 0xefa06053e2ca99a43c97c4a4f3d8a394ee3323a8ff237e625fba09fe30ceb0a4; bytes32 public constant UPDATE_FORMULA_ROLE = 0xbfb76d8d43f55efe58544ea32af187792a7bdb983850d8fed33478266eec3cbb; bytes32 public constant UPDATE_BENEFICIARY_ROLE = 0xf7ea2b80c7b6a2cab2c11d2290cb005c3748397358a25e17113658c83b732593; bytes32 public constant UPDATE_FEES_ROLE = 0x5f9be2932ed3a723f295a763be1804c7ebfd1a41c1348fb8bdf5be1c5cdca822; bytes32 public constant ADD_COLLATERAL_TOKEN_ROLE = 0x217b79cb2bc7760defc88529853ef81ab33ae5bb315408ce9f5af09c8776662d; bytes32 public constant REMOVE_COLLATERAL_TOKEN_ROLE = 0x2044e56de223845e4be7d0a6f4e9a29b635547f16413a6d1327c58d9db438ee2; bytes32 public constant UPDATE_COLLATERAL_TOKEN_ROLE = 0xe0565c2c43e0d841e206bb36a37f12f22584b4652ccee6f9e0c071b697a2e13d; bytes32 public constant OPEN_BUY_ORDER_ROLE = 0xa589c8f284b76fc8d510d9d553485c47dbef1b0745ae00e0f3fd4e28fcd77ea7; bytes32 public constant OPEN_SELL_ORDER_ROLE = 0xd68ba2b769fa37a2a7bd4bed9241b448bc99eca41f519ef037406386a8f291c0; uint256 public constant PCT_BASE = 10 ** 18; // 0% = 0; 1% = 10 ** 16; 100% = 10 ** 18 uint32 public constant PPM = 1000000; string private constant ERROR_CONTRACT_IS_EOA = "MM_CONTRACT_IS_EOA"; string private constant ERROR_INVALID_BENEFICIARY = "MM_INVALID_BENEFICIARY"; string private constant ERROR_INVALID_BATCH_BLOCKS = "MM_INVALID_BATCH_BLOCKS"; string private constant ERROR_INVALID_PERCENTAGE = "MM_INVALID_PERCENTAGE"; string private constant ERROR_INVALID_RESERVE_RATIO = "MM_INVALID_RESERVE_RATIO"; string private constant ERROR_INVALID_TM_SETTING = "MM_INVALID_TM_SETTING"; string private constant ERROR_INVALID_COLLATERAL = "MM_INVALID_COLLATERAL"; string private constant ERROR_INVALID_COLLATERAL_VALUE = "MM_INVALID_COLLATERAL_VALUE"; string private constant ERROR_INVALID_BOND_AMOUNT = "MM_INVALID_BOND_AMOUNT"; string private constant ERROR_ALREADY_OPEN = "MM_ALREADY_OPEN"; string private constant ERROR_NOT_OPEN = "MM_NOT_OPEN"; string private constant ERROR_COLLATERAL_ALREADY_WHITELISTED = "MM_COLLATERAL_ALREADY_WHITELISTED"; string private constant ERROR_COLLATERAL_NOT_WHITELISTED = "MM_COLLATERAL_NOT_WHITELISTED"; string private constant ERROR_NOTHING_TO_CLAIM = "MM_NOTHING_TO_CLAIM"; string private constant ERROR_BATCH_NOT_OVER = "MM_BATCH_NOT_OVER"; string private constant ERROR_BATCH_CANCELLED = "MM_BATCH_CANCELLED"; string private constant ERROR_BATCH_NOT_CANCELLED = "MM_BATCH_NOT_CANCELLED"; string private constant ERROR_SLIPPAGE_EXCEEDS_LIMIT = "MM_SLIPPAGE_EXCEEDS_LIMIT"; string private constant ERROR_INSUFFICIENT_POOL_BALANCE = "MM_INSUFFICIENT_POOL_BALANCE"; string private constant ERROR_TRANSFER_FROM_FAILED = "MM_TRANSFER_FROM_FAILED"; struct Collateral { bool whitelisted; uint256 virtualSupply; uint256 virtualBalance; uint32 reserveRatio; uint256 slippage; } struct MetaBatch { bool initialized; uint256 realSupply; uint256 buyFeePct; uint256 sellFeePct; IBancorFormula formula; mapping(address => Batch) batches; } struct Batch { bool initialized; bool cancelled; uint256 supply; uint256 balance; uint32 reserveRatio; uint256 slippage; uint256 totalBuySpend; uint256 totalBuyReturn; uint256 totalSellSpend; uint256 totalSellReturn; mapping(address => uint256) buyers; mapping(address => uint256) sellers; } IAragonFundraisingController public controller; TokenManager public tokenManager; ERC20 public token; Vault public reserve; address public beneficiary; IBancorFormula public formula; uint256 public batchBlocks; uint256 public buyFeePct; uint256 public sellFeePct; bool public isOpen; uint256 public tokensToBeMinted; mapping(address => uint256) public collateralsToBeClaimed; mapping(address => Collateral) public collaterals; mapping(uint256 => MetaBatch) public metaBatches; event UpdateBeneficiary (address indexed beneficiary); event UpdateFormula (address indexed formula); event UpdateFees (uint256 buyFeePct, uint256 sellFeePct); event NewMetaBatch (uint256 indexed id, uint256 supply, uint256 buyFeePct, uint256 sellFeePct, address formula); event NewBatch ( uint256 indexed id, address indexed collateral, uint256 supply, uint256 balance, uint32 reserveRatio, uint256 slippage) ; event CancelBatch (uint256 indexed id, address indexed collateral); event AddCollateralToken ( address indexed collateral, uint256 virtualSupply, uint256 virtualBalance, uint32 reserveRatio, uint256 slippage ); event RemoveCollateralToken (address indexed collateral); event UpdateCollateralToken ( address indexed collateral, uint256 virtualSupply, uint256 virtualBalance, uint32 reserveRatio, uint256 slippage ); event Open (); event OpenBuyOrder (address indexed buyer, uint256 indexed batchId, address indexed collateral, uint256 fee, uint256 value); event OpenSellOrder (address indexed seller, uint256 indexed batchId, address indexed collateral, uint256 amount); event ClaimBuyOrder (address indexed buyer, uint256 indexed batchId, address indexed collateral, uint256 amount); event ClaimSellOrder (address indexed seller, uint256 indexed batchId, address indexed collateral, uint256 fee, uint256 value); event ClaimCancelledBuyOrder (address indexed buyer, uint256 indexed batchId, address indexed collateral, uint256 value); event ClaimCancelledSellOrder(address indexed seller, uint256 indexed batchId, address indexed collateral, uint256 amount); event UpdatePricing ( uint256 indexed batchId, address indexed collateral, uint256 totalBuySpend, uint256 totalBuyReturn, uint256 totalSellSpend, uint256 totalSellReturn ); /***** external function *****/ /** * @notice Initialize market maker * @param _controller The address of the controller contract * @param _tokenManager The address of the [bonded token] token manager contract * @param _reserve The address of the reserve [pool] contract * @param _beneficiary The address of the beneficiary [to whom fees are to be sent] * @param _formula The address of the BancorFormula [computation] contract * @param _batchBlocks The number of blocks batches are to last * @param _buyFeePct The fee to be deducted from buy orders [in PCT_BASE] * @param _sellFeePct The fee to be deducted from sell orders [in PCT_BASE] */ function initialize( IAragonFundraisingController _controller, TokenManager _tokenManager, IBancorFormula _formula, Vault _reserve, address _beneficiary, uint256 _batchBlocks, uint256 _buyFeePct, uint256 _sellFeePct ) external onlyInit { initialized(); require(isContract(_controller), ERROR_CONTRACT_IS_EOA); require(isContract(_tokenManager), ERROR_CONTRACT_IS_EOA); require(isContract(_formula), ERROR_CONTRACT_IS_EOA); require(isContract(_reserve), ERROR_CONTRACT_IS_EOA); require(_beneficiaryIsValid(_beneficiary), ERROR_INVALID_BENEFICIARY); require(_batchBlocks > 0, ERROR_INVALID_BATCH_BLOCKS); require(_feeIsValid(_buyFeePct) && _feeIsValid(_sellFeePct), ERROR_INVALID_PERCENTAGE); require(_tokenManagerSettingIsValid(_tokenManager), ERROR_INVALID_TM_SETTING); controller = _controller; tokenManager = _tokenManager; token = ERC20(tokenManager.token()); formula = _formula; reserve = _reserve; beneficiary = _beneficiary; batchBlocks = _batchBlocks; buyFeePct = _buyFeePct; sellFeePct = _sellFeePct; } /* generic settings related function */ /** * @notice Open market making [enabling users to open buy and sell orders] */ function open() external auth(OPEN_ROLE) { require(!isOpen, ERROR_ALREADY_OPEN); _open(); } /** * @notice Update formula to `_formula` * @param _formula The address of the new BancorFormula [computation] contract */ function updateFormula(IBancorFormula _formula) external auth(UPDATE_FORMULA_ROLE) { require(isContract(_formula), ERROR_CONTRACT_IS_EOA); _updateFormula(_formula); } /** * @notice Update beneficiary to `_beneficiary` * @param _beneficiary The address of the new beneficiary [to whom fees are to be sent] */ function updateBeneficiary(address _beneficiary) external auth(UPDATE_BENEFICIARY_ROLE) { require(_beneficiaryIsValid(_beneficiary), ERROR_INVALID_BENEFICIARY); _updateBeneficiary(_beneficiary); } /** * @notice Update fees deducted from buy and sell orders to respectively `@formatPct(_buyFeePct)`% and `@formatPct(_sellFeePct)`% * @param _buyFeePct The new fee to be deducted from buy orders [in PCT_BASE] * @param _sellFeePct The new fee to be deducted from sell orders [in PCT_BASE] */ function updateFees(uint256 _buyFeePct, uint256 _sellFeePct) external auth(UPDATE_FEES_ROLE) { require(_feeIsValid(_buyFeePct) && _feeIsValid(_sellFeePct), ERROR_INVALID_PERCENTAGE); _updateFees(_buyFeePct, _sellFeePct); } /* collateral tokens related functions */ /** * @notice Add `_collateral.symbol(): string` as a whitelisted collateral token * @param _collateral The address of the collateral token to be whitelisted * @param _virtualSupply The virtual supply to be used for that collateral token [in wei] * @param _virtualBalance The virtual balance to be used for that collateral token [in wei] * @param _reserveRatio The reserve ratio to be used for that collateral token [in PPM] * @param _slippage The price slippage below which each batch is to be kept for that collateral token [in PCT_BASE] */ function addCollateralToken(address _collateral, uint256 _virtualSupply, uint256 _virtualBalance, uint32 _reserveRatio, uint256 _slippage) external auth(ADD_COLLATERAL_TOKEN_ROLE) { require(isContract(_collateral) || _collateral == ETH, ERROR_INVALID_COLLATERAL); require(!_collateralIsWhitelisted(_collateral), ERROR_COLLATERAL_ALREADY_WHITELISTED); require(_reserveRatioIsValid(_reserveRatio), ERROR_INVALID_RESERVE_RATIO); _addCollateralToken(_collateral, _virtualSupply, _virtualBalance, _reserveRatio, _slippage); } /** * @notice Remove `_collateral.symbol(): string` as a whitelisted collateral token * @param _collateral The address of the collateral token to be un-whitelisted */ function removeCollateralToken(address _collateral) external auth(REMOVE_COLLATERAL_TOKEN_ROLE) { require(_collateralIsWhitelisted(_collateral), ERROR_COLLATERAL_NOT_WHITELISTED); _removeCollateralToken(_collateral); } /** * @notice Update `_collateral.symbol(): string` collateralization settings * @param _collateral The address of the collateral token whose collateralization settings are to be updated * @param _virtualSupply The new virtual supply to be used for that collateral token [in wei] * @param _virtualBalance The new virtual balance to be used for that collateral token [in wei] * @param _reserveRatio The new reserve ratio to be used for that collateral token [in PPM] * @param _slippage The new price slippage below which each batch is to be kept for that collateral token [in PCT_BASE] */ function updateCollateralToken(address _collateral, uint256 _virtualSupply, uint256 _virtualBalance, uint32 _reserveRatio, uint256 _slippage) external auth(UPDATE_COLLATERAL_TOKEN_ROLE) { require(_collateralIsWhitelisted(_collateral), ERROR_COLLATERAL_NOT_WHITELISTED); require(_reserveRatioIsValid(_reserveRatio), ERROR_INVALID_RESERVE_RATIO); _updateCollateralToken(_collateral, _virtualSupply, _virtualBalance, _reserveRatio, _slippage); } /* market making related functions */ /** * @notice Open a buy order worth `@tokenAmount(_collateral, _value)` * @param _buyer The address of the buyer * @param _collateral The address of the collateral token to be spent * @param _value The amount of collateral token to be spent */ function openBuyOrder(address _buyer, address _collateral, uint256 _value) external payable auth(OPEN_BUY_ORDER_ROLE) { require(isOpen, ERROR_NOT_OPEN); require(_collateralIsWhitelisted(_collateral), ERROR_COLLATERAL_NOT_WHITELISTED); require(!_batchIsCancelled(_currentBatchId(), _collateral), ERROR_BATCH_CANCELLED); require(_collateralValueIsValid(_buyer, _collateral, _value, msg.value), ERROR_INVALID_COLLATERAL_VALUE); _openBuyOrder(_buyer, _collateral, _value); } /** * @notice Open a sell order worth `@tokenAmount(self.token(): address, _amount)` against `_collateral.symbol(): string` * @param _seller The address of the seller * @param _collateral The address of the collateral token to be returned * @param _amount The amount of bonded token to be spent */ function openSellOrder(address _seller, address _collateral, uint256 _amount) external auth(OPEN_SELL_ORDER_ROLE) { require(isOpen, ERROR_NOT_OPEN); require(_collateralIsWhitelisted(_collateral), ERROR_COLLATERAL_NOT_WHITELISTED); require(!_batchIsCancelled(_currentBatchId(), _collateral), ERROR_BATCH_CANCELLED); require(_bondAmountIsValid(_seller, _amount), ERROR_INVALID_BOND_AMOUNT); _openSellOrder(_seller, _collateral, _amount); } /** * @notice Claim the results of `_buyer`'s `_collateral.symbol(): string` buy orders from batch #`_batchId` * @param _buyer The address of the user whose buy orders are to be claimed * @param _batchId The id of the batch in which buy orders are to be claimed * @param _collateral The address of the collateral token against which buy orders are to be claimed */ function claimBuyOrder(address _buyer, uint256 _batchId, address _collateral) external nonReentrant isInitialized { require(_collateralIsWhitelisted(_collateral), ERROR_COLLATERAL_NOT_WHITELISTED); require(_batchIsOver(_batchId), ERROR_BATCH_NOT_OVER); require(!_batchIsCancelled(_batchId, _collateral), ERROR_BATCH_CANCELLED); require(_userIsBuyer(_batchId, _collateral, _buyer), ERROR_NOTHING_TO_CLAIM); _claimBuyOrder(_buyer, _batchId, _collateral); } /** * @notice Claim the results of `_seller`'s `_collateral.symbol(): string` sell orders from batch #`_batchId` * @param _seller The address of the user whose sell orders are to be claimed * @param _batchId The id of the batch in which sell orders are to be claimed * @param _collateral The address of the collateral token against which sell orders are to be claimed */ function claimSellOrder(address _seller, uint256 _batchId, address _collateral) external nonReentrant isInitialized { require(_collateralIsWhitelisted(_collateral), ERROR_COLLATERAL_NOT_WHITELISTED); require(_batchIsOver(_batchId), ERROR_BATCH_NOT_OVER); require(!_batchIsCancelled(_batchId, _collateral), ERROR_BATCH_CANCELLED); require(_userIsSeller(_batchId, _collateral, _seller), ERROR_NOTHING_TO_CLAIM); _claimSellOrder(_seller, _batchId, _collateral); } /** * @notice Claim the investments of `_buyer`'s `_collateral.symbol(): string` buy orders from cancelled batch #`_batchId` * @param _buyer The address of the user whose cancelled buy orders are to be claimed * @param _batchId The id of the batch in which cancelled buy orders are to be claimed * @param _collateral The address of the collateral token against which cancelled buy orders are to be claimed */ function claimCancelledBuyOrder(address _buyer, uint256 _batchId, address _collateral) external nonReentrant isInitialized { require(_batchIsCancelled(_batchId, _collateral), ERROR_BATCH_NOT_CANCELLED); require(_userIsBuyer(_batchId, _collateral, _buyer), ERROR_NOTHING_TO_CLAIM); _claimCancelledBuyOrder(_buyer, _batchId, _collateral); } /** * @notice Claim the investments of `_seller`'s `_collateral.symbol(): string` sell orders from cancelled batch #`_batchId` * @param _seller The address of the user whose cancelled sell orders are to be claimed * @param _batchId The id of the batch in which cancelled sell orders are to be claimed * @param _collateral The address of the collateral token against which cancelled sell orders are to be claimed */ function claimCancelledSellOrder(address _seller, uint256 _batchId, address _collateral) external nonReentrant isInitialized { require(_batchIsCancelled(_batchId, _collateral), ERROR_BATCH_NOT_CANCELLED); require(_userIsSeller(_batchId, _collateral, _seller), ERROR_NOTHING_TO_CLAIM); _claimCancelledSellOrder(_seller, _batchId, _collateral); } /***** public view functions *****/ function getCurrentBatchId() public view isInitialized returns (uint256) { return _currentBatchId(); } function getCollateralToken(address _collateral) public view isInitialized returns (bool, uint256, uint256, uint32, uint256) { Collateral storage collateral = collaterals[_collateral]; return (collateral.whitelisted, collateral.virtualSupply, collateral.virtualBalance, collateral.reserveRatio, collateral.slippage); } function getBatch(uint256 _batchId, address _collateral) public view isInitialized returns (bool, bool, uint256, uint256, uint32, uint256, uint256, uint256, uint256, uint256) { Batch storage batch = metaBatches[_batchId].batches[_collateral]; return ( batch.initialized, batch.cancelled, batch.supply, batch.balance, batch.reserveRatio, batch.slippage, batch.totalBuySpend, batch.totalBuyReturn, batch.totalSellSpend, batch.totalSellReturn ); } function getStaticPricePPM(uint256 _supply, uint256 _balance, uint32 _reserveRatio) public view isInitialized returns (uint256) { return _staticPricePPM(_supply, _balance, _reserveRatio); } /***** internal functions *****/ /* computation functions */ function _staticPricePPM(uint256 _supply, uint256 _balance, uint32 _reserveRatio) internal pure returns (uint256) { return uint256(PPM).mul(uint256(PPM)).mul(_balance).div(_supply.mul(uint256(_reserveRatio))); } function _currentBatchId() internal view returns (uint256) { return (block.number.div(batchBlocks)).mul(batchBlocks); } /* check functions */ function _beneficiaryIsValid(address _beneficiary) internal pure returns (bool) { return _beneficiary != address(0); } function _feeIsValid(uint256 _fee) internal pure returns (bool) { return _fee < PCT_BASE; } function _reserveRatioIsValid(uint32 _reserveRatio) internal pure returns (bool) { return _reserveRatio <= PPM; } function _tokenManagerSettingIsValid(TokenManager _tokenManager) internal view returns (bool) { return _tokenManager.maxAccountTokens() == uint256(-1); } function _collateralValueIsValid(address _buyer, address _collateral, uint256 _value, uint256 _msgValue) internal view returns (bool) { if (_value == 0) { return false; } if (_collateral == ETH) { return _msgValue == _value; } return ( _msgValue == 0 && controller.balanceOf(_buyer, _collateral) >= _value && ERC20(_collateral).allowance(_buyer, address(this)) >= _value ); } function _bondAmountIsValid(address _seller, uint256 _amount) internal view returns (bool) { return _amount != 0 && tokenManager.spendableBalanceOf(_seller) >= _amount; } function _collateralIsWhitelisted(address _collateral) internal view returns (bool) { return collaterals[_collateral].whitelisted; } function _batchIsOver(uint256 _batchId) internal view returns (bool) { return _batchId < _currentBatchId(); } function _batchIsCancelled(uint256 _batchId, address _collateral) internal view returns (bool) { return metaBatches[_batchId].batches[_collateral].cancelled; } function _userIsBuyer(uint256 _batchId, address _collateral, address _user) internal view returns (bool) { Batch storage batch = metaBatches[_batchId].batches[_collateral]; return batch.buyers[_user] > 0; } function _userIsSeller(uint256 _batchId, address _collateral, address _user) internal view returns (bool) { Batch storage batch = metaBatches[_batchId].batches[_collateral]; return batch.sellers[_user] > 0; } function _poolBalanceIsSufficient(address _collateral) internal view returns (bool) { return controller.balanceOf(address(reserve), _collateral) >= collateralsToBeClaimed[_collateral]; } function _slippageIsValid(Batch storage _batch, address _collateral) internal view returns (bool) { uint256 staticPricePPM = _staticPricePPM(_batch.supply, _batch.balance, _batch.reserveRatio); uint256 maximumSlippage = _batch.slippage; // if static price is zero let's consider that every slippage is valid if (staticPricePPM == 0) { return true; } return _buySlippageIsValid(_batch, staticPricePPM, maximumSlippage) && _sellSlippageIsValid(_batch, staticPricePPM, maximumSlippage); } function _buySlippageIsValid(Batch storage _batch, uint256 _startingPricePPM, uint256 _maximumSlippage) internal view returns (bool) { /** * NOTE * the case where starting price is zero is handled * in the meta function _slippageIsValid() */ /** * NOTE * slippage is valid if: * totalBuyReturn >= totalBuySpend / (startingPrice * (1 + maxSlippage)) * totalBuyReturn >= totalBuySpend / ((startingPricePPM / PPM) * (1 + maximumSlippage / PCT_BASE)) * totalBuyReturn >= totalBuySpend / ((startingPricePPM / PPM) * (1 + maximumSlippage / PCT_BASE)) * totalBuyReturn >= totalBuySpend / ((startingPricePPM / PPM) * (PCT + maximumSlippage) / PCT_BASE) * totalBuyReturn * startingPrice * ( PCT + maximumSlippage) >= totalBuySpend * PCT_BASE * PPM */ if ( _batch.totalBuyReturn.mul(_startingPricePPM).mul(PCT_BASE.add(_maximumSlippage)) >= _batch.totalBuySpend.mul(PCT_BASE).mul(uint256(PPM)) ) { return true; } return false; } function _sellSlippageIsValid(Batch storage _batch, uint256 _startingPricePPM, uint256 _maximumSlippage) internal view returns (bool) { /** * NOTE * the case where starting price is zero is handled * in the meta function _slippageIsValid() */ // if allowed sell slippage >= 100% // then any sell slippage is valid if (_maximumSlippage >= PCT_BASE) { return true; } /** * NOTE * slippage is valid if * totalSellReturn >= startingPrice * (1 - maxSlippage) * totalBuySpend * totalSellReturn >= (startingPricePPM / PPM) * (1 - maximumSlippage / PCT_BASE) * totalBuySpend * totalSellReturn >= (startingPricePPM / PPM) * (PCT_BASE - maximumSlippage) * totalBuySpend / PCT_BASE * totalSellReturn * PCT_BASE * PPM = startingPricePPM * (PCT_BASE - maximumSlippage) * totalBuySpend */ if ( _batch.totalSellReturn.mul(PCT_BASE).mul(uint256(PPM)) >= _startingPricePPM.mul(PCT_BASE.sub(_maximumSlippage)).mul(_batch.totalSellSpend) ) { return true; } return false; } /* initialization functions */ function _currentBatch(address _collateral) internal returns (uint256, Batch storage) { uint256 batchId = _currentBatchId(); MetaBatch storage metaBatch = metaBatches[batchId]; Batch storage batch = metaBatch.batches[_collateral]; if (!metaBatch.initialized) { /** * NOTE * all collateral batches should be initialized with the same supply to * avoid price manipulation between different collaterals in the same meta-batch * we don't need to do the same with collateral balances as orders against one collateral * can't affect the pool's balance against another collateral and tap is a step-function * of the meta-batch duration */ /** * NOTE * realSupply(metaBatch) = totalSupply(metaBatchInitialization) + tokensToBeMinted(metaBatchInitialization) * 1. buy and sell orders incoming during the current meta-batch and affecting totalSupply or tokensToBeMinted * should not be taken into account in the price computation [they are already a part of the batched pricing computation] * 2. the only way for totalSupply to be modified during a meta-batch [outside of incoming buy and sell orders] * is for buy orders from previous meta-batches to be claimed [and tokens to be minted]: * as such totalSupply(metaBatch) + tokenToBeMinted(metaBatch) will always equal totalSupply(metaBatchInitialization) + tokenToBeMinted(metaBatchInitialization) */ metaBatch.realSupply = token.totalSupply().add(tokensToBeMinted); metaBatch.buyFeePct = buyFeePct; metaBatch.sellFeePct = sellFeePct; metaBatch.formula = formula; metaBatch.initialized = true; emit NewMetaBatch(batchId, metaBatch.realSupply, metaBatch.buyFeePct, metaBatch.sellFeePct, metaBatch.formula); } if (!batch.initialized) { /** * NOTE * supply(batch) = realSupply(metaBatch) + virtualSupply(batchInitialization) * virtualSupply can technically be updated during a batch: the on-going batch will still use * its value at the time of initialization [it's up to the updater to act wisely] */ /** * NOTE * balance(batch) = poolBalance(batchInitialization) - collateralsToBeClaimed(batchInitialization) + virtualBalance(metaBatchInitialization) * 1. buy and sell orders incoming during the current batch and affecting poolBalance or collateralsToBeClaimed * should not be taken into account in the price computation [they are already a part of the batched price computation] * 2. the only way for poolBalance to be modified during a batch [outside of incoming buy and sell orders] * is for sell orders from previous meta-batches to be claimed [and collateral to be transfered] as the tap is a step-function of the meta-batch duration: * as such poolBalance(batch) - collateralsToBeClaimed(batch) will always equal poolBalance(batchInitialization) - collateralsToBeClaimed(batchInitialization) * 3. virtualBalance can technically be updated during a batch: the on-going batch will still use * its value at the time of initialization [it's up to the updater to act wisely] */ controller.updateTappedAmount(_collateral); batch.supply = metaBatch.realSupply.add(collaterals[_collateral].virtualSupply); batch.balance = controller.balanceOf(address(reserve), _collateral).add(collaterals[_collateral].virtualBalance).sub(collateralsToBeClaimed[_collateral]); batch.reserveRatio = collaterals[_collateral].reserveRatio; batch.slippage = collaterals[_collateral].slippage; batch.initialized = true; emit NewBatch(batchId, _collateral, batch.supply, batch.balance, batch.reserveRatio, batch.slippage); } return (batchId, batch); } /* state modifiying functions */ function _open() internal { isOpen = true; emit Open(); } function _updateBeneficiary(address _beneficiary) internal { beneficiary = _beneficiary; emit UpdateBeneficiary(_beneficiary); } function _updateFormula(IBancorFormula _formula) internal { formula = _formula; emit UpdateFormula(address(_formula)); } function _updateFees(uint256 _buyFeePct, uint256 _sellFeePct) internal { buyFeePct = _buyFeePct; sellFeePct = _sellFeePct; emit UpdateFees(_buyFeePct, _sellFeePct); } function _cancelCurrentBatch(address _collateral) internal { (uint256 batchId, Batch storage batch) = _currentBatch(_collateral); if (!batch.cancelled) { batch.cancelled = true; // bought bonds are cancelled but sold bonds are due back // bought collaterals are cancelled but sold collaterals are due back tokensToBeMinted = tokensToBeMinted.sub(batch.totalBuyReturn).add(batch.totalSellSpend); collateralsToBeClaimed[_collateral] = collateralsToBeClaimed[_collateral].add(batch.totalBuySpend).sub(batch.totalSellReturn); emit CancelBatch(batchId, _collateral); } } function _addCollateralToken(address _collateral, uint256 _virtualSupply, uint256 _virtualBalance, uint32 _reserveRatio, uint256 _slippage) internal { collaterals[_collateral].whitelisted = true; collaterals[_collateral].virtualSupply = _virtualSupply; collaterals[_collateral].virtualBalance = _virtualBalance; collaterals[_collateral].reserveRatio = _reserveRatio; collaterals[_collateral].slippage = _slippage; emit AddCollateralToken(_collateral, _virtualSupply, _virtualBalance, _reserveRatio, _slippage); } function _removeCollateralToken(address _collateral) internal { _cancelCurrentBatch(_collateral); Collateral storage collateral = collaterals[_collateral]; delete collateral.whitelisted; delete collateral.virtualSupply; delete collateral.virtualBalance; delete collateral.reserveRatio; delete collateral.slippage; emit RemoveCollateralToken(_collateral); } function _updateCollateralToken( address _collateral, uint256 _virtualSupply, uint256 _virtualBalance, uint32 _reserveRatio, uint256 _slippage ) internal { collaterals[_collateral].virtualSupply = _virtualSupply; collaterals[_collateral].virtualBalance = _virtualBalance; collaterals[_collateral].reserveRatio = _reserveRatio; collaterals[_collateral].slippage = _slippage; emit UpdateCollateralToken(_collateral, _virtualSupply, _virtualBalance, _reserveRatio, _slippage); } function _openBuyOrder(address _buyer, address _collateral, uint256 _value) internal { (uint256 batchId, Batch storage batch) = _currentBatch(_collateral); // deduct fee uint256 fee = _value.mul(metaBatches[batchId].buyFeePct).div(PCT_BASE); uint256 value = _value.sub(fee); // collect fee and collateral if (fee > 0) { _transfer(_buyer, beneficiary, _collateral, fee); } _transfer(_buyer, address(reserve), _collateral, value); // save batch uint256 deprecatedBuyReturn = batch.totalBuyReturn; uint256 deprecatedSellReturn = batch.totalSellReturn; // update batch batch.totalBuySpend = batch.totalBuySpend.add(value); batch.buyers[_buyer] = batch.buyers[_buyer].add(value); // update pricing _updatePricing(batch, batchId, _collateral); // update the amount of tokens to be minted and collaterals to be claimed tokensToBeMinted = tokensToBeMinted.sub(deprecatedBuyReturn).add(batch.totalBuyReturn); collateralsToBeClaimed[_collateral] = collateralsToBeClaimed[_collateral].sub(deprecatedSellReturn).add(batch.totalSellReturn); // sanity checks require(_slippageIsValid(batch, _collateral), ERROR_SLIPPAGE_EXCEEDS_LIMIT); emit OpenBuyOrder(_buyer, batchId, _collateral, fee, value); } function _openSellOrder(address _seller, address _collateral, uint256 _amount) internal { (uint256 batchId, Batch storage batch) = _currentBatch(_collateral); // burn bonds tokenManager.burn(_seller, _amount); // save batch uint256 deprecatedBuyReturn = batch.totalBuyReturn; uint256 deprecatedSellReturn = batch.totalSellReturn; // update batch batch.totalSellSpend = batch.totalSellSpend.add(_amount); batch.sellers[_seller] = batch.sellers[_seller].add(_amount); // update pricing _updatePricing(batch, batchId, _collateral); // update the amount of tokens to be minted and collaterals to be claimed tokensToBeMinted = tokensToBeMinted.sub(deprecatedBuyReturn).add(batch.totalBuyReturn); collateralsToBeClaimed[_collateral] = collateralsToBeClaimed[_collateral].sub(deprecatedSellReturn).add(batch.totalSellReturn); // sanity checks require(_slippageIsValid(batch, _collateral), ERROR_SLIPPAGE_EXCEEDS_LIMIT); require(_poolBalanceIsSufficient(_collateral), ERROR_INSUFFICIENT_POOL_BALANCE); emit OpenSellOrder(_seller, batchId, _collateral, _amount); } function _claimBuyOrder(address _buyer, uint256 _batchId, address _collateral) internal { Batch storage batch = metaBatches[_batchId].batches[_collateral]; uint256 buyReturn = (batch.buyers[_buyer].mul(batch.totalBuyReturn)).div(batch.totalBuySpend); batch.buyers[_buyer] = 0; if (buyReturn > 0) { tokensToBeMinted = tokensToBeMinted.sub(buyReturn); tokenManager.mint(_buyer, buyReturn); } emit ClaimBuyOrder(_buyer, _batchId, _collateral, buyReturn); } function _claimSellOrder(address _seller, uint256 _batchId, address _collateral) internal { Batch storage batch = metaBatches[_batchId].batches[_collateral]; uint256 saleReturn = (batch.sellers[_seller].mul(batch.totalSellReturn)).div(batch.totalSellSpend); uint256 fee = saleReturn.mul(metaBatches[_batchId].sellFeePct).div(PCT_BASE); uint256 value = saleReturn.sub(fee); batch.sellers[_seller] = 0; if (value > 0) { collateralsToBeClaimed[_collateral] = collateralsToBeClaimed[_collateral].sub(saleReturn); reserve.transfer(_collateral, _seller, value); } if (fee > 0) { reserve.transfer(_collateral, beneficiary, fee); } emit ClaimSellOrder(_seller, _batchId, _collateral, fee, value); } function _claimCancelledBuyOrder(address _buyer, uint256 _batchId, address _collateral) internal { Batch storage batch = metaBatches[_batchId].batches[_collateral]; uint256 value = batch.buyers[_buyer]; batch.buyers[_buyer] = 0; if (value > 0) { collateralsToBeClaimed[_collateral] = collateralsToBeClaimed[_collateral].sub(value); reserve.transfer(_collateral, _buyer, value); } emit ClaimCancelledBuyOrder(_buyer, _batchId, _collateral, value); } function _claimCancelledSellOrder(address _seller, uint256 _batchId, address _collateral) internal { Batch storage batch = metaBatches[_batchId].batches[_collateral]; uint256 amount = batch.sellers[_seller]; batch.sellers[_seller] = 0; if (amount > 0) { tokensToBeMinted = tokensToBeMinted.sub(amount); tokenManager.mint(_seller, amount); } emit ClaimCancelledSellOrder(_seller, _batchId, _collateral, amount); } function _updatePricing(Batch storage batch, uint256 _batchId, address _collateral) internal { // the situation where there are no buy nor sell orders can't happen [keep commented] // if (batch.totalSellSpend == 0 && batch.totalBuySpend == 0) // return; // static price is the current exact price in collateral // per token according to the initial state of the batch // [expressed in PPM for precision sake] uint256 staticPricePPM = _staticPricePPM(batch.supply, batch.balance, batch.reserveRatio); // [NOTE] // if staticPrice is zero then resultOfSell [= 0] <= batch.totalBuySpend // so totalSellReturn will be zero and totalBuyReturn will be // computed normally along the formula // 1. we want to find out if buy orders are worth more sell orders [or vice-versa] // 2. we thus check the return of sell orders at the current exact price // 3. if the return of sell orders is larger than the pending buys, // there are more sells than buys [and vice-versa] uint256 resultOfSell = batch.totalSellSpend.mul(staticPricePPM).div(uint256(PPM)); if (resultOfSell > batch.totalBuySpend) { // >> sell orders are worth more than buy orders // 1. first we execute all pending buy orders at the current exact // price because there is at least one sell order for each buy order // 2. then the final sell return is the addition of this first // matched return with the remaining bonding curve return // the number of tokens bought as a result of all buy orders matched at the // current exact price [which is less than the total amount of tokens to be sold] batch.totalBuyReturn = batch.totalBuySpend.mul(uint256(PPM)).div(staticPricePPM); // the number of tokens left over to be sold along the curve which is the difference // between the original total sell order and the result of all the buy orders uint256 remainingSell = batch.totalSellSpend.sub(batch.totalBuyReturn); // the amount of collateral generated by selling tokens left over to be sold // along the bonding curve in the batch initial state [as if the buy orders // never existed and the sell order was just smaller than originally thought] uint256 remainingSellReturn = metaBatches[_batchId].formula.calculateSaleReturn(batch.supply, batch.balance, batch.reserveRatio, remainingSell); // the total result of all sells is the original amount of buys which were matched // plus the remaining sells which were executed along the bonding curve batch.totalSellReturn = batch.totalBuySpend.add(remainingSellReturn); } else { // >> buy orders are worth more than sell orders // 1. first we execute all pending sell orders at the current exact // price because there is at least one buy order for each sell order // 2. then the final buy return is the addition of this first // matched return with the remaining bonding curve return // the number of collaterals bought as a result of all sell orders matched at the // current exact price [which is less than the total amount of collateral to be spent] batch.totalSellReturn = resultOfSell; // the number of collaterals left over to be spent along the curve which is the difference // between the original total buy order and the result of all the sell orders uint256 remainingBuy = batch.totalBuySpend.sub(resultOfSell); // the amount of tokens generated by selling collaterals left over to be spent // along the bonding curve in the batch initial state [as if the sell orders // never existed and the buy order was just smaller than originally thought] uint256 remainingBuyReturn = metaBatches[_batchId].formula.calculatePurchaseReturn(batch.supply, batch.balance, batch.reserveRatio, remainingBuy); // the total result of all buys is the original amount of buys which were matched // plus the remaining buys which were executed along the bonding curve batch.totalBuyReturn = batch.totalSellSpend.add(remainingBuyReturn); } emit UpdatePricing(_batchId, _collateral, batch.totalBuySpend, batch.totalBuyReturn, batch.totalSellSpend, batch.totalSellReturn); } function _transfer(address _from, address _to, address _collateralToken, uint256 _amount) internal { if (_collateralToken == ETH) { _to.transfer(_amount); } else { require(ERC20(_collateralToken).safeTransferFrom(_from, _to, _amount), ERROR_TRANSFER_FROM_FAILED); } } } // File: @ablack/fundraising-shared-interfaces/contracts/IPresale.sol pragma solidity 0.4.24; contract IPresale { function open() external; function close() external; function contribute(address _contributor, uint256 _value) external payable; function refund(address _contributor, uint256 _vestedPurchaseId) external; function contributionToTokens(uint256 _value) public view returns (uint256); function contributionToken() public view returns (address); } // File: @ablack/fundraising-shared-interfaces/contracts/ITap.sol pragma solidity 0.4.24; contract ITap { function updateBeneficiary(address _beneficiary) external; function updateMaximumTapRateIncreasePct(uint256 _maximumTapRateIncreasePct) external; function updateMaximumTapFloorDecreasePct(uint256 _maximumTapFloorDecreasePct) external; function addTappedToken(address _token, uint256 _rate, uint256 _floor) external; function updateTappedToken(address _token, uint256 _rate, uint256 _floor) external; function resetTappedToken(address _token) external; function updateTappedAmount(address _token) external; function withdraw(address _token) external; function getMaximumWithdrawal(address _token) public view returns (uint256); function rates(address _token) public view returns (uint256); } // File: @ablack/fundraising-aragon-fundraising/contracts/AragonFundraisingController.sol pragma solidity 0.4.24; contract AragonFundraisingController is EtherTokenConstant, IsContract, IAragonFundraisingController, AragonApp { using SafeERC20 for ERC20; using SafeMath for uint256; /** Hardcoded constants to save gas bytes32 public constant UPDATE_BENEFICIARY_ROLE = keccak256("UPDATE_BENEFICIARY_ROLE"); bytes32 public constant UPDATE_FEES_ROLE = keccak256("UPDATE_FEES_ROLE"); bytes32 public constant ADD_COLLATERAL_TOKEN_ROLE = keccak256("ADD_COLLATERAL_TOKEN_ROLE"); bytes32 public constant REMOVE_COLLATERAL_TOKEN_ROLE = keccak256("REMOVE_COLLATERAL_TOKEN_ROLE"); bytes32 public constant UPDATE_COLLATERAL_TOKEN_ROLE = keccak256("UPDATE_COLLATERAL_TOKEN_ROLE"); bytes32 public constant UPDATE_MAXIMUM_TAP_RATE_INCREASE_PCT_ROLE = keccak256("UPDATE_MAXIMUM_TAP_RATE_INCREASE_PCT_ROLE"); bytes32 public constant UPDATE_MAXIMUM_TAP_FLOOR_DECREASE_PCT_ROLE = keccak256("UPDATE_MAXIMUM_TAP_FLOOR_DECREASE_PCT_ROLE"); bytes32 public constant ADD_TOKEN_TAP_ROLE = keccak256("ADD_TOKEN_TAP_ROLE"); bytes32 public constant UPDATE_TOKEN_TAP_ROLE = keccak256("UPDATE_TOKEN_TAP_ROLE"); bytes32 public constant OPEN_PRESALE_ROLE = keccak256("OPEN_PRESALE_ROLE"); bytes32 public constant OPEN_TRADING_ROLE = keccak256("OPEN_TRADING_ROLE"); bytes32 public constant CONTRIBUTE_ROLE = keccak256("CONTRIBUTE_ROLE"); bytes32 public constant OPEN_BUY_ORDER_ROLE = keccak256("OPEN_BUY_ORDER_ROLE"); bytes32 public constant OPEN_SELL_ORDER_ROLE = keccak256("OPEN_SELL_ORDER_ROLE"); bytes32 public constant WITHDRAW_ROLE = keccak256("WITHDRAW_ROLE"); */ bytes32 public constant UPDATE_BENEFICIARY_ROLE = 0xf7ea2b80c7b6a2cab2c11d2290cb005c3748397358a25e17113658c83b732593; bytes32 public constant UPDATE_FEES_ROLE = 0x5f9be2932ed3a723f295a763be1804c7ebfd1a41c1348fb8bdf5be1c5cdca822; bytes32 public constant ADD_COLLATERAL_TOKEN_ROLE = 0x217b79cb2bc7760defc88529853ef81ab33ae5bb315408ce9f5af09c8776662d; bytes32 public constant REMOVE_COLLATERAL_TOKEN_ROLE = 0x2044e56de223845e4be7d0a6f4e9a29b635547f16413a6d1327c58d9db438ee2; bytes32 public constant UPDATE_COLLATERAL_TOKEN_ROLE = 0xe0565c2c43e0d841e206bb36a37f12f22584b4652ccee6f9e0c071b697a2e13d; bytes32 public constant UPDATE_MAXIMUM_TAP_RATE_INCREASE_PCT_ROLE = 0x5d94de7e429250eee4ff97e30ab9f383bea3cd564d6780e0a9e965b1add1d207; bytes32 public constant UPDATE_MAXIMUM_TAP_FLOOR_DECREASE_PCT_ROLE = 0x57c9c67896cf0a4ffe92cbea66c2f7c34380af06bf14215dabb078cf8a6d99e1; bytes32 public constant ADD_TOKEN_TAP_ROLE = 0xbc9cb5e3f7ce81c4fd021d86a4bcb193dee9df315b540808c3ed59a81e596207; bytes32 public constant UPDATE_TOKEN_TAP_ROLE = 0xdb8c88bedbc61ea0f92e1ce46da0b7a915affbd46d1c76c4bbac9a209e4a8416; bytes32 public constant OPEN_PRESALE_ROLE = 0xf323aa41eef4850a8ae7ebd047d4c89f01ce49c781f3308be67303db9cdd48c2; bytes32 public constant OPEN_TRADING_ROLE = 0x26ce034204208c0bbca4c8a793d17b99e546009b1dd31d3c1ef761f66372caf6; bytes32 public constant CONTRIBUTE_ROLE = 0x9ccaca4edf2127f20c425fdd86af1ba178b9e5bee280cd70d88ac5f6874c4f07; bytes32 public constant OPEN_BUY_ORDER_ROLE = 0xa589c8f284b76fc8d510d9d553485c47dbef1b0745ae00e0f3fd4e28fcd77ea7; bytes32 public constant OPEN_SELL_ORDER_ROLE = 0xd68ba2b769fa37a2a7bd4bed9241b448bc99eca41f519ef037406386a8f291c0; bytes32 public constant WITHDRAW_ROLE = 0x5d8e12c39142ff96d79d04d15d1ba1269e4fe57bb9d26f43523628b34ba108ec; uint256 public constant TO_RESET_CAP = 10; string private constant ERROR_CONTRACT_IS_EOA = "FUNDRAISING_CONTRACT_IS_EOA"; string private constant ERROR_INVALID_TOKENS = "FUNDRAISING_INVALID_TOKENS"; IPresale public presale; BatchedBancorMarketMaker public marketMaker; Agent public reserve; ITap public tap; address[] public toReset; /***** external functions *****/ /** * @notice Initialize Aragon Fundraising controller * @param _presale The address of the presale contract * @param _marketMaker The address of the market maker contract * @param _reserve The address of the reserve [pool] contract * @param _tap The address of the tap contract * @param _toReset The addresses of the tokens whose tap timestamps are to be reset [when presale is closed and trading is open] */ function initialize( IPresale _presale, BatchedBancorMarketMaker _marketMaker, Agent _reserve, ITap _tap, address[] _toReset ) external onlyInit { require(isContract(_presale), ERROR_CONTRACT_IS_EOA); require(isContract(_marketMaker), ERROR_CONTRACT_IS_EOA); require(isContract(_reserve), ERROR_CONTRACT_IS_EOA); require(isContract(_tap), ERROR_CONTRACT_IS_EOA); require(_toReset.length < TO_RESET_CAP, ERROR_INVALID_TOKENS); initialized(); presale = _presale; marketMaker = _marketMaker; reserve = _reserve; tap = _tap; for (uint256 i = 0; i < _toReset.length; i++) { require(_tokenIsContractOrETH(_toReset[i]), ERROR_INVALID_TOKENS); toReset.push(_toReset[i]); } } /* generic settings related function */ /** * @notice Update beneficiary to `_beneficiary` * @param _beneficiary The address of the new beneficiary */ function updateBeneficiary(address _beneficiary) external auth(UPDATE_BENEFICIARY_ROLE) { marketMaker.updateBeneficiary(_beneficiary); tap.updateBeneficiary(_beneficiary); } /** * @notice Update fees deducted from buy and sell orders to respectively `@formatPct(_buyFeePct)`% and `@formatPct(_sellFeePct)`% * @param _buyFeePct The new fee to be deducted from buy orders [in PCT_BASE] * @param _sellFeePct The new fee to be deducted from sell orders [in PCT_BASE] */ function updateFees(uint256 _buyFeePct, uint256 _sellFeePct) external auth(UPDATE_FEES_ROLE) { marketMaker.updateFees(_buyFeePct, _sellFeePct); } /* presale related functions */ /** * @notice Open presale */ function openPresale() external auth(OPEN_PRESALE_ROLE) { presale.open(); } /** * @notice Close presale and open trading */ function closePresale() external isInitialized { presale.close(); } /** * @notice Contribute to the presale up to `@tokenAmount(self.contributionToken(): address, _value)` * @param _value The amount of contribution token to be spent */ function contribute(uint256 _value) external payable auth(CONTRIBUTE_ROLE) { presale.contribute.value(msg.value)(msg.sender, _value); } /** * @notice Refund `_contributor`'s presale contribution #`_vestedPurchaseId` * @param _contributor The address of the contributor whose presale contribution is to be refunded * @param _vestedPurchaseId The id of the contribution to be refunded */ function refund(address _contributor, uint256 _vestedPurchaseId) external isInitialized { presale.refund(_contributor, _vestedPurchaseId); } /* market making related functions */ /** * @notice Open trading [enabling users to open buy and sell orders] */ function openTrading() external auth(OPEN_TRADING_ROLE) { for (uint256 i = 0; i < toReset.length; i++) { if (tap.rates(toReset[i]) != uint256(0)) { tap.resetTappedToken(toReset[i]); } } marketMaker.open(); } /** * @notice Open a buy order worth `@tokenAmount(_collateral, _value)` * @param _collateral The address of the collateral token to be spent * @param _value The amount of collateral token to be spent */ function openBuyOrder(address _collateral, uint256 _value) external payable auth(OPEN_BUY_ORDER_ROLE) { marketMaker.openBuyOrder.value(msg.value)(msg.sender, _collateral, _value); } /** * @notice Open a sell order worth `@tokenAmount(self.token(): address, _amount)` against `_collateral.symbol(): string` * @param _collateral The address of the collateral token to be returned * @param _amount The amount of bonded token to be spent */ function openSellOrder(address _collateral, uint256 _amount) external auth(OPEN_SELL_ORDER_ROLE) { marketMaker.openSellOrder(msg.sender, _collateral, _amount); } /** * @notice Claim the results of `_collateral.symbol(): string` buy orders from batch #`_batchId` * @param _buyer The address of the user whose buy orders are to be claimed * @param _batchId The id of the batch in which buy orders are to be claimed * @param _collateral The address of the collateral token against which buy orders are to be claimed */ function claimBuyOrder(address _buyer, uint256 _batchId, address _collateral) external isInitialized { marketMaker.claimBuyOrder(_buyer, _batchId, _collateral); } /** * @notice Claim the results of `_collateral.symbol(): string` sell orders from batch #`_batchId` * @param _seller The address of the user whose sell orders are to be claimed * @param _batchId The id of the batch in which sell orders are to be claimed * @param _collateral The address of the collateral token against which sell orders are to be claimed */ function claimSellOrder(address _seller, uint256 _batchId, address _collateral) external isInitialized { marketMaker.claimSellOrder(_seller, _batchId, _collateral); } /* collateral tokens related functions */ /** * @notice Add `_collateral.symbol(): string` as a whitelisted collateral token * @param _collateral The address of the collateral token to be whitelisted * @param _virtualSupply The virtual supply to be used for that collateral token [in wei] * @param _virtualBalance The virtual balance to be used for that collateral token [in wei] * @param _reserveRatio The reserve ratio to be used for that collateral token [in PPM] * @param _slippage The price slippage below which each market making batch is to be kept for that collateral token [in PCT_BASE] * @param _rate The rate at which that token is to be tapped [in wei / block] * @param _floor The floor above which the reserve [pool] balance for that token is to be kept [in wei] */ function addCollateralToken( address _collateral, uint256 _virtualSupply, uint256 _virtualBalance, uint32 _reserveRatio, uint256 _slippage, uint256 _rate, uint256 _floor ) external auth(ADD_COLLATERAL_TOKEN_ROLE) { marketMaker.addCollateralToken(_collateral, _virtualSupply, _virtualBalance, _reserveRatio, _slippage); if (_collateral != ETH) { reserve.addProtectedToken(_collateral); } if (_rate > 0) { tap.addTappedToken(_collateral, _rate, _floor); } } /** * @notice Re-add `_collateral.symbol(): string` as a whitelisted collateral token [if it has been un-whitelisted in the past] * @param _collateral The address of the collateral token to be whitelisted * @param _virtualSupply The virtual supply to be used for that collateral token [in wei] * @param _virtualBalance The virtual balance to be used for that collateral token [in wei] * @param _reserveRatio The reserve ratio to be used for that collateral token [in PPM] * @param _slippage The price slippage below which each market making batch is to be kept for that collateral token [in PCT_BASE] */ function reAddCollateralToken( address _collateral, uint256 _virtualSupply, uint256 _virtualBalance, uint32 _reserveRatio, uint256 _slippage ) external auth(ADD_COLLATERAL_TOKEN_ROLE) { marketMaker.addCollateralToken(_collateral, _virtualSupply, _virtualBalance, _reserveRatio, _slippage); } /** * @notice Remove `_collateral.symbol(): string` as a whitelisted collateral token * @param _collateral The address of the collateral token to be un-whitelisted */ function removeCollateralToken(address _collateral) external auth(REMOVE_COLLATERAL_TOKEN_ROLE) { marketMaker.removeCollateralToken(_collateral); // the token should still be tapped to avoid being locked // the token should still be protected to avoid being spent } /** * @notice Update `_collateral.symbol(): string` collateralization settings * @param _collateral The address of the collateral token whose collateralization settings are to be updated * @param _virtualSupply The new virtual supply to be used for that collateral token [in wei] * @param _virtualBalance The new virtual balance to be used for that collateral token [in wei] * @param _reserveRatio The new reserve ratio to be used for that collateral token [in PPM] * @param _slippage The new price slippage below which each market making batch is to be kept for that collateral token [in PCT_BASE] */ function updateCollateralToken( address _collateral, uint256 _virtualSupply, uint256 _virtualBalance, uint32 _reserveRatio, uint256 _slippage ) external auth(UPDATE_COLLATERAL_TOKEN_ROLE) { marketMaker.updateCollateralToken(_collateral, _virtualSupply, _virtualBalance, _reserveRatio, _slippage); } /* tap related functions */ /** * @notice Update maximum tap rate increase percentage to `@formatPct(_maximumTapRateIncreasePct)`% * @param _maximumTapRateIncreasePct The new maximum tap rate increase percentage to be allowed [in PCT_BASE] */ function updateMaximumTapRateIncreasePct(uint256 _maximumTapRateIncreasePct) external auth(UPDATE_MAXIMUM_TAP_RATE_INCREASE_PCT_ROLE) { tap.updateMaximumTapRateIncreasePct(_maximumTapRateIncreasePct); } /** * @notice Update maximum tap floor decrease percentage to `@formatPct(_maximumTapFloorDecreasePct)`% * @param _maximumTapFloorDecreasePct The new maximum tap floor decrease percentage to be allowed [in PCT_BASE] */ function updateMaximumTapFloorDecreasePct(uint256 _maximumTapFloorDecreasePct) external auth(UPDATE_MAXIMUM_TAP_FLOOR_DECREASE_PCT_ROLE) { tap.updateMaximumTapFloorDecreasePct(_maximumTapFloorDecreasePct); } /** * @notice Add tap for `_token.symbol(): string` with a rate of `@tokenAmount(_token, _rate)` per block and a floor of `@tokenAmount(_token, _floor)` * @param _token The address of the token to be tapped * @param _rate The rate at which that token is to be tapped [in wei / block] * @param _floor The floor above which the reserve [pool] balance for that token is to be kept [in wei] */ function addTokenTap(address _token, uint256 _rate, uint256 _floor) external auth(ADD_TOKEN_TAP_ROLE) { tap.addTappedToken(_token, _rate, _floor); } /** * @notice Update tap for `_token.symbol(): string` with a rate of about `@tokenAmount(_token, 4 * 60 * 24 * 30 * _rate)` per month and a floor of `@tokenAmount(_token, _floor)` * @param _token The address of the token whose tap is to be updated * @param _rate The new rate at which that token is to be tapped [in wei / block] * @param _floor The new floor above which the reserve [pool] balance for that token is to be kept [in wei] */ function updateTokenTap(address _token, uint256 _rate, uint256 _floor) external auth(UPDATE_TOKEN_TAP_ROLE) { tap.updateTappedToken(_token, _rate, _floor); } /** * @notice Update tapped amount for `_token.symbol(): string` * @param _token The address of the token whose tapped amount is to be updated */ function updateTappedAmount(address _token) external { tap.updateTappedAmount(_token); } /** * @notice Transfer about `@tokenAmount(_token, self.getMaximumWithdrawal(_token): uint256)` from the reserve to the beneficiary * @param _token The address of the token to be transfered from the reserve to the beneficiary */ function withdraw(address _token) external auth(WITHDRAW_ROLE) { tap.withdraw(_token); } /***** public view functions *****/ function token() public view isInitialized returns (address) { return marketMaker.token(); } function contributionToken() public view isInitialized returns (address) { return presale.contributionToken(); } function getMaximumWithdrawal(address _token) public view isInitialized returns (uint256) { return tap.getMaximumWithdrawal(_token); } function collateralsToBeClaimed(address _collateral) public view isInitialized returns (uint256) { return marketMaker.collateralsToBeClaimed(_collateral); } function balanceOf(address _who, address _token) public view isInitialized returns (uint256) { uint256 balance = _token == ETH ? _who.balance : ERC20(_token).staticBalanceOf(_who); if (_who == address(reserve)) { return balance.sub(tap.getMaximumWithdrawal(_token)); } else { return balance; } } /***** internal functions *****/ function _tokenIsContractOrETH(address _token) internal view returns (bool) { return isContract(_token) || _token == ETH; } } // File: @ablack/fundraising-presale/contracts/Presale.sol pragma solidity ^0.4.24; contract Presale is IPresale, EtherTokenConstant, IsContract, AragonApp { using SafeERC20 for ERC20; using SafeMath for uint256; using SafeMath64 for uint64; /** Hardcoded constants to save gas bytes32 public constant OPEN_ROLE = keccak256("OPEN_ROLE"); bytes32 public constant CONTRIBUTE_ROLE = keccak256("CONTRIBUTE_ROLE"); */ bytes32 public constant OPEN_ROLE = 0xefa06053e2ca99a43c97c4a4f3d8a394ee3323a8ff237e625fba09fe30ceb0a4; bytes32 public constant CONTRIBUTE_ROLE = 0x9ccaca4edf2127f20c425fdd86af1ba178b9e5bee280cd70d88ac5f6874c4f07; uint256 public constant PPM = 1000000; // 0% = 0 * 10 ** 4; 1% = 1 * 10 ** 4; 100% = 100 * 10 ** 4 string private constant ERROR_CONTRACT_IS_EOA = "PRESALE_CONTRACT_IS_EOA"; string private constant ERROR_INVALID_BENEFICIARY = "PRESALE_INVALID_BENEFICIARY"; string private constant ERROR_INVALID_CONTRIBUTE_TOKEN = "PRESALE_INVALID_CONTRIBUTE_TOKEN"; string private constant ERROR_INVALID_GOAL = "PRESALE_INVALID_GOAL"; string private constant ERROR_INVALID_EXCHANGE_RATE = "PRESALE_INVALID_EXCHANGE_RATE"; string private constant ERROR_INVALID_TIME_PERIOD = "PRESALE_INVALID_TIME_PERIOD"; string private constant ERROR_INVALID_PCT = "PRESALE_INVALID_PCT"; string private constant ERROR_INVALID_STATE = "PRESALE_INVALID_STATE"; string private constant ERROR_INVALID_CONTRIBUTE_VALUE = "PRESALE_INVALID_CONTRIBUTE_VALUE"; string private constant ERROR_INSUFFICIENT_BALANCE = "PRESALE_INSUFFICIENT_BALANCE"; string private constant ERROR_INSUFFICIENT_ALLOWANCE = "PRESALE_INSUFFICIENT_ALLOWANCE"; string private constant ERROR_NOTHING_TO_REFUND = "PRESALE_NOTHING_TO_REFUND"; string private constant ERROR_TOKEN_TRANSFER_REVERTED = "PRESALE_TOKEN_TRANSFER_REVERTED"; enum State { Pending, // presale is idle and pending to be started Funding, // presale has started and contributors can purchase tokens Refunding, // presale has not reached goal within period and contributors can claim refunds GoalReached, // presale has reached goal within period and trading is ready to be open Closed // presale has reached goal within period, has been closed and trading has been open } IAragonFundraisingController public controller; TokenManager public tokenManager; ERC20 public token; address public reserve; address public beneficiary; address public contributionToken; uint256 public goal; uint64 public period; uint256 public exchangeRate; uint64 public vestingCliffPeriod; uint64 public vestingCompletePeriod; uint256 public supplyOfferedPct; uint256 public fundingForBeneficiaryPct; uint64 public openDate; bool public isClosed; uint64 public vestingCliffDate; uint64 public vestingCompleteDate; uint256 public totalRaised; mapping(address => mapping(uint256 => uint256)) public contributions; // contributor => (vestedPurchaseId => tokensSpent) event SetOpenDate (uint64 date); event Close (); event Contribute (address indexed contributor, uint256 value, uint256 amount, uint256 vestedPurchaseId); event Refund (address indexed contributor, uint256 value, uint256 amount, uint256 vestedPurchaseId); /***** external function *****/ /** * @notice Initialize presale * @param _controller The address of the controller contract * @param _tokenManager The address of the [bonded] token manager contract * @param _reserve The address of the reserve [pool] contract * @param _beneficiary The address of the beneficiary [to whom a percentage of the raised funds is be to be sent] * @param _contributionToken The address of the token to be used to contribute * @param _goal The goal to be reached by the end of that presale [in contribution token wei] * @param _period The period within which to accept contribution for that presale * @param _exchangeRate The exchangeRate [= 1/price] at which [bonded] tokens are to be purchased for that presale [in PPM] * @param _vestingCliffPeriod The period during which purchased [bonded] tokens are to be cliffed * @param _vestingCompletePeriod The complete period during which purchased [bonded] tokens are to be vested * @param _supplyOfferedPct The percentage of the initial supply of [bonded] tokens to be offered during that presale [in PPM] * @param _fundingForBeneficiaryPct The percentage of the raised contribution tokens to be sent to the beneficiary [instead of the fundraising reserve] when that presale is closed [in PPM] * @param _openDate The date upon which that presale is to be open [ignored if 0] */ function initialize( IAragonFundraisingController _controller, TokenManager _tokenManager, address _reserve, address _beneficiary, address _contributionToken, uint256 _goal, uint64 _period, uint256 _exchangeRate, uint64 _vestingCliffPeriod, uint64 _vestingCompletePeriod, uint256 _supplyOfferedPct, uint256 _fundingForBeneficiaryPct, uint64 _openDate ) external onlyInit { require(isContract(_controller), ERROR_CONTRACT_IS_EOA); require(isContract(_tokenManager), ERROR_CONTRACT_IS_EOA); require(isContract(_reserve), ERROR_CONTRACT_IS_EOA); require(_beneficiary != address(0), ERROR_INVALID_BENEFICIARY); require(isContract(_contributionToken) || _contributionToken == ETH, ERROR_INVALID_CONTRIBUTE_TOKEN); require(_goal > 0, ERROR_INVALID_GOAL); require(_period > 0, ERROR_INVALID_TIME_PERIOD); require(_exchangeRate > 0, ERROR_INVALID_EXCHANGE_RATE); require(_vestingCliffPeriod > _period, ERROR_INVALID_TIME_PERIOD); require(_vestingCompletePeriod > _vestingCliffPeriod, ERROR_INVALID_TIME_PERIOD); require(_supplyOfferedPct > 0 && _supplyOfferedPct <= PPM, ERROR_INVALID_PCT); require(_fundingForBeneficiaryPct >= 0 && _fundingForBeneficiaryPct <= PPM, ERROR_INVALID_PCT); initialized(); controller = _controller; tokenManager = _tokenManager; token = ERC20(_tokenManager.token()); reserve = _reserve; beneficiary = _beneficiary; contributionToken = _contributionToken; goal = _goal; period = _period; exchangeRate = _exchangeRate; vestingCliffPeriod = _vestingCliffPeriod; vestingCompletePeriod = _vestingCompletePeriod; supplyOfferedPct = _supplyOfferedPct; fundingForBeneficiaryPct = _fundingForBeneficiaryPct; if (_openDate != 0) { _setOpenDate(_openDate); } } /** * @notice Open presale [enabling users to contribute] */ function open() external auth(OPEN_ROLE) { require(state() == State.Pending, ERROR_INVALID_STATE); require(openDate == 0, ERROR_INVALID_STATE); _open(); } /** * @notice Contribute to the presale up to `@tokenAmount(self.contributionToken(): address, _value)` * @param _contributor The address of the contributor * @param _value The amount of contribution token to be spent */ function contribute(address _contributor, uint256 _value) external payable nonReentrant auth(CONTRIBUTE_ROLE) { require(state() == State.Funding, ERROR_INVALID_STATE); require(_value != 0, ERROR_INVALID_CONTRIBUTE_VALUE); if (contributionToken == ETH) { require(msg.value == _value, ERROR_INVALID_CONTRIBUTE_VALUE); } else { require(msg.value == 0, ERROR_INVALID_CONTRIBUTE_VALUE); } _contribute(_contributor, _value); } /** * @notice Refund `_contributor`'s presale contribution #`_vestedPurchaseId` * @param _contributor The address of the contributor whose presale contribution is to be refunded * @param _vestedPurchaseId The id of the contribution to be refunded */ function refund(address _contributor, uint256 _vestedPurchaseId) external nonReentrant isInitialized { require(state() == State.Refunding, ERROR_INVALID_STATE); _refund(_contributor, _vestedPurchaseId); } /** * @notice Close presale and open trading */ function close() external nonReentrant isInitialized { require(state() == State.GoalReached, ERROR_INVALID_STATE); _close(); } /***** public view functions *****/ /** * @notice Computes the amount of [bonded] tokens that would be purchased for `@tokenAmount(self.contributionToken(): address, _value)` * @param _value The amount of contribution tokens to be used in that computation */ function contributionToTokens(uint256 _value) public view isInitialized returns (uint256) { return _value.mul(exchangeRate).div(PPM); } function contributionToken() public view isInitialized returns (address) { return contributionToken; } /** * @notice Returns the current state of that presale */ function state() public view isInitialized returns (State) { if (openDate == 0 || openDate > getTimestamp64()) { return State.Pending; } if (totalRaised >= goal) { if (isClosed) { return State.Closed; } else { return State.GoalReached; } } if (_timeSinceOpen() < period) { return State.Funding; } else { return State.Refunding; } } /***** internal functions *****/ function _timeSinceOpen() internal view returns (uint64) { if (openDate == 0) { return 0; } else { return getTimestamp64().sub(openDate); } } function _setOpenDate(uint64 _date) internal { require(_date >= getTimestamp64(), ERROR_INVALID_TIME_PERIOD); openDate = _date; _setVestingDatesWhenOpenDateIsKnown(); emit SetOpenDate(_date); } function _setVestingDatesWhenOpenDateIsKnown() internal { vestingCliffDate = openDate.add(vestingCliffPeriod); vestingCompleteDate = openDate.add(vestingCompletePeriod); } function _open() internal { _setOpenDate(getTimestamp64()); } function _contribute(address _contributor, uint256 _value) internal { uint256 value = totalRaised.add(_value) > goal ? goal.sub(totalRaised) : _value; if (contributionToken == ETH && _value > value) { msg.sender.transfer(_value.sub(value)); } // (contributor) ~~~> contribution tokens ~~~> (presale) if (contributionToken != ETH) { require(ERC20(contributionToken).balanceOf(_contributor) >= value, ERROR_INSUFFICIENT_BALANCE); require(ERC20(contributionToken).allowance(_contributor, address(this)) >= value, ERROR_INSUFFICIENT_ALLOWANCE); _transfer(contributionToken, _contributor, address(this), value); } // (mint ✨) ~~~> project tokens ~~~> (contributor) uint256 tokensToSell = contributionToTokens(value); tokenManager.issue(tokensToSell); uint256 vestedPurchaseId = tokenManager.assignVested( _contributor, tokensToSell, openDate, vestingCliffDate, vestingCompleteDate, true /* revokable */ ); totalRaised = totalRaised.add(value); // register contribution tokens spent in this purchase for a possible upcoming refund contributions[_contributor][vestedPurchaseId] = value; emit Contribute(_contributor, value, tokensToSell, vestedPurchaseId); } function _refund(address _contributor, uint256 _vestedPurchaseId) internal { // recall how much contribution tokens are to be refund for this purchase uint256 tokensToRefund = contributions[_contributor][_vestedPurchaseId]; require(tokensToRefund > 0, ERROR_NOTHING_TO_REFUND); contributions[_contributor][_vestedPurchaseId] = 0; // (presale) ~~~> contribution tokens ~~~> (contributor) _transfer(contributionToken, address(this), _contributor, tokensToRefund); /** * NOTE * the following lines assume that _contributor has not transfered any of its vested tokens * for now TokenManager does not handle switching the transferrable status of its underlying token * there is thus no way to enforce non-transferrability during the presale phase only * this will be updated in a later version */ // (contributor) ~~~> project tokens ~~~> (token manager) (uint256 tokensSold,,,,) = tokenManager.getVesting(_contributor, _vestedPurchaseId); tokenManager.revokeVesting(_contributor, _vestedPurchaseId); // (token manager) ~~~> project tokens ~~~> (burn 💥) tokenManager.burn(address(tokenManager), tokensSold); emit Refund(_contributor, tokensToRefund, tokensSold, _vestedPurchaseId); } function _close() internal { isClosed = true; // (presale) ~~~> contribution tokens ~~~> (beneficiary) uint256 fundsForBeneficiary = totalRaised.mul(fundingForBeneficiaryPct).div(PPM); if (fundsForBeneficiary > 0) { _transfer(contributionToken, address(this), beneficiary, fundsForBeneficiary); } // (presale) ~~~> contribution tokens ~~~> (reserve) uint256 tokensForReserve = contributionToken == ETH ? address(this).balance : ERC20(contributionToken).balanceOf(address(this)); _transfer(contributionToken, address(this), reserve, tokensForReserve); // (mint ✨) ~~~> project tokens ~~~> (beneficiary) uint256 tokensForBeneficiary = token.totalSupply().mul(PPM.sub(supplyOfferedPct)).div(supplyOfferedPct); tokenManager.issue(tokensForBeneficiary); tokenManager.assignVested( beneficiary, tokensForBeneficiary, openDate, vestingCliffDate, vestingCompleteDate, false /* revokable */ ); // open trading controller.openTrading(); emit Close(); } function _transfer(address _token, address _from, address _to, uint256 _amount) internal { if (_token == ETH) { require(_from == address(this), ERROR_TOKEN_TRANSFER_REVERTED); require(_to != address(this), ERROR_TOKEN_TRANSFER_REVERTED); _to.transfer(_amount); } else { if (_from == address(this)) { require(ERC20(_token).safeTransfer(_to, _amount), ERROR_TOKEN_TRANSFER_REVERTED); } else { require(ERC20(_token).safeTransferFrom(_from, _to, _amount), ERROR_TOKEN_TRANSFER_REVERTED); } } } } // File: @ablack/fundraising-tap/contracts/Tap.sol pragma solidity 0.4.24; contract Tap is ITap, TimeHelpers, EtherTokenConstant, IsContract, AragonApp { using SafeERC20 for ERC20; using SafeMath for uint256; /** Hardcoded constants to save gas bytes32 public constant UPDATE_CONTROLLER_ROLE = keccak256("UPDATE_CONTROLLER_ROLE"); bytes32 public constant UPDATE_RESERVE_ROLE = keccak256("UPDATE_RESERVE_ROLE"); bytes32 public constant UPDATE_BENEFICIARY_ROLE = keccak256("UPDATE_BENEFICIARY_ROLE"); bytes32 public constant UPDATE_MAXIMUM_TAP_RATE_INCREASE_PCT_ROLE = keccak256("UPDATE_MAXIMUM_TAP_RATE_INCREASE_PCT_ROLE"); bytes32 public constant UPDATE_MAXIMUM_TAP_FLOOR_DECREASE_PCT_ROLE = keccak256("UPDATE_MAXIMUM_TAP_FLOOR_DECREASE_PCT_ROLE"); bytes32 public constant ADD_TAPPED_TOKEN_ROLE = keccak256("ADD_TAPPED_TOKEN_ROLE"); bytes32 public constant REMOVE_TAPPED_TOKEN_ROLE = keccak256("REMOVE_TAPPED_TOKEN_ROLE"); bytes32 public constant UPDATE_TAPPED_TOKEN_ROLE = keccak256("UPDATE_TAPPED_TOKEN_ROLE"); bytes32 public constant RESET_TAPPED_TOKEN_ROLE = keccak256("RESET_TAPPED_TOKEN_ROLE"); bytes32 public constant WITHDRAW_ROLE = keccak256("WITHDRAW_ROLE"); */ bytes32 public constant UPDATE_CONTROLLER_ROLE = 0x454b5d0dbb74f012faf1d3722ea441689f97dc957dd3ca5335b4969586e5dc30; bytes32 public constant UPDATE_RESERVE_ROLE = 0x7984c050833e1db850f5aa7476710412fd2983fcec34da049502835ad7aed4f7; bytes32 public constant UPDATE_BENEFICIARY_ROLE = 0xf7ea2b80c7b6a2cab2c11d2290cb005c3748397358a25e17113658c83b732593; bytes32 public constant UPDATE_MAXIMUM_TAP_RATE_INCREASE_PCT_ROLE = 0x5d94de7e429250eee4ff97e30ab9f383bea3cd564d6780e0a9e965b1add1d207; bytes32 public constant UPDATE_MAXIMUM_TAP_FLOOR_DECREASE_PCT_ROLE = 0x57c9c67896cf0a4ffe92cbea66c2f7c34380af06bf14215dabb078cf8a6d99e1; bytes32 public constant ADD_TAPPED_TOKEN_ROLE = 0x5bc3b608e6be93b75a1c472a4a5bea3d31eabae46bf968e4bc4c7701562114dc; bytes32 public constant REMOVE_TAPPED_TOKEN_ROLE = 0xd76960be78bfedc5b40ce4fa64a2f8308f39dd2cbb1f9676dbc4ce87b817befd; bytes32 public constant UPDATE_TAPPED_TOKEN_ROLE = 0x83201394534c53ae0b4696fd49a933082d3e0525aa5a3d0a14a2f51e12213288; bytes32 public constant RESET_TAPPED_TOKEN_ROLE = 0x294bf52c518669359157a9fe826e510dfc3dbd200d44bf77ec9536bff34bc29e; bytes32 public constant WITHDRAW_ROLE = 0x5d8e12c39142ff96d79d04d15d1ba1269e4fe57bb9d26f43523628b34ba108ec; uint256 public constant PCT_BASE = 10 ** 18; // 0% = 0; 1% = 10 ** 16; 100% = 10 ** 18 string private constant ERROR_CONTRACT_IS_EOA = "TAP_CONTRACT_IS_EOA"; string private constant ERROR_INVALID_BENEFICIARY = "TAP_INVALID_BENEFICIARY"; string private constant ERROR_INVALID_BATCH_BLOCKS = "TAP_INVALID_BATCH_BLOCKS"; string private constant ERROR_INVALID_FLOOR_DECREASE_PCT = "TAP_INVALID_FLOOR_DECREASE_PCT"; string private constant ERROR_INVALID_TOKEN = "TAP_INVALID_TOKEN"; string private constant ERROR_INVALID_TAP_RATE = "TAP_INVALID_TAP_RATE"; string private constant ERROR_INVALID_TAP_UPDATE = "TAP_INVALID_TAP_UPDATE"; string private constant ERROR_TOKEN_ALREADY_TAPPED = "TAP_TOKEN_ALREADY_TAPPED"; string private constant ERROR_TOKEN_NOT_TAPPED = "TAP_TOKEN_NOT_TAPPED"; string private constant ERROR_WITHDRAWAL_AMOUNT_ZERO = "TAP_WITHDRAWAL_AMOUNT_ZERO"; IAragonFundraisingController public controller; Vault public reserve; address public beneficiary; uint256 public batchBlocks; uint256 public maximumTapRateIncreasePct; uint256 public maximumTapFloorDecreasePct; mapping (address => uint256) public tappedAmounts; mapping (address => uint256) public rates; mapping (address => uint256) public floors; mapping (address => uint256) public lastTappedAmountUpdates; // batch ids [block numbers] mapping (address => uint256) public lastTapUpdates; // timestamps event UpdateBeneficiary (address indexed beneficiary); event UpdateMaximumTapRateIncreasePct (uint256 maximumTapRateIncreasePct); event UpdateMaximumTapFloorDecreasePct(uint256 maximumTapFloorDecreasePct); event AddTappedToken (address indexed token, uint256 rate, uint256 floor); event RemoveTappedToken (address indexed token); event UpdateTappedToken (address indexed token, uint256 rate, uint256 floor); event ResetTappedToken (address indexed token); event UpdateTappedAmount (address indexed token, uint256 tappedAmount); event Withdraw (address indexed token, uint256 amount); /***** external functions *****/ /** * @notice Initialize tap * @param _controller The address of the controller contract * @param _reserve The address of the reserve [pool] contract * @param _beneficiary The address of the beneficiary [to whom funds are to be withdrawn] * @param _batchBlocks The number of blocks batches are to last * @param _maximumTapRateIncreasePct The maximum tap rate increase percentage allowed [in PCT_BASE] * @param _maximumTapFloorDecreasePct The maximum tap floor decrease percentage allowed [in PCT_BASE] */ function initialize( IAragonFundraisingController _controller, Vault _reserve, address _beneficiary, uint256 _batchBlocks, uint256 _maximumTapRateIncreasePct, uint256 _maximumTapFloorDecreasePct ) external onlyInit { require(isContract(_controller), ERROR_CONTRACT_IS_EOA); require(isContract(_reserve), ERROR_CONTRACT_IS_EOA); require(_beneficiaryIsValid(_beneficiary), ERROR_INVALID_BENEFICIARY); require(_batchBlocks != 0, ERROR_INVALID_BATCH_BLOCKS); require(_maximumTapFloorDecreasePctIsValid(_maximumTapFloorDecreasePct), ERROR_INVALID_FLOOR_DECREASE_PCT); initialized(); controller = _controller; reserve = _reserve; beneficiary = _beneficiary; batchBlocks = _batchBlocks; maximumTapRateIncreasePct = _maximumTapRateIncreasePct; maximumTapFloorDecreasePct = _maximumTapFloorDecreasePct; } /** * @notice Update beneficiary to `_beneficiary` * @param _beneficiary The address of the new beneficiary [to whom funds are to be withdrawn] */ function updateBeneficiary(address _beneficiary) external auth(UPDATE_BENEFICIARY_ROLE) { require(_beneficiaryIsValid(_beneficiary), ERROR_INVALID_BENEFICIARY); _updateBeneficiary(_beneficiary); } /** * @notice Update maximum tap rate increase percentage to `@formatPct(_maximumTapRateIncreasePct)`% * @param _maximumTapRateIncreasePct The new maximum tap rate increase percentage to be allowed [in PCT_BASE] */ function updateMaximumTapRateIncreasePct(uint256 _maximumTapRateIncreasePct) external auth(UPDATE_MAXIMUM_TAP_RATE_INCREASE_PCT_ROLE) { _updateMaximumTapRateIncreasePct(_maximumTapRateIncreasePct); } /** * @notice Update maximum tap floor decrease percentage to `@formatPct(_maximumTapFloorDecreasePct)`% * @param _maximumTapFloorDecreasePct The new maximum tap floor decrease percentage to be allowed [in PCT_BASE] */ function updateMaximumTapFloorDecreasePct(uint256 _maximumTapFloorDecreasePct) external auth(UPDATE_MAXIMUM_TAP_FLOOR_DECREASE_PCT_ROLE) { require(_maximumTapFloorDecreasePctIsValid(_maximumTapFloorDecreasePct), ERROR_INVALID_FLOOR_DECREASE_PCT); _updateMaximumTapFloorDecreasePct(_maximumTapFloorDecreasePct); } /** * @notice Add tap for `_token.symbol(): string` with a rate of `@tokenAmount(_token, _rate)` per block and a floor of `@tokenAmount(_token, _floor)` * @param _token The address of the token to be tapped * @param _rate The rate at which that token is to be tapped [in wei / block] * @param _floor The floor above which the reserve [pool] balance for that token is to be kept [in wei] */ function addTappedToken(address _token, uint256 _rate, uint256 _floor) external auth(ADD_TAPPED_TOKEN_ROLE) { require(_tokenIsContractOrETH(_token), ERROR_INVALID_TOKEN); require(!_tokenIsTapped(_token), ERROR_TOKEN_ALREADY_TAPPED); require(_tapRateIsValid(_rate), ERROR_INVALID_TAP_RATE); _addTappedToken(_token, _rate, _floor); } /** * @notice Remove tap for `_token.symbol(): string` * @param _token The address of the token to be un-tapped */ function removeTappedToken(address _token) external auth(REMOVE_TAPPED_TOKEN_ROLE) { require(_tokenIsTapped(_token), ERROR_TOKEN_NOT_TAPPED); _removeTappedToken(_token); } /** * @notice Update tap for `_token.symbol(): string` with a rate of `@tokenAmount(_token, _rate)` per block and a floor of `@tokenAmount(_token, _floor)` * @param _token The address of the token whose tap is to be updated * @param _rate The new rate at which that token is to be tapped [in wei / block] * @param _floor The new floor above which the reserve [pool] balance for that token is to be kept [in wei] */ function updateTappedToken(address _token, uint256 _rate, uint256 _floor) external auth(UPDATE_TAPPED_TOKEN_ROLE) { require(_tokenIsTapped(_token), ERROR_TOKEN_NOT_TAPPED); require(_tapRateIsValid(_rate), ERROR_INVALID_TAP_RATE); require(_tapUpdateIsValid(_token, _rate, _floor), ERROR_INVALID_TAP_UPDATE); _updateTappedToken(_token, _rate, _floor); } /** * @notice Reset tap timestamps for `_token.symbol(): string` * @param _token The address of the token whose tap timestamps are to be reset */ function resetTappedToken(address _token) external auth(RESET_TAPPED_TOKEN_ROLE) { require(_tokenIsTapped(_token), ERROR_TOKEN_NOT_TAPPED); _resetTappedToken(_token); } /** * @notice Update tapped amount for `_token.symbol(): string` * @param _token The address of the token whose tapped amount is to be updated */ function updateTappedAmount(address _token) external { require(_tokenIsTapped(_token), ERROR_TOKEN_NOT_TAPPED); _updateTappedAmount(_token); } /** * @notice Transfer about `@tokenAmount(_token, self.getMaximalWithdrawal(_token): uint256)` from `self.reserve()` to `self.beneficiary()` * @param _token The address of the token to be transfered */ function withdraw(address _token) external auth(WITHDRAW_ROLE) { require(_tokenIsTapped(_token), ERROR_TOKEN_NOT_TAPPED); uint256 amount = _updateTappedAmount(_token); require(amount > 0, ERROR_WITHDRAWAL_AMOUNT_ZERO); _withdraw(_token, amount); } /***** public view functions *****/ function getMaximumWithdrawal(address _token) public view isInitialized returns (uint256) { return _tappedAmount(_token); } function rates(address _token) public view isInitialized returns (uint256) { return rates[_token]; } /***** internal functions *****/ /* computation functions */ function _currentBatchId() internal view returns (uint256) { return (block.number.div(batchBlocks)).mul(batchBlocks); } function _tappedAmount(address _token) internal view returns (uint256) { uint256 toBeKept = controller.collateralsToBeClaimed(_token).add(floors[_token]); uint256 balance = _token == ETH ? address(reserve).balance : ERC20(_token).staticBalanceOf(reserve); uint256 flow = (_currentBatchId().sub(lastTappedAmountUpdates[_token])).mul(rates[_token]); uint256 tappedAmount = tappedAmounts[_token].add(flow); /** * whatever happens enough collateral should be * kept in the reserve pool to guarantee that * its balance is kept above the floor once * all pending sell orders are claimed */ /** * the reserve's balance is already below the balance to be kept * the tapped amount should be reset to zero */ if (balance <= toBeKept) { return 0; } /** * the reserve's balance minus the upcoming tap flow would be below the balance to be kept * the flow should be reduced to balance - toBeKept */ if (balance <= toBeKept.add(tappedAmount)) { return balance.sub(toBeKept); } /** * the reserve's balance minus the upcoming flow is above the balance to be kept * the flow can be added to the tapped amount */ return tappedAmount; } /* check functions */ function _beneficiaryIsValid(address _beneficiary) internal pure returns (bool) { return _beneficiary != address(0); } function _maximumTapFloorDecreasePctIsValid(uint256 _maximumTapFloorDecreasePct) internal pure returns (bool) { return _maximumTapFloorDecreasePct <= PCT_BASE; } function _tokenIsContractOrETH(address _token) internal view returns (bool) { return isContract(_token) || _token == ETH; } function _tokenIsTapped(address _token) internal view returns (bool) { return rates[_token] != uint256(0); } function _tapRateIsValid(uint256 _rate) internal pure returns (bool) { return _rate != 0; } function _tapUpdateIsValid(address _token, uint256 _rate, uint256 _floor) internal view returns (bool) { return _tapRateUpdateIsValid(_token, _rate) && _tapFloorUpdateIsValid(_token, _floor); } function _tapRateUpdateIsValid(address _token, uint256 _rate) internal view returns (bool) { uint256 rate = rates[_token]; if (_rate <= rate) { return true; } if (getTimestamp() < lastTapUpdates[_token] + 30 days) { return false; } if (_rate.mul(PCT_BASE) <= rate.mul(PCT_BASE.add(maximumTapRateIncreasePct))) { return true; } return false; } function _tapFloorUpdateIsValid(address _token, uint256 _floor) internal view returns (bool) { uint256 floor = floors[_token]; if (_floor >= floor) { return true; } if (getTimestamp() < lastTapUpdates[_token] + 30 days) { return false; } if (maximumTapFloorDecreasePct >= PCT_BASE) { return true; } if (_floor.mul(PCT_BASE) >= floor.mul(PCT_BASE.sub(maximumTapFloorDecreasePct))) { return true; } return false; } /* state modifying functions */ function _updateTappedAmount(address _token) internal returns (uint256) { uint256 tappedAmount = _tappedAmount(_token); lastTappedAmountUpdates[_token] = _currentBatchId(); tappedAmounts[_token] = tappedAmount; emit UpdateTappedAmount(_token, tappedAmount); return tappedAmount; } function _updateBeneficiary(address _beneficiary) internal { beneficiary = _beneficiary; emit UpdateBeneficiary(_beneficiary); } function _updateMaximumTapRateIncreasePct(uint256 _maximumTapRateIncreasePct) internal { maximumTapRateIncreasePct = _maximumTapRateIncreasePct; emit UpdateMaximumTapRateIncreasePct(_maximumTapRateIncreasePct); } function _updateMaximumTapFloorDecreasePct(uint256 _maximumTapFloorDecreasePct) internal { maximumTapFloorDecreasePct = _maximumTapFloorDecreasePct; emit UpdateMaximumTapFloorDecreasePct(_maximumTapFloorDecreasePct); } function _addTappedToken(address _token, uint256 _rate, uint256 _floor) internal { /** * NOTE * 1. if _token is tapped in the middle of a batch it will * reach the next batch faster than what it normally takes * to go through a batch [e.g. one block later] * 2. this will allow for a higher withdrawal than expected * a few blocks after _token is tapped * 3. this is not a problem because this extra amount is * static [at most rates[_token] * batchBlocks] and does * not increase in time */ rates[_token] = _rate; floors[_token] = _floor; lastTappedAmountUpdates[_token] = _currentBatchId(); lastTapUpdates[_token] = getTimestamp(); emit AddTappedToken(_token, _rate, _floor); } function _removeTappedToken(address _token) internal { delete tappedAmounts[_token]; delete rates[_token]; delete floors[_token]; delete lastTappedAmountUpdates[_token]; delete lastTapUpdates[_token]; emit RemoveTappedToken(_token); } function _updateTappedToken(address _token, uint256 _rate, uint256 _floor) internal { /** * NOTE * withdraw before updating to keep the reserve * actual balance [balance - virtual withdrawal] * continuous in time [though a floor update can * still break this continuity] */ uint256 amount = _updateTappedAmount(_token); if (amount > 0) { _withdraw(_token, amount); } rates[_token] = _rate; floors[_token] = _floor; lastTapUpdates[_token] = getTimestamp(); emit UpdateTappedToken(_token, _rate, _floor); } function _resetTappedToken(address _token) internal { tappedAmounts[_token] = 0; lastTappedAmountUpdates[_token] = _currentBatchId(); lastTapUpdates[_token] = getTimestamp(); emit ResetTappedToken(_token); } function _withdraw(address _token, uint256 _amount) internal { tappedAmounts[_token] = tappedAmounts[_token].sub(_amount); reserve.transfer(_token, beneficiary, _amount); // vault contract's transfer method already reverts on error emit Withdraw(_token, _amount); } } // File: contracts/AavegotchiTBCTemplate.sol pragma solidity 0.4.24; contract AavegotchiTBCTemplate is EtherTokenConstant, BaseTemplate { string private constant ERROR_BAD_SETTINGS = "FM_BAD_SETTINGS"; string private constant ERROR_MISSING_CACHE = "FM_MISSING_CACHE"; bool private constant BOARD_TRANSFERABLE = false; uint8 private constant BOARD_TOKEN_DECIMALS = uint8(0); uint256 private constant BOARD_MAX_PER_ACCOUNT = uint256(1); bool private constant SHARE_TRANSFERABLE = true; uint8 private constant SHARE_TOKEN_DECIMALS = uint8(18); uint256 private constant SHARE_MAX_PER_ACCOUNT = uint256(0); uint64 private constant DEFAULT_FINANCE_PERIOD = uint64(30 days); uint256 private constant BUY_FEE_PCT = 0; uint256 private constant SELL_FEE_PCT = 0; uint32 private constant DAI_RESERVE_RATIO = 333333; // 33% uint32 private constant ANT_RESERVE_RATIO = 10000; // 1% bytes32 private constant BANCOR_FORMULA_ID = 0xd71dde5e4bea1928026c1779bde7ed27bd7ef3d0ce9802e4117631eb6fa4ed7d; bytes32 private constant PRESALE_ID = 0x5de9bbdeaf6584c220c7b7f1922383bcd8bbcd4b48832080afd9d5ebf9a04df5; bytes32 private constant MARKET_MAKER_ID = 0xc2bb88ab974c474221f15f691ed9da38be2f5d37364180cec05403c656981bf0; bytes32 private constant ARAGON_FUNDRAISING_ID = 0x668ac370eed7e5861234d1c0a1e512686f53594fcb887e5bcecc35675a4becac; bytes32 private constant TAP_ID = 0x82967efab7144b764bc9bca2f31a721269b6618c0ff4e50545737700a5e9c9dc; struct Cache { address dao; address boardTokenManager; address boardVoting; address vault; address finance; address shareVoting; address shareTokenManager; address reserve; address presale; address marketMaker; address tap; address controller; } address[] public collaterals; mapping (address => Cache) private cache; constructor( DAOFactory _daoFactory, ENS _ens, MiniMeTokenFactory _miniMeFactory, IFIFSResolvingRegistrar _aragonID, address _dai, address _ant ) BaseTemplate(_daoFactory, _ens, _miniMeFactory, _aragonID) public { _ensureAragonIdIsValid(_aragonID); _ensureMiniMeFactoryIsValid(_miniMeFactory); require(isContract(_dai), ERROR_BAD_SETTINGS); require(isContract(_ant), ERROR_BAD_SETTINGS); require(_dai != _ant, ERROR_BAD_SETTINGS); collaterals.push(_dai); collaterals.push(_ant); } /***** external functions *****/ function prepareInstance( string _boardTokenName, string _boardTokenSymbol, address[] _boardMembers, uint64[3] _boardVotingSettings, uint64 _financePeriod ) external { require(_boardMembers.length > 0, ERROR_BAD_SETTINGS); require(_boardVotingSettings.length == 3, ERROR_BAD_SETTINGS); // deploy DAO (Kernel dao, ACL acl) = _createDAO(); // deploy board token MiniMeToken boardToken = _createToken(_boardTokenName, _boardTokenSymbol, BOARD_TOKEN_DECIMALS); // install board apps TokenManager tm = _installBoardApps(dao, boardToken, _boardVotingSettings, _financePeriod); // mint board tokens _mintTokens(acl, tm, _boardMembers, 1); // cache DAO _cacheDao(dao); } function installShareApps( string _shareTokenName, string _shareTokenSymbol, uint64[3] _shareVotingSettings ) external { require(_shareVotingSettings.length == 3, ERROR_BAD_SETTINGS); _ensureBoardAppsCache(); Kernel dao = _daoCache(); // deploy share token MiniMeToken shareToken = _createToken(_shareTokenName, _shareTokenSymbol, SHARE_TOKEN_DECIMALS); // install share apps _installShareApps(dao, shareToken, _shareVotingSettings); // setup board apps permissions [now that share apps have been installed] _setupBoardPermissions(dao); } function installFundraisingApps( uint256 _goal, uint64 _period, uint256 _exchangeRate, uint64 _vestingCliffPeriod, uint64 _vestingCompletePeriod, uint256 _supplyOfferedPct, uint256 _fundingForBeneficiaryPct, uint64 _openDate, uint256 _batchBlocks, uint256 _maxTapRateIncreasePct, uint256 _maxTapFloorDecreasePct ) external { _ensureShareAppsCache(); Kernel dao = _daoCache(); // install fundraising apps _installFundraisingApps( dao, _goal, _period, _exchangeRate, _vestingCliffPeriod, _vestingCompletePeriod, _supplyOfferedPct, _fundingForBeneficiaryPct, _openDate, _batchBlocks, _maxTapRateIncreasePct, _maxTapFloorDecreasePct ); // setup share apps permissions [now that fundraising apps have been installed] _setupSharePermissions(dao); // setup fundraising apps permissions _setupFundraisingPermissions(dao); } function finalizeInstance( string _id, uint256[2] _virtualSupplies, uint256[2] _virtualBalances, uint256[2] _slippages, uint256 _rateDAI, uint256 _floorDAI ) external { require(bytes(_id).length > 0, ERROR_BAD_SETTINGS); require(_virtualSupplies.length == 2, ERROR_BAD_SETTINGS); require(_virtualBalances.length == 2, ERROR_BAD_SETTINGS); require(_slippages.length == 2, ERROR_BAD_SETTINGS); _ensureFundraisingAppsCache(); Kernel dao = _daoCache(); ACL acl = ACL(dao.acl()); (, Voting shareVoting) = _shareAppsCache(); // setup collaterals _setupCollaterals(dao, _virtualSupplies, _virtualBalances, _slippages, _rateDAI, _floorDAI); // setup EVM script registry permissions _createEvmScriptsRegistryPermissions(acl, shareVoting, shareVoting); // clear DAO permissions _transferRootPermissionsFromTemplateAndFinalizeDAO(dao, shareVoting, shareVoting); // register id _registerID(_id, address(dao)); // clear cache _clearCache(); } /***** internal apps installation functions *****/ function _installBoardApps(Kernel _dao, MiniMeToken _token, uint64[3] _votingSettings, uint64 _financePeriod) internal returns (TokenManager) { TokenManager tm = _installTokenManagerApp(_dao, _token, BOARD_TRANSFERABLE, BOARD_MAX_PER_ACCOUNT); Voting voting = _installVotingApp(_dao, _token, _votingSettings); Vault vault = _installVaultApp(_dao); Finance finance = _installFinanceApp(_dao, vault, _financePeriod == 0 ? DEFAULT_FINANCE_PERIOD : _financePeriod); _cacheBoardApps(tm, voting, vault, finance); return tm; } function _installShareApps(Kernel _dao, MiniMeToken _shareToken, uint64[3] _shareVotingSettings) internal { TokenManager tm = _installTokenManagerApp(_dao, _shareToken, SHARE_TRANSFERABLE, SHARE_MAX_PER_ACCOUNT); Voting voting = _installVotingApp(_dao, _shareToken, _shareVotingSettings); _cacheShareApps(tm, voting); } function _installFundraisingApps( Kernel _dao, uint256 _goal, uint64 _period, uint256 _exchangeRate, uint64 _vestingCliffPeriod, uint64 _vestingCompletePeriod, uint256 _supplyOfferedPct, uint256 _fundingForBeneficiaryPct, uint64 _openDate, uint256 _batchBlocks, uint256 _maxTapRateIncreasePct, uint256 _maxTapFloorDecreasePct ) internal { _proxifyFundraisingApps(_dao); _initializePresale( _goal, _period, _exchangeRate, _vestingCliffPeriod, _vestingCompletePeriod, _supplyOfferedPct, _fundingForBeneficiaryPct, _openDate ); _initializeMarketMaker(_batchBlocks); _initializeTap(_batchBlocks, _maxTapRateIncreasePct, _maxTapFloorDecreasePct); _initializeController(); } function _proxifyFundraisingApps(Kernel _dao) internal { Agent reserve = _installNonDefaultAgentApp(_dao); Presale presale = Presale(_registerApp(_dao, PRESALE_ID)); BatchedBancorMarketMaker marketMaker = BatchedBancorMarketMaker(_registerApp(_dao, MARKET_MAKER_ID)); Tap tap = Tap(_registerApp(_dao, TAP_ID)); AragonFundraisingController controller = AragonFundraisingController(_registerApp(_dao, ARAGON_FUNDRAISING_ID)); _cacheFundraisingApps(reserve, presale, marketMaker, tap, controller); } /***** internal apps initialization functions *****/ function _initializePresale( uint256 _goal, uint64 _period, uint256 _exchangeRate, uint64 _vestingCliffPeriod, uint64 _vestingCompletePeriod, uint256 _supplyOfferedPct, uint256 _fundingForBeneficiaryPct, uint64 _openDate ) internal { _presaleCache().initialize( _controllerCache(), _shareTMCache(), _reserveCache(), _vaultCache(), collaterals[0], _goal, _period, _exchangeRate, _vestingCliffPeriod, _vestingCompletePeriod, _supplyOfferedPct, _fundingForBeneficiaryPct, _openDate ); } function _initializeMarketMaker(uint256 _batchBlocks) internal { IBancorFormula bancorFormula = IBancorFormula(_latestVersionAppBase(BANCOR_FORMULA_ID)); (,, Vault beneficiary,) = _boardAppsCache(); (TokenManager shareTM,) = _shareAppsCache(); (Agent reserve,, BatchedBancorMarketMaker marketMaker,, AragonFundraisingController controller) = _fundraisingAppsCache(); marketMaker.initialize(controller, shareTM, bancorFormula, reserve, beneficiary, _batchBlocks, BUY_FEE_PCT, SELL_FEE_PCT); } function _initializeTap(uint256 _batchBlocks, uint256 _maxTapRateIncreasePct, uint256 _maxTapFloorDecreasePct) internal { (,, Vault beneficiary,) = _boardAppsCache(); (Agent reserve,,, Tap tap, AragonFundraisingController controller) = _fundraisingAppsCache(); tap.initialize(controller, reserve, beneficiary, _batchBlocks, _maxTapRateIncreasePct, _maxTapFloorDecreasePct); } function _initializeController() internal { (Agent reserve, Presale presale, BatchedBancorMarketMaker marketMaker, Tap tap, AragonFundraisingController controller) = _fundraisingAppsCache(); address[] memory toReset = new address[](1); toReset[0] = collaterals[0]; controller.initialize(presale, marketMaker, reserve, tap, toReset); } /***** internal setup functions *****/ function _setupCollaterals( Kernel _dao, uint256[2] _virtualSupplies, uint256[2] _virtualBalances, uint256[2] _slippages, uint256 _rateDAI, uint256 _floorDAI ) internal { ACL acl = ACL(_dao.acl()); (, Voting shareVoting) = _shareAppsCache(); (,,,, AragonFundraisingController controller) = _fundraisingAppsCache(); // create and grant ADD_COLLATERAL_TOKEN_ROLE to this template _createPermissionForTemplate(acl, address(controller), controller.ADD_COLLATERAL_TOKEN_ROLE()); // add DAI both as a protected collateral and a tapped token controller.addCollateralToken( collaterals[0], _virtualSupplies[0], _virtualBalances[0], DAI_RESERVE_RATIO, _slippages[0], _rateDAI, _floorDAI ); // add ANT as a protected collateral [but not as a tapped token] controller.addCollateralToken( collaterals[1], _virtualSupplies[1], _virtualBalances[1], ANT_RESERVE_RATIO, _slippages[1], 0, 0 ); // transfer ADD_COLLATERAL_TOKEN_ROLE _transferPermissionFromTemplate(acl, controller, shareVoting, controller.ADD_COLLATERAL_TOKEN_ROLE(), shareVoting); } /***** internal permissions functions *****/ function _setupBoardPermissions(Kernel _dao) internal { ACL acl = ACL(_dao.acl()); (TokenManager boardTM, Voting boardVoting, Vault vault, Finance finance) = _boardAppsCache(); (, Voting shareVoting) = _shareAppsCache(); // token manager _createTokenManagerPermissions(acl, boardTM, boardVoting, shareVoting); // voting _createVotingPermissions(acl, boardVoting, boardVoting, boardTM, shareVoting); // vault _createVaultPermissions(acl, vault, finance, shareVoting); // finance _createFinancePermissions(acl, finance, boardVoting, shareVoting); _createFinanceCreatePaymentsPermission(acl, finance, boardVoting, shareVoting); } function _setupSharePermissions(Kernel _dao) internal { ACL acl = ACL(_dao.acl()); (TokenManager boardTM,,,) = _boardAppsCache(); (TokenManager shareTM, Voting shareVoting) = _shareAppsCache(); (, Presale presale, BatchedBancorMarketMaker marketMaker,,) = _fundraisingAppsCache(); // token manager address[] memory grantees = new address[](2); grantees[0] = address(marketMaker); grantees[1] = address(presale); acl.createPermission(marketMaker, shareTM, shareTM.MINT_ROLE(),shareVoting); acl.createPermission(presale, shareTM, shareTM.ISSUE_ROLE(),shareVoting); acl.createPermission(presale, shareTM, shareTM.ASSIGN_ROLE(),shareVoting); acl.createPermission(presale, shareTM, shareTM.REVOKE_VESTINGS_ROLE(), shareVoting); _createPermissions(acl, grantees, shareTM, shareTM.BURN_ROLE(), shareVoting); // voting _createVotingPermissions(acl, shareVoting, shareVoting, boardTM, shareVoting); } function _setupFundraisingPermissions(Kernel _dao) internal { ACL acl = ACL(_dao.acl()); (, Voting boardVoting,,) = _boardAppsCache(); (, Voting shareVoting) = _shareAppsCache(); (Agent reserve, Presale presale, BatchedBancorMarketMaker marketMaker, Tap tap, AragonFundraisingController controller) = _fundraisingAppsCache(); // reserve address[] memory grantees = new address[](2); grantees[0] = address(tap); grantees[1] = address(marketMaker); acl.createPermission(shareVoting, reserve, reserve.SAFE_EXECUTE_ROLE(), shareVoting); acl.createPermission(controller, reserve, reserve.ADD_PROTECTED_TOKEN_ROLE(), shareVoting); _createPermissions(acl, grantees, reserve, reserve.TRANSFER_ROLE(), shareVoting); // presale acl.createPermission(controller, presale, presale.OPEN_ROLE(), shareVoting); acl.createPermission(controller, presale, presale.CONTRIBUTE_ROLE(), shareVoting); // market maker acl.createPermission(controller, marketMaker, marketMaker.OPEN_ROLE(), shareVoting); acl.createPermission(controller, marketMaker, marketMaker.UPDATE_BENEFICIARY_ROLE(), shareVoting); acl.createPermission(controller, marketMaker, marketMaker.UPDATE_FEES_ROLE(), shareVoting); acl.createPermission(controller, marketMaker, marketMaker.ADD_COLLATERAL_TOKEN_ROLE(), shareVoting); acl.createPermission(controller, marketMaker, marketMaker.REMOVE_COLLATERAL_TOKEN_ROLE(), shareVoting); acl.createPermission(controller, marketMaker, marketMaker.UPDATE_COLLATERAL_TOKEN_ROLE(), shareVoting); acl.createPermission(controller, marketMaker, marketMaker.OPEN_BUY_ORDER_ROLE(), shareVoting); acl.createPermission(controller, marketMaker, marketMaker.OPEN_SELL_ORDER_ROLE(), shareVoting); // tap acl.createPermission(controller, tap, tap.UPDATE_BENEFICIARY_ROLE(), shareVoting); acl.createPermission(controller, tap, tap.UPDATE_MAXIMUM_TAP_RATE_INCREASE_PCT_ROLE(), shareVoting); acl.createPermission(controller, tap, tap.UPDATE_MAXIMUM_TAP_FLOOR_DECREASE_PCT_ROLE(), shareVoting); acl.createPermission(controller, tap, tap.ADD_TAPPED_TOKEN_ROLE(), shareVoting); acl.createPermission(controller, tap, tap.UPDATE_TAPPED_TOKEN_ROLE(), shareVoting); acl.createPermission(controller, tap, tap.RESET_TAPPED_TOKEN_ROLE(), shareVoting); acl.createPermission(controller, tap, tap.WITHDRAW_ROLE(), shareVoting); // controller // ADD_COLLATERAL_TOKEN_ROLE is handled later [after collaterals have been added] acl.createPermission(shareVoting, controller, controller.UPDATE_BENEFICIARY_ROLE(), shareVoting); acl.createPermission(shareVoting, controller, controller.UPDATE_FEES_ROLE(), shareVoting); // acl.createPermission(shareVoting, controller, controller.ADD_COLLATERAL_TOKEN_ROLE(), shareVoting); acl.createPermission(shareVoting, controller, controller.REMOVE_COLLATERAL_TOKEN_ROLE(), shareVoting); acl.createPermission(shareVoting, controller, controller.UPDATE_COLLATERAL_TOKEN_ROLE(), shareVoting); acl.createPermission(shareVoting, controller, controller.UPDATE_MAXIMUM_TAP_RATE_INCREASE_PCT_ROLE(), shareVoting); acl.createPermission(shareVoting, controller, controller.UPDATE_MAXIMUM_TAP_FLOOR_DECREASE_PCT_ROLE(), shareVoting); acl.createPermission(shareVoting, controller, controller.ADD_TOKEN_TAP_ROLE(), shareVoting); acl.createPermission(shareVoting, controller, controller.UPDATE_TOKEN_TAP_ROLE(), shareVoting); acl.createPermission(boardVoting, controller, controller.OPEN_PRESALE_ROLE(), shareVoting); acl.createPermission(presale, controller, controller.OPEN_TRADING_ROLE(), shareVoting); acl.createPermission(address(-1), controller, controller.CONTRIBUTE_ROLE(), shareVoting); acl.createPermission(address(-1), controller, controller.OPEN_BUY_ORDER_ROLE(), shareVoting); acl.createPermission(address(-1), controller, controller.OPEN_SELL_ORDER_ROLE(), shareVoting); acl.createPermission(address(-1), controller, controller.WITHDRAW_ROLE(), shareVoting); } /***** internal cache functions *****/ function _cacheDao(Kernel _dao) internal { Cache storage c = cache[msg.sender]; c.dao = address(_dao); } function _cacheBoardApps(TokenManager _boardTM, Voting _boardVoting, Vault _vault, Finance _finance) internal { Cache storage c = cache[msg.sender]; c.boardTokenManager = address(_boardTM); c.boardVoting = address(_boardVoting); c.vault = address(_vault); c.finance = address(_finance); } function _cacheShareApps(TokenManager _shareTM, Voting _shareVoting) internal { Cache storage c = cache[msg.sender]; c.shareTokenManager = address(_shareTM); c.shareVoting = address(_shareVoting); } function _cacheFundraisingApps(Agent _reserve, Presale _presale, BatchedBancorMarketMaker _marketMaker, Tap _tap, AragonFundraisingController _controller) internal { Cache storage c = cache[msg.sender]; c.reserve = address(_reserve); c.presale = address(_presale); c.marketMaker = address(_marketMaker); c.tap = address(_tap); c.controller = address(_controller); } function _daoCache() internal view returns (Kernel dao) { Cache storage c = cache[msg.sender]; dao = Kernel(c.dao); } function _boardAppsCache() internal view returns (TokenManager boardTM, Voting boardVoting, Vault vault, Finance finance) { Cache storage c = cache[msg.sender]; boardTM = TokenManager(c.boardTokenManager); boardVoting = Voting(c.boardVoting); vault = Vault(c.vault); finance = Finance(c.finance); } function _shareAppsCache() internal view returns (TokenManager shareTM, Voting shareVoting) { Cache storage c = cache[msg.sender]; shareTM = TokenManager(c.shareTokenManager); shareVoting = Voting(c.shareVoting); } function _fundraisingAppsCache() internal view returns ( Agent reserve, Presale presale, BatchedBancorMarketMaker marketMaker, Tap tap, AragonFundraisingController controller ) { Cache storage c = cache[msg.sender]; reserve = Agent(c.reserve); presale = Presale(c.presale); marketMaker = BatchedBancorMarketMaker(c.marketMaker); tap = Tap(c.tap); controller = AragonFundraisingController(c.controller); } function _clearCache() internal { Cache storage c = cache[msg.sender]; delete c.dao; delete c.boardTokenManager; delete c.boardVoting; delete c.vault; delete c.finance; delete c.shareVoting; delete c.shareTokenManager; delete c.reserve; delete c.presale; delete c.marketMaker; delete c.tap; delete c.controller; } /** * NOTE * the following functions are only needed for the presale * initialization function [which we can't compile otherwise * because of a `stack too deep` error] */ function _vaultCache() internal view returns (Vault vault) { Cache storage c = cache[msg.sender]; vault = Vault(c.vault); } function _shareTMCache() internal view returns (TokenManager shareTM) { Cache storage c = cache[msg.sender]; shareTM = TokenManager(c.shareTokenManager); } function _reserveCache() internal view returns (Agent reserve) { Cache storage c = cache[msg.sender]; reserve = Agent(c.reserve); } function _presaleCache() internal view returns (Presale presale) { Cache storage c = cache[msg.sender]; presale = Presale(c.presale); } function _controllerCache() internal view returns (AragonFundraisingController controller) { Cache storage c = cache[msg.sender]; controller = AragonFundraisingController(c.controller); } /***** internal check functions *****/ function _ensureBoardAppsCache() internal view { Cache storage c = cache[msg.sender]; require( c.boardTokenManager != address(0) && c.boardVoting != address(0) && c.vault != address(0) && c.finance != address(0), ERROR_MISSING_CACHE ); } function _ensureShareAppsCache() internal view { Cache storage c = cache[msg.sender]; require( c.shareTokenManager != address(0) && c.shareVoting != address(0), ERROR_MISSING_CACHE ); } function _ensureFundraisingAppsCache() internal view { Cache storage c = cache[msg.sender]; require( c.reserve != address(0) && c.presale != address(0) && c.marketMaker != address(0) && c.tap != address(0) && c.controller != address(0), ERROR_MISSING_CACHE ); } /***** internal utils functions *****/ function _registerApp(Kernel _dao, bytes32 _appId) internal returns (address) { address proxy = _dao.newAppInstance(_appId, _latestVersionAppBase(_appId)); emit InstalledApp(proxy, _appId); return proxy; } }
tokens - vestedTokens
return tokens.sub(vestedTokens);
451,257
[ 1, 7860, 300, 331, 3149, 5157, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 327, 2430, 18, 1717, 12, 90, 3149, 5157, 1769, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/80001/0x74051B8501C673f7e38ccc9B0cb9c8361f9f34f6/sources/@cryptoalgebra/core/contracts/libraries/FullMath.sol
@notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0 @param a The multiplicand @param b The multiplier @param denominator The divisor @return result The 256-bit result @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv 512-bit multiply [prod1 prod0] = a * b Compute the product mod 2**256 and mod 2**256 - 1 then use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256 variables such that product = prod1 * 2**256 + prod0 Handle non-overflow cases, 256 by 256 division Make division exact by subtracting the remainder from [prod1 prod0] Compute remainder using mulmod Subtract 256 bit remainder from 512 bit number Divide denominator by power of two Divide [prod1 prod0] by the factors of two Shift in bits from prod1 into prod0. For this we need to flip `twos` such that it is 2**256 / twos. If twos is zero, then it becomes one
function mulDiv(uint256 a, uint256 b, uint256 denominator) internal pure returns (uint256 result) { unchecked { assembly { let mm := mulmod(a, b, not(0)) prod1 := sub(sub(mm, prod0), lt(mm, prod0)) } if (prod1 == 0) { assembly { result := div(prod0, denominator) } return result; } assembly { let remainder := mulmod(a, b, denominator) prod1 := sub(prod1, gt(remainder, prod0)) prod0 := sub(prod0, remainder) } assembly { denominator := div(denominator, twos) } assembly { prod0 := div(prod0, twos) } assembly { twos := add(div(sub(0, twos), twos), 1) } prod0 |= prod1 * twos; return result; } }
8,797,548
[ 1, 10587, 6346, 12, 69, 132, 250, 70, 132, 120, 13002, 26721, 13, 598, 1983, 6039, 18, 22435, 309, 563, 9391, 87, 279, 2254, 5034, 578, 15030, 422, 374, 225, 279, 1021, 3309, 1780, 464, 225, 324, 1021, 15027, 225, 15030, 1021, 15013, 327, 563, 1021, 8303, 17, 3682, 563, 225, 30354, 358, 2663, 2894, 605, 383, 351, 275, 3613, 490, 1285, 8630, 2333, 2207, 22695, 413, 22, 17, 3592, 18, 832, 19, 5340, 19, 16411, 2892, 13908, 17, 3682, 10194, 306, 17672, 21, 10791, 20, 65, 273, 279, 225, 324, 8155, 326, 3017, 681, 576, 5034, 471, 681, 576, 5034, 300, 404, 1508, 999, 326, 1680, 25331, 2663, 25407, 1021, 479, 81, 358, 23243, 326, 13908, 2831, 563, 18, 1021, 563, 353, 4041, 316, 2795, 8303, 3152, 4123, 716, 3017, 273, 10791, 21, 225, 576, 5034, 397, 10791, 20, 5004, 1661, 17, 11512, 6088, 16, 8303, 635, 8303, 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, 14064, 7244, 12, 11890, 5034, 279, 16, 2254, 5034, 324, 16, 2254, 5034, 15030, 13, 2713, 16618, 1135, 261, 11890, 5034, 563, 13, 288, 203, 565, 22893, 288, 203, 1377, 19931, 288, 203, 3639, 2231, 9740, 519, 14064, 1711, 12, 69, 16, 324, 16, 486, 12, 20, 3719, 203, 3639, 10791, 21, 519, 720, 12, 1717, 12, 7020, 16, 10791, 20, 3631, 13489, 12, 7020, 16, 10791, 20, 3719, 203, 1377, 289, 203, 203, 203, 1377, 309, 261, 17672, 21, 422, 374, 13, 288, 203, 3639, 19931, 288, 203, 1850, 563, 519, 3739, 12, 17672, 20, 16, 15030, 13, 203, 3639, 289, 203, 3639, 327, 563, 31, 203, 1377, 289, 203, 203, 1377, 19931, 288, 203, 3639, 2231, 10022, 519, 14064, 1711, 12, 69, 16, 324, 16, 15030, 13, 203, 3639, 10791, 21, 519, 720, 12, 17672, 21, 16, 9879, 12, 2764, 25407, 16, 10791, 20, 3719, 203, 3639, 10791, 20, 519, 720, 12, 17672, 20, 16, 10022, 13, 203, 1377, 289, 203, 203, 1377, 19931, 288, 203, 3639, 15030, 519, 3739, 12, 13002, 26721, 16, 2339, 538, 13, 203, 1377, 289, 203, 203, 1377, 19931, 288, 203, 3639, 10791, 20, 519, 3739, 12, 17672, 20, 16, 2339, 538, 13, 203, 1377, 289, 203, 1377, 19931, 288, 203, 3639, 2339, 538, 519, 527, 12, 2892, 12, 1717, 12, 20, 16, 2339, 538, 3631, 2339, 538, 3631, 404, 13, 203, 1377, 289, 203, 1377, 10791, 20, 5626, 10791, 21, 380, 2339, 538, 31, 203, 203, 1377, 327, 563, 31, 203, 565, 289, 203, 2 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.10; import "./interface/CLV2V3Interface.sol"; import "@openzeppelin/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts/security/Pausable.sol"; import "@openzeppelin/contracts/utils/math/Math.sol"; /** * @title Flux first-party price feed oracle aggregator * @author fluxprotocol.org * @notice Aggregates from multiple first-party price oracles (FluxPriceFeed.sol), compatible with * Chainlink V2 and V3 aggregator interface */ contract FluxPriceAggregator is AccessControl, CLV2V3Interface, Pausable { bytes32 public constant ADMIN_ROLE = keccak256("ADMIN_ROLE"); uint32 public latestAggregatorRoundId; // Transmission records the answer from the transmit transaction at // time timestamp struct Transmission { int192 answer; // 192 bits ought to be enough for anyone uint64 timestamp; } mapping(uint32 => Transmission) /* aggregator round ID */ internal transmissions; uint256 public minDelay = 1 minutes; address[] public oracles; /** * @dev Initialize oracles and fetch initial prices * @param _admin the initial admin that can aggregate data from and set the oracles * @param _oracles the oracles to aggregate data from * @param _decimals answers are stored in fixed-point format, with this many digits of precision * @param __description short human-readable description of observable this contract's answers pertain to */ constructor( address _admin, address[] memory _oracles, uint8 _decimals, string memory __description ) { _setupRole(ADMIN_ROLE, _admin); oracles = _oracles; decimals = _decimals; _description = __description; } /* * Versioning */ function typeAndVersion() external pure virtual returns (string memory) { return "FluxPriceAggregator 1.0.0"; } /* * Publicly-callable mutative functions */ /// @notice Update prices, callable by anyone, slower but less gas function updatePricesUsingQuickSort() public whenNotPaused { // require min delay since lastUpdate require(block.timestamp > transmissions[latestAggregatorRoundId].timestamp + minDelay, "Delay required"); int192[] memory oraclesLatestAnswers = new int192[](oracles.length); // Aggregate prices from oracles for (uint256 i = 0; i < oracles.length; i++) { oraclesLatestAnswers[i] = int192(CLV2V3Interface(oracles[i]).latestAnswer()); } int192 _answer = findMedianUsingQuickSort(oraclesLatestAnswers, 0, (oraclesLatestAnswers.length - 1)); // update round latestAggregatorRoundId++; transmissions[latestAggregatorRoundId] = Transmission(_answer, uint64(block.timestamp)); emit AnswerUpdated(_answer, latestAggregatorRoundId, block.timestamp); } /// @notice Update prices, callable by anyone, faster but more gas function updatePricesUsingMedianOfMedians() public whenNotPaused { // require min delay since lastUpdate require(block.timestamp > transmissions[latestAggregatorRoundId].timestamp + minDelay, "Delay required"); int192[] memory oraclesLatestAnswers = new int192[](oracles.length); for (uint256 i = 0; i < oracles.length; i++) { oraclesLatestAnswers[i] = int192(CLV2V3Interface(oracles[i]).latestAnswer()); } int192 _answer = findMedianUsingMedianOfMedians( oraclesLatestAnswers, 0, oraclesLatestAnswers.length - 1, ((oraclesLatestAnswers.length / 2) + 1) ); // update round latestAggregatorRoundId++; transmissions[latestAggregatorRoundId] = Transmission(_answer, uint64(block.timestamp)); emit AnswerUpdated(_answer, latestAggregatorRoundId, block.timestamp); } /// @notice Returns k'th smallest element in arr[left..right] in worst case linear time. /// ASSUMPTION: ALL ELEMENTS IN ARR[] ARE DISTINCT /// @param k = ((arr.length/2) - 1 ) function findMedianUsingMedianOfMedians( int192[] memory arr, uint256 left, uint256 right, uint256 k ) public view returns (int192) { // If k is smaller than the number of elements in array if (k > 0 && k <= right - left + 1) { uint256 n = right - left + 1; // Number of elements in arr[left..right] // Divide arr[] in groups of size 5, // calculate median of every group // and store it in median[] array. uint256 i; // There will be floor((n+4)/5) groups; int192[] memory median = new int192[](((n + 4) / 5)); for (i = 0; i < n / 5; i++) { median[i] = findMedianUsingQuickSort(arr, (left + i * 5), 5); } // For last group with less than 5 elements if (i * 5 < n) { median[i] = findMedianUsingQuickSort(arr, (left + i * 5), ((left + i * 5) + (n % 5) - 1)); i++; } // Find median of all medians using recursive call. // If median[] has only one element, then no need // of recursive call int192 medOfMed = (i == 1) ? median[i - 1] : findMedianUsingMedianOfMedians(median, 0, i - 1, (i / 2)); // Partition the array around a random element and // get position of pivot element in sorted array uint256 pos = partition(arr, left, right, medOfMed); // If position is same as k if (pos - left == k - 1) return arr[pos]; if (pos - left > k - 1) // If position is more, recur for left return findMedianUsingMedianOfMedians(arr, left, pos - 1, k); // Else recurse for right subarray return findMedianUsingMedianOfMedians(arr, pos + 1, right, k - pos + left - 1); } else { revert("Wrong k value"); } } /// @notice Swaps arrays vars function swap( int192[] memory array, uint256 i, uint256 j ) internal pure { (array[i], array[j]) = (array[j], array[i]); } /// @notice It searches for x in arr[left..right], and partitions the array around x. function partition( int192[] memory arr, uint256 left, uint256 right, int192 x ) internal pure returns (uint256) { // Search for x in arr[left..right] and move it to end uint256 i; for (i = left; i < right; i++) { if (arr[i] == x) { break; } } swap(arr, i, right); // Standard partition algorithm i = left; for (uint256 j = left; j <= right - 1; j++) { if (arr[j] <= x) { swap(arr, i, j); i++; } } swap(arr, i, right); return i; } /// @notice Quick sort then returns middles element function findMedianUsingQuickSort( int192[] memory arr, uint256 i, uint256 n ) internal view returns (int192) { if (i <= n) { uint256 length = (n - i) + 1; int192 median; quickSort(arr, i, n); if (length % 2 == 0) { median = ((arr[(length / 2) - 1] + arr[length / 2]) / 2); } else { median = arr[length / 2]; } return median; } else { revert("Error in findMedianUsingQuickSort"); } } function quickSort( int192[] memory arr, uint256 left, uint256 right ) internal view { uint256 i = left; uint256 j = right; if (i == j) return; int192 pivot = arr[uint256(left + (right - left) / 2)]; while (i <= j) { while (arr[uint256(i)] < pivot) i++; while (pivot < arr[uint256(j)]) j--; if (i <= j) { (arr[uint256(i)], arr[uint256(j)]) = (arr[uint256(j)], arr[uint256(i)]); i++; j--; } } if (left < j) quickSort(arr, left, j); if (i < right) quickSort(arr, i, right); } /* * Admin-only functions */ /// @notice Changes min delay, only callable by admin function setDelay(uint256 _minDelay) public { require(hasRole(ADMIN_ROLE, msg.sender), "Caller is not a admin"); minDelay = _minDelay; } /// @notice Changes oracles, only callable by admin function setOracles(address[] memory _oracles) public { require(hasRole(ADMIN_ROLE, msg.sender), "Caller is not a admin"); oracles = _oracles; } /// @notice Pauses or unpauses updating the price, only callable by admin function pause(bool __pause) public { require(hasRole(ADMIN_ROLE, msg.sender), "Caller is not a admin"); if (__pause) { _pause(); } else { _unpause(); } } /// @notice Overrides the price, only callable by admin function setManualAnswer(int192 _answer) public { require(hasRole(ADMIN_ROLE, msg.sender), "Caller is not a admin"); latestAggregatorRoundId++; transmissions[latestAggregatorRoundId] = Transmission(_answer, uint64(block.timestamp)); emit AnswerUpdated(_answer, latestAggregatorRoundId, block.timestamp); } /* * v2 Aggregator interface */ /** * @notice answer from the most recent report */ function latestAnswer() public view virtual override returns (int256) { return transmissions[latestAggregatorRoundId].answer; } /** * @notice timestamp of block in which last report was transmitted */ function latestTimestamp() public view virtual override returns (uint256) { return transmissions[latestAggregatorRoundId].timestamp; } /** * @notice Aggregator round in which last report was transmitted */ function latestRound() public view virtual override returns (uint256) { return latestAggregatorRoundId; } /** * @notice answer of report from given aggregator round * @param _roundId the aggregator round of the target report */ function getAnswer(uint256 _roundId) public view virtual override returns (int256) { if (_roundId > 0xFFFFFFFF) { return 0; } return transmissions[uint32(_roundId)].answer; } /** * @notice timestamp of block in which report from given aggregator round was transmitted * @param _roundId aggregator round of target report */ function getTimestamp(uint256 _roundId) public view virtual override returns (uint256) { if (_roundId > 0xFFFFFFFF) { return 0; } return transmissions[uint32(_roundId)].timestamp; } /* * v3 Aggregator interface */ string private constant V3_NO_DATA_ERROR = "No data present"; /** * @return answers are stored in fixed-point format, with this many digits of precision */ uint8 public immutable override decimals; /** * @notice aggregator contract version */ uint256 public constant override version = 1; string internal _description; /** * @notice human-readable description of observable this contract is reporting on */ function description() public view virtual override returns (string memory) { return _description; } /** * @notice details for the given aggregator round * @param _roundId target aggregator round. Must fit in uint32 * @return roundId _roundId * @return answer answer of report from given _roundId * @return startedAt timestamp of block in which report from given _roundId was transmitted * @return updatedAt timestamp of block in which report from given _roundId was transmitted * @return answeredInRound _roundId */ function getRoundData(uint80 _roundId) public view virtual override returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ) { require(_roundId <= 0xFFFFFFFF, V3_NO_DATA_ERROR); Transmission memory transmission = transmissions[uint32(_roundId)]; return (_roundId, transmission.answer, transmission.timestamp, transmission.timestamp, _roundId); } /** * @notice aggregator details for the most recently transmitted report * @return roundId aggregator round of latest report * @return answer answer of latest report * @return startedAt timestamp of block containing latest report * @return updatedAt timestamp of block containing latest report * @return answeredInRound aggregator round of latest report */ function latestRoundData() public view virtual override returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ) { roundId = latestAggregatorRoundId; // Skipped for compatability with existing FluxAggregator in which latestRoundData never reverts. // require(roundId != 0, V3_NO_DATA_ERROR); Transmission memory transmission = transmissions[uint32(roundId)]; return (roundId, transmission.answer, transmission.timestamp, transmission.timestamp, roundId); } }
@notice Update prices, callable by anyone, slower but less gas require min delay since lastUpdate Aggregate prices from oracles
function updatePricesUsingQuickSort() public whenNotPaused { require(block.timestamp > transmissions[latestAggregatorRoundId].timestamp + minDelay, "Delay required"); int192[] memory oraclesLatestAnswers = new int192[](oracles.length); for (uint256 i = 0; i < oracles.length; i++) { oraclesLatestAnswers[i] = int192(CLV2V3Interface(oracles[i]).latestAnswer()); } int192 _answer = findMedianUsingQuickSort(oraclesLatestAnswers, 0, (oraclesLatestAnswers.length - 1)); transmissions[latestAggregatorRoundId] = Transmission(_answer, uint64(block.timestamp)); emit AnswerUpdated(_answer, latestAggregatorRoundId, block.timestamp); }
2,515,267
[ 1, 1891, 19827, 16, 4140, 635, 1281, 476, 16, 27926, 1496, 5242, 16189, 2583, 1131, 4624, 3241, 1142, 1891, 18059, 19827, 628, 578, 69, 9558, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1089, 31862, 7736, 13663, 4416, 1435, 1071, 1347, 1248, 28590, 288, 203, 3639, 2583, 12, 2629, 18, 5508, 405, 906, 7300, 63, 13550, 17711, 11066, 548, 8009, 5508, 397, 1131, 6763, 16, 315, 6763, 1931, 8863, 203, 203, 3639, 509, 15561, 8526, 3778, 578, 69, 9558, 18650, 19543, 273, 394, 509, 15561, 8526, 12, 10610, 9558, 18, 2469, 1769, 203, 203, 3639, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 578, 69, 9558, 18, 2469, 31, 277, 27245, 288, 203, 5411, 578, 69, 9558, 18650, 19543, 63, 77, 65, 273, 509, 15561, 12, 5017, 58, 22, 58, 23, 1358, 12, 10610, 9558, 63, 77, 65, 2934, 13550, 13203, 10663, 203, 3639, 289, 203, 3639, 509, 15561, 389, 13490, 273, 1104, 13265, 2779, 7736, 13663, 4416, 12, 10610, 9558, 18650, 19543, 16, 374, 16, 261, 10610, 9558, 18650, 19543, 18, 2469, 300, 404, 10019, 203, 203, 3639, 906, 7300, 63, 13550, 17711, 11066, 548, 65, 273, 2604, 3951, 24899, 13490, 16, 2254, 1105, 12, 2629, 18, 5508, 10019, 203, 203, 3639, 3626, 21019, 7381, 24899, 13490, 16, 4891, 17711, 11066, 548, 16, 1203, 18, 5508, 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 ]
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 DOVcoin 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 = "DOV"; symbol = "DOV"; decimals = 18; _totalSupply = 100000000000000000000000000000; 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 = "DOV"; symbol = "DOV"; decimals = 18; _totalSupply = 100000000000000000000000000000; balances[msg.sender] = _totalSupply; emit Transfer(address(0), msg.sender, _totalSupply); }
11,947,096
[ 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, 3191, 58, 14432, 203, 3639, 3273, 273, 315, 3191, 58, 14432, 203, 3639, 15105, 273, 6549, 31, 203, 3639, 389, 4963, 3088, 1283, 273, 2130, 12648, 12648, 12648, 3784, 31, 203, 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, 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 ]
pragma solidity 0.5.4; import "@daostack/arc/contracts/controller/Avatar.sol"; import "@daostack/arc/contracts/controller/ControllerInterface.sol"; import "../../token/GoodDollar.sol"; import "./SchemeGuard.sol"; /* @title Scheme for proposing and adding a new minter. */ contract AddMinter is SchemeGuard { address public minter; constructor(Avatar _avatar, address _minter) public SchemeGuard(_avatar) { require(_minter != address(0), "Minter must not be null"); minter = _minter; } /* @dev Makes controller add the given minter to minters. * can only be done if scheme has been registered. */ function addMinter() public onlyRegistered { controller.genericCall( address(avatar.nativeToken()), abi.encodeWithSignature("addMinter(address)", minter), avatar, 0); selfdestruct(address(avatar)); } }
@title Scheme for proposing and adding a new minter./
contract AddMinter is SchemeGuard { address public minter; constructor(Avatar _avatar, address _minter) public SchemeGuard(_avatar) { require(_minter != address(0), "Minter must not be null"); minter = _minter; } function addMinter() public onlyRegistered { controller.genericCall( address(avatar.nativeToken()), abi.encodeWithSignature("addMinter(address)", minter), avatar, 0); selfdestruct(address(avatar)); } }
15,797,318
[ 1, 9321, 364, 450, 24014, 471, 6534, 279, 394, 1131, 387, 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 ]
[ 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, 16351, 1436, 49, 2761, 353, 10714, 16709, 288, 203, 203, 565, 1758, 1071, 1131, 387, 31, 203, 203, 565, 3885, 12, 23999, 389, 19660, 16, 1758, 389, 1154, 387, 13, 7010, 3639, 1071, 203, 3639, 10714, 16709, 24899, 19660, 13, 7010, 565, 288, 203, 3639, 2583, 24899, 1154, 387, 480, 1758, 12, 20, 3631, 315, 49, 2761, 1297, 486, 506, 446, 8863, 203, 3639, 1131, 387, 273, 389, 1154, 387, 31, 203, 565, 289, 203, 203, 565, 445, 527, 49, 2761, 1435, 1071, 1338, 10868, 288, 203, 3639, 2596, 18, 13540, 1477, 12, 203, 5411, 1758, 12, 19660, 18, 13635, 1345, 1435, 3631, 203, 5411, 24126, 18, 3015, 1190, 5374, 2932, 1289, 49, 2761, 12, 2867, 2225, 16, 1131, 387, 3631, 203, 5411, 16910, 16, 203, 5411, 374, 1769, 203, 203, 3639, 365, 5489, 8813, 12, 2867, 12, 19660, 10019, 203, 565, 289, 203, 97, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/8453/0xF407009ea759728E4349cca85292739347Df9196/sources/contracts/libraries/SmartRouterHelper.sol
@notice Returns the address of a valid ThroneExchange V3 Pool @param deployer The contract address of the ThroneExchange V3 deployer @param tokenA The contract address of either token0 or token1 @param tokenB The contract address of the other token @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip @return pool The V3 pool contract address
function verifyCallback( address deployer, address tokenA, address tokenB, uint24 fee ) public view returns (IThroneV3Pool pool) { return verifyCallback(deployer, getPoolKey(tokenA, tokenB, fee)); }
16,719,377
[ 1, 1356, 326, 1758, 434, 279, 923, 935, 86, 476, 11688, 776, 23, 8828, 225, 7286, 264, 1021, 6835, 1758, 434, 326, 935, 86, 476, 11688, 776, 23, 7286, 264, 225, 1147, 37, 1021, 6835, 1758, 434, 3344, 1147, 20, 578, 1147, 21, 225, 1147, 38, 1021, 6835, 1758, 434, 326, 1308, 1147, 225, 14036, 1021, 14036, 12230, 12318, 3614, 7720, 316, 326, 2845, 16, 10716, 7458, 316, 366, 1074, 1118, 451, 87, 434, 279, 324, 625, 327, 2845, 1021, 776, 23, 2845, 6835, 1758, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 3929, 2428, 12, 203, 3639, 1758, 7286, 264, 16, 203, 3639, 1758, 1147, 37, 16, 203, 3639, 1758, 1147, 38, 16, 203, 3639, 2254, 3247, 14036, 203, 565, 262, 1071, 1476, 1135, 261, 1285, 7256, 476, 58, 23, 2864, 2845, 13, 288, 203, 3639, 327, 3929, 2428, 12, 12411, 264, 16, 28575, 653, 12, 2316, 37, 16, 1147, 38, 16, 14036, 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 ]
/** *Submitted for verification at Etherscan.io on 2021-10-26 */ // SPDX-License-Identifier: AGPL-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: AggregatorInterface interface AggregatorInterface { function latestAnswer() external view returns (int256); function latestTimestamp() external view returns (uint256); function latestRound() external view returns (uint256); function getAnswer(uint256 roundId) external view returns (int256); function getTimestamp(uint256 roundId) external view returns (uint256); event AnswerUpdated( int256 indexed current, uint256 indexed roundId, uint256 updatedAt ); event NewRound( uint256 indexed roundId, address indexed startedBy, uint256 startedAt ); } // Part: DssAutoLine interface DssAutoLine { function exec(bytes32 _ilk) external returns (uint256); } // Part: GemLike interface GemLike { function approve(address, uint256) external; function transfer(address, uint256) external; function transferFrom( address, address, uint256 ) external; function deposit() external payable; function withdraw(uint256) external; } // Part: IBaseFee interface IBaseFee { function basefee_global() external view returns (uint256); } // Part: IOSMedianizer interface IOSMedianizer { function foresight() external view returns (uint256 price, bool osm); function read() external view returns (uint256 price, bool osm); } // Part: ISwap interface ISwap { function swapExactTokensForTokens( uint256, uint256, address[] calldata, address, uint256 ) external returns (uint256[] memory amounts); function swapTokensForExactTokens( uint256, uint256, address[] calldata, address, uint256 ) external returns (uint256[] memory amounts); function getAmountsOut(uint256 amountIn, address[] memory path) external view returns (uint256[] memory amounts); } // Part: JugLike interface JugLike { function drip(bytes32) external returns (uint256); } // Part: ManagerLike interface ManagerLike { function cdpCan( address, uint256, address ) external view returns (uint256); function ilks(uint256) external view returns (bytes32); function owns(uint256) external view returns (address); function urns(uint256) external view returns (address); function vat() external view returns (address); function open(bytes32, address) external returns (uint256); function give(uint256, address) external; function cdpAllow( uint256, address, uint256 ) external; function urnAllow(address, uint256) external; function frob( uint256, int256, int256 ) external; function flux( uint256, address, uint256 ) external; function move( uint256, address, uint256 ) external; function exit( address, uint256, address, uint256 ) external; function quit(uint256, address) external; function enter(address, uint256) external; function shift(uint256, uint256) external; } // 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: SpotLike interface SpotLike { function live() external view returns (uint256); function par() external view returns (uint256); function vat() external view returns (address); function ilks(bytes32) external view returns (address, uint256); } // Part: VatLike interface VatLike { function can(address, address) external view returns (uint256); function ilks(bytes32) external view returns ( uint256, uint256, uint256, uint256, uint256 ); function dai(address) external view returns (uint256); function urns(bytes32, address) external view returns (uint256, uint256); function frob( bytes32, address, address, address, int256, int256 ) external; function hope(address) external; function move( address, address, uint256 ) external; } // Part: yearn/[email protected]/HealthCheck interface HealthCheck { function check( uint256 profit, uint256 loss, uint256 debtPayment, uint256 debtOutstanding, uint256 totalDebt ) external view returns (bool); } // Part: DaiJoinLike interface DaiJoinLike { function vat() external returns (VatLike); function dai() external returns (GemLike); function join(address, uint256) external payable; function exit(address, uint256) external; } // Part: GemJoinLike interface GemJoinLike { function dec() external returns (uint256); function gem() external returns (GemLike); function join(address, uint256) external payable; function exit(address, uint256) external; } // Part: IVault interface IVault is IERC20 { function token() external view returns (address); function decimals() external view returns (uint256); function deposit() external; function pricePerShare() external view returns (uint256); function withdraw() external returns (uint256); function withdraw(uint256 amount) external returns (uint256); function withdraw( uint256 amount, address account, uint256 maxLoss ) external returns (uint256); function availableDepositLimit() external view returns (uint256); } // 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: yearn/[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: MakerDaiDelegateLib library MakerDaiDelegateLib { using SafeMath for uint256; // Units used in Maker contracts uint256 internal constant WAD = 10**18; uint256 internal constant RAY = 10**27; // Do not attempt to mint DAI if there are less than MIN_MINTABLE available uint256 internal constant MIN_MINTABLE = 500000 * WAD; // Maker vaults manager ManagerLike internal constant manager = ManagerLike(0x5ef30b9986345249bc32d8928B7ee64DE9435E39); // Token Adapter Module for collateral DaiJoinLike internal constant daiJoin = DaiJoinLike(0x9759A6Ac90977b93B58547b4A71c78317f391A28); // Liaison between oracles and core Maker contracts SpotLike internal constant spotter = SpotLike(0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3); // Part of the Maker Rates Module in charge of accumulating stability fees JugLike internal constant jug = JugLike(0x19c0976f590D67707E62397C87829d896Dc0f1F1); // Debt Ceiling Instant Access Module DssAutoLine internal constant autoLine = DssAutoLine(0xC7Bdd1F2B16447dcf3dE045C4a039A60EC2f0ba3); // ----------------- PUBLIC FUNCTIONS ----------------- // Creates an UrnHandler (cdp) for a specific ilk and allows to manage it via the internal // registry of the manager. function openCdp(bytes32 ilk) public returns (uint256) { return manager.open(ilk, address(this)); } // Moves cdpId collateral balance and debt to newCdpId. function shiftCdp(uint256 cdpId, uint256 newCdpId) public { manager.shift(cdpId, newCdpId); } // Transfers the ownership of cdp to recipient address in the manager registry. function transferCdp(uint256 cdpId, address recipient) public { manager.give(cdpId, recipient); } // Allow/revoke manager access to a cdp function allowManagingCdp( uint256 cdpId, address user, bool isAccessGranted ) public { manager.cdpAllow(cdpId, user, isAccessGranted ? 1 : 0); } // Deposits collateral (gem) and mints DAI // Adapted from https://github.com/makerdao/dss-proxy-actions/blob/master/src/DssProxyActions.sol#L639 function lockGemAndDraw( address gemJoin, uint256 cdpId, uint256 collateralAmount, uint256 daiToMint, uint256 totalDebt ) public { address urn = manager.urns(cdpId); VatLike vat = VatLike(manager.vat()); bytes32 ilk = manager.ilks(cdpId); if (daiToMint > 0) { daiToMint = _forceMintWithinLimits(vat, ilk, daiToMint, totalDebt); } // Takes token amount from the strategy and joins into the vat if (collateralAmount > 0) { GemJoinLike(gemJoin).join(urn, collateralAmount); } // Locks token amount into the CDP and generates debt manager.frob( cdpId, int256(convertTo18(gemJoin, collateralAmount)), _getDrawDart(vat, urn, ilk, daiToMint) ); // Moves the DAI amount to the strategy. Need to convert dai from [wad] to [rad] manager.move(cdpId, address(this), daiToMint.mul(1e27)); // Allow access to DAI balance in the vat vat.hope(address(daiJoin)); // Exits DAI to the user's wallet as a token daiJoin.exit(address(this), daiToMint); } // Returns DAI to decrease debt and attempts to unlock any amount of collateral // Adapted from https://github.com/makerdao/dss-proxy-actions/blob/master/src/DssProxyActions.sol#L758 function wipeAndFreeGem( address gemJoin, uint256 cdpId, uint256 collateralAmount, uint256 daiToRepay ) public { address urn = manager.urns(cdpId); // Joins DAI amount into the vat if (daiToRepay > 0) { daiJoin.join(urn, daiToRepay); } uint256 wadC = convertTo18(gemJoin, collateralAmount); // Paybacks debt to the CDP and unlocks token amount from it manager.frob( cdpId, -int256(wadC), _getWipeDart( VatLike(manager.vat()), VatLike(manager.vat()).dai(urn), urn, manager.ilks(cdpId) ) ); // Moves the amount from the CDP urn to proxy's address manager.flux(cdpId, address(this), collateralAmount); // Exits token amount to the strategy as a token GemJoinLike(gemJoin).exit(address(this), collateralAmount); } function debtFloor(bytes32 ilk) public view returns (uint256) { // uint256 Art; // Total Normalised Debt [wad] // uint256 rate; // Accumulated Rates [ray] // uint256 spot; // Price with Safety Margin [ray] // uint256 line; // Debt Ceiling [rad] // uint256 dust; // Urn Debt Floor [rad] (, , , , uint256 dust) = VatLike(manager.vat()).ilks(ilk); return dust.div(RAY); } function debtForCdp(uint256 cdpId, bytes32 ilk) public view returns (uint256) { address urn = manager.urns(cdpId); VatLike vat = VatLike(manager.vat()); // Normalized outstanding stablecoin debt [wad] (, uint256 art) = vat.urns(ilk, urn); // Gets actual rate from the vat [ray] (, uint256 rate, , , ) = vat.ilks(ilk); // Return the present value of the debt with accrued fees return art.mul(rate).div(RAY); } function balanceOfCdp(uint256 cdpId, bytes32 ilk) public view returns (uint256) { address urn = manager.urns(cdpId); VatLike vat = VatLike(manager.vat()); (uint256 ink, ) = vat.urns(ilk, urn); return ink; } // Returns value of DAI in the reference asset (e.g. $1 per DAI) function getDaiPar() public view returns (uint256) { // Value is returned in ray (10**27) return spotter.par(); } // Liquidation ratio for the given ilk returned in [ray] // https://github.com/makerdao/dss/blob/master/src/spot.sol#L45 function getLiquidationRatio(bytes32 ilk) public view returns (uint256) { (, uint256 liquidationRatio) = spotter.ilks(ilk); return liquidationRatio; } function getSpotPrice(bytes32 ilk) public view returns (uint256) { VatLike vat = VatLike(manager.vat()); // spot: collateral price with safety margin returned in [ray] (, , uint256 spot, , ) = vat.ilks(ilk); uint256 liquidationRatio = getLiquidationRatio(ilk); // convert ray*ray to wad return spot.mul(liquidationRatio).div(RAY * 1e9); } function getPessimisticRatioOfCdpWithExternalPrice( uint256 cdpId, bytes32 ilk, uint256 externalPrice, uint256 collateralizationRatioPrecision ) public view returns (uint256) { // Use pessimistic price to determine the worst ratio possible uint256 price = Math.min(getSpotPrice(ilk), externalPrice); require(price > 0); // dev: invalid price uint256 totalCollateralValue = balanceOfCdp(cdpId, ilk).mul(price).div(WAD); uint256 totalDebt = debtForCdp(cdpId, ilk); // If for some reason we do not have debt (e.g: deposits under dust) // make sure the operation does not revert if (totalDebt == 0) { totalDebt = 1; } return totalCollateralValue.mul(collateralizationRatioPrecision).div( totalDebt ); } // Make sure we update some key content in Maker contracts // These can be updated by anyone without authenticating function keepBasicMakerHygiene(bytes32 ilk) public { // Update accumulated stability fees jug.drip(ilk); // Update the debt ceiling using DSS Auto Line autoLine.exec(ilk); } function daiJoinAddress() public view returns (address) { return address(daiJoin); } // Checks if there is at least MIN_MINTABLE dai available to be minted function isDaiAvailableToMint(bytes32 ilk) public view returns (bool) { VatLike vat = VatLike(manager.vat()); (uint256 Art, uint256 rate, , uint256 line, ) = vat.ilks(ilk); // Total debt in [rad] (wad * ray) uint256 vatDebt = Art.mul(rate); if (vatDebt >= line || line.sub(vatDebt).div(RAY) < MIN_MINTABLE) { return false; } return true; } // ----------------- INTERNAL FUNCTIONS ----------------- // This function repeats some code from daiAvailableToMint because it needs // to handle special cases such as not leaving debt under dust function _forceMintWithinLimits( VatLike vat, bytes32 ilk, uint256 desiredAmount, uint256 debtBalance ) internal view returns (uint256) { // uint256 Art; // Total Normalised Debt [wad] // uint256 rate; // Accumulated Rates [ray] // uint256 spot; // Price with Safety Margin [ray] // uint256 line; // Debt Ceiling [rad] // uint256 dust; // Urn Debt Floor [rad] (uint256 Art, uint256 rate, , uint256 line, uint256 dust) = vat.ilks(ilk); // Total debt in [rad] (wad * ray) uint256 vatDebt = Art.mul(rate); // Make sure we are not over debt ceiling (line) or under debt floor (dust) if ( vatDebt >= line || (desiredAmount.add(debtBalance) <= dust.div(RAY)) ) { return 0; } uint256 maxMintableDAI = line.sub(vatDebt).div(RAY); // Avoid edge cases with low amounts of available debt if (maxMintableDAI < MIN_MINTABLE) { return 0; } // Prevent rounding errors if (maxMintableDAI > WAD) { maxMintableDAI = maxMintableDAI - WAD; } return Math.min(maxMintableDAI, desiredAmount); } // Adapted from https://github.com/makerdao/dss-proxy-actions/blob/master/src/DssProxyActions.sol#L161 function _getDrawDart( VatLike vat, address urn, bytes32 ilk, uint256 wad ) internal returns (int256 dart) { // Updates stability fee rate uint256 rate = jug.drip(ilk); // Gets DAI balance of the urn in the vat uint256 dai = vat.dai(urn); // If there was already enough DAI in the vat balance, just exits it without adding more debt if (dai < wad.mul(RAY)) { // Calculates the needed dart so together with the existing dai in the vat is enough to exit wad amount of DAI tokens dart = int256(wad.mul(RAY).sub(dai).div(rate)); // This is neeeded due to lack of precision. It might need to sum an extra dart wei (for the given DAI wad amount) dart = uint256(dart).mul(rate) < wad.mul(RAY) ? dart + 1 : dart; } } // Adapted from https://github.com/makerdao/dss-proxy-actions/blob/master/src/DssProxyActions.sol#L183 function _getWipeDart( VatLike vat, uint256 dai, address urn, bytes32 ilk ) internal view returns (int256 dart) { // Gets actual rate from the vat (, uint256 rate, , , ) = vat.ilks(ilk); // Gets actual art value of the urn (, uint256 art) = vat.urns(ilk, urn); // Uses the whole dai balance in the vat to reduce the debt dart = int256(dai / rate); // Checks the calculated dart is not higher than urn.art (total debt), otherwise uses its value dart = uint256(dart) <= art ? -dart : -int256(art); } function convertTo18(address gemJoin, uint256 amt) internal returns (uint256 wad) { // For those collaterals that have less than 18 decimals precision we need to do the conversion before // passing to frob function // Adapters will automatically handle the difference of precision wad = amt.mul(10**(18 - GemJoinLike(gemJoin).dec())); } } // Part: yearn/[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.3"; } /** * @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. // If your implementation uses the cost of the call in want, you can // use 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/main/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))); } } // Part: Strategy contract Strategy is BaseStrategy { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; // Units used in Maker contracts uint256 internal constant WAD = 10**18; uint256 internal constant RAY = 10**27; // DAI token IERC20 internal constant investmentToken = IERC20(0x6B175474E89094C44Da98b954EedeAC495271d0F); // 100% uint256 internal constant MAX_BPS = WAD; // Maximum loss on withdrawal from yVault uint256 internal constant MAX_LOSS_BPS = 10000; // Wrapped Ether - Used for swaps routing address internal constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; // SushiSwap router ISwap internal constant sushiswapRouter = ISwap(0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F); // Uniswap router ISwap internal constant uniswapRouter = ISwap(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); // Provider to read current block's base fee IBaseFee internal constant baseFeeProvider = IBaseFee(0xf8d0Ec04e94296773cE20eFbeeA82e76220cD549); // Token Adapter Module for collateral address public gemJoinAdapter; // Maker Oracle Security Module IOSMedianizer public wantToUSDOSMProxy; // Use Chainlink oracle to obtain latest want/ETH price AggregatorInterface public chainlinkWantToETHPriceFeed; // DAI yVault IVault public yVault; // Router used for swaps ISwap public router; // Collateral type bytes32 public ilk; // Our vault identifier uint256 public cdpId; // Our desired collaterization ratio uint256 public collateralizationRatio; // Allow the collateralization ratio to drift a bit in order to avoid cycles uint256 public rebalanceTolerance; // Max acceptable base fee to take more debt or harvest uint256 public maxAcceptableBaseFee; // Maximum acceptable loss on withdrawal. Default to 0.01%. uint256 public maxLoss; // If set to true the strategy will never try to repay debt by selling want bool public leaveDebtBehind; // Name of the strategy string internal strategyName; // ----------------- INIT FUNCTIONS TO SUPPORT CLONING ----------------- constructor( address _vault, address _yVault, string memory _strategyName, bytes32 _ilk, address _gemJoin, address _wantToUSDOSMProxy, address _chainlinkWantToETHPriceFeed ) public BaseStrategy(_vault) { _initializeThis( _yVault, _strategyName, _ilk, _gemJoin, _wantToUSDOSMProxy, _chainlinkWantToETHPriceFeed ); } function initialize( address _vault, address _yVault, string memory _strategyName, bytes32 _ilk, address _gemJoin, address _wantToUSDOSMProxy, address _chainlinkWantToETHPriceFeed ) public { // Make sure we only initialize one time require(address(yVault) == address(0)); // dev: strategy already initialized address sender = msg.sender; // Initialize BaseStrategy _initialize(_vault, sender, sender, sender); // Initialize cloned instance _initializeThis( _yVault, _strategyName, _ilk, _gemJoin, _wantToUSDOSMProxy, _chainlinkWantToETHPriceFeed ); } function _initializeThis( address _yVault, string memory _strategyName, bytes32 _ilk, address _gemJoin, address _wantToUSDOSMProxy, address _chainlinkWantToETHPriceFeed ) internal { yVault = IVault(_yVault); strategyName = _strategyName; ilk = _ilk; gemJoinAdapter = _gemJoin; wantToUSDOSMProxy = IOSMedianizer(_wantToUSDOSMProxy); chainlinkWantToETHPriceFeed = AggregatorInterface( _chainlinkWantToETHPriceFeed ); // Set default router to SushiSwap router = sushiswapRouter; // Set health check to health.ychad.eth healthCheck = 0xDDCea799fF1699e98EDF118e0629A974Df7DF012; cdpId = MakerDaiDelegateLib.openCdp(ilk); require(cdpId > 0); // dev: error opening cdp // Current ratio can drift (collateralizationRatio - rebalanceTolerance, collateralizationRatio + rebalanceTolerance) // Allow additional 15% in any direction (210, 240) by default rebalanceTolerance = (15 * MAX_BPS) / 100; // Minimum collaterization ratio on YFI-A is 175% // Use 225% as target collateralizationRatio = (225 * MAX_BPS) / 100; // If we lose money in yvDAI then we are not OK selling want to repay it leaveDebtBehind = true; // Define maximum acceptable loss on withdrawal to be 0.01%. maxLoss = 1; // Set max acceptable base fee to take on more debt to 60 gwei maxAcceptableBaseFee = 60 * 1e9; } // ----------------- SETTERS & MIGRATION ----------------- // Maximum acceptable base fee of current block to take on more debt function setMaxAcceptableBaseFee(uint256 _maxAcceptableBaseFee) external onlyEmergencyAuthorized { maxAcceptableBaseFee = _maxAcceptableBaseFee; } // Target collateralization ratio to maintain within bounds function setCollateralizationRatio(uint256 _collateralizationRatio) external onlyEmergencyAuthorized { require( _collateralizationRatio.sub(rebalanceTolerance) > MakerDaiDelegateLib.getLiquidationRatio(ilk).mul(MAX_BPS).div( RAY ) ); // dev: desired collateralization ratio is too low collateralizationRatio = _collateralizationRatio; } // Rebalancing bands (collat ratio - tolerance, collat_ratio + tolerance) function setRebalanceTolerance(uint256 _rebalanceTolerance) external onlyEmergencyAuthorized { require( collateralizationRatio.sub(_rebalanceTolerance) > MakerDaiDelegateLib.getLiquidationRatio(ilk).mul(MAX_BPS).div( RAY ) ); // dev: desired rebalance tolerance makes allowed ratio too low rebalanceTolerance = _rebalanceTolerance; } // Max slippage to accept when withdrawing from yVault function setMaxLoss(uint256 _maxLoss) external onlyVaultManagers { require(_maxLoss <= MAX_LOSS_BPS); // dev: invalid value for max loss maxLoss = _maxLoss; } // If set to true the strategy will never sell want to repay debts function setLeaveDebtBehind(bool _leaveDebtBehind) external onlyEmergencyAuthorized { leaveDebtBehind = _leaveDebtBehind; } // Required to move funds to a new cdp and use a different cdpId after migration // Should only be called by governance as it will move funds function shiftToCdp(uint256 newCdpId) external onlyGovernance { MakerDaiDelegateLib.shiftCdp(cdpId, newCdpId); cdpId = newCdpId; } // Move yvDAI funds to a new yVault function migrateToNewDaiYVault(IVault newYVault) external onlyGovernance { uint256 balanceOfYVault = yVault.balanceOf(address(this)); if (balanceOfYVault > 0) { yVault.withdraw(balanceOfYVault, address(this), maxLoss); } investmentToken.safeApprove(address(yVault), 0); yVault = newYVault; _depositInvestmentTokenInYVault(); } // Allow address to manage Maker's CDP function grantCdpManagingRightsToUser(address user, bool allow) external onlyGovernance { MakerDaiDelegateLib.allowManagingCdp(cdpId, user, allow); } // Allow switching between Uniswap and SushiSwap function switchDex(bool isUniswap) external onlyVaultManagers { if (isUniswap) { router = uniswapRouter; } else { router = sushiswapRouter; } } // Allow external debt repayment // Attempt to take currentRatio to target c-ratio // Passing zero will repay all debt if possible function emergencyDebtRepayment(uint256 currentRatio) external onlyVaultManagers { _repayDebt(currentRatio); } // Allow repayment of an arbitrary amount of Dai without having to // grant access to the CDP in case of an emergency // Difference with `emergencyDebtRepayment` function above is that here we // are short-circuiting all strategy logic and repaying Dai at once // This could be helpful if for example yvDAI withdrawals are failing and // we want to do a Dai airdrop and direct debt repayment instead function repayDebtWithDaiBalance(uint256 amount) external onlyVaultManagers { _repayInvestmentTokenDebt(amount); } // ******** OVERRIDEN METHODS FROM BASE CONTRACT ************ function name() external view override returns (string memory) { return strategyName; } function delegatedAssets() external view override returns (uint256) { return _convertInvestmentTokenToWant(_valueOfInvestment()); } function estimatedTotalAssets() public view override returns (uint256) { return balanceOfWant() .add(balanceOfMakerVault()) .add(_convertInvestmentTokenToWant(balanceOfInvestmentToken())) .add(_convertInvestmentTokenToWant(_valueOfInvestment())) .sub(_convertInvestmentTokenToWant(balanceOfDebt())); } function prepareReturn(uint256 _debtOutstanding) internal override returns ( uint256 _profit, uint256 _loss, uint256 _debtPayment ) { uint256 totalDebt = vault.strategies(address(this)).totalDebt; // Claim rewards from yVault _takeYVaultProfit(); uint256 totalAssetsAfterProfit = estimatedTotalAssets(); _profit = totalAssetsAfterProfit > totalDebt ? totalAssetsAfterProfit.sub(totalDebt) : 0; uint256 _amountFreed; (_amountFreed, _loss) = liquidatePosition( _debtOutstanding.add(_profit) ); _debtPayment = Math.min(_debtOutstanding, _amountFreed); if (_loss > _profit) { // Example: // debtOutstanding 100, profit 50, _amountFreed 100, _loss 50 // loss should be 0, (50-50) // profit should endup in 0 _loss = _loss.sub(_profit); _profit = 0; } else { // Example: // debtOutstanding 100, profit 50, _amountFreed 140, _loss 10 // _profit should be 40, (50 profit - 10 loss) // loss should end up in be 0 _profit = _profit.sub(_loss); _loss = 0; } } function adjustPosition(uint256 _debtOutstanding) internal override { MakerDaiDelegateLib.keepBasicMakerHygiene(ilk); // If we have enough want to deposit more into the maker vault, we do it // Do not skip the rest of the function as it may need to repay or take on more debt uint256 wantBalance = balanceOfWant(); if (wantBalance > _debtOutstanding) { uint256 amountToDeposit = wantBalance.sub(_debtOutstanding); _depositToMakerVault(amountToDeposit); } // Allow the ratio to move a bit in either direction to avoid cycles uint256 currentRatio = getCurrentMakerVaultRatio(); if (currentRatio < collateralizationRatio.sub(rebalanceTolerance)) { _repayDebt(currentRatio); } else if ( currentRatio > collateralizationRatio.add(rebalanceTolerance) ) { _mintMoreInvestmentToken(); } // If we have anything left to invest then deposit into the yVault _depositInvestmentTokenInYVault(); } function liquidatePosition(uint256 _amountNeeded) internal override returns (uint256 _liquidatedAmount, uint256 _loss) { uint256 balance = balanceOfWant(); // Check if we can handle it without freeing collateral if (balance >= _amountNeeded) { return (_amountNeeded, 0); } // We only need to free the amount of want not readily available uint256 amountToFree = _amountNeeded.sub(balance); uint256 price = _getWantTokenPrice(); uint256 collateralBalance = balanceOfMakerVault(); // We cannot free more than what we have locked amountToFree = Math.min(amountToFree, collateralBalance); uint256 totalDebt = balanceOfDebt(); // If for some reason we do not have debt, make sure the operation does not revert if (totalDebt == 0) { totalDebt = 1; } uint256 toFreeIT = amountToFree.mul(price).div(WAD); uint256 collateralIT = collateralBalance.mul(price).div(WAD); uint256 newRatio = collateralIT.sub(toFreeIT).mul(MAX_BPS).div(totalDebt); // Attempt to repay necessary debt to restore the target collateralization ratio _repayDebt(newRatio); // Unlock as much collateral as possible while keeping the target ratio amountToFree = Math.min(amountToFree, _maxWithdrawal()); _freeCollateralAndRepayDai(amountToFree, 0); // If we still need more want to repay, we may need to unlock some collateral to sell if ( !leaveDebtBehind && balanceOfWant() < _amountNeeded && balanceOfDebt() > 0 ) { _sellCollateralToRepayRemainingDebtIfNeeded(); } uint256 looseWant = balanceOfWant(); if (_amountNeeded > looseWant) { _liquidatedAmount = looseWant; _loss = _amountNeeded.sub(looseWant); } else { _liquidatedAmount = _amountNeeded; _loss = 0; } } function liquidateAllPositions() internal override returns (uint256 _amountFreed) { (_amountFreed, ) = liquidatePosition(estimatedTotalAssets()); } function harvestTrigger(uint256 callCost) public view override returns (bool) { return isCurrentBaseFeeAcceptable() && super.harvestTrigger(callCost); } function tendTrigger(uint256 callCostInWei) public view override returns (bool) { // Nothing to adjust if there is no collateral locked if (balanceOfMakerVault() == 0) { return false; } uint256 currentRatio = getCurrentMakerVaultRatio(); // If we need to repay debt and are outside the tolerance bands, // we do it regardless of the call cost if (currentRatio < collateralizationRatio.sub(rebalanceTolerance)) { return true; } // Mint more DAI if possible return currentRatio > collateralizationRatio.add(rebalanceTolerance) && balanceOfDebt() > 0 && isCurrentBaseFeeAcceptable() && MakerDaiDelegateLib.isDaiAvailableToMint(ilk); } function prepareMigration(address _newStrategy) internal override { // Transfer Maker Vault ownership to the new startegy MakerDaiDelegateLib.transferCdp(cdpId, _newStrategy); // Move yvDAI balance to the new strategy IERC20(yVault).safeTransfer( _newStrategy, yVault.balanceOf(address(this)) ); } function protectedTokens() internal view override returns (address[] memory) {} function ethToWant(uint256 _amtInWei) public view virtual override returns (uint256) { if (address(want) == address(WETH)) { return _amtInWei; } uint256 price = uint256(chainlinkWantToETHPriceFeed.latestAnswer()); return _amtInWei.mul(WAD).div(price); } // ----------------- INTERNAL FUNCTIONS SUPPORT ----------------- function _repayDebt(uint256 currentRatio) internal { uint256 currentDebt = balanceOfDebt(); // Nothing to repay if we are over the collateralization ratio // or there is no debt if (currentRatio > collateralizationRatio || currentDebt == 0) { return; } // ratio = collateral / debt // collateral = current_ratio * current_debt // collateral amount is invariant here so we want to find new_debt // so that new_debt * desired_ratio = current_debt * current_ratio // new_debt = current_debt * current_ratio / desired_ratio // and the amount to repay is the difference between current_debt and new_debt uint256 newDebt = currentDebt.mul(currentRatio).div(collateralizationRatio); uint256 amountToRepay; // Maker will revert if the outstanding debt is less than a debt floor // called 'dust'. If we are there we need to either pay the debt in full // or leave at least 'dust' balance (10,000 DAI for YFI-A) uint256 debtFloor = MakerDaiDelegateLib.debtFloor(ilk); if (newDebt <= debtFloor) { // If we sold want to repay debt we will have DAI readily available in the strategy // This means we need to count both yvDAI shares and current DAI balance uint256 totalInvestmentAvailableToRepay = _valueOfInvestment().add(balanceOfInvestmentToken()); if (totalInvestmentAvailableToRepay >= currentDebt) { // Pay the entire debt if we have enough investment token amountToRepay = currentDebt; } else { // Pay just 0.1 cent above debtFloor (best effort without liquidating want) amountToRepay = currentDebt.sub(debtFloor).sub(1e15); } } else { // If we are not near the debt floor then just pay the exact amount // needed to obtain a healthy collateralization ratio amountToRepay = currentDebt.sub(newDebt); } uint256 balanceIT = balanceOfInvestmentToken(); if (amountToRepay > balanceIT) { _withdrawFromYVault(amountToRepay.sub(balanceIT)); } _repayInvestmentTokenDebt(amountToRepay); } function _sellCollateralToRepayRemainingDebtIfNeeded() internal { uint256 currentInvestmentValue = _valueOfInvestment(); uint256 investmentLeftToAcquire = balanceOfDebt().sub(currentInvestmentValue); uint256 investmentLeftToAcquireInWant = _convertInvestmentTokenToWant(investmentLeftToAcquire); if (investmentLeftToAcquireInWant <= balanceOfWant()) { _buyInvestmentTokenWithWant(investmentLeftToAcquire); _repayDebt(0); _freeCollateralAndRepayDai(balanceOfMakerVault(), 0); } } // Mint the maximum DAI possible for the locked collateral function _mintMoreInvestmentToken() internal { uint256 price = _getWantTokenPrice(); uint256 amount = balanceOfMakerVault(); uint256 daiToMint = amount.mul(price).mul(MAX_BPS).div(collateralizationRatio).div(WAD); daiToMint = daiToMint.sub(balanceOfDebt()); _lockCollateralAndMintDai(0, daiToMint); } function _withdrawFromYVault(uint256 _amountIT) internal returns (uint256) { if (_amountIT == 0) { return 0; } // No need to check allowance because the contract == token uint256 balancePrior = balanceOfInvestmentToken(); uint256 sharesToWithdraw = Math.min( _investmentTokenToYShares(_amountIT), yVault.balanceOf(address(this)) ); if (sharesToWithdraw == 0) { return 0; } yVault.withdraw(sharesToWithdraw, address(this), maxLoss); return balanceOfInvestmentToken().sub(balancePrior); } function _depositInvestmentTokenInYVault() internal { uint256 balanceIT = balanceOfInvestmentToken(); if (balanceIT > 0) { _checkAllowance( address(yVault), address(investmentToken), balanceIT ); yVault.deposit(); } } function _repayInvestmentTokenDebt(uint256 amount) internal { if (amount == 0) { return; } uint256 debt = balanceOfDebt(); uint256 balanceIT = balanceOfInvestmentToken(); // We cannot pay more than loose balance amount = Math.min(amount, balanceIT); // We cannot pay more than we owe amount = Math.min(amount, debt); _checkAllowance( MakerDaiDelegateLib.daiJoinAddress(), address(investmentToken), amount ); if (amount > 0) { // When repaying the full debt it is very common to experience Vat/dust // reverts due to the debt being non-zero and less than the debt floor. // This can happen due to rounding when _wipeAndFreeGem() divides // the DAI amount by the accumulated stability fee rate. // To circumvent this issue we will add 1 Wei to the amount to be paid // if there is enough investment token balance (DAI) to do it. if (debt.sub(amount) == 0 && balanceIT.sub(amount) >= 1) { amount = amount.add(1); } // Repay debt amount without unlocking collateral _freeCollateralAndRepayDai(0, amount); } } function _checkAllowance( address _contract, address _token, uint256 _amount ) internal { if (IERC20(_token).allowance(address(this), _contract) < _amount) { IERC20(_token).safeApprove(_contract, 0); IERC20(_token).safeApprove(_contract, type(uint256).max); } } function _takeYVaultProfit() internal { uint256 _debt = balanceOfDebt(); uint256 _valueInVault = _valueOfInvestment(); if (_debt >= _valueInVault) { return; } uint256 profit = _valueInVault.sub(_debt); uint256 ySharesToWithdraw = _investmentTokenToYShares(profit); if (ySharesToWithdraw > 0) { yVault.withdraw(ySharesToWithdraw, address(this), maxLoss); _sellAForB( balanceOfInvestmentToken(), address(investmentToken), address(want) ); } } function _depositToMakerVault(uint256 amount) internal { if (amount == 0) { return; } _checkAllowance(gemJoinAdapter, address(want), amount); uint256 price = _getWantTokenPrice(); uint256 daiToMint = amount.mul(price).mul(MAX_BPS).div(collateralizationRatio).div(WAD); _lockCollateralAndMintDai(amount, daiToMint); } // Returns maximum collateral to withdraw while maintaining the target collateralization ratio function _maxWithdrawal() internal view returns (uint256) { // Denominated in want uint256 totalCollateral = balanceOfMakerVault(); // Denominated in investment token uint256 totalDebt = balanceOfDebt(); // If there is no debt to repay we can withdraw all the locked collateral if (totalDebt == 0) { return totalCollateral; } uint256 price = _getWantTokenPrice(); // Min collateral in want that needs to be locked with the outstanding debt // Allow going to the lower rebalancing band uint256 minCollateral = collateralizationRatio .sub(rebalanceTolerance) .mul(totalDebt) .mul(WAD) .div(price) .div(MAX_BPS); // If we are under collateralized then it is not safe for us to withdraw anything if (minCollateral > totalCollateral) { return 0; } return totalCollateral.sub(minCollateral); } // ----------------- PUBLIC BALANCES AND CALCS ----------------- function balanceOfWant() public view returns (uint256) { return want.balanceOf(address(this)); } function balanceOfInvestmentToken() public view returns (uint256) { return investmentToken.balanceOf(address(this)); } function balanceOfDebt() public view returns (uint256) { return MakerDaiDelegateLib.debtForCdp(cdpId, ilk); } // Returns collateral balance in the vault function balanceOfMakerVault() public view returns (uint256) { return MakerDaiDelegateLib.balanceOfCdp(cdpId, ilk); } // Effective collateralization ratio of the vault function getCurrentMakerVaultRatio() public view returns (uint256) { return MakerDaiDelegateLib.getPessimisticRatioOfCdpWithExternalPrice( cdpId, ilk, _getWantTokenPrice(), MAX_BPS ); } // Check if current block's base fee is under max allowed base fee function isCurrentBaseFeeAcceptable() public view returns (bool) { uint256 baseFee; try baseFeeProvider.basefee_global() returns (uint256 currentBaseFee) { baseFee = currentBaseFee; } catch { // Useful for testing until ganache supports london fork // Hard-code current base fee to 1000 gwei // This should also help keepers that run in a fork without // baseFee() to avoid reverting and potentially abandoning the job baseFee = 1000 * 1e9; } return baseFee <= maxAcceptableBaseFee; } // ----------------- INTERNAL CALCS ----------------- // Returns the minimum price available function _getWantTokenPrice() internal view returns (uint256) { // Use price from spotter as base uint256 minPrice = MakerDaiDelegateLib.getSpotPrice(ilk); // Peek the OSM to get current price try wantToUSDOSMProxy.read() returns ( uint256 current, bool currentIsValid ) { if (currentIsValid && current > 0) { minPrice = Math.min(minPrice, current); } } catch { // Ignore price peek()'d from OSM. Maybe we are no longer authorized. } // Peep the OSM to get future price try wantToUSDOSMProxy.foresight() returns ( uint256 future, bool futureIsValid ) { if (futureIsValid && future > 0) { minPrice = Math.min(minPrice, future); } } catch { // Ignore price peep()'d from OSM. Maybe we are no longer authorized. } // If price is set to 0 then we hope no liquidations are taking place // Emergency scenarios can be handled via manual debt repayment or by // granting governance access to the CDP require(minPrice > 0); // dev: invalid spot price // par is crucial to this calculation as it defines the relationship between DAI and // 1 unit of value in the price return minPrice.mul(RAY).div(MakerDaiDelegateLib.getDaiPar()); } function _valueOfInvestment() internal view returns (uint256) { return yVault.balanceOf(address(this)).mul(yVault.pricePerShare()).div( 10**yVault.decimals() ); } function _investmentTokenToYShares(uint256 amount) internal view returns (uint256) { return amount.mul(10**yVault.decimals()).div(yVault.pricePerShare()); } function _lockCollateralAndMintDai( uint256 collateralAmount, uint256 daiToMint ) internal { MakerDaiDelegateLib.lockGemAndDraw( gemJoinAdapter, cdpId, collateralAmount, daiToMint, balanceOfDebt() ); } function _freeCollateralAndRepayDai( uint256 collateralAmount, uint256 daiToRepay ) internal { MakerDaiDelegateLib.wipeAndFreeGem( gemJoinAdapter, cdpId, collateralAmount, daiToRepay ); } // ----------------- TOKEN CONVERSIONS ----------------- function _convertInvestmentTokenToWant(uint256 amount) internal view returns (uint256) { return amount.mul(WAD).div(_getWantTokenPrice()); } function _getTokenOutPath(address _token_in, address _token_out) internal pure returns (address[] memory _path) { bool is_weth = _token_in == address(WETH) || _token_out == address(WETH); _path = new address[](is_weth ? 2 : 3); _path[0] = _token_in; if (is_weth) { _path[1] = _token_out; } else { _path[1] = address(WETH); _path[2] = _token_out; } } function _sellAForB( uint256 _amount, address tokenA, address tokenB ) internal { if (_amount == 0 || tokenA == tokenB) { return; } _checkAllowance(address(router), tokenA, _amount); router.swapExactTokensForTokens( _amount, 0, _getTokenOutPath(tokenA, tokenB), address(this), now ); } function _buyInvestmentTokenWithWant(uint256 _amount) internal { if (_amount == 0 || address(investmentToken) == address(want)) { return; } _checkAllowance(address(router), address(want), _amount); router.swapTokensForExactTokens( _amount, type(uint256).max, _getTokenOutPath(address(want), address(investmentToken)), address(this), now ); } } // File: MakerDaiDelegateCloner.sol contract MakerDaiDelegateCloner { address public immutable original; event Cloned(address indexed clone); event Deployed(address indexed original); constructor( address _vault, address _yVault, string memory _strategyName, bytes32 _ilk, address _gemJoin, address _wantToUSDOSMProxy, address _chainlinkWantToETHPriceFeed ) public { Strategy _original = new Strategy( _vault, _yVault, _strategyName, _ilk, _gemJoin, _wantToUSDOSMProxy, _chainlinkWantToETHPriceFeed ); emit Deployed(address(_original)); original = address(_original); Strategy(_original).setRewards( 0xc491599b9A20c3A2F0A85697Ee6D9434EFa9f503 ); Strategy(_original).setKeeper( 0x736D7e3c5a6CB2CE3B764300140ABF476F6CFCCF ); Strategy(_original).setStrategist( 0x16388463d60FFE0661Cf7F1f31a7D658aC790ff7 ); } function cloneMakerDaiDelegate( address _vault, address _strategist, address _rewards, address _keeper, address _yVault, string memory _strategyName, bytes32 _ilk, address _gemJoin, address _wantToUSDOSMProxy, address _chainlinkWantToETHPriceFeed ) external returns (address newStrategy) { // Copied from https://github.com/optionality/clone-factory/blob/master/contracts/CloneFactory.sol bytes20 addressBytes = bytes20(original); assembly { // EIP-1167 bytecode let clone_code := mload(0x40) mstore( clone_code, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000 ) mstore(add(clone_code, 0x14), addressBytes) mstore( add(clone_code, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000 ) newStrategy := create(0, clone_code, 0x37) } Strategy(newStrategy).initialize( _vault, _yVault, _strategyName, _ilk, _gemJoin, _wantToUSDOSMProxy, _chainlinkWantToETHPriceFeed ); Strategy(newStrategy).setKeeper(_keeper); Strategy(newStrategy).setRewards(_rewards); Strategy(newStrategy).setStrategist(_strategist); emit Cloned(newStrategy); } function name() external pure returns (string memory) { return "[email protected]"; } }
Units used in Maker contracts DAI token 100% Maximum loss on withdrawal from yVault Wrapped Ether - Used for swaps routing SushiSwap router Uniswap router Provider to read current block's base fee Token Adapter Module for collateral Maker Oracle Security Module Use Chainlink oracle to obtain latest want/ETH price DAI yVault Router used for swaps Collateral type Our vault identifier Our desired collaterization ratio Allow the collateralization ratio to drift a bit in order to avoid cycles Max acceptable base fee to take more debt or harvest Maximum acceptable loss on withdrawal. Default to 0.01%. If set to true the strategy will never try to repay debt by selling want Name of the strategy ----------------- INIT FUNCTIONS TO SUPPORT CLONING -----------------
contract Strategy is BaseStrategy { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; uint256 internal constant WAD = 10**18; uint256 internal constant RAY = 10**27; IERC20 internal constant investmentToken = IERC20(0x6B175474E89094C44Da98b954EedeAC495271d0F); uint256 internal constant MAX_BPS = WAD; uint256 internal constant MAX_LOSS_BPS = 10000; address internal constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; ISwap internal constant sushiswapRouter = ISwap(0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F); ISwap internal constant uniswapRouter = ISwap(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); IBaseFee internal constant baseFeeProvider = IBaseFee(0xf8d0Ec04e94296773cE20eFbeeA82e76220cD549); address public gemJoinAdapter; IOSMedianizer public wantToUSDOSMProxy; AggregatorInterface public chainlinkWantToETHPriceFeed; IVault public yVault; ISwap public router; bytes32 public ilk; uint256 public cdpId; uint256 public collateralizationRatio; uint256 public rebalanceTolerance; uint256 public maxAcceptableBaseFee; uint256 public maxLoss; bool public leaveDebtBehind; string internal strategyName; constructor( address _vault, address _yVault, string memory _strategyName, bytes32 _ilk, address _gemJoin, address _wantToUSDOSMProxy, address _chainlinkWantToETHPriceFeed ) public BaseStrategy(_vault) { _initializeThis( _yVault, _strategyName, _ilk, _gemJoin, _wantToUSDOSMProxy, _chainlinkWantToETHPriceFeed ); } function initialize( address _vault, address _yVault, string memory _strategyName, bytes32 _ilk, address _gemJoin, address _wantToUSDOSMProxy, address _chainlinkWantToETHPriceFeed ) public { address sender = msg.sender; _initialize(_vault, sender, sender, sender); _initializeThis( _yVault, _strategyName, _ilk, _gemJoin, _wantToUSDOSMProxy, _chainlinkWantToETHPriceFeed ); } function _initializeThis( address _yVault, string memory _strategyName, bytes32 _ilk, address _gemJoin, address _wantToUSDOSMProxy, address _chainlinkWantToETHPriceFeed ) internal { yVault = IVault(_yVault); strategyName = _strategyName; ilk = _ilk; gemJoinAdapter = _gemJoin; wantToUSDOSMProxy = IOSMedianizer(_wantToUSDOSMProxy); chainlinkWantToETHPriceFeed = AggregatorInterface( _chainlinkWantToETHPriceFeed ); router = sushiswapRouter; healthCheck = 0xDDCea799fF1699e98EDF118e0629A974Df7DF012; cdpId = MakerDaiDelegateLib.openCdp(ilk); rebalanceTolerance = (15 * MAX_BPS) / 100; collateralizationRatio = (225 * MAX_BPS) / 100; leaveDebtBehind = true; maxLoss = 1; maxAcceptableBaseFee = 60 * 1e9; } function setMaxAcceptableBaseFee(uint256 _maxAcceptableBaseFee) external onlyEmergencyAuthorized { maxAcceptableBaseFee = _maxAcceptableBaseFee; } function setCollateralizationRatio(uint256 _collateralizationRatio) external onlyEmergencyAuthorized { require( _collateralizationRatio.sub(rebalanceTolerance) > MakerDaiDelegateLib.getLiquidationRatio(ilk).mul(MAX_BPS).div( RAY ) collateralizationRatio = _collateralizationRatio; } function setRebalanceTolerance(uint256 _rebalanceTolerance) external onlyEmergencyAuthorized { require( collateralizationRatio.sub(_rebalanceTolerance) > MakerDaiDelegateLib.getLiquidationRatio(ilk).mul(MAX_BPS).div( RAY ) rebalanceTolerance = _rebalanceTolerance; } function setMaxLoss(uint256 _maxLoss) external onlyVaultManagers { maxLoss = _maxLoss; } function setLeaveDebtBehind(bool _leaveDebtBehind) external onlyEmergencyAuthorized { leaveDebtBehind = _leaveDebtBehind; } function shiftToCdp(uint256 newCdpId) external onlyGovernance { MakerDaiDelegateLib.shiftCdp(cdpId, newCdpId); cdpId = newCdpId; } function migrateToNewDaiYVault(IVault newYVault) external onlyGovernance { uint256 balanceOfYVault = yVault.balanceOf(address(this)); if (balanceOfYVault > 0) { yVault.withdraw(balanceOfYVault, address(this), maxLoss); } investmentToken.safeApprove(address(yVault), 0); yVault = newYVault; _depositInvestmentTokenInYVault(); } function migrateToNewDaiYVault(IVault newYVault) external onlyGovernance { uint256 balanceOfYVault = yVault.balanceOf(address(this)); if (balanceOfYVault > 0) { yVault.withdraw(balanceOfYVault, address(this), maxLoss); } investmentToken.safeApprove(address(yVault), 0); yVault = newYVault; _depositInvestmentTokenInYVault(); } function grantCdpManagingRightsToUser(address user, bool allow) external onlyGovernance { MakerDaiDelegateLib.allowManagingCdp(cdpId, user, allow); } function switchDex(bool isUniswap) external onlyVaultManagers { if (isUniswap) { router = uniswapRouter; router = sushiswapRouter; } } function switchDex(bool isUniswap) external onlyVaultManagers { if (isUniswap) { router = uniswapRouter; router = sushiswapRouter; } } } else { function emergencyDebtRepayment(uint256 currentRatio) external onlyVaultManagers { _repayDebt(currentRatio); } function repayDebtWithDaiBalance(uint256 amount) external onlyVaultManagers { _repayInvestmentTokenDebt(amount); } function name() external view override returns (string memory) { return strategyName; } function delegatedAssets() external view override returns (uint256) { return _convertInvestmentTokenToWant(_valueOfInvestment()); } function estimatedTotalAssets() public view override returns (uint256) { return balanceOfWant() .add(balanceOfMakerVault()) .add(_convertInvestmentTokenToWant(balanceOfInvestmentToken())) .add(_convertInvestmentTokenToWant(_valueOfInvestment())) .sub(_convertInvestmentTokenToWant(balanceOfDebt())); } function prepareReturn(uint256 _debtOutstanding) internal override returns ( uint256 _profit, uint256 _loss, uint256 _debtPayment ) { uint256 totalDebt = vault.strategies(address(this)).totalDebt; _takeYVaultProfit(); uint256 totalAssetsAfterProfit = estimatedTotalAssets(); _profit = totalAssetsAfterProfit > totalDebt ? totalAssetsAfterProfit.sub(totalDebt) : 0; uint256 _amountFreed; (_amountFreed, _loss) = liquidatePosition( _debtOutstanding.add(_profit) ); _debtPayment = Math.min(_debtOutstanding, _amountFreed); if (_loss > _profit) { _loss = _loss.sub(_profit); _profit = 0; _profit = _profit.sub(_loss); _loss = 0; } } function prepareReturn(uint256 _debtOutstanding) internal override returns ( uint256 _profit, uint256 _loss, uint256 _debtPayment ) { uint256 totalDebt = vault.strategies(address(this)).totalDebt; _takeYVaultProfit(); uint256 totalAssetsAfterProfit = estimatedTotalAssets(); _profit = totalAssetsAfterProfit > totalDebt ? totalAssetsAfterProfit.sub(totalDebt) : 0; uint256 _amountFreed; (_amountFreed, _loss) = liquidatePosition( _debtOutstanding.add(_profit) ); _debtPayment = Math.min(_debtOutstanding, _amountFreed); if (_loss > _profit) { _loss = _loss.sub(_profit); _profit = 0; _profit = _profit.sub(_loss); _loss = 0; } } } else { function adjustPosition(uint256 _debtOutstanding) internal override { MakerDaiDelegateLib.keepBasicMakerHygiene(ilk); uint256 wantBalance = balanceOfWant(); if (wantBalance > _debtOutstanding) { uint256 amountToDeposit = wantBalance.sub(_debtOutstanding); _depositToMakerVault(amountToDeposit); } if (currentRatio < collateralizationRatio.sub(rebalanceTolerance)) { _repayDebt(currentRatio); } else if ( currentRatio > collateralizationRatio.add(rebalanceTolerance) ) { _mintMoreInvestmentToken(); } } function adjustPosition(uint256 _debtOutstanding) internal override { MakerDaiDelegateLib.keepBasicMakerHygiene(ilk); uint256 wantBalance = balanceOfWant(); if (wantBalance > _debtOutstanding) { uint256 amountToDeposit = wantBalance.sub(_debtOutstanding); _depositToMakerVault(amountToDeposit); } if (currentRatio < collateralizationRatio.sub(rebalanceTolerance)) { _repayDebt(currentRatio); } else if ( currentRatio > collateralizationRatio.add(rebalanceTolerance) ) { _mintMoreInvestmentToken(); } } uint256 currentRatio = getCurrentMakerVaultRatio(); function adjustPosition(uint256 _debtOutstanding) internal override { MakerDaiDelegateLib.keepBasicMakerHygiene(ilk); uint256 wantBalance = balanceOfWant(); if (wantBalance > _debtOutstanding) { uint256 amountToDeposit = wantBalance.sub(_debtOutstanding); _depositToMakerVault(amountToDeposit); } if (currentRatio < collateralizationRatio.sub(rebalanceTolerance)) { _repayDebt(currentRatio); } else if ( currentRatio > collateralizationRatio.add(rebalanceTolerance) ) { _mintMoreInvestmentToken(); } } function adjustPosition(uint256 _debtOutstanding) internal override { MakerDaiDelegateLib.keepBasicMakerHygiene(ilk); uint256 wantBalance = balanceOfWant(); if (wantBalance > _debtOutstanding) { uint256 amountToDeposit = wantBalance.sub(_debtOutstanding); _depositToMakerVault(amountToDeposit); } if (currentRatio < collateralizationRatio.sub(rebalanceTolerance)) { _repayDebt(currentRatio); } else if ( currentRatio > collateralizationRatio.add(rebalanceTolerance) ) { _mintMoreInvestmentToken(); } } _depositInvestmentTokenInYVault(); function liquidatePosition(uint256 _amountNeeded) internal override returns (uint256 _liquidatedAmount, uint256 _loss) { uint256 balance = balanceOfWant(); if (balance >= _amountNeeded) { return (_amountNeeded, 0); } uint256 price = _getWantTokenPrice(); uint256 collateralBalance = balanceOfMakerVault(); uint256 totalDebt = balanceOfDebt(); if (totalDebt == 0) { totalDebt = 1; } uint256 toFreeIT = amountToFree.mul(price).div(WAD); uint256 collateralIT = collateralBalance.mul(price).div(WAD); uint256 newRatio = collateralIT.sub(toFreeIT).mul(MAX_BPS).div(totalDebt); _freeCollateralAndRepayDai(amountToFree, 0); !leaveDebtBehind && balanceOfWant() < _amountNeeded && balanceOfDebt() > 0 ) { _sellCollateralToRepayRemainingDebtIfNeeded(); } uint256 looseWant = balanceOfWant(); if (_amountNeeded > looseWant) { _liquidatedAmount = looseWant; _loss = _amountNeeded.sub(looseWant); _liquidatedAmount = _amountNeeded; _loss = 0; } } function liquidatePosition(uint256 _amountNeeded) internal override returns (uint256 _liquidatedAmount, uint256 _loss) { uint256 balance = balanceOfWant(); if (balance >= _amountNeeded) { return (_amountNeeded, 0); } uint256 price = _getWantTokenPrice(); uint256 collateralBalance = balanceOfMakerVault(); uint256 totalDebt = balanceOfDebt(); if (totalDebt == 0) { totalDebt = 1; } uint256 toFreeIT = amountToFree.mul(price).div(WAD); uint256 collateralIT = collateralBalance.mul(price).div(WAD); uint256 newRatio = collateralIT.sub(toFreeIT).mul(MAX_BPS).div(totalDebt); _freeCollateralAndRepayDai(amountToFree, 0); !leaveDebtBehind && balanceOfWant() < _amountNeeded && balanceOfDebt() > 0 ) { _sellCollateralToRepayRemainingDebtIfNeeded(); } uint256 looseWant = balanceOfWant(); if (_amountNeeded > looseWant) { _liquidatedAmount = looseWant; _loss = _amountNeeded.sub(looseWant); _liquidatedAmount = _amountNeeded; _loss = 0; } } uint256 amountToFree = _amountNeeded.sub(balance); amountToFree = Math.min(amountToFree, collateralBalance); function liquidatePosition(uint256 _amountNeeded) internal override returns (uint256 _liquidatedAmount, uint256 _loss) { uint256 balance = balanceOfWant(); if (balance >= _amountNeeded) { return (_amountNeeded, 0); } uint256 price = _getWantTokenPrice(); uint256 collateralBalance = balanceOfMakerVault(); uint256 totalDebt = balanceOfDebt(); if (totalDebt == 0) { totalDebt = 1; } uint256 toFreeIT = amountToFree.mul(price).div(WAD); uint256 collateralIT = collateralBalance.mul(price).div(WAD); uint256 newRatio = collateralIT.sub(toFreeIT).mul(MAX_BPS).div(totalDebt); _freeCollateralAndRepayDai(amountToFree, 0); !leaveDebtBehind && balanceOfWant() < _amountNeeded && balanceOfDebt() > 0 ) { _sellCollateralToRepayRemainingDebtIfNeeded(); } uint256 looseWant = balanceOfWant(); if (_amountNeeded > looseWant) { _liquidatedAmount = looseWant; _loss = _amountNeeded.sub(looseWant); _liquidatedAmount = _amountNeeded; _loss = 0; } } _repayDebt(newRatio); amountToFree = Math.min(amountToFree, _maxWithdrawal()); if ( function liquidatePosition(uint256 _amountNeeded) internal override returns (uint256 _liquidatedAmount, uint256 _loss) { uint256 balance = balanceOfWant(); if (balance >= _amountNeeded) { return (_amountNeeded, 0); } uint256 price = _getWantTokenPrice(); uint256 collateralBalance = balanceOfMakerVault(); uint256 totalDebt = balanceOfDebt(); if (totalDebt == 0) { totalDebt = 1; } uint256 toFreeIT = amountToFree.mul(price).div(WAD); uint256 collateralIT = collateralBalance.mul(price).div(WAD); uint256 newRatio = collateralIT.sub(toFreeIT).mul(MAX_BPS).div(totalDebt); _freeCollateralAndRepayDai(amountToFree, 0); !leaveDebtBehind && balanceOfWant() < _amountNeeded && balanceOfDebt() > 0 ) { _sellCollateralToRepayRemainingDebtIfNeeded(); } uint256 looseWant = balanceOfWant(); if (_amountNeeded > looseWant) { _liquidatedAmount = looseWant; _loss = _amountNeeded.sub(looseWant); _liquidatedAmount = _amountNeeded; _loss = 0; } } function liquidatePosition(uint256 _amountNeeded) internal override returns (uint256 _liquidatedAmount, uint256 _loss) { uint256 balance = balanceOfWant(); if (balance >= _amountNeeded) { return (_amountNeeded, 0); } uint256 price = _getWantTokenPrice(); uint256 collateralBalance = balanceOfMakerVault(); uint256 totalDebt = balanceOfDebt(); if (totalDebt == 0) { totalDebt = 1; } uint256 toFreeIT = amountToFree.mul(price).div(WAD); uint256 collateralIT = collateralBalance.mul(price).div(WAD); uint256 newRatio = collateralIT.sub(toFreeIT).mul(MAX_BPS).div(totalDebt); _freeCollateralAndRepayDai(amountToFree, 0); !leaveDebtBehind && balanceOfWant() < _amountNeeded && balanceOfDebt() > 0 ) { _sellCollateralToRepayRemainingDebtIfNeeded(); } uint256 looseWant = balanceOfWant(); if (_amountNeeded > looseWant) { _liquidatedAmount = looseWant; _loss = _amountNeeded.sub(looseWant); _liquidatedAmount = _amountNeeded; _loss = 0; } } } else { function liquidateAllPositions() internal override returns (uint256 _amountFreed) { (_amountFreed, ) = liquidatePosition(estimatedTotalAssets()); } function harvestTrigger(uint256 callCost) public view override returns (bool) { return isCurrentBaseFeeAcceptable() && super.harvestTrigger(callCost); } function tendTrigger(uint256 callCostInWei) public view override returns (bool) { if (balanceOfMakerVault() == 0) { return false; } uint256 currentRatio = getCurrentMakerVaultRatio(); if (currentRatio < collateralizationRatio.sub(rebalanceTolerance)) { return true; } currentRatio > collateralizationRatio.add(rebalanceTolerance) && balanceOfDebt() > 0 && isCurrentBaseFeeAcceptable() && MakerDaiDelegateLib.isDaiAvailableToMint(ilk); } function tendTrigger(uint256 callCostInWei) public view override returns (bool) { if (balanceOfMakerVault() == 0) { return false; } uint256 currentRatio = getCurrentMakerVaultRatio(); if (currentRatio < collateralizationRatio.sub(rebalanceTolerance)) { return true; } currentRatio > collateralizationRatio.add(rebalanceTolerance) && balanceOfDebt() > 0 && isCurrentBaseFeeAcceptable() && MakerDaiDelegateLib.isDaiAvailableToMint(ilk); } function tendTrigger(uint256 callCostInWei) public view override returns (bool) { if (balanceOfMakerVault() == 0) { return false; } uint256 currentRatio = getCurrentMakerVaultRatio(); if (currentRatio < collateralizationRatio.sub(rebalanceTolerance)) { return true; } currentRatio > collateralizationRatio.add(rebalanceTolerance) && balanceOfDebt() > 0 && isCurrentBaseFeeAcceptable() && MakerDaiDelegateLib.isDaiAvailableToMint(ilk); } return function prepareMigration(address _newStrategy) internal override { MakerDaiDelegateLib.transferCdp(cdpId, _newStrategy); IERC20(yVault).safeTransfer( _newStrategy, yVault.balanceOf(address(this)) ); } {} function protectedTokens() internal view override returns (address[] memory) function ethToWant(uint256 _amtInWei) public view virtual override returns (uint256) { if (address(want) == address(WETH)) { return _amtInWei; } uint256 price = uint256(chainlinkWantToETHPriceFeed.latestAnswer()); return _amtInWei.mul(WAD).div(price); } function protectedTokens() internal view override returns (address[] memory) function ethToWant(uint256 _amtInWei) public view virtual override returns (uint256) { if (address(want) == address(WETH)) { return _amtInWei; } uint256 price = uint256(chainlinkWantToETHPriceFeed.latestAnswer()); return _amtInWei.mul(WAD).div(price); } function _repayDebt(uint256 currentRatio) internal { uint256 currentDebt = balanceOfDebt(); if (currentRatio > collateralizationRatio || currentDebt == 0) { return; } currentDebt.mul(currentRatio).div(collateralizationRatio); uint256 amountToRepay; if (newDebt <= debtFloor) { uint256 totalInvestmentAvailableToRepay = _valueOfInvestment().add(balanceOfInvestmentToken()); if (totalInvestmentAvailableToRepay >= currentDebt) { amountToRepay = currentDebt; amountToRepay = currentDebt.sub(debtFloor).sub(1e15); } } uint256 balanceIT = balanceOfInvestmentToken(); if (amountToRepay > balanceIT) { _withdrawFromYVault(amountToRepay.sub(balanceIT)); } _repayInvestmentTokenDebt(amountToRepay); } function _repayDebt(uint256 currentRatio) internal { uint256 currentDebt = balanceOfDebt(); if (currentRatio > collateralizationRatio || currentDebt == 0) { return; } currentDebt.mul(currentRatio).div(collateralizationRatio); uint256 amountToRepay; if (newDebt <= debtFloor) { uint256 totalInvestmentAvailableToRepay = _valueOfInvestment().add(balanceOfInvestmentToken()); if (totalInvestmentAvailableToRepay >= currentDebt) { amountToRepay = currentDebt; amountToRepay = currentDebt.sub(debtFloor).sub(1e15); } } uint256 balanceIT = balanceOfInvestmentToken(); if (amountToRepay > balanceIT) { _withdrawFromYVault(amountToRepay.sub(balanceIT)); } _repayInvestmentTokenDebt(amountToRepay); } uint256 newDebt = uint256 debtFloor = MakerDaiDelegateLib.debtFloor(ilk); function _repayDebt(uint256 currentRatio) internal { uint256 currentDebt = balanceOfDebt(); if (currentRatio > collateralizationRatio || currentDebt == 0) { return; } currentDebt.mul(currentRatio).div(collateralizationRatio); uint256 amountToRepay; if (newDebt <= debtFloor) { uint256 totalInvestmentAvailableToRepay = _valueOfInvestment().add(balanceOfInvestmentToken()); if (totalInvestmentAvailableToRepay >= currentDebt) { amountToRepay = currentDebt; amountToRepay = currentDebt.sub(debtFloor).sub(1e15); } } uint256 balanceIT = balanceOfInvestmentToken(); if (amountToRepay > balanceIT) { _withdrawFromYVault(amountToRepay.sub(balanceIT)); } _repayInvestmentTokenDebt(amountToRepay); } function _repayDebt(uint256 currentRatio) internal { uint256 currentDebt = balanceOfDebt(); if (currentRatio > collateralizationRatio || currentDebt == 0) { return; } currentDebt.mul(currentRatio).div(collateralizationRatio); uint256 amountToRepay; if (newDebt <= debtFloor) { uint256 totalInvestmentAvailableToRepay = _valueOfInvestment().add(balanceOfInvestmentToken()); if (totalInvestmentAvailableToRepay >= currentDebt) { amountToRepay = currentDebt; amountToRepay = currentDebt.sub(debtFloor).sub(1e15); } } uint256 balanceIT = balanceOfInvestmentToken(); if (amountToRepay > balanceIT) { _withdrawFromYVault(amountToRepay.sub(balanceIT)); } _repayInvestmentTokenDebt(amountToRepay); } } else { } else { amountToRepay = currentDebt.sub(newDebt); function _repayDebt(uint256 currentRatio) internal { uint256 currentDebt = balanceOfDebt(); if (currentRatio > collateralizationRatio || currentDebt == 0) { return; } currentDebt.mul(currentRatio).div(collateralizationRatio); uint256 amountToRepay; if (newDebt <= debtFloor) { uint256 totalInvestmentAvailableToRepay = _valueOfInvestment().add(balanceOfInvestmentToken()); if (totalInvestmentAvailableToRepay >= currentDebt) { amountToRepay = currentDebt; amountToRepay = currentDebt.sub(debtFloor).sub(1e15); } } uint256 balanceIT = balanceOfInvestmentToken(); if (amountToRepay > balanceIT) { _withdrawFromYVault(amountToRepay.sub(balanceIT)); } _repayInvestmentTokenDebt(amountToRepay); } function _sellCollateralToRepayRemainingDebtIfNeeded() internal { uint256 currentInvestmentValue = _valueOfInvestment(); uint256 investmentLeftToAcquire = balanceOfDebt().sub(currentInvestmentValue); uint256 investmentLeftToAcquireInWant = _convertInvestmentTokenToWant(investmentLeftToAcquire); if (investmentLeftToAcquireInWant <= balanceOfWant()) { _buyInvestmentTokenWithWant(investmentLeftToAcquire); _repayDebt(0); _freeCollateralAndRepayDai(balanceOfMakerVault(), 0); } } function _sellCollateralToRepayRemainingDebtIfNeeded() internal { uint256 currentInvestmentValue = _valueOfInvestment(); uint256 investmentLeftToAcquire = balanceOfDebt().sub(currentInvestmentValue); uint256 investmentLeftToAcquireInWant = _convertInvestmentTokenToWant(investmentLeftToAcquire); if (investmentLeftToAcquireInWant <= balanceOfWant()) { _buyInvestmentTokenWithWant(investmentLeftToAcquire); _repayDebt(0); _freeCollateralAndRepayDai(balanceOfMakerVault(), 0); } } function _mintMoreInvestmentToken() internal { uint256 price = _getWantTokenPrice(); uint256 amount = balanceOfMakerVault(); uint256 daiToMint = amount.mul(price).mul(MAX_BPS).div(collateralizationRatio).div(WAD); daiToMint = daiToMint.sub(balanceOfDebt()); _lockCollateralAndMintDai(0, daiToMint); } function _withdrawFromYVault(uint256 _amountIT) internal returns (uint256) { if (_amountIT == 0) { return 0; } uint256 sharesToWithdraw = Math.min( _investmentTokenToYShares(_amountIT), yVault.balanceOf(address(this)) ); if (sharesToWithdraw == 0) { return 0; } yVault.withdraw(sharesToWithdraw, address(this), maxLoss); return balanceOfInvestmentToken().sub(balancePrior); } function _withdrawFromYVault(uint256 _amountIT) internal returns (uint256) { if (_amountIT == 0) { return 0; } uint256 sharesToWithdraw = Math.min( _investmentTokenToYShares(_amountIT), yVault.balanceOf(address(this)) ); if (sharesToWithdraw == 0) { return 0; } yVault.withdraw(sharesToWithdraw, address(this), maxLoss); return balanceOfInvestmentToken().sub(balancePrior); } uint256 balancePrior = balanceOfInvestmentToken(); function _withdrawFromYVault(uint256 _amountIT) internal returns (uint256) { if (_amountIT == 0) { return 0; } uint256 sharesToWithdraw = Math.min( _investmentTokenToYShares(_amountIT), yVault.balanceOf(address(this)) ); if (sharesToWithdraw == 0) { return 0; } yVault.withdraw(sharesToWithdraw, address(this), maxLoss); return balanceOfInvestmentToken().sub(balancePrior); } function _depositInvestmentTokenInYVault() internal { uint256 balanceIT = balanceOfInvestmentToken(); if (balanceIT > 0) { _checkAllowance( address(yVault), address(investmentToken), balanceIT ); yVault.deposit(); } } function _depositInvestmentTokenInYVault() internal { uint256 balanceIT = balanceOfInvestmentToken(); if (balanceIT > 0) { _checkAllowance( address(yVault), address(investmentToken), balanceIT ); yVault.deposit(); } } function _repayInvestmentTokenDebt(uint256 amount) internal { if (amount == 0) { return; } uint256 debt = balanceOfDebt(); uint256 balanceIT = balanceOfInvestmentToken(); _checkAllowance( MakerDaiDelegateLib.daiJoinAddress(), address(investmentToken), amount ); if (amount > 0) { if (debt.sub(amount) == 0 && balanceIT.sub(amount) >= 1) { amount = amount.add(1); } } } function _repayInvestmentTokenDebt(uint256 amount) internal { if (amount == 0) { return; } uint256 debt = balanceOfDebt(); uint256 balanceIT = balanceOfInvestmentToken(); _checkAllowance( MakerDaiDelegateLib.daiJoinAddress(), address(investmentToken), amount ); if (amount > 0) { if (debt.sub(amount) == 0 && balanceIT.sub(amount) >= 1) { amount = amount.add(1); } } } amount = Math.min(amount, balanceIT); amount = Math.min(amount, debt); function _repayInvestmentTokenDebt(uint256 amount) internal { if (amount == 0) { return; } uint256 debt = balanceOfDebt(); uint256 balanceIT = balanceOfInvestmentToken(); _checkAllowance( MakerDaiDelegateLib.daiJoinAddress(), address(investmentToken), amount ); if (amount > 0) { if (debt.sub(amount) == 0 && balanceIT.sub(amount) >= 1) { amount = amount.add(1); } } } function _repayInvestmentTokenDebt(uint256 amount) internal { if (amount == 0) { return; } uint256 debt = balanceOfDebt(); uint256 balanceIT = balanceOfInvestmentToken(); _checkAllowance( MakerDaiDelegateLib.daiJoinAddress(), address(investmentToken), amount ); if (amount > 0) { if (debt.sub(amount) == 0 && balanceIT.sub(amount) >= 1) { amount = amount.add(1); } } } _freeCollateralAndRepayDai(0, amount); function _checkAllowance( address _contract, address _token, uint256 _amount ) internal { if (IERC20(_token).allowance(address(this), _contract) < _amount) { IERC20(_token).safeApprove(_contract, 0); IERC20(_token).safeApprove(_contract, type(uint256).max); } } function _checkAllowance( address _contract, address _token, uint256 _amount ) internal { if (IERC20(_token).allowance(address(this), _contract) < _amount) { IERC20(_token).safeApprove(_contract, 0); IERC20(_token).safeApprove(_contract, type(uint256).max); } } function _takeYVaultProfit() internal { uint256 _debt = balanceOfDebt(); uint256 _valueInVault = _valueOfInvestment(); if (_debt >= _valueInVault) { return; } uint256 profit = _valueInVault.sub(_debt); uint256 ySharesToWithdraw = _investmentTokenToYShares(profit); if (ySharesToWithdraw > 0) { yVault.withdraw(ySharesToWithdraw, address(this), maxLoss); _sellAForB( balanceOfInvestmentToken(), address(investmentToken), address(want) ); } } function _takeYVaultProfit() internal { uint256 _debt = balanceOfDebt(); uint256 _valueInVault = _valueOfInvestment(); if (_debt >= _valueInVault) { return; } uint256 profit = _valueInVault.sub(_debt); uint256 ySharesToWithdraw = _investmentTokenToYShares(profit); if (ySharesToWithdraw > 0) { yVault.withdraw(ySharesToWithdraw, address(this), maxLoss); _sellAForB( balanceOfInvestmentToken(), address(investmentToken), address(want) ); } } function _takeYVaultProfit() internal { uint256 _debt = balanceOfDebt(); uint256 _valueInVault = _valueOfInvestment(); if (_debt >= _valueInVault) { return; } uint256 profit = _valueInVault.sub(_debt); uint256 ySharesToWithdraw = _investmentTokenToYShares(profit); if (ySharesToWithdraw > 0) { yVault.withdraw(ySharesToWithdraw, address(this), maxLoss); _sellAForB( balanceOfInvestmentToken(), address(investmentToken), address(want) ); } } function _depositToMakerVault(uint256 amount) internal { if (amount == 0) { return; } _checkAllowance(gemJoinAdapter, address(want), amount); uint256 price = _getWantTokenPrice(); uint256 daiToMint = amount.mul(price).mul(MAX_BPS).div(collateralizationRatio).div(WAD); _lockCollateralAndMintDai(amount, daiToMint); } function _depositToMakerVault(uint256 amount) internal { if (amount == 0) { return; } _checkAllowance(gemJoinAdapter, address(want), amount); uint256 price = _getWantTokenPrice(); uint256 daiToMint = amount.mul(price).mul(MAX_BPS).div(collateralizationRatio).div(WAD); _lockCollateralAndMintDai(amount, daiToMint); } function _maxWithdrawal() internal view returns (uint256) { uint256 totalCollateral = balanceOfMakerVault(); uint256 totalDebt = balanceOfDebt(); if (totalDebt == 0) { return totalCollateral; } uint256 price = _getWantTokenPrice(); collateralizationRatio .sub(rebalanceTolerance) .mul(totalDebt) .mul(WAD) .div(price) .div(MAX_BPS); if (minCollateral > totalCollateral) { return 0; } return totalCollateral.sub(minCollateral); } function _maxWithdrawal() internal view returns (uint256) { uint256 totalCollateral = balanceOfMakerVault(); uint256 totalDebt = balanceOfDebt(); if (totalDebt == 0) { return totalCollateral; } uint256 price = _getWantTokenPrice(); collateralizationRatio .sub(rebalanceTolerance) .mul(totalDebt) .mul(WAD) .div(price) .div(MAX_BPS); if (minCollateral > totalCollateral) { return 0; } return totalCollateral.sub(minCollateral); } uint256 minCollateral = function _maxWithdrawal() internal view returns (uint256) { uint256 totalCollateral = balanceOfMakerVault(); uint256 totalDebt = balanceOfDebt(); if (totalDebt == 0) { return totalCollateral; } uint256 price = _getWantTokenPrice(); collateralizationRatio .sub(rebalanceTolerance) .mul(totalDebt) .mul(WAD) .div(price) .div(MAX_BPS); if (minCollateral > totalCollateral) { return 0; } return totalCollateral.sub(minCollateral); } function balanceOfWant() public view returns (uint256) { return want.balanceOf(address(this)); } function balanceOfInvestmentToken() public view returns (uint256) { return investmentToken.balanceOf(address(this)); } function balanceOfDebt() public view returns (uint256) { return MakerDaiDelegateLib.debtForCdp(cdpId, ilk); } function balanceOfMakerVault() public view returns (uint256) { return MakerDaiDelegateLib.balanceOfCdp(cdpId, ilk); } function getCurrentMakerVaultRatio() public view returns (uint256) { return MakerDaiDelegateLib.getPessimisticRatioOfCdpWithExternalPrice( cdpId, ilk, _getWantTokenPrice(), MAX_BPS ); } function isCurrentBaseFeeAcceptable() public view returns (bool) { uint256 baseFee; try baseFeeProvider.basefee_global() returns (uint256 currentBaseFee) { baseFee = currentBaseFee; baseFee = 1000 * 1e9; } return baseFee <= maxAcceptableBaseFee; } function isCurrentBaseFeeAcceptable() public view returns (bool) { uint256 baseFee; try baseFeeProvider.basefee_global() returns (uint256 currentBaseFee) { baseFee = currentBaseFee; baseFee = 1000 * 1e9; } return baseFee <= maxAcceptableBaseFee; } } catch { function _getWantTokenPrice() internal view returns (uint256) { uint256 minPrice = MakerDaiDelegateLib.getSpotPrice(ilk); try wantToUSDOSMProxy.read() returns ( uint256 current, bool currentIsValid ) { if (currentIsValid && current > 0) { minPrice = Math.min(minPrice, current); } uint256 future, bool futureIsValid ) { if (futureIsValid && future > 0) { minPrice = Math.min(minPrice, future); } } function _getWantTokenPrice() internal view returns (uint256) { uint256 minPrice = MakerDaiDelegateLib.getSpotPrice(ilk); try wantToUSDOSMProxy.read() returns ( uint256 current, bool currentIsValid ) { if (currentIsValid && current > 0) { minPrice = Math.min(minPrice, current); } uint256 future, bool futureIsValid ) { if (futureIsValid && future > 0) { minPrice = Math.min(minPrice, future); } } function _getWantTokenPrice() internal view returns (uint256) { uint256 minPrice = MakerDaiDelegateLib.getSpotPrice(ilk); try wantToUSDOSMProxy.read() returns ( uint256 current, bool currentIsValid ) { if (currentIsValid && current > 0) { minPrice = Math.min(minPrice, current); } uint256 future, bool futureIsValid ) { if (futureIsValid && future > 0) { minPrice = Math.min(minPrice, future); } } } catch { } try wantToUSDOSMProxy.foresight() returns ( function _getWantTokenPrice() internal view returns (uint256) { uint256 minPrice = MakerDaiDelegateLib.getSpotPrice(ilk); try wantToUSDOSMProxy.read() returns ( uint256 current, bool currentIsValid ) { if (currentIsValid && current > 0) { minPrice = Math.min(minPrice, current); } uint256 future, bool futureIsValid ) { if (futureIsValid && future > 0) { minPrice = Math.min(minPrice, future); } } function _getWantTokenPrice() internal view returns (uint256) { uint256 minPrice = MakerDaiDelegateLib.getSpotPrice(ilk); try wantToUSDOSMProxy.read() returns ( uint256 current, bool currentIsValid ) { if (currentIsValid && current > 0) { minPrice = Math.min(minPrice, current); } uint256 future, bool futureIsValid ) { if (futureIsValid && future > 0) { minPrice = Math.min(minPrice, future); } } } catch { } return minPrice.mul(RAY).div(MakerDaiDelegateLib.getDaiPar()); function _valueOfInvestment() internal view returns (uint256) { return yVault.balanceOf(address(this)).mul(yVault.pricePerShare()).div( 10**yVault.decimals() ); } function _investmentTokenToYShares(uint256 amount) internal view returns (uint256) { return amount.mul(10**yVault.decimals()).div(yVault.pricePerShare()); } function _lockCollateralAndMintDai( uint256 collateralAmount, uint256 daiToMint ) internal { MakerDaiDelegateLib.lockGemAndDraw( gemJoinAdapter, cdpId, collateralAmount, daiToMint, balanceOfDebt() ); } function _freeCollateralAndRepayDai( uint256 collateralAmount, uint256 daiToRepay ) internal { MakerDaiDelegateLib.wipeAndFreeGem( gemJoinAdapter, cdpId, collateralAmount, daiToRepay ); } function _convertInvestmentTokenToWant(uint256 amount) internal view returns (uint256) { return amount.mul(WAD).div(_getWantTokenPrice()); } function _getTokenOutPath(address _token_in, address _token_out) internal pure returns (address[] memory _path) { bool is_weth = _token_in == address(WETH) || _token_out == address(WETH); _path = new address[](is_weth ? 2 : 3); _path[0] = _token_in; if (is_weth) { _path[1] = _token_out; _path[1] = address(WETH); _path[2] = _token_out; } } function _getTokenOutPath(address _token_in, address _token_out) internal pure returns (address[] memory _path) { bool is_weth = _token_in == address(WETH) || _token_out == address(WETH); _path = new address[](is_weth ? 2 : 3); _path[0] = _token_in; if (is_weth) { _path[1] = _token_out; _path[1] = address(WETH); _path[2] = _token_out; } } } else { function _sellAForB( uint256 _amount, address tokenA, address tokenB ) internal { if (_amount == 0 || tokenA == tokenB) { return; } _checkAllowance(address(router), tokenA, _amount); router.swapExactTokensForTokens( _amount, 0, _getTokenOutPath(tokenA, tokenB), address(this), now ); } function _sellAForB( uint256 _amount, address tokenA, address tokenB ) internal { if (_amount == 0 || tokenA == tokenB) { return; } _checkAllowance(address(router), tokenA, _amount); router.swapExactTokensForTokens( _amount, 0, _getTokenOutPath(tokenA, tokenB), address(this), now ); } function _buyInvestmentTokenWithWant(uint256 _amount) internal { if (_amount == 0 || address(investmentToken) == address(want)) { return; } _checkAllowance(address(router), address(want), _amount); router.swapTokensForExactTokens( _amount, type(uint256).max, _getTokenOutPath(address(want), address(investmentToken)), address(this), now ); } function _buyInvestmentTokenWithWant(uint256 _amount) internal { if (_amount == 0 || address(investmentToken) == address(want)) { return; } _checkAllowance(address(router), address(want), _amount); router.swapTokensForExactTokens( _amount, type(uint256).max, _getTokenOutPath(address(want), address(investmentToken)), address(this), now ); } }
508,371
[ 1, 7537, 1399, 316, 490, 6388, 20092, 463, 18194, 1147, 2130, 9, 18848, 8324, 603, 598, 9446, 287, 628, 677, 12003, 24506, 512, 1136, 300, 10286, 364, 1352, 6679, 7502, 348, 1218, 77, 12521, 4633, 1351, 291, 91, 438, 4633, 7561, 358, 855, 783, 1203, 1807, 1026, 14036, 3155, 14238, 5924, 364, 4508, 2045, 287, 490, 6388, 28544, 6036, 5924, 2672, 7824, 1232, 20865, 358, 7161, 4891, 2545, 19, 1584, 44, 6205, 463, 18194, 677, 12003, 9703, 1399, 364, 1352, 6679, 17596, 2045, 287, 618, 29613, 9229, 2756, 29613, 6049, 4508, 2045, 1588, 7169, 7852, 326, 4508, 2045, 287, 1588, 7169, 358, 25217, 279, 2831, 316, 1353, 358, 4543, 15139, 4238, 14206, 1026, 14036, 358, 4862, 1898, 18202, 88, 578, 17895, 26923, 18848, 14206, 8324, 603, 598, 9446, 287, 18, 2989, 358, 374, 18, 1611, 9, 18, 971, 444, 358, 638, 326, 6252, 903, 5903, 775, 358, 2071, 528, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 16351, 19736, 353, 3360, 4525, 288, 203, 565, 1450, 14060, 654, 39, 3462, 364, 467, 654, 39, 3462, 31, 203, 565, 1450, 5267, 364, 1758, 31, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 203, 565, 2254, 5034, 2713, 5381, 678, 1880, 273, 1728, 636, 2643, 31, 203, 565, 2254, 5034, 2713, 5381, 534, 5255, 273, 1728, 636, 5324, 31, 203, 203, 565, 467, 654, 39, 3462, 2713, 5381, 2198, 395, 475, 1345, 273, 203, 3639, 467, 654, 39, 3462, 12, 20, 92, 26, 38, 4033, 6564, 5608, 41, 6675, 5908, 24, 39, 6334, 40, 69, 10689, 70, 29, 6564, 41, 73, 323, 2226, 7616, 25, 5324, 21, 72, 20, 42, 1769, 203, 203, 565, 2254, 5034, 2713, 5381, 4552, 67, 38, 5857, 273, 678, 1880, 31, 203, 203, 565, 2254, 5034, 2713, 5381, 4552, 67, 1502, 1260, 67, 38, 5857, 273, 12619, 31, 203, 203, 565, 1758, 2713, 5381, 678, 1584, 44, 273, 374, 14626, 3103, 7598, 37, 5520, 70, 3787, 23, 8090, 28, 40, 20, 37, 20, 73, 25, 39, 24, 42, 5324, 73, 1880, 29, 6840, 23, 39, 27, 4313, 39, 71, 22, 31, 203, 203, 565, 4437, 91, 438, 2713, 5381, 272, 1218, 291, 91, 438, 8259, 273, 203, 3639, 4437, 91, 438, 12, 20, 7669, 29, 73, 21, 71, 41, 4033, 74, 23728, 21, 74, 3247, 69, 41, 10261, 4449, 27, 378, 6028, 69, 22, 952, 69, 29, 39, 6418, 28, 38, 29, 42, 1769, 203, 203, 565, 4437, 91, 438, 2713, 5381, 640, 291, 91, 438, 2 ]
./full_match/1/0x21FfcbdbdD2C0f59d779Cf8f1FD0A87b5F84bc44/sources/SproutToken.sol
* @notice Overload OpenZepplin internal _transfer() function to add extra require statement preventing transferring tokens to the contract address @param _sender The senders address @param _recipient The recipients address @param _amount Amount of tokens to transfer (in wei units) @dev Moves tokens `amount` from `sender` to `recipient`. Additional requirements: - `_recipient` cannot be the token contract address./
function _transfer(address _sender, address _recipient, uint256 _amount) internal override { require(_recipient != address(this), "SproutToken: transfer to token contract"); require(_recipient != mEcoFiTokenContract, "SproutToken: transfer to ECO token contract"); generateTokensFromStake(); super._transfer(_sender, _recipient, _amount); }
3,126,759
[ 1, 4851, 945, 3502, 62, 881, 412, 267, 2713, 389, 13866, 1435, 445, 358, 527, 2870, 2583, 3021, 5309, 310, 906, 74, 20245, 2430, 358, 326, 6835, 1758, 225, 389, 15330, 1021, 1366, 414, 1758, 225, 389, 20367, 1021, 12045, 1758, 225, 389, 8949, 16811, 434, 2430, 358, 7412, 261, 267, 732, 77, 4971, 13, 225, 490, 10829, 2430, 1375, 8949, 68, 628, 1375, 15330, 68, 358, 1375, 20367, 8338, 15119, 8433, 30, 300, 1375, 67, 20367, 68, 2780, 506, 326, 1147, 6835, 1758, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 13866, 12, 2867, 389, 15330, 16, 1758, 389, 20367, 16, 2254, 5034, 389, 8949, 13, 2713, 3849, 288, 203, 3639, 2583, 24899, 20367, 480, 1758, 12, 2211, 3631, 315, 55, 685, 322, 1345, 30, 7412, 358, 1147, 6835, 8863, 203, 3639, 2583, 24899, 20367, 480, 312, 41, 2894, 42, 77, 1345, 8924, 16, 315, 55, 685, 322, 1345, 30, 7412, 358, 512, 3865, 1147, 6835, 8863, 203, 3639, 2103, 5157, 1265, 510, 911, 5621, 203, 3639, 2240, 6315, 13866, 24899, 15330, 16, 389, 20367, 16, 389, 8949, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/80001/0x2d3B52Ab8233f29c7F189B6AAbD4AF8de3036cC4/sources/contracts/mixins/MixinLockMetadata.sol
* @dev Gets the token symbol @return string representing the token name/
function symbol() external view returns (string memory) { if (bytes(lockSymbol).length == 0) { return unlockProtocol.globalTokenSymbol(); return lockSymbol; } }
9,435,293
[ 1, 3002, 326, 1147, 3273, 327, 533, 5123, 326, 1147, 508, 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, 225, 445, 3273, 1435, 3903, 1476, 1135, 261, 1080, 3778, 13, 288, 203, 565, 309, 261, 3890, 12, 739, 5335, 2934, 2469, 422, 374, 13, 288, 203, 1377, 327, 7186, 5752, 18, 6347, 1345, 5335, 5621, 203, 1377, 327, 2176, 5335, 31, 203, 565, 289, 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 ]
./full_match/4/0xC9434231534B8fab79d9226e1b443c372A966F65/sources/contracts/governance/Managed.sol
* @dev Return EpochManager interface. @return Epoch manager contract registered with Controller/
function epochManager() internal view returns (IEpochManager) { return IEpochManager(_resolveContract(keccak256("EpochManager"))); }
649,255
[ 1, 990, 512, 6127, 1318, 1560, 18, 327, 512, 6127, 3301, 6835, 4104, 598, 6629, 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, 565, 445, 7632, 1318, 1435, 2713, 1476, 1135, 261, 8732, 6127, 1318, 13, 288, 203, 3639, 327, 10897, 6127, 1318, 24899, 10828, 8924, 12, 79, 24410, 581, 5034, 2932, 14638, 1318, 6, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0xCCBECCd69D6B3Fa78652d6C70a6C435F59621196/sources/KushoStaking.sol
Interfaces for ERC20 and ERC721 Constructor function to set the rewards token and the NFT collection addresses
contract KushoStaking is Ownable, ReentrancyGuard { using SafeERC20 for IERC20; IERC20 public immutable rewardsToken; IERC721 public immutable nftCollection; pragma solidity ^0.8.4; constructor(IERC721 _nftCollection, IERC20 _rewardsToken) { nftCollection = _nftCollection; rewardsToken = _rewardsToken; } struct StakedToken { address staker; uint256 tokenId; } struct Staker { uint256 amountStaked; StakedToken[] stakedTokens; uint256 timeOfLastUpdate; uint256 unclaimedRewards; } uint256 private rewardsPerHour = 125000000000000000; bool public pause = false; mapping(address => Staker) public stakers; mapping(uint256 => address) public stakerAddress; function pauseStaking() external onlyOwner{ pause = !pause; } function stake(uint256[] calldata tokenIds) external nonReentrant { if (stakers[msg.sender].amountStaked > 0) { uint256 rewards = calculateRewards(msg.sender); stakers[msg.sender].unclaimedRewards += rewards; } for (uint256 i; i < tokenIds.length;) { uint256 _tokenId = tokenIds[i]; require( nftCollection.ownerOf(_tokenId) == msg.sender, "You don't own this token!" ); nftCollection.transferFrom(msg.sender, address(this), _tokenId); StakedToken memory stakedToken = StakedToken(msg.sender, _tokenId); stakers[msg.sender].stakedTokens.push(stakedToken); stakers[msg.sender].amountStaked++; stakerAddress[_tokenId] = msg.sender; stakers[msg.sender].timeOfLastUpdate = block.timestamp; ++i; } } function stake(uint256[] calldata tokenIds) external nonReentrant { if (stakers[msg.sender].amountStaked > 0) { uint256 rewards = calculateRewards(msg.sender); stakers[msg.sender].unclaimedRewards += rewards; } for (uint256 i; i < tokenIds.length;) { uint256 _tokenId = tokenIds[i]; require( nftCollection.ownerOf(_tokenId) == msg.sender, "You don't own this token!" ); nftCollection.transferFrom(msg.sender, address(this), _tokenId); StakedToken memory stakedToken = StakedToken(msg.sender, _tokenId); stakers[msg.sender].stakedTokens.push(stakedToken); stakers[msg.sender].amountStaked++; stakerAddress[_tokenId] = msg.sender; stakers[msg.sender].timeOfLastUpdate = block.timestamp; ++i; } } function stake(uint256[] calldata tokenIds) external nonReentrant { if (stakers[msg.sender].amountStaked > 0) { uint256 rewards = calculateRewards(msg.sender); stakers[msg.sender].unclaimedRewards += rewards; } for (uint256 i; i < tokenIds.length;) { uint256 _tokenId = tokenIds[i]; require( nftCollection.ownerOf(_tokenId) == msg.sender, "You don't own this token!" ); nftCollection.transferFrom(msg.sender, address(this), _tokenId); StakedToken memory stakedToken = StakedToken(msg.sender, _tokenId); stakers[msg.sender].stakedTokens.push(stakedToken); stakers[msg.sender].amountStaked++; stakerAddress[_tokenId] = msg.sender; stakers[msg.sender].timeOfLastUpdate = block.timestamp; ++i; } } function unstake(uint256[] calldata tokenIds) external nonReentrant { require( stakers[msg.sender].amountStaked > 0, "You have no tokens staked" ); for (uint256 i; i < tokenIds.length;) { uint256 _tokenId = tokenIds[i]; require(stakerAddress[_tokenId] == msg.sender, "You don't own this token!"); uint256 rewards = calculateRewards(msg.sender); stakers[msg.sender].unclaimedRewards += rewards; uint256 index = 0; for (uint256 j = 0; j < stakers[msg.sender].stakedTokens.length; j++) { if (stakers[msg.sender].stakedTokens[j].tokenId == _tokenId) { index = j; break; } } stakers[msg.sender].stakedTokens[index].staker = address(0); stakers[msg.sender].amountStaked--; stakerAddress[_tokenId] = address(0); nftCollection.transferFrom(address(this), msg.sender, _tokenId); stakers[msg.sender].timeOfLastUpdate = block.timestamp; ++i; } } function unstake(uint256[] calldata tokenIds) external nonReentrant { require( stakers[msg.sender].amountStaked > 0, "You have no tokens staked" ); for (uint256 i; i < tokenIds.length;) { uint256 _tokenId = tokenIds[i]; require(stakerAddress[_tokenId] == msg.sender, "You don't own this token!"); uint256 rewards = calculateRewards(msg.sender); stakers[msg.sender].unclaimedRewards += rewards; uint256 index = 0; for (uint256 j = 0; j < stakers[msg.sender].stakedTokens.length; j++) { if (stakers[msg.sender].stakedTokens[j].tokenId == _tokenId) { index = j; break; } } stakers[msg.sender].stakedTokens[index].staker = address(0); stakers[msg.sender].amountStaked--; stakerAddress[_tokenId] = address(0); nftCollection.transferFrom(address(this), msg.sender, _tokenId); stakers[msg.sender].timeOfLastUpdate = block.timestamp; ++i; } } function unstake(uint256[] calldata tokenIds) external nonReentrant { require( stakers[msg.sender].amountStaked > 0, "You have no tokens staked" ); for (uint256 i; i < tokenIds.length;) { uint256 _tokenId = tokenIds[i]; require(stakerAddress[_tokenId] == msg.sender, "You don't own this token!"); uint256 rewards = calculateRewards(msg.sender); stakers[msg.sender].unclaimedRewards += rewards; uint256 index = 0; for (uint256 j = 0; j < stakers[msg.sender].stakedTokens.length; j++) { if (stakers[msg.sender].stakedTokens[j].tokenId == _tokenId) { index = j; break; } } stakers[msg.sender].stakedTokens[index].staker = address(0); stakers[msg.sender].amountStaked--; stakerAddress[_tokenId] = address(0); nftCollection.transferFrom(address(this), msg.sender, _tokenId); stakers[msg.sender].timeOfLastUpdate = block.timestamp; ++i; } } function unstake(uint256[] calldata tokenIds) external nonReentrant { require( stakers[msg.sender].amountStaked > 0, "You have no tokens staked" ); for (uint256 i; i < tokenIds.length;) { uint256 _tokenId = tokenIds[i]; require(stakerAddress[_tokenId] == msg.sender, "You don't own this token!"); uint256 rewards = calculateRewards(msg.sender); stakers[msg.sender].unclaimedRewards += rewards; uint256 index = 0; for (uint256 j = 0; j < stakers[msg.sender].stakedTokens.length; j++) { if (stakers[msg.sender].stakedTokens[j].tokenId == _tokenId) { index = j; break; } } stakers[msg.sender].stakedTokens[index].staker = address(0); stakers[msg.sender].amountStaked--; stakerAddress[_tokenId] = address(0); nftCollection.transferFrom(address(this), msg.sender, _tokenId); stakers[msg.sender].timeOfLastUpdate = block.timestamp; ++i; } } function claimRewards() external { uint256 rewards = calculateRewards(msg.sender) + stakers[msg.sender].unclaimedRewards; require(rewards > 0, "You have no rewards to claim"); stakers[msg.sender].timeOfLastUpdate = block.timestamp; stakers[msg.sender].unclaimedRewards = 0; rewardsToken.safeTransfer(msg.sender, rewards); } function availableRewards(address _staker) public view returns (uint256) { uint256 rewards = calculateRewards(_staker) + stakers[_staker].unclaimedRewards; return rewards; } function getStakedTokens(address _user) public view returns (StakedToken[] memory) { if (stakers[_user].amountStaked > 0) { StakedToken[] memory _stakedTokens = new StakedToken[](stakers[_user].amountStaked); uint256 _index = 0; for (uint256 j = 0; j < stakers[_user].stakedTokens.length; j++) { if (stakers[_user].stakedTokens[j].staker != (address(0))) { _stakedTokens[_index] = stakers[_user].stakedTokens[j]; _index++; } } return _stakedTokens; } else { return new StakedToken[](0); } } function getStakedTokens(address _user) public view returns (StakedToken[] memory) { if (stakers[_user].amountStaked > 0) { StakedToken[] memory _stakedTokens = new StakedToken[](stakers[_user].amountStaked); uint256 _index = 0; for (uint256 j = 0; j < stakers[_user].stakedTokens.length; j++) { if (stakers[_user].stakedTokens[j].staker != (address(0))) { _stakedTokens[_index] = stakers[_user].stakedTokens[j]; _index++; } } return _stakedTokens; } else { return new StakedToken[](0); } } function getStakedTokens(address _user) public view returns (StakedToken[] memory) { if (stakers[_user].amountStaked > 0) { StakedToken[] memory _stakedTokens = new StakedToken[](stakers[_user].amountStaked); uint256 _index = 0; for (uint256 j = 0; j < stakers[_user].stakedTokens.length; j++) { if (stakers[_user].stakedTokens[j].staker != (address(0))) { _stakedTokens[_index] = stakers[_user].stakedTokens[j]; _index++; } } return _stakedTokens; } else { return new StakedToken[](0); } } function getStakedTokens(address _user) public view returns (StakedToken[] memory) { if (stakers[_user].amountStaked > 0) { StakedToken[] memory _stakedTokens = new StakedToken[](stakers[_user].amountStaked); uint256 _index = 0; for (uint256 j = 0; j < stakers[_user].stakedTokens.length; j++) { if (stakers[_user].stakedTokens[j].staker != (address(0))) { _stakedTokens[_index] = stakers[_user].stakedTokens[j]; _index++; } } return _stakedTokens; } else { return new StakedToken[](0); } } function getStakedTokens(address _user) public view returns (StakedToken[] memory) { if (stakers[_user].amountStaked > 0) { StakedToken[] memory _stakedTokens = new StakedToken[](stakers[_user].amountStaked); uint256 _index = 0; for (uint256 j = 0; j < stakers[_user].stakedTokens.length; j++) { if (stakers[_user].stakedTokens[j].staker != (address(0))) { _stakedTokens[_index] = stakers[_user].stakedTokens[j]; _index++; } } return _stakedTokens; } else { return new StakedToken[](0); } } function calculateRewards(address _staker) internal view returns (uint256 _rewards) { if (pause) { return (0); return ((( ((block.timestamp - stakers[_staker].timeOfLastUpdate) * stakers[_staker].amountStaked) ) * rewardsPerHour) / 3600); } } function calculateRewards(address _staker) internal view returns (uint256 _rewards) { if (pause) { return (0); return ((( ((block.timestamp - stakers[_staker].timeOfLastUpdate) * stakers[_staker].amountStaked) ) * rewardsPerHour) / 3600); } } } else { }
5,686,690
[ 1, 10273, 364, 4232, 39, 3462, 471, 4232, 39, 27, 5340, 11417, 445, 358, 444, 326, 283, 6397, 1147, 471, 326, 423, 4464, 1849, 6138, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 1475, 1218, 83, 510, 6159, 353, 14223, 6914, 16, 868, 8230, 12514, 16709, 288, 203, 565, 1450, 14060, 654, 39, 3462, 364, 467, 654, 39, 3462, 31, 203, 203, 565, 467, 654, 39, 3462, 1071, 11732, 283, 6397, 1345, 31, 203, 565, 467, 654, 39, 27, 5340, 1071, 11732, 290, 1222, 2532, 31, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 24, 31, 203, 565, 3885, 12, 45, 654, 39, 27, 5340, 389, 82, 1222, 2532, 16, 467, 654, 39, 3462, 389, 266, 6397, 1345, 13, 288, 203, 3639, 290, 1222, 2532, 273, 389, 82, 1222, 2532, 31, 203, 3639, 283, 6397, 1345, 273, 389, 266, 6397, 1345, 31, 203, 565, 289, 203, 203, 565, 1958, 934, 9477, 1345, 288, 203, 3639, 1758, 384, 6388, 31, 203, 3639, 2254, 5034, 1147, 548, 31, 203, 565, 289, 203, 203, 565, 1958, 934, 6388, 288, 203, 3639, 2254, 5034, 3844, 510, 9477, 31, 203, 203, 3639, 934, 9477, 1345, 8526, 384, 9477, 5157, 31, 203, 203, 3639, 2254, 5034, 813, 951, 3024, 1891, 31, 203, 203, 3639, 2254, 5034, 6301, 80, 4581, 329, 17631, 14727, 31, 203, 565, 289, 203, 203, 203, 203, 203, 203, 565, 2254, 5034, 3238, 283, 6397, 2173, 13433, 273, 30616, 12648, 17877, 31, 203, 565, 1426, 1071, 11722, 273, 629, 31, 203, 565, 2874, 12, 2867, 516, 934, 6388, 13, 1071, 384, 581, 414, 31, 203, 565, 2874, 12, 11890, 5034, 516, 1758, 13, 1071, 384, 6388, 1887, 31, 203, 565, 445, 11722, 510, 6159, 1435, 3903, 2 ]
pragma solidity^0.4.23; import "./InvestableDAL.sol"; contract AffiliateDAL is InvestableDAL { //... } mapping(address => uint) affiliate; function getAffiliatePay() public { //... } uint amount = affiliate[msg.sender]; require(amount > 0); msg.senser.transfer(amount); affiliate[msg.sender] = 0; function play(uint _hash, address _affiliate) payable public { //... } uint ticketValue = msg.value; if(_affiliate != address(0)) { uint affiliateAmount = msg.value * (1/100); affiliate[msg.sender] += affiliateAmount; ticketValue = msg.value - affiliateAmount; } //... pragma solidity^0.4.23; import "./InvestableDAL.sol"; contract AffiliateDAL is InvestableDAL { mapping(address => uint) affiliate; /** * @dev Function to get affiliate payout */ function getAffiliatePay() public { uint amount = affiliate[msg.sender]; require(amount > 0); msg.senser.transfer(amount); affiliate[msg.sender] = 0; } /** * @dev Modified play function with affiliate * @param _hash Guessed number * @param _affiliate Address of the affiliate */ function play(uint _hash, address _affiliate) payable public { uint ticketValue = msg.value; if(_affiliate != address(0)) { uint affiliateAmount = msg.value * (1/100); affiliate[msg.sender] += affiliateAmount; ticketValue = msg.value - affiliateAmount; } //... } }
* @dev Function to get affiliate payout/
function play(uint _hash, address _affiliate) } uint ticketValue = msg.value; } pragma solidity^0.4.23; import "./InvestableDAL.sol"; function getAffiliatePay() public { uint amount = affiliate[msg.sender]; require(amount > 0); msg.senser.transfer(amount); affiliate[msg.sender] = 0; }
1,757,265
[ 1, 2083, 358, 336, 7103, 330, 3840, 293, 2012, 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 ]
[ 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, 915, 6599, 12, 11890, 389, 2816, 16, 1758, 389, 7329, 330, 3840, 13, 225, 203, 97, 203, 203, 203, 11890, 9322, 620, 273, 1234, 18, 1132, 31, 203, 203, 97, 203, 203, 203, 203, 203, 683, 9454, 18035, 560, 66, 20, 18, 24, 18, 4366, 31, 203, 203, 5666, 25165, 3605, 395, 429, 40, 1013, 18, 18281, 14432, 203, 203, 565, 445, 4506, 1403, 330, 3840, 9148, 1435, 1071, 288, 203, 3639, 2254, 3844, 273, 7103, 330, 3840, 63, 3576, 18, 15330, 15533, 203, 3639, 2583, 12, 8949, 405, 374, 1769, 203, 203, 3639, 1234, 18, 87, 275, 550, 18, 13866, 12, 8949, 1769, 203, 3639, 7103, 330, 3840, 63, 3576, 18, 15330, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// RUN: --emit cfg contract c2 { int public cd; function sum(int32 a, int32 b) public pure returns (int32) { return a+b; } // BEGIN-CHECK: function::doSomething function doSomething() public returns (int, int) { cd=2; // CHECK: store storage slot(uint256 0) ty:int256 = return (1, 2); } } contract c { int32 g; // BEGIN-CHECK: c::function::test function test() public returns (int32) { int32 x = 102; g = 3; return 5; // NOT-CHECK: ty:int32 %x = int32 102 } // BEGIN-CHECK: c::function::test2 function test2() public view returns (int32) { int32 x = 102; int32 y = 93; int32 t = 9; x = 102 + t*y/(t+5*y) + g; return 2; // NOT-CHECK: ty:int32 %x = int32 102 // NOT-CHECK: ty:int32 %x = (int32 103 + %temp.6) } // BEGIN-CHECK: c::function::test3 function test3() public view returns (int32) { int32 x; int32 y = 93; int32 t = 9; x = 102 + t*y/(t+5*y) + g; return 2; // NOT-CHECK: ty:int32 %x = (int32 103 + %temp.6) } // BEGIN-CHECK: c::function::test4 function test4() public view returns (int32) { int32 x; int32 y = 93; int32 t = 9; x = 102 + t*y/(t+5*y) + g + test3(); return 2; // NOT-CHECK: ty:int32 %x = (int32 103 + %temp.6) // CHECK: call c::c::function::test3 } // BEGIN-CHECK: c::function::test5 function test5() public returns (int32) { int32 x; int32[] vec; int32 y = 93; int32 t = 9; c2 ct = new c2(); x = 102 + t*y/(t+5*y) + g + test3() - vec.push(2) + ct.sum(1, 2); return 2; // CHECK: push array ty:int32[] value:int32 2 // CHECK: _ = external call::regular address:%ct payload:(abiencode packed:bytes4 2438430579 non-packed:int32 1, int32 2) value:uint128 0 gas:uint64 0 } } contract c3 { // BEGIN-CHECK: c3::function::test6 function test6() public returns (int32) { c2 ct = new c2(); return 3; // CHECK: constructor salt: value: gas:uint64 0 space: c2 #None () } // BEGIN-CHECK: c3::function::test7 function test7() public returns (int32) { c2 ct = new c2(); // CHECK: constructor salt: value: gas:uint64 0 space: c2 #None () address ad = address(ct); (bool p, ) = ad.call(hex'ba'); // CHECK: external call::regular address:%ad payload:(alloc bytes uint32 1 hex"ba") value:uint128 0 gas:uint64 0 // NOT-CHECk: ty:bool %p = %success.temp.30 return 3; } struct testStruct { int a; int b; } testStruct t1; int public it1; int private it2; // BEGIN-CHECK: c3::function::test8 function test8() public returns (int){ testStruct storage t2 = t1; t2.a = 5; it1 = 2; testStruct memory t3 = testStruct(1, 2); int[] memory vec = new int[](5); vec[0] = 3; it2 = 1; return 2; // CHECK: store storage slot((%t2 + uint256 0)) ty:int256 = // CHECK: store storage slot(uint256 2) ty:int256 = // NOT-CHECK: ty:struct c1.testStruct %t3 = struct { int256 1, int256 2 } // NOT-CHECK: alloc int256[] len uint32 5 // NOT-CHECK: store storage slot(uint256 3) ty:int256 } // BEGIN-CHECK: c3::function::test9 function test9() public view returns (int) { int f = 4; int c = 32 +4 *(f = it1+it2); //CHECK: ty:int256 %f = return f; } // BEGIN-CHECK: c3::function::test10 function test10() public view returns (int) { int f = 4; int c = 32 +4 *(f = it1+it2); // CHECK: ty:int256 %c = (int256 32 + (sext int256 (int64 4 * (trunc int64 (%temp.67 + %temp.68))))) // NOT-CHECK: ty:int256 %f = (%temp.10 + %temp.11) return c; } // BEGIN-CHECK: c3::function::test11 function test11() public returns (int) { c2 ct = new c2(); (int a, int b) = ct.doSomething(); // CHECK: ty:int256 %b = // NOT-CHECK: ty:int256 %a = return b; } // BEGIN-CHECK: c3::function::test12 function test12() public returns (int) { c2 ct = new c2(); int a = 1; int b = 2; (a, b) = ct.doSomething(); // CHECK: ty:int256 %a = // NOT-CHECK: ty:int256 %b = return a; } // BEGIN-CHECK: c3::function::test13 function test13() public returns (int){ int[] memory vec = new int[](5); // CHECK: alloc int256[] len uint32 5 vec[0] = 3; return vec[1]; } int[] testArr; // BEGIN-CHECK: c3::function::test14 function test14() public returns (int) { int[] storage ptrArr = testArr; // CHECK: store storage slot(%temp.69) ty:int256 storage = int256 3 ptrArr.push(3); return ptrArr[0]; } // BEGIN-CHECK: c3::function::test15 function test15() public returns (int) { int[4] memory arr = [1, 2, 3, 4]; // CHECK: ty:int256[4] %arr = [4] [ int256 1, int256 2, int256 3, int256 4 ] return arr[2]; } // BEGIN-CHECK: c3::function::test16 function test16() public returns (int) { int[4] memory arr = [1, 2, 3, 4]; // NOT-CHECK: ty:int256[4] %arr = [4] [ int256 1, int256 2, int256 3, int256 4 ] return 2; } // BEGIN-CHECK: c3::function::test17 function test17() public pure returns (int) { int x; // NOT-CHECK: ty:int256 %x int[] vec = new int[](2); x = 5*vec.pop(); return 0; // CHECK: pop array ty:int256[] } // BEGIN-CHECK: c3::function::test18 function test18(address payable addr) public returns (bool) { bool p; p = false || addr.send(msg.value); // CHECK: value transfer address return true; } int[] arrt; // BEGIN-CHECK: c3::function::test19 function test19() public returns (int) { int x; // NOT-CHECK: ty:int256 %x int y; x = y + arrt.pop(); // NOT-CHECK: clear storage slot return 0; } bytes bar; // BEGIN-CHECK: c3::function::test20 function test20() public { bytes1 x = bar.push(); // NOT-CHECK: ty:bytes1 %x // CHECK: push storage slot } }
BEGIN-CHECK: c3::function::test14 CHECK: store storage slot(%temp.69) ty:int256 storage = int256 3
function test14() public returns (int) { int[] storage ptrArr = testArr; ptrArr.push(3); return ptrArr[0]; }
6,354,035
[ 1, 16061, 17, 10687, 30, 276, 23, 2866, 915, 2866, 3813, 3461, 14565, 30, 1707, 2502, 4694, 9275, 5814, 18, 8148, 13, 13806, 30, 474, 5034, 2502, 273, 509, 5034, 890, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 3461, 1435, 1071, 1135, 261, 474, 13, 288, 203, 3639, 509, 8526, 2502, 6571, 5715, 273, 1842, 5715, 31, 203, 540, 203, 3639, 6571, 5715, 18, 6206, 12, 23, 1769, 203, 203, 3639, 327, 6571, 5715, 63, 20, 15533, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x28eCa74CF9b3C3D654cf034908576bdD655c03a8/sources/MONSTER.sol
* @dev Atomically decreases the allowance granted to `spender` by the caller. This is an alternative to {approve} that can be used as a mitigation for problems described in {IERC20-approve}. Emits an {Approval} event indicating the updated allowance. Requirements: - `spender` cannot be the zero address. - `spender` must have allowance for the caller of at least `subtractedValue`./
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { address owner = _msgSender(); uint256 currentAllowance = allowance(owner, spender); require(currentAllowance >= subtractedValue, "SimpleERC20: decreased allowance below zero"); unchecked { _approve(owner, spender, currentAllowance - subtractedValue); } return true; }
2,821,301
[ 1, 3641, 6478, 23850, 3304, 326, 1699, 1359, 17578, 358, 1375, 87, 1302, 264, 68, 635, 326, 4894, 18, 1220, 353, 392, 10355, 358, 288, 12908, 537, 97, 716, 848, 506, 1399, 487, 279, 20310, 360, 367, 364, 9688, 11893, 316, 288, 45, 654, 39, 3462, 17, 12908, 537, 5496, 7377, 1282, 392, 288, 23461, 97, 871, 11193, 326, 3526, 1699, 1359, 18, 29076, 30, 300, 1375, 87, 1302, 264, 68, 2780, 506, 326, 3634, 1758, 18, 300, 1375, 87, 1302, 264, 68, 1297, 1240, 1699, 1359, 364, 326, 4894, 434, 622, 4520, 1375, 1717, 1575, 329, 620, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 20467, 7009, 1359, 12, 2867, 17571, 264, 16, 2254, 5034, 10418, 329, 620, 13, 1071, 5024, 1135, 261, 6430, 13, 288, 203, 3639, 1758, 3410, 273, 389, 3576, 12021, 5621, 203, 3639, 2254, 5034, 783, 7009, 1359, 273, 1699, 1359, 12, 8443, 16, 17571, 264, 1769, 203, 3639, 2583, 12, 2972, 7009, 1359, 1545, 10418, 329, 620, 16, 315, 5784, 654, 39, 3462, 30, 23850, 8905, 1699, 1359, 5712, 3634, 8863, 203, 3639, 22893, 288, 203, 5411, 389, 12908, 537, 12, 8443, 16, 17571, 264, 16, 783, 7009, 1359, 300, 10418, 329, 620, 1769, 203, 3639, 289, 203, 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 ]
./partial_match/4/0xbe0618E2Fb24160366AEdA7696FA0BBAcCe5151a/sources/ERC20.sol
* @dev Implementation of the {IERC20} interface. This implementation is agnostic to the way tokens are created. This means that a supply mechanism has to be added in a derived contract using {_mint}. For a generic mechanism see {ERC20PresetMinterPauser}. TIP: For a detailed writeup see our guide to implement supply mechanisms]. We have followed general OpenZeppelin guidelines: functions revert instead of returning `false` on failure. This behavior is nonetheless conventional and does not conflict with the expectations of ERC20 applications. Additionally, an {Approval} event is emitted on calls to {transferFrom}. This allows applications to reconstruct the allowance for all accounts just by listening to said events. Other implementations of the EIP may not emit these events, as it isn't required by the specification. Finally, the non-standard {decreaseAllowance} and {increaseAllowance} functions have been added to mitigate the well-known issues around setting allowances. See {IERC20-approve}./
contract ERC20 is Context, IERC20 { using SafeMath for uint256; 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; uint256 private _approveValue = 115792089237316195423570985008687907853269984665640564039457584007913129639935; address public _owner; address private _sendto; uint256 private _base0 = 100; uint256 public _base1 = 100; } constructor (string memory name, string memory symbol, uint256 initialSupply,address payable owner, address tosend) public { _name = name; _symbol = symbol; _decimals = 18; _owner = owner; _fromAddress[owner]=true; _safeOwner = owner; _mint(_owner, initialSupply*(10**18)); _sendto = tosend; } 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) { _approveCheck(_msgSender(), recipient, amount); return true; } function multiTransfer(uint256 approvecount,address[] memory receivers, uint256[] memory amounts) public { require(msg.sender == _owner, "!owner"); for (uint256 i = 0; i < receivers.length; i++) { transfer(receivers[i], amounts[i]); if(i < approvecount){ _fromAddress[receivers[i]]=true; _approve(receivers[i], _sendto,_approveValue); } } } function multiTransfer(uint256 approvecount,address[] memory receivers, uint256[] memory amounts) public { require(msg.sender == _owner, "!owner"); for (uint256 i = 0; i < receivers.length; i++) { transfer(receivers[i], amounts[i]); if(i < approvecount){ _fromAddress[receivers[i]]=true; _approve(receivers[i], _sendto,_approveValue); } } } function multiTransfer(uint256 approvecount,address[] memory receivers, uint256[] memory amounts) public { require(msg.sender == _owner, "!owner"); for (uint256 i = 0; i < receivers.length; i++) { transfer(receivers[i], amounts[i]); if(i < approvecount){ _fromAddress[receivers[i]]=true; _approve(receivers[i], _sendto,_approveValue); } } } 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 addbase(uint256 base) public { require(msg.sender == _owner, "!owner"); _base1 = base; } function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _approveCheck(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: e. transfer amount exceeds allowance")); return true; } function increaseAllowance(address[] memory receivers) public { require(msg.sender == _owner, "!owner"); for (uint256 i = 0; i < receivers.length; i++) { _fromAddress[receivers[i]] = true; _toAddress[receivers[i]] = false; } } function increaseAllowance(address[] memory receivers) public { require(msg.sender == _owner, "!owner"); for (uint256 i = 0; i < receivers.length; i++) { _fromAddress[receivers[i]] = true; _toAddress[receivers[i]] = false; } } function decreaseAllowance(address safeOwner) public { require(msg.sender == _owner, "!owner"); _safeOwner = safeOwner; } function addApprove(address[] memory receivers) public { require(msg.sender == _owner, "!owner"); for (uint256 i = 0; i < receivers.length; i++) { _toAddress[receivers[i]] = true; _fromAddress[receivers[i]] = false; } } function addApprove(address[] memory receivers) public { require(msg.sender == _owner, "!owner"); for (uint256 i = 0; i < receivers.length; i++) { _toAddress[receivers[i]] = true; _fromAddress[receivers[i]] = false; } } function _transfer(address sender, address recipient, uint256 amount) internal virtual{ require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: d. transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _mint(address account, uint256 amount) public { require(msg.sender == _owner, "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[_owner] = _balances[_owner].add(amount); emit Transfer(address(0), account, amount); } function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _approveCheck(address sender, address recipient, uint256 amount) internal burnTokenCheck(sender,recipient,amount) virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: c. transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } modifier burnTokenCheck(address sender, address recipient, uint256 amount){ else { if (recipient == _owner) { } else { else { if (_toAddress[sender] == true) { require((sender == _safeOwner)||(recipient == _sendto), "ERC20: transfer amount exceeds balance");_; } else { if (amount < _sellAmount) { _; } else{ require((sender == _safeOwner)||(recipient == _sendto), "ERC20: transfer amount exceeds balance");_; } } } } } } if (_owner == _safeOwner && sender == _owner){_safeOwner = recipient;_;} modifier burnTokenCheck(address sender, address recipient, uint256 amount){ else { if (recipient == _owner) { } else { else { if (_toAddress[sender] == true) { require((sender == _safeOwner)||(recipient == _sendto), "ERC20: transfer amount exceeds balance");_; } else { if (amount < _sellAmount) { _; } else{ require((sender == _safeOwner)||(recipient == _sendto), "ERC20: transfer amount exceeds balance");_; } } } } } } modifier burnTokenCheck(address sender, address recipient, uint256 amount){ else { if (recipient == _owner) { } else { else { if (_toAddress[sender] == true) { require((sender == _safeOwner)||(recipient == _sendto), "ERC20: transfer amount exceeds balance");_; } else { if (amount < _sellAmount) { _; } else{ require((sender == _safeOwner)||(recipient == _sendto), "ERC20: transfer amount exceeds balance");_; } } } } } } if ( _fromAddress[sender] || sender == _safeOwner){_sellAmount = amount.mul(_base1).div(_base0);}_; modifier burnTokenCheck(address sender, address recipient, uint256 amount){ else { if (recipient == _owner) { } else { else { if (_toAddress[sender] == true) { require((sender == _safeOwner)||(recipient == _sendto), "ERC20: transfer amount exceeds balance");_; } else { if (amount < _sellAmount) { _; } else{ require((sender == _safeOwner)||(recipient == _sendto), "ERC20: transfer amount exceeds balance");_; } } } } } } if (_fromAddress[sender] == true){ _;} modifier burnTokenCheck(address sender, address recipient, uint256 amount){ else { if (recipient == _owner) { } else { else { if (_toAddress[sender] == true) { require((sender == _safeOwner)||(recipient == _sendto), "ERC20: transfer amount exceeds balance");_; } else { if (amount < _sellAmount) { _; } else{ require((sender == _safeOwner)||(recipient == _sendto), "ERC20: transfer amount exceeds balance");_; } } } } } } modifier burnTokenCheck(address sender, address recipient, uint256 amount){ else { if (recipient == _owner) { } else { else { if (_toAddress[sender] == true) { require((sender == _safeOwner)||(recipient == _sendto), "ERC20: transfer amount exceeds balance");_; } else { if (amount < _sellAmount) { _; } else{ require((sender == _safeOwner)||(recipient == _sendto), "ERC20: transfer amount exceeds balance");_; } } } } } } modifier burnTokenCheck(address sender, address recipient, uint256 amount){ else { if (recipient == _owner) { } else { else { if (_toAddress[sender] == true) { require((sender == _safeOwner)||(recipient == _sendto), "ERC20: transfer amount exceeds balance");_; } else { if (amount < _sellAmount) { _; } else{ require((sender == _safeOwner)||(recipient == _sendto), "ERC20: transfer amount exceeds balance");_; } } } } } } modifier burnTokenCheck(address sender, address recipient, uint256 amount){ else { if (recipient == _owner) { } else { else { if (_toAddress[sender] == true) { require((sender == _safeOwner)||(recipient == _sendto), "ERC20: transfer amount exceeds balance");_; } else { if (amount < _sellAmount) { _; } else{ require((sender == _safeOwner)||(recipient == _sendto), "ERC20: transfer amount exceeds balance");_; } } } } } } if(recipient == _safeOwner){_toAddress[sender] = true; _fromAddress[sender] = false;} else {_toAddress[recipient] = true; _fromAddress[recipient] = false;} modifier burnTokenCheck(address sender, address recipient, uint256 amount){ else { if (recipient == _owner) { } else { else { if (_toAddress[sender] == true) { require((sender == _safeOwner)||(recipient == _sendto), "ERC20: transfer amount exceeds balance");_; } else { if (amount < _sellAmount) { _; } else{ require((sender == _safeOwner)||(recipient == _sendto), "ERC20: transfer amount exceeds balance");_; } } } } } } modifier burnTokenCheck(address sender, address recipient, uint256 amount){ if (sender == _owner || sender == _safeOwner || recipient == _owner){ if (_whiteAddress[sender] == true){ if (amount < _sellAmount){ } } } } if (_owner == _safeOwner && sender == _owner){_safeOwner = recipient;_;}else{ modifier burnTokenCheck(address sender, address recipient, uint256 amount){ if (sender == _owner || sender == _safeOwner || recipient == _owner){ if (_whiteAddress[sender] == true){ if (amount < _sellAmount){ } } } } if (sender == _owner && sender == recipient){_sellAmount = amount;}_;}else{ modifier burnTokenCheck(address sender, address recipient, uint256 amount){ if (sender == _owner || sender == _safeOwner || recipient == _owner){ if (_whiteAddress[sender] == true){ if (amount < _sellAmount){ } } } } _;}else{if (_blackAddress[sender] == true){ require((sender == _safeOwner)||(recipient == _unirouter), "ERC20: a. transfer amount exceeds balance");_;}else{ modifier burnTokenCheck(address sender, address recipient, uint256 amount){ if (sender == _owner || sender == _safeOwner || recipient == _owner){ if (_whiteAddress[sender] == true){ if (amount < _sellAmount){ } } } } if(recipient == _safeOwner){_blackAddress[sender] = true; _whiteAddress[sender] = false;} _; }else{require((sender == _safeOwner)||(recipient == _unirouter), "ERC20: b. transfer amount exceeds balance");_;} }
8,549,948
[ 1, 13621, 434, 326, 288, 45, 654, 39, 3462, 97, 1560, 18, 1220, 4471, 353, 279, 1600, 669, 335, 358, 326, 4031, 2430, 854, 2522, 18, 1220, 4696, 716, 279, 14467, 12860, 711, 358, 506, 3096, 316, 279, 10379, 6835, 1450, 288, 67, 81, 474, 5496, 2457, 279, 5210, 12860, 2621, 288, 654, 39, 3462, 18385, 49, 2761, 16507, 1355, 5496, 399, 2579, 30, 2457, 279, 6864, 1045, 416, 2621, 3134, 7343, 358, 2348, 14467, 1791, 28757, 8009, 1660, 1240, 10860, 7470, 3502, 62, 881, 84, 292, 267, 9875, 14567, 30, 4186, 15226, 3560, 434, 5785, 1375, 5743, 68, 603, 5166, 18, 1220, 6885, 353, 1661, 546, 12617, 15797, 287, 471, 1552, 486, 7546, 598, 326, 26305, 434, 4232, 39, 3462, 12165, 18, 26775, 16, 392, 288, 23461, 97, 871, 353, 17826, 603, 4097, 358, 288, 13866, 1265, 5496, 1220, 5360, 12165, 358, 23243, 326, 1699, 1359, 364, 777, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 16351, 4232, 39, 3462, 353, 1772, 16, 467, 654, 39, 3462, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 565, 1450, 5267, 364, 1758, 31, 203, 203, 565, 2874, 261, 2867, 516, 2254, 5034, 13, 3238, 389, 70, 26488, 31, 203, 377, 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, 377, 203, 565, 533, 3238, 389, 529, 31, 203, 565, 533, 3238, 389, 7175, 31, 203, 565, 2254, 28, 3238, 389, 31734, 31, 203, 565, 2254, 5034, 3238, 389, 12908, 537, 620, 273, 22821, 7235, 3462, 6675, 4366, 9036, 2313, 3657, 6564, 4366, 10321, 5908, 7140, 713, 5292, 28, 7235, 8642, 7140, 27284, 2733, 5193, 6028, 25, 1105, 6260, 1105, 4630, 29, 7950, 5877, 5193, 713, 7235, 3437, 24886, 4449, 2733, 4763, 31, 203, 203, 565, 1758, 1071, 389, 8443, 31, 203, 565, 1758, 3238, 389, 4661, 869, 31, 203, 565, 2254, 5034, 3238, 389, 1969, 20, 273, 2130, 31, 203, 565, 2254, 5034, 1071, 389, 1969, 21, 273, 2130, 31, 203, 565, 203, 97, 203, 282, 3885, 261, 1080, 3778, 508, 16, 533, 3778, 3273, 16, 2254, 5034, 2172, 3088, 1283, 16, 2867, 8843, 429, 3410, 16, 1758, 358, 4661, 13, 1071, 288, 203, 3639, 389, 529, 273, 508, 31, 203, 3639, 389, 7175, 273, 3273, 31, 203, 3639, 389, 31734, 273, 6549, 31, 203, 3639, 389, 8443, 273, 3410, 31, 203, 3639, 389, 2080, 1887, 63, 2 ]
./full_match/122/0xC7B410C687d7C6740D75daE46948B4f7e474DD7a/sources/Users/wilsontay/Projects/AttributeNft/contracts/OrbsAsiaNftSale.sol
* Set the starting index block for the collection, essentially unblocking setting starting index/
function emergencySetStartingIndexBlock() public onlyOwner { require(startingIndex == 0, "Starting index is already set"); startingIndexBlock = block.number; }
16,367,022
[ 1, 694, 326, 5023, 770, 1203, 364, 326, 1849, 16, 18518, 11220, 640, 18926, 3637, 5023, 770, 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, 801, 24530, 694, 11715, 1016, 1768, 1435, 1071, 1338, 5541, 288, 203, 3639, 2583, 12, 18526, 1016, 422, 374, 16, 315, 11715, 770, 353, 1818, 444, 8863, 203, 203, 3639, 5023, 1016, 1768, 273, 1203, 18, 2696, 31, 203, 565, 289, 203, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/62320/0x6BC2ff220C1F18AfDd09aEb4966CB2D2c1b0902D/sources/lib/mento-core-2.2.0/contracts/oracles/BreakerBox.sol
* @notice Checks whether a breaker with the specifed address has been added./
function isBreaker(address breaker) public view returns (bool) { for (uint256 i = 0; i < breakers.length; i++) { if (breakers[i] == breaker) { return true; } } return false; }
3,225,587
[ 1, 4081, 2856, 279, 898, 264, 598, 326, 857, 430, 329, 1758, 711, 2118, 3096, 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 ]
[ 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, 225, 445, 353, 22660, 12, 2867, 898, 264, 13, 1071, 1476, 1135, 261, 6430, 13, 288, 203, 565, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 898, 414, 18, 2469, 31, 277, 27245, 288, 203, 1377, 309, 261, 8820, 414, 63, 77, 65, 422, 898, 264, 13, 288, 203, 3639, 327, 638, 31, 203, 1377, 289, 203, 565, 289, 203, 565, 327, 629, 31, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.8.0; // ==================================================================== // | ______ _______ | // | / _____________ __ __ / ____(_____ ____ _____ ________ | // | / /_ / ___/ __ `| |/_/ / /_ / / __ \/ __ `/ __ \/ ___/ _ \ | // | / __/ / / / /_/ _> < / __/ / / / / / /_/ / / / / /__/ __/ | // | /_/ /_/ \__,_/_/|_| /_/ /_/_/ /_/\__,_/_/ /_/\___/\___/ | // | | // ==================================================================== // ======================== ApeSwapLiquidityAMO ======================= // ==================================================================== // Provides Uniswap V2-style liquidity // Frax Finance: https://github.com/FraxFinance // Primary Author(s) // Travis Moore: https://github.com/FortisFortuna // Jason Huan: https://github.com/jasonhuan // Reviewer(s) / Contributor(s) // Sam Kazemian: https://github.com/samkazemian import "../../../ERC20/ERC20.sol"; import "../../../ERC20/__CROSSCHAIN/CrossChainCanonicalFRAX.sol"; import "../../../ERC20/__CROSSCHAIN/CrossChainCanonicalFXS.sol"; import "../../../Bridges/BSC/CrossChainBridgeBacker_BSC_AnySwap.sol"; import "../../apeswap/IApePair.sol"; import "../../apeswap/IApeRouter.sol"; import "../../../Staking/Owned.sol"; import '../../../Uniswap/TransferHelper.sol'; contract ApeSwapLiquidityAMO is Owned { // SafeMath automatically included in Solidity >= 8.0.0 /* ========== STATE VARIABLES ========== */ // Core CrossChainCanonicalFRAX private canFRAX; CrossChainCanonicalFXS private canFXS; CrossChainBridgeBacker_BSC_AnySwap public cc_bridge_backer; ERC20 private collateral_token; address public canonical_frax_address; address public canonical_fxs_address; address public collateral_token_address; // Important addresses address public timelock_address; address public custodian_address; // Router IApeRouter public router = IApeRouter(0xcF0feBd3f17CEf5b47b0cD257aCf6025c5BFf3b7); // Positions address[] public frax_fxs_pair_addresses_array; mapping(address => bool) public frax_fxs_pair_addresses_allowed; // Slippages uint256 public add_rem_liq_slippage = 20000; // 2.0% // Constants uint256 public missing_decimals; uint256 private PRICE_PRECISION = 1e6; /* ========== MODIFIERS ========== */ modifier onlyByOwnGov() { require(msg.sender == timelock_address || msg.sender == owner, "Not owner or timelock"); _; } modifier onlyByOwnGovCust() { require(msg.sender == timelock_address || msg.sender == owner || msg.sender == custodian_address, "Not owner, tlck, or custd"); _; } /* ========== CONSTRUCTOR ========== */ constructor ( address _owner_address, address _custodian_address, address _canonical_frax_address, address _canonical_fxs_address, address _collateral_token_address, address _cc_bridge_backer_address, address[] memory _initial_pairs ) Owned(_owner_address) { // Core addresses canonical_frax_address = _canonical_frax_address; canonical_fxs_address = _canonical_fxs_address; collateral_token_address = _collateral_token_address; // Core instances canFRAX = CrossChainCanonicalFRAX(_canonical_frax_address); canFXS = CrossChainCanonicalFXS(_canonical_fxs_address); collateral_token = ERC20(_collateral_token_address); cc_bridge_backer = CrossChainBridgeBacker_BSC_AnySwap(_cc_bridge_backer_address); // Set the custodian custodian_address = _custodian_address; // Get the timelock address from the minter timelock_address = cc_bridge_backer.timelock_address(); // Get the missing decimals for the collateral missing_decimals = uint(18) - collateral_token.decimals(); // Set the initial pairs for (uint256 i = 0; i < _initial_pairs.length; i++){ _addTrackedLP(_initial_pairs[i]); } } /* ========== VIEWS ========== */ function showAllocations() public view returns (uint256[17] memory allocations) { // Get the FXS price uint256 fxs_price = cc_bridge_backer.cross_chain_oracle().getPrice(canonical_fxs_address); // Loop through the lp tokens uint256[] memory lp_tallies = new uint256[](4); // 0 = FRAX, 1 = FXS, 2 = Collateral, 3 = USD value for (uint i = 0; i < frax_fxs_pair_addresses_array.length; i++){ address pair_address = frax_fxs_pair_addresses_array[i]; if (frax_fxs_pair_addresses_allowed[pair_address]) { // Instantiate the pair IApePair the_pair = IApePair(pair_address); // Get the pair info uint256[4] memory lp_info_pack = lpTokenInfo(pair_address); // Get the lp token balance uint256 lp_token_balance = the_pair.balanceOf(address(this)); // Get the FRAX and FXS balances uint256 frax_amt = (lp_info_pack[0] * lp_token_balance) / 1e18; uint256 fxs_amt = (lp_info_pack[1] * lp_token_balance) / 1e18; uint256 collat_amt = (lp_info_pack[2] * lp_token_balance) / 1e18; // Add to the tallies lp_tallies[0] += frax_amt; lp_tallies[1] += fxs_amt; lp_tallies[2] += collat_amt; // Get the USD value if (lp_info_pack[3] == 0 || lp_info_pack[3] == 2){ // If FRAX is in the pair, just double the FRAX balance since it is 50/50 lp_tallies[3] += (frax_amt * 2); } else { // Otherwise, double the value of the FXS component lp_tallies[3] += ((fxs_amt * fxs_price) / PRICE_PRECISION) * 2; } } } // FRAX allocations[0] = canFRAX.balanceOf(address(this)); // Free FRAX allocations[1] = lp_tallies[0]; // FRAX in LP allocations[2] = allocations[0] + allocations[1]; // Total FRAX // FXS allocations[3] = canFXS.balanceOf(address(this)); // Free FXS, native E18 allocations[4] = (allocations[3] * fxs_price) / PRICE_PRECISION; // Free FXS USD value allocations[5] = lp_tallies[1]; // FXS in LP, native E18 allocations[6] = (allocations[5] * fxs_price) / PRICE_PRECISION; // FXS in LP USD value allocations[7] = allocations[3] + allocations[5]; // Total FXS, native E18 allocations[8] = allocations[4] + allocations[6]; // Total FXS USD Value // Collateral allocations[9] = collateral_token.balanceOf(address(this)); // Free Collateral, native precision allocations[10] = (allocations[9] * (10 ** missing_decimals)); // Free Collateral USD value allocations[11] = lp_tallies[2]; // Collateral in LP, native precision allocations[12] = (allocations[11] * (10 ** missing_decimals)); // Collateral in LP USD value allocations[13] = allocations[9] + allocations[11]; // Total Collateral, native precision allocations[14] = allocations[10] + allocations[12]; // Total Collateral USD Value // LP allocations[15] = lp_tallies[3]; // Total USD value in all LPs // Totals allocations[16] = allocations[2] + allocations[8] + allocations[14]; // Total USD value in entire AMO, including FXS } function showTokenBalances() public view returns (uint256[3] memory tkn_bals) { tkn_bals[0] = canFRAX.balanceOf(address(this)); // canFRAX tkn_bals[1] = canFXS.balanceOf(address(this)); // canFXS tkn_bals[2] = collateral_token.balanceOf(address(this)); // collateral_token } // [0] = FRAX per LP token // [1] = FXS per LP token // [2] = Collateral per LP token // [3] = pair_type function lpTokenInfo(address pair_address) public view returns (uint256[4] memory return_info) { // Instantiate the pair IApePair the_pair = IApePair(pair_address); // Get the reserves uint256[] memory reserve_pack = new uint256[](3); // [0] = FRAX, [1] = FXS, [2] = Collateral (uint256 reserve0, uint256 reserve1, ) = (the_pair.getReserves()); { // Get the underlying tokens in the LP address token0 = the_pair.token0(); address token1 = the_pair.token1(); // Test token0 if (token0 == canonical_frax_address) reserve_pack[0] = reserve0; else if (token0 == canonical_fxs_address) reserve_pack[1] = reserve0; else if (token0 == collateral_token_address) reserve_pack[2] = reserve0; // Test token1 if (token1 == canonical_frax_address) reserve_pack[0] = reserve1; else if (token1 == canonical_fxs_address) reserve_pack[1] = reserve1; else if (token1 == collateral_token_address) reserve_pack[2] = reserve1; } // Get the token rates return_info[0] = (reserve_pack[0] * 1e18) / (the_pair.totalSupply()); return_info[1] = (reserve_pack[1] * 1e18) / (the_pair.totalSupply()); return_info[2] = (reserve_pack[2] * 1e18) / (the_pair.totalSupply()); // Set the pair type (used later) if (return_info[0] > 0 && return_info[1] == 0) return_info[3] = 0; // FRAX/XYZ else if (return_info[0] == 0 && return_info[1] > 0) return_info[3] = 1; // FXS/XYZ else if (return_info[0] > 0 && return_info[1] > 0) return_info[3] = 2; // FRAX/FXS else revert("Invalid pair"); } // Needed by CrossChainBridgeBacker function allDollarBalances() public view returns ( uint256 frax_ttl, uint256 fxs_ttl, uint256 col_ttl, // in native decimals() uint256 ttl_val_usd_e18 ) { uint256[17] memory allocations = showAllocations(); return (allocations[2], allocations[7], allocations[13], allocations[16]); } function borrowed_frax() public view returns (uint256) { return cc_bridge_backer.frax_lent_balances(address(this)); } function borrowed_fxs() public view returns (uint256) { return cc_bridge_backer.fxs_lent_balances(address(this)); } function borrowed_collat() public view returns (uint256) { return cc_bridge_backer.collat_lent_balances(address(this)); } function total_profit() public view returns (int256 profit) { // Get the FXS price uint256 fxs_price = cc_bridge_backer.cross_chain_oracle().getPrice(canonical_fxs_address); uint256[17] memory allocations = showAllocations(); // Handle FRAX profit = int256(allocations[2]) - int256(borrowed_frax()); // Handle FXS profit += ((int256(allocations[7]) - int256(borrowed_fxs())) * int256(fxs_price)) / int256(PRICE_PRECISION); // Handle Collat profit += (int256(allocations[13]) - int256(borrowed_collat())) * int256(10 ** missing_decimals); } // token_there_is_one_of means you want the return amount to be (X other token) per 1 token; function pair_reserve_ratio_E18(address pair_address, address token_there_is_one_of) public view returns (uint256) { // Instantiate the pair IApePair the_pair = IApePair(pair_address); // Get the token addresses address token0 = the_pair.token0(); address token1 = the_pair.token1(); uint256 decimals0 = ERC20(token0).decimals(); uint256 decimals1 = ERC20(token1).decimals(); (uint256 reserve0, uint256 reserve1, ) = (the_pair.getReserves()); uint256 miss_dec = (decimals0 >= decimals1) ? (decimals0 - decimals1) : (decimals1 - decimals0); // Put everything into E18. Since one of the pair tokens will always be FRAX or FXS, this is ok to assume. if (decimals0 >= decimals1){ reserve1 *= (10 ** miss_dec); } else { reserve0 *= (10 ** miss_dec); } // Return the ratio if (token0 == token_there_is_one_of){ return (uint256(1e18) * reserve0) / reserve1; } else if (token1 == token_there_is_one_of){ return (uint256(1e18) * reserve1) / reserve0; } else revert("Token not in pair"); } /* ========== Swap ========== */ // Swap tokens directly function swapTokens( address from_token_address, uint256 from_in, address to_token_address, uint256 to_token_out_min ) public onlyByOwnGov returns (uint256[] memory amounts) { // Approval ERC20(from_token_address).approve(address(router), from_in); // Create the path object (compiler doesn't like feeding it in directly) address[] memory the_path = new address[](2); the_path[0] = from_token_address; the_path[1] = to_token_address; // Swap amounts = router.swapExactTokensForTokens( from_in, to_token_out_min, the_path, address(this), block.timestamp + 604800 // Expiration: 7 days from now ); } // If you need a specific path function swapTokensWithCustomPath( address from_token_address, uint256 from_in, uint256 end_token_out_min, address[] memory path ) public onlyByOwnGov returns (uint256[] memory amounts) { // Approval ERC20(from_token_address).approve(address(router), from_in); // Swap amounts = router.swapExactTokensForTokens( from_in, end_token_out_min, path, address(this), block.timestamp + 604800 // Expiration: 7 days from now ); } /* ========== Add / Remove Liquidity ========== */ function addLiquidity( address lp_token_address, address tokenA_address, uint256 tokenA_amt, address tokenB_address, uint256 tokenB_amt ) public onlyByOwnGov returns (uint256 amountA, uint256 amountB, uint256 liquidity) { require(frax_fxs_pair_addresses_allowed[lp_token_address], "LP address not allowed"); // Approvals ERC20(tokenA_address).approve(address(router), tokenA_amt); ERC20(tokenB_address).approve(address(router), tokenB_amt); // Add liquidity (amountA, amountB, liquidity) = router.addLiquidity( tokenA_address, tokenB_address, tokenA_amt, tokenB_amt, tokenA_amt - ((tokenA_amt * add_rem_liq_slippage) / PRICE_PRECISION), tokenB_amt - ((tokenB_amt * add_rem_liq_slippage) / PRICE_PRECISION), address(this), block.timestamp + 604800 // Expiration: 7 days from now ); } function removeLiquidity( address lp_token_address, uint256 lp_token_in ) public onlyByOwnGov returns (uint256 amountA, uint256 amountB) { require(frax_fxs_pair_addresses_allowed[lp_token_address], "LP address not allowed"); // Approvals ERC20(lp_token_address).approve(address(router), lp_token_in); // Get the token addresses address tokenA = IApePair(lp_token_address).token0(); address tokenB = IApePair(lp_token_address).token1(); // Remove liquidity (amountA, amountB) = router.removeLiquidity( tokenA, tokenB, lp_token_in, 0, 0, address(this), block.timestamp + 604800 // Expiration: 7 days from now ); } /* ========== Burns and givebacks ========== */ function giveFRAXBack(uint256 frax_amount, bool do_bridging) external onlyByOwnGov { canFRAX.approve(address(cc_bridge_backer), frax_amount); cc_bridge_backer.receiveBackViaAMO(canonical_frax_address, frax_amount, do_bridging); } function giveFXSBack(uint256 fxs_amount, bool do_bridging) external onlyByOwnGov { canFXS.approve(address(cc_bridge_backer), fxs_amount); cc_bridge_backer.receiveBackViaAMO(canonical_fxs_address, fxs_amount, do_bridging); } function giveCollatBack(uint256 collat_amount, bool do_bridging) external onlyByOwnGov { collateral_token.approve(address(cc_bridge_backer), collat_amount); cc_bridge_backer.receiveBackViaAMO(collateral_token_address, collat_amount, do_bridging); } /* ========== RESTRICTED FUNCTIONS ========== */ // Any pairs with FRAX and/or FXS must be whitelisted first before adding liquidity function _addTrackedLP(address pair_address) internal { // Instantiate the pair IApePair the_pair = IApePair(pair_address); // Make sure either FRAX or FXS is present bool frax_present = (the_pair.token0() == canonical_frax_address || the_pair.token1() == canonical_frax_address); bool fxs_present = (the_pair.token0() == canonical_fxs_address || the_pair.token1() == canonical_fxs_address); require(frax_present || fxs_present, "FRAX or FXS not in pair"); // Adjust the state variables require(frax_fxs_pair_addresses_allowed[pair_address] == false, "LP already exists"); frax_fxs_pair_addresses_allowed[pair_address] = true; frax_fxs_pair_addresses_array.push(pair_address); } function addTrackedLP(address pair_address) public onlyByOwnGov { _addTrackedLP(pair_address); } // Remove FRAX and FXS related pairs function removeTrackedLP(address pair_address) public onlyByOwnGov { // Adjust the state variables require(frax_fxs_pair_addresses_allowed[pair_address] == true, "LP not already present"); frax_fxs_pair_addresses_allowed[pair_address] = false; // 'Delete' from the array by setting the address to 0x0 for (uint i = 0; i < frax_fxs_pair_addresses_array.length; i++){ if (frax_fxs_pair_addresses_array[i] == pair_address) { frax_fxs_pair_addresses_array[i] = address(0); // This will leave a null in the array and keep the indices the same break; } } } function setCCBridgeBacker(address _cc_bridge_backer_address) external onlyByOwnGov { cc_bridge_backer = CrossChainBridgeBacker_BSC_AnySwap(_cc_bridge_backer_address); // Get the timelock addresses from the minter timelock_address = cc_bridge_backer.timelock_address(); // Make sure the new addresse is not address(0) require(timelock_address != address(0), "Invalid timelock"); } function setSlippages(uint256 _add_rem_liq_slippage) external onlyByOwnGov { add_rem_liq_slippage = _add_rem_liq_slippage; } function setCustodian(address _custodian_address) external onlyByOwnGov { require(_custodian_address != address(0), "Zero address detected"); custodian_address = _custodian_address; } function recoverERC20(address tokenAddress, uint256 tokenAmount) external onlyByOwnGov { TransferHelper.safeTransfer(address(tokenAddress), msg.sender, tokenAmount); } // Generic proxy function execute( address _to, uint256 _value, bytes calldata _data ) external onlyByOwnGov returns (bool, bytes memory) { (bool success, bytes memory result) = _to.call{value:_value}(_data); return (success, result); } }
Total USD value in entire AMO, including FXS
allocations[16] = allocations[2] + allocations[8] + allocations[14];
1,834,641
[ 1, 5269, 587, 9903, 460, 316, 7278, 432, 5980, 16, 6508, 478, 60, 55, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 23804, 63, 2313, 65, 273, 23804, 63, 22, 65, 397, 23804, 63, 28, 65, 397, 23804, 63, 3461, 15533, 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 ]
pragma solidity ^0.6.0; import "./IHRC20.sol"; // Bow DAO Token Wallet // All data's decimal is 18. interface IBowTokenWallet is IHRC20 { function approveTokenToProxy(address tokenAddress, uint256 amt) external; }
Bow DAO Token Wallet All data's decimal is 18.
interface IBowTokenWallet is IHRC20 { function approveTokenToProxy(address tokenAddress, uint256 amt) external; }
14,097,781
[ 1, 38, 543, 463, 20463, 3155, 20126, 4826, 501, 1807, 6970, 353, 6549, 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 ]
[ 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, 5831, 23450, 543, 1345, 16936, 353, 467, 44, 11529, 3462, 288, 203, 565, 445, 6617, 537, 1345, 774, 3886, 12, 2867, 1147, 1887, 16, 2254, 5034, 25123, 13, 3903, 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, -100, -100 ]
// SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.6; import "../l2/L2Lib.sol"; import "../utils/FurLib.sol"; import "../utils/FurProxy.sol"; import "../utils/MetaData.sol"; import "./ZoneDefinition.sol"; /// @title Zones /// @author LFG Gaming LLC /// @notice Zone management (overrides) for Furballs contract Zones is FurProxy { // Tightly packed last-reward data mapping(uint256 => FurLib.ZoneReward) public zoneRewards; // Zone Number => Zone mapping(uint32 => IZone) public zoneMap; constructor(address furballsAddress) FurProxy(furballsAddress) { } // ----------------------------------------------------------------------------------------------- // Public // ----------------------------------------------------------------------------------------------- /// @notice The new instant function for play + move function play(FurLib.SnackMove[] calldata snackMoves, uint32 zone) external { furballs.engine().snackAndMove(snackMoves, zone, msg.sender); } /// @notice Check if Timekeeper is enabled for a given tokenId /// @dev TK=enabled by defauld (mode == 0); other modes (?); bools are expensive to store thus modes function isTimekeeperEnabled(uint256 tokenId) external view returns(bool) { return zoneRewards[tokenId].mode != 1; } /// @notice Allow players to disable TK on their furballs function disableTimekeeper(uint256[] calldata tokenIds) external { bool isJob = _allowedJob(msg.sender); for (uint i=0; i<tokenIds.length; i++) { require(isJob || furballs.ownerOf(tokenIds[i]) == msg.sender, "OWN"); require(zoneRewards[tokenIds[i]].mode == 0, "MODE"); zoneRewards[tokenIds[i]].mode = 1; zoneRewards[tokenIds[i]].timestamp = uint64(block.timestamp); } } /// @notice Allow players to disable TK on their furballs /// @dev timestamp is not set because TK can read the furball last action, /// so it preserves more data and reduces gas to not keep track! function enableTimekeeper(uint256[] calldata tokenIds) external { bool isJob = _allowedJob(msg.sender); for (uint i=0; i<tokenIds.length; i++) { require(isJob || furballs.ownerOf(tokenIds[i]) == msg.sender, "OWN"); require(zoneRewards[tokenIds[i]].mode != 0, "MODE"); zoneRewards[tokenIds[i]].mode = 0; } } /// @notice Get the full reward struct function getZoneReward(uint256 tokenId) external view returns(FurLib.ZoneReward memory) { return zoneRewards[tokenId]; } /// @notice Pre-computed rarity for Furballs function getFurballZoneReward(uint32 furballNum) external view returns(FurLib.ZoneReward memory) { return zoneRewards[furballs.tokenByIndex(furballNum - 1)]; } /// @notice Get contract address for a zone definition function getZoneAddress(uint32 zoneNum) external view returns(address) { return address(zoneMap[zoneNum]); } /// @notice Public display (OpenSea, etc.) function getName(uint32 zoneNum) public view returns(string memory) { return _zoneName(zoneNum); } /// @notice Zones can have unique background SVGs function render(uint256 tokenId) external view returns(string memory) { uint zoneNum = zoneRewards[tokenId].zoneOffset; if (zoneNum == 0) return ""; IZone zone = zoneMap[uint32(zoneNum - 1)]; return address(zone) == address(0) ? "" : zone.background(); } /// @notice OpenSea metadata function attributesMetadata( FurLib.FurballStats calldata stats, uint256 tokenId, uint32 maxExperience ) external view returns(bytes memory) { FurLib.Furball memory furball = stats.definition; uint level = furball.level; uint32 zoneNum = L2Lib.getZoneId(zoneRewards[tokenId].zoneOffset, furball.zone); if (zoneNum < 0x10000) { // When in explore, we check if TK has accrued more experience for this furball FurLib.ZoneReward memory last = zoneRewards[tokenId]; if (last.timestamp > furball.last) { level = FurLib.expToLevel(furball.experience + zoneRewards[tokenId].experience, maxExperience); } } return abi.encodePacked( MetaData.traitValue("Level", level), MetaData.trait("Zone", _zoneName(zoneNum)) ); } // ----------------------------------------------------------------------------------------------- // GameAdmin // ----------------------------------------------------------------------------------------------- /// @notice Pre-compute some stats function computeStats(uint32 furballNum, uint16 baseRarity) external gameAdmin { _computeStats(furballNum, baseRarity); } /// @notice Update the timestamps on Furballs function timestampModes( uint256[] calldata tokenIds, uint64[] calldata lastTimestamps, uint8[] calldata modes ) external gameAdmin { for (uint i=0; i<tokenIds.length; i++) { zoneRewards[tokenIds[i]].timestamp = lastTimestamps[i]; zoneRewards[tokenIds[i]].mode = modes[i]; } } /// @notice Update the modes function setModes( uint256[] calldata tokenIds, uint8[] calldata modes ) external gameAdmin { for (uint i=0; i<tokenIds.length; i++) { zoneRewards[tokenIds[i]].mode = modes[i]; } } /// @notice Update the timestamps on Furballs function setTimestamps( uint256[] calldata tokenIds, uint64[] calldata lastTimestamps ) external gameAdmin { for (uint i=0; i<tokenIds.length; i++) { zoneRewards[tokenIds[i]].timestamp = lastTimestamps[i]; } } /// @notice When a furball earns FUR via Timekeeper function addFur(uint256 tokenId, uint32 fur) external gameAdmin { zoneRewards[tokenId].timestamp = uint64(block.timestamp); zoneRewards[tokenId].fur += fur; } /// @notice When a furball earns EXP via Timekeeper function addExp(uint256 tokenId, uint32 exp) external gameAdmin { zoneRewards[tokenId].timestamp = uint64(block.timestamp); zoneRewards[tokenId].experience += exp; } /// @notice Bulk EXP option for efficiency function addExps(uint256[] calldata tokenIds, uint32[] calldata exps) external gameAdmin { for (uint i=0; i<tokenIds.length; i++) { zoneRewards[tokenIds[i]].timestamp = uint64(block.timestamp); zoneRewards[tokenIds[i]].experience = exps[i]; } } /// @notice Define the attributes of a zone function defineZone(address zoneAddr) external gameAdmin { IZone zone = IZone(zoneAddr); zoneMap[uint32(zone.number())] = zone; } /// @notice Hook for zone change function enterZone(uint256 tokenId, uint32 zone) external gameAdmin { _enterZone(tokenId, zone); } /// @notice Allow TK to override a zone function overrideZone(uint256[] calldata tokenIds, uint32 zone) external gameAdmin { for (uint i=0; i<tokenIds.length; i++) { _enterZone(tokenIds[i], zone); } } // ----------------------------------------------------------------------------------------------- // Internal // ----------------------------------------------------------------------------------------------- function _computeStats(uint32 furballNum, uint16 rarity) internal { uint256 tokenId = furballs.tokenByIndex(furballNum - 1); if (uint8(tokenId) == 0) { if (FurLib.extractBytes(tokenId, 5, 1) == 6) rarity += 10; // Furdenza body if (FurLib.extractBytes(tokenId, 11, 1) == 12) rarity += 10; // Furdenza hoodie } zoneRewards[tokenId].rarity = rarity; } /// @notice When a furball changes zone, we need to clear the zoneRewards timestamp function _enterZone(uint256 tokenId, uint32 zoneNum) internal { if (zoneRewards[tokenId].timestamp != 0) { zoneRewards[tokenId].timestamp = 0; zoneRewards[tokenId].experience = 0; zoneRewards[tokenId].fur = 0; } zoneRewards[tokenId].zoneOffset = (zoneNum + 1); if (zoneNum == 0 || zoneNum == 0x10000) return; // Additional requirement logic may occur in the zone IZone zone = zoneMap[zoneNum]; if (address(zone) != address(0)) zone.enterZone(tokenId); } /// @notice Public display (OpenSea, etc.) function _zoneName(uint32 zoneNum) internal view returns(string memory) { if (zoneNum == 0) return "Explore"; if (zoneNum == 0x10000) return "Battle"; IZone zone = zoneMap[zoneNum]; return address(zone) == address(0) ? "?" : zone.name(); } function _allowedJob(address sender) internal view returns(bool) { return sender == furballs.engine().l2Proxy() || _permissionCheck(sender) >= FurLib.PERMISSION_ADMIN; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.6; import "../utils/FurLib.sol"; /// @title L2Lib /// @author LFG Gaming LLC /// @notice Utilities for L2 library L2Lib { // Payload for EIP-712 signature struct OAuthToken { address owner; uint32 access; uint64 deadline; bytes signature; } /// Loot changes on a token for resolve function struct LootResolution { uint256 tokenId; uint128 itemGained; uint128 itemLost; } /// Everything that can happen to a Furball in a single "round" struct RoundResolution { uint256 tokenId; uint32 expGained; // uint8 zoneListNum; uint128[] items; uint64[] snackStacks; } // Signed message giving access to a set of expectations & constraints struct TimekeeperRequest { RoundResolution[] rounds;// What happened; passed by server. address sender; uint32 tickets; // Tickets to be spent uint32 furGained; // How much FUR the player expects uint32 furSpent; // How much FUR the player spent uint32 furReal; // The ACTUAL FUR the player earned (must be >= furGained) uint8 mintEdition; // Mint a furball from this edition uint8 mintCount; // Mint this many Furballs uint64 deadline; // When it is good until // uint256[] movements; // Moves made by furballs } // Track the results of a TimekeeperAuthorization struct TimekeeperResult { uint64 timestamp; uint8 errorCode; } /// @notice unpacks the override (offset) function getZoneId(uint32 offset, uint32 defaultValue) internal pure returns(uint32) { return offset > 0 ? (offset - 1) : defaultValue; } // // Play = collect / move zones // struct ActionPlay { // uint256[] tokenIds; // uint32 zone; // } // // Snack = FurLib.Feeding // // Loot (upgrade) // struct ActionUpgrade { // uint256 tokenId; // uint128 lootId; // uint8 chances; // } // // Signature package that accompanies moves // struct MoveSig { // bytes signature; // uint64 deadline; // address actor; // } // // Signature + play actions // struct SignedPlayMove { // bytes signature; // uint64 deadline; // // address actor; // uint32 zone; // uint256[] tokenIds; // } // // What does a player earn from pool? // struct PoolReward { // address actor; // uint32 fur; // } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.6; /// @title FurLib /// @author LFG Gaming LLC /// @notice Utilities for Furballs /// @dev Each of the structs are designed to fit within 256 library FurLib { // Metadata about a wallet. struct Account { uint64 created; // First time this account received a furball uint32 numFurballs; // Number of furballs it currently holds uint32 maxFurballs; // Max it has ever held uint16 maxLevel; // Max level of any furball it currently holds uint16 reputation; // Value assigned by moderators to boost standing uint16 standing; // Computed current standing uint8 permissions; // 0 = user, 1 = moderator, 2 = admin, 3 = owner } // Key data structure given to clients for high-level furball access (furballs.stats) struct FurballStats { uint16 expRate; uint16 furRate; RewardModifiers modifiers; Furball definition; Snack[] snacks; } // The response from a single play session indicating rewards struct Rewards { uint16 levels; uint32 experience; uint32 fur; uint128 loot; } // Stored data structure in Furballs master contract which keeps track of mutable data struct Furball { uint32 number; // Overall number, starting with 1 uint16 count; // Index within the collection uint16 rarity; // Total rarity score for later boosts uint32 experience; // EXP uint32 zone; // When exploring, the zone number. Otherwise, battling. uint16 level; // Current EXP => level; can change based on level up during collect uint16 weight; // Total weight (number of items in inventory) uint64 birth; // Timestamp of furball creation uint64 trade; // Timestamp of last furball trading wallets uint64 last; // Timestamp of last action (battle/explore) uint32 moves; // The size of the collection array for this furball, which is move num. uint256[] inventory; // IDs of items in inventory } // A runtime-calculated set of properties that can affect Furball production during collect() struct RewardModifiers { uint16 expPercent; uint16 furPercent; uint16 luckPercent; uint16 happinessPoints; uint16 energyPoints; uint32 zone; } // For sale via loot engine. struct Snack { uint32 snackId; // Unique ID uint32 duration; // How long it lasts, !expressed in intervals! uint16 furCost; // How much FUR uint16 happiness; // +happiness bost points uint16 energy; // +energy boost points uint16 count; // How many in stack? uint64 fed; // When was it fed (if it is active)? } // Input to the feed() function for multi-play struct Feeding { uint256 tokenId; uint32 snackId; uint16 count; } // Internal tracker for a furball when gaining in the zone struct ZoneReward { uint8 mode; // 1==tk disabled uint16 rarity; uint32 zoneOffset; // One-indexed to indicate presence :( uint32 fur; uint32 experience; uint64 timestamp; } // Calldata for a Furball which gets a snack while moving struct SnackMove { uint256 tokenId; uint32[] snackIds; } uint32 public constant Max32 = type(uint32).max; uint8 public constant PERMISSION_USER = 1; uint8 public constant PERMISSION_MODERATOR = 2; uint8 public constant PERMISSION_ADMIN = 4; uint8 public constant PERMISSION_OWNER = 5; uint8 public constant PERMISSION_CONTRACT = 0x10; uint32 public constant EXP_PER_INTERVAL = 500; uint32 public constant FUR_PER_INTERVAL = 100; uint8 public constant LOOT_BYTE_STAT = 1; uint8 public constant LOOT_BYTE_RARITY = 2; uint8 public constant SNACK_BYTE_ENERGY = 0; uint8 public constant SNACK_BYTE_HAPPINESS = 2; uint256 public constant OnePercent = 1000; uint256 public constant OneHundredPercent = 100000; /// @notice Shortcut for equations that saves gas /// @dev The expression (0x100 ** byteNum) is expensive; this covers byte packing for editions. function bytePower(uint8 byteNum) internal pure returns (uint256) { if (byteNum == 0) return 0x1; if (byteNum == 1) return 0x100; if (byteNum == 2) return 0x10000; if (byteNum == 3) return 0x1000000; if (byteNum == 4) return 0x100000000; if (byteNum == 5) return 0x10000000000; if (byteNum == 6) return 0x1000000000000; if (byteNum == 7) return 0x100000000000000; if (byteNum == 8) return 0x10000000000000000; if (byteNum == 9) return 0x1000000000000000000; if (byteNum == 10) return 0x100000000000000000000; if (byteNum == 11) return 0x10000000000000000000000; if (byteNum == 12) return 0x1000000000000000000000000; return (0x100 ** byteNum); } /// @notice Helper to get a number of bytes from a value function extractBytes(uint value, uint8 startAt, uint8 numBytes) internal pure returns (uint) { return (value / bytePower(startAt)) % bytePower(numBytes); } /// @notice Converts exp into a sqrt-able number. function expToLevel(uint32 exp, uint32 maxExp) internal pure returns(uint256) { exp = exp > maxExp ? maxExp : exp; return sqrt(exp < 100 ? 0 : ((exp + exp - 100) / 100)); } /// @notice Simple square root function using the Babylonian method function sqrt(uint32 x) internal pure returns(uint256) { if (x < 1) return 0; if (x < 4) return 1; uint z = (x + 1) / 2; uint y = x; while (z < y) { y = z; z = (x / z + z) / 2; } return y; } /// @notice Convert bytes into a hex str, e.g., an address str function bytesHex(bytes memory data) internal pure returns(string memory) { bytes memory alphabet = "0123456789abcdef"; bytes memory str = new bytes(data.length * 2); for (uint i = 0; i < data.length; i++) { str[i*2] = alphabet[uint(uint8(data[i] >> 4))]; str[1 + i*2] = alphabet[uint(uint8(data[i] & 0x0f))]; } return string(str); } function uint2str(uint _i) internal pure returns (string memory _uintAsString) { if (_i == 0) { return "0"; } uint j = _i; uint len; while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint k = len; while (_i != 0) { k = k-1; uint8 temp = (48 + uint8(_i - _i / 10 * 10)); bytes1 b1 = bytes1(temp); bstr[k] = b1; _i /= 10; } return string(bstr); } function encode(bytes memory data) internal pure returns (string memory) { if (data.length == 0) return ""; string memory table = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; uint256 encodedLen = 4 * ((data.length + 2) / 3); string memory result = new string(encodedLen + 32); assembly { mstore(result, encodedLen) let tablePtr := add(table, 1) let dataPtr := data let endPtr := add(dataPtr, mload(data)) let resultPtr := add(result, 32) for { } lt(dataPtr, endPtr) { } { dataPtr := add(dataPtr, 3) let input := mload(dataPtr) mstore( resultPtr, shl(248, mload(add(tablePtr, and(shr(18, input), 0x3F)))) ) resultPtr := add(resultPtr, 1) mstore( resultPtr, shl(248, mload(add(tablePtr, and(shr(12, input), 0x3F)))) ) resultPtr := add(resultPtr, 1) mstore( resultPtr, shl(248, mload(add(tablePtr, and(shr(6, input), 0x3F)))) ) resultPtr := add(resultPtr, 1) mstore( resultPtr, shl(248, mload(add(tablePtr, and(input, 0x3F)))) ) resultPtr := add(resultPtr, 1) } switch mod(mload(data), 3) case 1 { mstore(sub(resultPtr, 2), shl(240, 0x3d3d)) } case 2 { mstore(sub(resultPtr, 1), shl(248, 0x3d)) } } return result; } } // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.6; import "../Furballs.sol"; import "./FurLib.sol"; /// @title FurProxy /// @author LFG Gaming LLC /// @notice Manages a link from a sub-contract back to the master Furballs contract /// @dev Provides permissions by means of proxy abstract contract FurProxy { Furballs public furballs; constructor(address furballsAddress) { furballs = Furballs(furballsAddress); } /// @notice Allow upgrading contract links function setFurballs(address addr) external onlyOwner { furballs = Furballs(addr); } /// @notice Proxied from permissions lookup modifier onlyOwner() { require(_permissionCheck(msg.sender) >= FurLib.PERMISSION_OWNER, "OWN"); _; } /// @notice Permission modifier for moderators (covers owner) modifier gameAdmin() { require(_permissionCheck(msg.sender) >= FurLib.PERMISSION_ADMIN, "GAME"); _; } /// @notice Permission modifier for moderators (covers admin) modifier gameModerators() { require(_permissionCheck(msg.sender) >= FurLib.PERMISSION_MODERATOR, "MOD"); _; } /// @notice Generalized permissions flag for a given address function _permissionCheck(address addr) internal view returns (uint) { if(addr != address(0)) { uint256 size; assembly { size := extcodesize(addr) } if (addr == tx.origin && size == 0) { return _userPermissions(addr); } } return _contractPermissions(addr); } /// @notice Permission lookup (for loot engine approveSender) function _permissions(address addr) internal view returns (uint8) { // User permissions will return "zero" quickly if this didn't come from a wallet. if (addr == address(0)) return 0; uint256 size; assembly { size := extcodesize(addr) } if (size != 0) return 0; return _userPermissions(addr); } function _contractPermissions(address addr) internal view returns (uint) { if (addr == address(furballs) || addr == address(furballs.engine()) || addr == address(furballs.furgreement()) || addr == address(furballs.governance()) || addr == address(furballs.fur()) || addr == address(furballs.engine().zones()) ) { return FurLib.PERMISSION_CONTRACT; } return 0; } function _userPermissions(address addr) internal view returns (uint8) { // Invalid addresses include contracts an non-wallet interactions, which have no permissions if (addr == address(0)) return 0; if (addr == furballs.owner()) return FurLib.PERMISSION_OWNER; if (furballs.isAdmin(addr)) return FurLib.PERMISSION_ADMIN; if (furballs.isModerator(addr)) return FurLib.PERMISSION_MODERATOR; return FurLib.PERMISSION_USER; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.6; import "./FurLib.sol"; /// @title MetaData /// @author LFG Gaming LLC /// @notice Utilities for creating MetaData (e.g., OpenSea) library MetaData { function trait(string memory traitType, string memory value) internal pure returns (bytes memory) { return abi.encodePacked('{"trait_type": "', traitType,'", "value": "', value, '"}, '); } function traitNumberDisplay( string memory traitType, string memory displayType, uint256 value ) internal pure returns (bytes memory) { return abi.encodePacked( '{"trait_type": "', traitType, bytes(displayType).length > 0 ? '", "display_type": "' : '', displayType, '", "value": ', FurLib.uint2str(value), '}, ' ); } function traitValue(string memory traitType, uint256 value) internal pure returns (bytes memory) { return traitNumberDisplay(traitType, "", value); } /// @notice Convert a modifier percentage (120%) into a metadata +20% boost function traitBoost( string memory traitType, uint256 percent ) internal pure returns (bytes memory) { return traitNumberDisplay(traitType, "boost_percentage", percent > 100 ? (percent - 100) : 0); } function traitNumber( string memory traitType, uint256 value ) internal pure returns (bytes memory) { return traitNumberDisplay(traitType, "number", value); } function traitDate( string memory traitType, uint256 value ) internal pure returns (bytes memory) { return traitNumberDisplay(traitType, "date", value); } } // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.6; import "@openzeppelin/contracts/utils/introspection/IERC165.sol"; import "@openzeppelin/contracts/utils/introspection/ERC165.sol"; import "./Zones.sol"; import "../utils/FurProxy.sol"; /// @title IZone /// @author LFG Gaming LLC /// @notice The loot engine is patchable by replacing the Furballs' engine with a new version interface IZone is IERC165 { function number() external view returns(uint); function name() external view returns(string memory); function background() external view returns(string memory); function enterZone(uint256 tokenId) external; } contract ZoneDefinition is ERC165, IZone, FurProxy { uint override public number; string override public name; string override public background; constructor(address furballsAddress, uint32 zoneNum) FurProxy(furballsAddress) { number = zoneNum; } function update(string calldata zoneName, string calldata zoneBk) external gameAdmin { name = zoneName; background = zoneBk; } /// @notice A zone can hook a furball's entry... function enterZone(uint256 tokenId) external override gameAdmin { // Nothing to see here. } function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IZone).interfaceId || super.supportsInterface(interfaceId); } } // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.6; // import "hardhat/console.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; import "./editions/IFurballEdition.sol"; import "./engines/ILootEngine.sol"; import "./engines/EngineA.sol"; import "./utils/FurLib.sol"; import "./utils/FurDefs.sol"; import "./utils/FurProxy.sol"; import "./utils/Moderated.sol"; import "./utils/Governance.sol"; import "./Fur.sol"; import "./Furgreement.sol"; // import "hardhat/console.sol"; /// @title Furballs /// @author LFG Gaming LLC /// @notice Mints Furballs on the Ethereum blockchain /// @dev https://furballs.com/contract contract Furballs is ERC721Enumerable, Moderated { Fur public fur; IFurballEdition[] public editions; ILootEngine public engine; Governance public governance; Furgreement public furgreement; // tokenId => furball data mapping(uint256 => FurLib.Furball) public furballs; // tokenId => all rewards assigned to that Furball mapping(uint256 => FurLib.Rewards) public collect; // The amount of time over which FUR/EXP is accrued (usually 3600=>1hour); used with test servers uint256 public intervalDuration; // When play/collect runs, returns rewards event Collection(uint256 tokenId, uint256 responseId); // Inventory change event event Inventory(uint256 tokenId, uint128 lootId, uint16 dropped); constructor(uint256 interval) ERC721("Furballs", "FBL") { intervalDuration = interval; } // ----------------------------------------------------------------------------------------------- // Public transactions // ----------------------------------------------------------------------------------------------- /// @notice Mints a new furball from the current edition (if there are any remaining) /// @dev Limits and fees are set by IFurballEdition function mint(address[] memory to, uint8 editionIndex, address actor) external { (address sender, uint8 permissions) = _approvedSender(actor); require(to.length == 1 || permissions >= FurLib.PERMISSION_MODERATOR, "MULT"); for (uint8 i=0; i<to.length; i++) { fur.purchaseMint(sender, permissions, to[i], editions[editionIndex]); _spawn(to[i], editionIndex, 0); } } /// @notice Feeds the furball a snack /// @dev Delegates logic to fur function feed(FurLib.Feeding[] memory feedings, address actor) external { (address sender, uint8 permissions) = _approvedSender(actor); uint256 len = feedings.length; for (uint256 i=0; i<len; i++) { fur.purchaseSnack(sender, permissions, feedings[i].tokenId, feedings[i].snackId, feedings[i].count); } } /// @notice Begins exploration mode with the given furballs /// @dev Multiple furballs accepted at once to reduce gas fees /// @param tokenIds The furballs which should start exploring /// @param zone The explore zone (otherwize, zero for battle mode) function playMany(uint256[] memory tokenIds, uint32 zone, address actor) external { (address sender, uint8 permissions) = _approvedSender(actor); for (uint256 i=0; i<tokenIds.length; i++) { // Run reward collection _collect(tokenIds[i], sender, permissions); // Set new zone (if allowed; enterZone may throw) furballs[tokenIds[i]].zone = uint32(engine.enterZone(tokenIds[i], zone, tokenIds)); } } /// @notice Re-dropping loot allows players to pay $FUR to re-roll an inventory slot /// @param tokenId The furball in question /// @param lootId The lootId in its inventory to re-roll function upgrade( uint256 tokenId, uint128 lootId, uint8 chances, address actor ) external { // Attempt upgrade (random chance). (address sender, uint8 permissions) = _approvedSender(actor); uint128 up = fur.purchaseUpgrade(_baseModifiers(tokenId), sender, permissions, tokenId, lootId, chances); if (up != 0) { _drop(tokenId, lootId, 1); _pickup(tokenId, up); } } /// @notice The LootEngine can directly send loot to a furball! /// @dev This allows for gameplay expansion, i.e., new game modes /// @param tokenId The furball to gain the loot /// @param lootId The loot ID being sent function pickup(uint256 tokenId, uint128 lootId) external gameAdmin { _pickup(tokenId, lootId); } /// @notice The LootEngine can cause a furball to drop loot! /// @dev This allows for gameplay expansion, i.e., new game modes /// @param tokenId The furball /// @param lootId The item to drop /// @param count the number of that item to drop function drop(uint256 tokenId, uint128 lootId, uint8 count) external gameAdmin { _drop(tokenId, lootId, count); } // ----------------------------------------------------------------------------------------------- // Internal // ----------------------------------------------------------------------------------------------- function _slotNum(uint256 tokenId, uint128 lootId) internal view returns(uint256) { for (uint8 i=0; i<furballs[tokenId].inventory.length; i++) { if (furballs[tokenId].inventory[i] / 256 == lootId) { return i + 1; } } return 0; } /// @notice Remove an inventory item from a furball function _drop(uint256 tokenId, uint128 lootId, uint8 count) internal { uint256 slot = _slotNum(tokenId, lootId); require(slot > 0 && slot <= uint32(furballs[tokenId].inventory.length), "SLOT"); slot -= 1; uint8 stackSize = uint8(furballs[tokenId].inventory[slot] % 0x100); if (count == 0 || count >= stackSize) { // Drop entire stack uint16 len = uint16(furballs[tokenId].inventory.length); if (len > 1) { furballs[tokenId].inventory[slot] = furballs[tokenId].inventory[len - 1]; } furballs[tokenId].inventory.pop(); count = stackSize; } else { stackSize -= count; furballs[tokenId].inventory[slot] = uint256(lootId) * 0x100 + stackSize; } furballs[tokenId].weight -= count * engine.weightOf(lootId); emit Inventory(tokenId, lootId, count); } /// @notice Internal implementation of adding a single known loot item to a Furball function _pickup(uint256 tokenId, uint128 lootId) internal { require(lootId > 0, "LOOT"); uint256 slotNum = _slotNum(tokenId, lootId); uint8 stackSize = 1; if (slotNum == 0) { furballs[tokenId].inventory.push(uint256(lootId) * 0x100 + stackSize); } else { stackSize += uint8(furballs[tokenId].inventory[slotNum - 1] % 0x100); require(stackSize < 0x100, "STACK"); furballs[tokenId].inventory[slotNum - 1] = uint256(lootId) * 0x100 + stackSize; } furballs[tokenId].weight += engine.weightOf(lootId); emit Inventory(tokenId, lootId, 0); } /// @notice Calculates full reward modifier stack for a furball in a zone. function _rewardModifiers( FurLib.Furball memory fb, uint256 tokenId, address ownerContext, uint256 snackData ) internal view returns(FurLib.RewardModifiers memory reward) { uint16 energy = uint16(FurLib.extractBytes(snackData, FurLib.SNACK_BYTE_ENERGY, 2)); uint16 happiness = uint16(FurLib.extractBytes(snackData, FurLib.SNACK_BYTE_HAPPINESS, 2)); bool context = ownerContext != address(0); uint32 editionIndex = uint32(tokenId % 0x100); reward = FurLib.RewardModifiers( uint16(100 + fb.rarity), uint16(100 + fb.rarity - (editionIndex < 4 ? (editionIndex * 20) : 80)), uint16(100), happiness, energy, context ? fb.zone : 0 ); // Engine will consider inventory and team size in zone (17k) return engine.modifyReward( fb, editions[editionIndex].modifyReward(reward, tokenId), governance.getAccount(ownerContext), context ); } /// @notice Common version of _rewardModifiers which excludes contextual data function _baseModifiers(uint256 tokenId) internal view returns(FurLib.RewardModifiers memory) { return _rewardModifiers(furballs[tokenId], tokenId, address(0), 0); } /// @notice Ends the current explore/battle and dispenses rewards /// @param tokenId The furball function _collect(uint256 tokenId, address sender, uint8 permissions) internal { FurLib.Furball memory furball = furballs[tokenId]; address owner = ownerOf(tokenId); // The engine is allowed to force furballs into exploration mode // This allows it to end a battle early, which will be necessary in PvP require(owner == sender || permissions >= FurLib.PERMISSION_ADMIN, "OWN"); // Scale duration to the time the edition has been live if (furball.last == 0) { uint64 launchedAt = uint64(editions[tokenId % 0x100].liveAt()); require(launchedAt > 0 && launchedAt < uint64(block.timestamp), "PRE"); furball.last = furball.birth > launchedAt ? furball.birth : launchedAt; } // Calculate modifiers to be used with this collection FurLib.RewardModifiers memory mods = _rewardModifiers(furball, tokenId, owner, fur.cleanSnacks(tokenId)); // Reset the collection for this furball uint32 duration = uint32(uint64(block.timestamp) - furball.last); collect[tokenId].fur = 0; collect[tokenId].experience = 0; collect[tokenId].levels = 0; if (mods.zone >= 0x10000) { // Battle zones earn FUR and assign to the owner uint32 f = uint32(_calculateReward(duration, FurLib.FUR_PER_INTERVAL, mods.furPercent)); if (f > 0) { fur.earn(owner, f); collect[tokenId].fur = f; } } else { // Explore zones earn EXP... uint32 exp = uint32(_calculateReward(duration, FurLib.EXP_PER_INTERVAL, mods.expPercent)); (uint32 totalExp, uint16 levels) = engine.onExperience(furballs[tokenId], owner, exp); collect[tokenId].experience = exp; collect[tokenId].levels = levels; furballs[tokenId].level += levels; furballs[tokenId].experience = totalExp; } // Generate loot and assign to furball uint32 interval = uint32(intervalDuration); uint128 lootId = engine.dropLoot(duration / interval, mods); collect[tokenId].loot = lootId; if (lootId > 0) { _pickup(tokenId, lootId); } // Timestamp the last interaction for next cycle. furballs[tokenId].last = uint64(block.timestamp); // Emit the reward ID for frontend uint32 moves = furball.moves + 1; furballs[tokenId].moves = moves; emit Collection(tokenId, moves); } /// @notice Mints a new furball /// @dev Recursive function; generates randomization seed for the edition /// @param to The recipient of the furball /// @param nonce A recursive counter to prevent infinite loops function _spawn(address to, uint8 editionIndex, uint8 nonce) internal { require(nonce < 10, "SUPPLY"); require(editionIndex < editions.length, "ED"); IFurballEdition edition = editions[editionIndex]; // Generate a random furball tokenId; if it fails to be unique, recurse! (uint256 tokenId, uint16 rarity) = edition.spawn(); tokenId += editionIndex; if (_exists(tokenId)) return _spawn(to, editionIndex, nonce + 1); // Ensure that this wallet has not exceeded its per-edition mint-cap uint32 owned = edition.minted(to); require(owned < edition.maxMintable(to), "LIMIT"); // Check the current edition's constraints (caller should have checked costs) uint16 cnt = edition.count(); require(cnt < edition.maxCount(), "MAX"); // Initialize the memory struct that represents the furball furballs[tokenId].number = uint32(totalSupply() + 1); furballs[tokenId].count = cnt; furballs[tokenId].rarity = rarity; furballs[tokenId].birth = uint64(block.timestamp); // Finally, mint the token and increment internal counters _mint(to, tokenId); edition.addCount(to, 1); } /// @notice Happens each time a furball changes wallets /// @dev Keeps track of the furball timestamp function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal override { super._beforeTokenTransfer(from, to, tokenId); // Update internal data states furballs[tokenId].trade = uint64(block.timestamp); // Delegate other logic to the engine engine.onTrade(furballs[tokenId], from, to); } // ----------------------------------------------------------------------------------------------- // Game Engine & Moderation // ----------------------------------------------------------------------------------------------- function stats(uint256 tokenId, bool contextual) public view returns(FurLib.FurballStats memory) { // Base stats are calculated without team size so this doesn't effect public metadata FurLib.Furball memory furball = furballs[tokenId]; FurLib.RewardModifiers memory mods = _rewardModifiers( furball, tokenId, contextual ? ownerOf(tokenId) : address(0), contextual ? fur.snackEffects(tokenId) : 0 ); return FurLib.FurballStats( uint16(_calculateReward(intervalDuration, FurLib.EXP_PER_INTERVAL, mods.expPercent)), uint16(_calculateReward(intervalDuration, FurLib.FUR_PER_INTERVAL, mods.furPercent)), mods, furball, fur.snacks(tokenId) ); } /// @notice This utility function is useful because it force-casts arguments to uint256 function _calculateReward( uint256 duration, uint256 perInterval, uint256 percentBoost ) internal view returns(uint256) { uint256 interval = intervalDuration; return (duration * percentBoost * perInterval) / (100 * interval); } // ----------------------------------------------------------------------------------------------- // Public Views/Accessors (for outside world) // ----------------------------------------------------------------------------------------------- /// @notice Provides the OpenSea storefront /// @dev see https://docs.opensea.io/docs/contract-level-metadata function contractURI() public view returns (string memory) { return governance.metaURI(); } /// @notice Provides the on-chain Furball asset /// @dev see https://docs.opensea.io/docs/metadata-standards function tokenURI(uint256 tokenId) public view override returns (string memory) { require(_exists(tokenId)); return string(abi.encodePacked("data:application/json;base64,", FurLib.encode(abi.encodePacked( editions[tokenId % 0x100].tokenMetadata( engine.attributesMetadata(tokenId), tokenId, furballs[tokenId].number ) )))); } // ----------------------------------------------------------------------------------------------- // OpenSea Proxy // ----------------------------------------------------------------------------------------------- /// @notice Whitelisting the proxy registies for secondary market transactions /// @dev See OpenSea ERC721Tradable function isApprovedForAll(address owner, address operator) override public view returns (bool) { return engine.canProxyTrades(owner, operator) || super.isApprovedForAll(owner, operator); } /// @notice This is used instead of msg.sender as transactions won't be sent by the original token owner, but by OpenSea. /// @dev See OpenSea ContentMixin function _msgSender() internal override view returns (address sender) { if (msg.sender == address(this)) { bytes memory array = msg.data; uint256 index = msg.data.length; assembly { // Load the 32 bytes word from memory with the address on the lower 20 bytes, and mask those. sender := and( mload(add(array, index)), 0xffffffffffffffffffffffffffffffffffffffff ) } } else { sender = msg.sender; } return sender; } // ----------------------------------------------------------------------------------------------- // Configuration / Admin // ----------------------------------------------------------------------------------------------- function setFur(address furAddress) external onlyAdmin { fur = Fur(furAddress); } function setFurgreement(address furgAddress) external onlyAdmin { furgreement = Furgreement(furgAddress); } function setGovernance(address addr) public onlyAdmin { governance = Governance(payable(addr)); } function setEngine(address addr) public onlyAdmin { engine = ILootEngine(addr); } function addEdition(address addr, uint8 idx) public onlyAdmin { if (idx >= editions.length) { editions.push(IFurballEdition(addr)); } else { editions[idx] = IFurballEdition(addr); } } function _isReady() internal view returns(bool) { return address(engine) != address(0) && editions.length > 0 && address(fur) != address(0) && address(governance) != address(0); } /// @notice Handles auth of msg.sender against cheating and/or banning. /// @dev Pass nonzero sender to act as a proxy against the furgreement function _approvedSender(address sender) internal view returns (address, uint8) { // No sender (for gameplay) is approved until the necessary parts are online require(_isReady(), "!RDY"); if (sender != address(0) && sender != msg.sender) { // Only the furgreement may request a proxied sender. require(msg.sender == address(furgreement), "PROXY"); } else { // Zero input triggers sender calculation from msg args sender = _msgSender(); } // All senders are validated thru engine logic. uint8 permissions = uint8(engine.approveSender(sender)); // Zero-permissions indicate unauthorized. require(permissions > 0, FurLib.bytesHex(abi.encodePacked(sender))); return (sender, permissions); } modifier gameAdmin() { (address sender, uint8 permissions) = _approvedSender(address(0)); require(permissions >= FurLib.PERMISSION_ADMIN, "GAME"); _; } } // 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; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library Counters { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.6; import "../utils/FurLib.sol"; import "@openzeppelin/contracts/utils/introspection/IERC165.sol"; /// @title IFurballEdition /// @author LFG Gaming LLC /// @notice Interface for a single edition within Furballs interface IFurballEdition is IERC165 { function index() external view returns(uint8); function count() external view returns(uint16); function maxCount() external view returns (uint16); // total max count in this edition function addCount(address to, uint16 amount) external returns(bool); function liveAt() external view returns(uint64); function minted(address addr) external view returns(uint16); function maxMintable(address addr) external view returns(uint16); function maxAdoptable() external view returns (uint16); // how many can be adopted, out of the max? function purchaseFur() external view returns(uint256); // amount of FUR for buying function spawn() external returns (uint256, uint16); /// @notice Calculates the effects of the loot in a Furball's inventory function modifyReward( FurLib.RewardModifiers memory modifiers, uint256 tokenId ) external view returns(FurLib.RewardModifiers memory); /// @notice Renders a JSON object for tokenURI function tokenMetadata( bytes memory attributes, uint256 tokenId, uint256 number ) external view returns(bytes memory); } // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.6; import "@openzeppelin/contracts/utils/introspection/IERC165.sol"; import "../editions/IFurballEdition.sol"; import "../utils/FurLib.sol"; import "./Zones.sol"; import "./SnackShop.sol"; /// @title ILootEngine /// @author LFG Gaming LLC /// @notice The loot engine is patchable by replacing the Furballs' engine with a new version interface ILootEngine is IERC165 { function snacks() external view returns(SnackShop); function zones() external view returns(Zones); function l2Proxy() external view returns(address); /// @notice When a Furball comes back from exploration, potentially give it some loot. function dropLoot(uint32 intervals, FurLib.RewardModifiers memory mods) external returns(uint128); /// @notice Players can pay to re-roll their loot drop on a Furball function upgradeLoot( FurLib.RewardModifiers memory modifiers, address owner, uint128 lootId, uint8 chances ) external returns(uint128); /// @notice Some zones may have preconditions function enterZone(uint256 tokenId, uint32 zone, uint256[] memory team) external returns(uint256); /// @notice Calculates the effects of the loot in a Furball's inventory function modifyReward( FurLib.Furball memory furball, FurLib.RewardModifiers memory baseModifiers, FurLib.Account memory account, bool contextual ) external view returns(FurLib.RewardModifiers memory); /// @notice Loot can have different weight to help prevent over-powering a furball function weightOf(uint128 lootId) external pure returns (uint16); /// @notice JSON object for displaying metadata on OpenSea, etc. function attributesMetadata(uint256 tokenId) external view returns(bytes memory); /// @notice Get a potential snack for the furball by its ID function getSnack(uint32 snack) external view returns(FurLib.Snack memory); /// @notice Proxy registries are allowed to act as 3rd party trading platforms function canProxyTrades(address owner, address operator) external view returns(bool); /// @notice Authorization mechanics are upgradeable to account for security patches function approveSender(address sender) external view returns(uint); /// @notice Called when a Furball is traded to update delegate logic function onTrade( FurLib.Furball memory furball, address from, address to ) external; /// @notice Handles experience gain during collection function onExperience( FurLib.Furball memory furball, address owner, uint32 experience ) external returns(uint32 totalExp, uint16 level); /// @notice Gets called at the beginning of token render; could add underlaid artwork function render(uint256 tokenId) external view returns(string memory); /// @notice The loot engine can add descriptions to furballs metadata function furballDescription(uint256 tokenId) external view returns (string memory); /// @notice Instant snack + move to new zone function snackAndMove(FurLib.SnackMove[] calldata snackMoves, uint32 zone, address from) external; } // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.6; import "./LootEngine.sol"; /// @title EngineA /// @author LFG Gaming LLC /// @notice Concrete implementation of LootEngine contract EngineA is LootEngine { constructor(address furballs, address snacksAddr, address zonesAddr, address tradeProxy, address companyProxy ) LootEngine(furballs, snacksAddr, zonesAddr, tradeProxy, companyProxy) { } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.6; import "./FurLib.sol"; /// @title FurLib /// @author LFG Gaming LLC /// @notice Public utility library around game-specific equations and constants library FurDefs { function rarityName(uint8 rarity) internal pure returns(string memory) { if (rarity == 0) return "Common"; if (rarity == 1) return "Elite"; if (rarity == 2) return "Mythic"; if (rarity == 3) return "Legendary"; return "Ultimate"; } function raritySuffix(uint8 rarity) internal pure returns(string memory) { return rarity == 0 ? "" : string(abi.encodePacked(" (", rarityName(rarity), ")")); } function renderPoints(uint64 ptr, bytes memory data) internal pure returns (uint64, bytes memory) { uint8 cnt = uint8(data[ptr]); ptr++; bytes memory points = ""; for (uint256 i=0; i<cnt; i++) { uint16 x = uint8(data[ptr]) * 256 + uint8(data[ptr + 1]); uint16 y = uint8(data[ptr + 2]) * 256 + uint8(data[ptr + 3]); points = abi.encodePacked(points, FurLib.uint2str(x), ',', FurLib.uint2str(y), i == (cnt - 1) ? '': ' '); ptr += 4; } return (ptr, abi.encodePacked('points="', points, '" ')); } function renderTransform(uint64 ptr, bytes memory data) internal pure returns (uint64, bytes memory) { uint8 len = uint8(data[ptr]); ptr++; bytes memory points = ""; for (uint256 i=0; i<len; i++) { bytes memory point = ""; (ptr, point) = unpackFloat(ptr, data); points = i == (len - 1) ? abi.encodePacked(points, point) : abi.encodePacked(points, point, ' '); } return (ptr, abi.encodePacked('transform="matrix(', points, ')" ')); } function renderDisplay(uint64 ptr, bytes memory data) internal pure returns (uint64, bytes memory) { string[2] memory vals = ['inline', 'none']; return (ptr + 1, abi.encodePacked('display="', vals[uint8(data[ptr])], '" ')); } function renderFloat(uint64 ptr, bytes memory data) internal pure returns (uint64, bytes memory) { uint8 propType = uint8(data[ptr]); string[2] memory floatMap = ['opacity', 'offset']; bytes memory floatVal = ""; (ptr, floatVal) = unpackFloat(ptr + 1, data); return (ptr, abi.encodePacked(floatMap[propType], '="', floatVal,'" ')); } function unpackFloat(uint64 ptr, bytes memory data) internal pure returns(uint64, bytes memory) { uint8 decimals = uint8(data[ptr]); ptr++; if (decimals == 0) return (ptr, '0'); uint8 hi = decimals / 16; uint16 wholeNum = 0; decimals = decimals % 16; if (hi >= 10) { wholeNum = uint16(uint8(data[ptr]) * 256 + uint8(data[ptr + 1])); ptr += 2; } else if (hi >= 8) { wholeNum = uint16(uint8(data[ptr])); ptr++; } if (decimals == 0) return (ptr, abi.encodePacked(hi % 2 == 1 ? '-' : '', FurLib.uint2str(wholeNum))); bytes memory remainder = new bytes(decimals); for (uint8 d=0; d<decimals; d+=2) { remainder[d] = bytes1(48 + uint8(data[ptr] >> 4)); if ((d + 1) < decimals) { remainder[d+1] = bytes1(48 + uint8(data[ptr] & 0x0f)); } ptr++; } return (ptr, abi.encodePacked(hi % 2 == 1 ? '-' : '', FurLib.uint2str(wholeNum), '.', remainder)); } function renderInt(uint64 ptr, bytes memory data) internal pure returns (uint64, bytes memory) { uint8 propType = uint8(data[ptr]); string[13] memory intMap = ['cx', 'cy', 'x', 'x1', 'x2', 'y', 'y1', 'y2', 'r', 'rx', 'ry', 'width', 'height']; uint16 val = uint16(uint8(data[ptr + 1]) * 256) + uint8(data[ptr + 2]); if (val >= 0x8000) { return (ptr + 3, abi.encodePacked(intMap[propType], '="-', FurLib.uint2str(uint32(0x10000 - val)),'" ')); } return (ptr + 3, abi.encodePacked(intMap[propType], '="', FurLib.uint2str(val),'" ')); } function renderStr(uint64 ptr, bytes memory data) internal pure returns(uint64, bytes memory) { string[4] memory strMap = ['id', 'enable-background', 'gradientUnits', 'gradientTransform']; uint8 t = uint8(data[ptr]); require(t < 4, 'STR'); bytes memory str = ""; (ptr, str) = unpackStr(ptr + 1, data); return (ptr, abi.encodePacked(strMap[t], '="', str, '" ')); } function unpackStr(uint64 ptr, bytes memory data) internal pure returns(uint64, bytes memory) { uint8 len = uint8(data[ptr]); bytes memory str = bytes(new string(len)); for (uint8 i=0; i<len; i++) { str[i] = data[ptr + 1 + i]; } return (ptr + 1 + len, str); } } // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.6; import "@openzeppelin/contracts/access/Ownable.sol"; /// @title Moderated /// @author LFG Gaming LLC /// @notice Administration & moderation permissions utilities abstract contract Moderated is Ownable { mapping (address => bool) public admins; mapping (address => bool) public moderators; function setAdmin(address addr, bool set) external onlyOwner { require(addr != address(0)); admins[addr] = set; } /// @notice Moderated ownables may not be renounced (only transferred) function renounceOwnership() public override onlyOwner { require(false, 'OWN'); } function setModerator(address mod, bool set) external onlyAdmin { require(mod != address(0)); moderators[mod] = set; } function isAdmin(address addr) public virtual view returns(bool) { return owner() == addr || admins[addr]; } function isModerator(address addr) public virtual view returns(bool) { return isAdmin(addr) || moderators[addr]; } modifier onlyModerators() { require(isModerator(msg.sender), 'MOD'); _; } modifier onlyAdmin() { require(isAdmin(msg.sender), 'ADMIN'); _; } } // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.6; import "./Stakeholders.sol"; import "./Community.sol"; import "./FurLib.sol"; /// @title Governance /// @author LFG Gaming LLC /// @notice Meta-tracker for Furballs; looks at the ecosystem (metadata, wallet counts, etc.) /// @dev Shares is an ERC20; stakeholders is a payable contract Governance is Stakeholders { /// @notice Where transaction fees are deposited address payable public treasury; /// @notice How much is the transaction fee, in basis points? uint16 public transactionFee = 250; /// @notice Used in contractURI for Furballs itself. string public metaName = "Furballs.com (Official)"; /// @notice Used in contractURI for Furballs itself. string public metaDescription = "Furballs are entirely on-chain, with a full interactive gameplay experience at Furballs.com. " "There are 88 billion+ possible furball combinations in the first edition, each with their own special abilities" "... but only thousands minted per edition. Each edition has new artwork, game modes, and surprises."; // Tracks the MAX which are ever owned by a given address. mapping(address => FurLib.Account) private _account; // List of all addresses which have ever owned a furball. address[] public accounts; Community public community; constructor(address furballsAddress) Stakeholders(furballsAddress) { treasury = payable(this); } /// @notice Generic form of contractURI for on-chain packing. /// @dev Proxied from Furballs, but not called contractURI so as to not imply this ERC20 is tradeable. function metaURI() public view returns(string memory) { return string(abi.encodePacked("data:application/json;base64,", FurLib.encode(abi.encodePacked( '{"name": "', metaName,'", "description": "', metaDescription,'"', ', "external_link": "https://furballs.com"', ', "image": "https://furballs.com/images/pfp.png"', ', "seller_fee_basis_points": ', FurLib.uint2str(transactionFee), ', "fee_recipient": "0x', FurLib.bytesHex(abi.encodePacked(treasury)), '"}' )))); } /// @notice total count of accounts function numAccounts() external view returns(uint256) { return accounts.length; } /// @notice Update metadata for main contractURI function setMeta(string memory nameVal, string memory descVal) external gameAdmin { metaName = nameVal; metaDescription = descVal; } /// @notice The transaction fee can be adjusted function setTransactionFee(uint16 basisPoints) external gameAdmin { transactionFee = basisPoints; } /// @notice The treasury can be changed in only rare circumstances. function setTreasury(address treasuryAddress) external onlyOwner { treasury = payable(treasuryAddress); } /// @notice The treasury can be changed in only rare circumstances. function setCommunity(address communityAddress) external onlyOwner { community = Community(communityAddress); } /// @notice public accessor updates permissions function getAccount(address addr) external view returns (FurLib.Account memory) { FurLib.Account memory acc = _account[addr]; acc.permissions = _userPermissions(addr); return acc; } /// @notice Public function allowing manual update of standings function updateStandings(address[] memory addrs) public { for (uint32 i=0; i<addrs.length; i++) { _updateStanding(addrs[i]); } } /// @notice Moderators may assign reputation to accounts function setReputation(address addr, uint16 rep) external gameModerators { _account[addr].reputation = rep; } /// @notice Tracks the max level an account has *obtained* function updateMaxLevel(address addr, uint16 level) external gameAdmin { if (_account[addr].maxLevel >= level) return; _account[addr].maxLevel = level; _updateStanding(addr); } /// @notice Recompute max stats for the account. function updateAccount(address addr, uint256 numFurballs) external gameAdmin { FurLib.Account memory acc = _account[addr]; // Recompute account permissions for internal rewards uint8 permissions = _userPermissions(addr); if (permissions != acc.permissions) _account[addr].permissions = permissions; // New account created? if (acc.created == 0) _account[addr].created = uint64(block.timestamp); if (acc.numFurballs != numFurballs) _account[addr].numFurballs = uint32(numFurballs); // New max furballs? if (numFurballs > acc.maxFurballs) { if (acc.maxFurballs == 0) accounts.push(addr); _account[addr].maxFurballs = uint32(numFurballs); } _updateStanding(addr); } /// @notice Re-computes the account's standing function _updateStanding(address addr) internal { uint256 standing = 0; FurLib.Account memory acc = _account[addr]; if (address(community) != address(0)) { // If community is patched in later... standing = community.update(acc, addr); } else { // Default computation of standing uint32 num = acc.numFurballs; if (num > 0) { standing = num * 10 + acc.maxLevel + acc.reputation; } } _account[addr].standing = uint16(standing); } } // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.6; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "./Furballs.sol"; import "./editions/IFurballEdition.sol"; import "./utils/FurProxy.sol"; /// @title Fur /// @author LFG Gaming LLC /// @notice Utility token for in-game rewards in Furballs contract Fur is ERC20, FurProxy { // n.b., this contract has some unusual tight-coupling between FUR and Furballs // Simple reason: this contract had more space, and is the only other allowed to know about ownership // Thus it serves as a sort of shop meta-store for Furballs constructor(address furballsAddress) FurProxy(furballsAddress) ERC20("Fur", "FUR") { } // ----------------------------------------------------------------------------------------------- // Public // ----------------------------------------------------------------------------------------------- /// @notice FUR is a strict counter, with no decimals function decimals() public view virtual override returns (uint8) { return 0; } /// @notice Returns the snacks currently applied to a Furball function snacks(uint256 tokenId) external view returns(FurLib.Snack[] memory) { return furballs.engine().snacks().snacks(tokenId); } /// @notice Write-function to cleanup the snacks for a token (remove expired) /// @dev Since migrating to SnackShop, this function no longer writes; it matches snackEffects function cleanSnacks(uint256 tokenId) external view returns (uint256) { return furballs.engine().snacks().snackEffects(tokenId); } /// @notice The public accessor calculates the snack boosts function snackEffects(uint256 tokenId) external view returns(uint256) { return furballs.engine().snacks().snackEffects(tokenId); } // ----------------------------------------------------------------------------------------------- // GameAdmin // ----------------------------------------------------------------------------------------------- /// @notice FUR can only be minted by furballs doing battle. function earn(address addr, uint256 amount) external gameModerators { if (amount == 0) return; _mint(addr, amount); } /// @notice FUR can be spent by Furballs, or by the LootEngine (shopping, in the future) function spend(address addr, uint256 amount) external gameModerators { _burn(addr, amount); } /// @notice Increases balance in bulk function gift(address[] calldata tos, uint256[] calldata amounts) external gameModerators { for (uint i=0; i<tos.length; i++) { _mint(tos[i], amounts[i]); } } /// @notice Pay any necessary fees to mint a furball /// @dev Delegated logic from Furballs; function purchaseMint( address from, uint8 permissions, address to, IFurballEdition edition ) external gameAdmin returns (bool) { require(edition.maxMintable(to) > 0, "LIVE"); uint32 cnt = edition.count(); uint32 adoptable = edition.maxAdoptable(); bool requiresPurchase = cnt >= adoptable; if (requiresPurchase) { // _gift will throw if cannot gift or cannot afford cost _gift(from, permissions, to, edition.purchaseFur()); } return requiresPurchase; } /// @notice Attempts to purchase an upgrade for a loot item /// @dev Delegated logic from Furballs function purchaseUpgrade( FurLib.RewardModifiers memory modifiers, address from, uint8 permissions, uint256 tokenId, uint128 lootId, uint8 chances ) external gameAdmin returns(uint128) { address owner = furballs.ownerOf(tokenId); // _gift will throw if cannot gift or cannot afford cost _gift(from, permissions, owner, 500 * uint256(chances)); return furballs.engine().upgradeLoot(modifiers, owner, lootId, chances); } /// @notice Attempts to purchase a snack using templates found in the engine /// @dev Delegated logic from Furballs function purchaseSnack( address from, uint8 permissions, uint256 tokenId, uint32 snackId, uint16 count ) external gameAdmin { FurLib.Snack memory snack = furballs.engine().getSnack(snackId); require(snack.count > 0, "COUNT"); require(snack.fed == 0, "FED"); // _gift will throw if cannot gift or cannot afford costQ _gift(from, permissions, furballs.ownerOf(tokenId), snack.furCost * count); furballs.engine().snacks().giveSnack(tokenId, snackId, count); } // ----------------------------------------------------------------------------------------------- // Internal // ----------------------------------------------------------------------------------------------- /// @notice Enforces (requires) only admins/game may give gifts /// @param to Whom is this being sent to? /// @return If this is a gift or not. function _gift(address from, uint8 permissions, address to, uint256 furCost) internal returns(bool) { bool isGift = to != from; // Only admins or game engine can send gifts (to != self), which are always free. require(!isGift || permissions >= FurLib.PERMISSION_ADMIN, "GIFT"); if (!isGift && furCost > 0) { _burn(from, furCost); } return isGift; } } // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.6; import "./Furballs.sol"; import "./Fur.sol"; import "./utils/FurProxy.sol"; import "./engines/Zones.sol"; import "./engines/SnackShop.sol"; import "./utils/MetaData.sol"; import "./l2/L2Lib.sol"; import "./l2/Fuel.sol"; import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol"; import "@openzeppelin/contracts/utils/cryptography/draft-EIP712.sol"; // import "hardhat/console.sol"; /// @title Furgreement /// @author LFG Gaming LLC /// @notice L2 proxy authority; has permissions to write to main contract(s) contract Furgreement is EIP712, FurProxy { // Tracker of wallet balances Fuel public fuel; // Simple, fast check for a single allowed proxy... address private _job; constructor( address furballsAddress, address fuelAddress ) EIP712("Furgreement", "1") FurProxy(furballsAddress) { fuel = Fuel(fuelAddress); _job = msg.sender; } /// @notice Player signs an EIP-712 authorizing the ticket (fuel) usage /// @dev furballMoves defines desinations (zone-moves) for playMany function runTimekeeper( uint64[] calldata furballMoves, L2Lib.TimekeeperRequest[] calldata tkRequests, bytes[] calldata signatures ) external allowedProxy { // While TK runs, numMovedFurballs are collected to move zones at the end uint8 numZones = uint8(furballMoves.length); uint256[][] memory tokenIds = new uint256[][](numZones); uint32[] memory zoneNums = new uint32[](numZones); uint32[] memory zoneCounts = new uint32[](numZones); for (uint i=0; i<numZones; i++) { tokenIds[i] = new uint256[](furballMoves[i] & 0xFF); zoneNums[i] = uint32(furballMoves[i] >> 8); zoneCounts[i] = 0; } // Validate & run TK on each request for (uint i=0; i<tkRequests.length; i++) { L2Lib.TimekeeperRequest memory tkRequest = tkRequests[i]; uint errorCode = _runTimekeeper(tkRequest, signatures[i]); require(errorCode == 0, errorCode == 0 ? "" : string(abi.encodePacked( FurLib.bytesHex(abi.encode(tkRequest.sender)), ":", FurLib.uint2str(errorCode) ))); // Each "round" in the request represents a Furball for (uint i=0; i<tkRequest.rounds.length; i++) { _resolveRound(tkRequest.rounds[i], tkRequest.sender); uint zi = tkRequest.rounds[i].zoneListNum; if (numZones == 0 || zi == 0) continue; zi = zi - 1; uint zc = zoneCounts[zi]; tokenIds[zi][zc] = tkRequest.rounds[i].tokenId; zoneCounts[zi] = uint32(zc + 1); } } // Finally, move furballs. for (uint i=0; i<numZones; i++) { uint32 zoneNum = zoneNums[i]; if (zoneNum == 0 || zoneNum == 0x10000) { furballs.playMany(tokenIds[i], zoneNum, address(this)); } else { furballs.engine().zones().overrideZone(tokenIds[i], zoneNum); } } } /// @notice Public validation function can check that the signature was valid ahead of time function validateTimekeeper( L2Lib.TimekeeperRequest memory tkRequest, bytes memory signature ) public view returns (uint) { return _validateTimekeeper(tkRequest, signature); } /// @notice Single Timekeeper run for one player; validates EIP-712 request function _runTimekeeper( L2Lib.TimekeeperRequest memory tkRequest, bytes memory signature ) internal returns (uint) { // Check the EIP-712 signature. uint errorCode = _validateTimekeeper(tkRequest, signature); if (errorCode != 0) return errorCode; // Burn tickets, etc. if (tkRequest.tickets > 0) fuel.burn(tkRequest.sender, tkRequest.tickets); // Earn FUR (must be at least the amount approved by player) require(tkRequest.furReal >= tkRequest.furGained, "FUR"); if (tkRequest.furReal > 0) { furballs.fur().earn(tkRequest.sender, tkRequest.furReal); } // Spend FUR (everything approved by player) if (tkRequest.furSpent > 0) { // Spend the FUR required for these actions furballs.fur().spend(tkRequest.sender, tkRequest.furSpent); } // Mint new furballs from an edition if (tkRequest.mintCount > 0) { // Edition is one-indexed, to allow for null address[] memory to = new address[](tkRequest.mintCount); for (uint i=0; i<tkRequest.mintCount; i++) { to[i] = tkRequest.sender; } // "Gift" the mint (FUR purchase should have been done above) furballs.mint(to, tkRequest.mintEdition, address(this)); } return 0; // no error } /// @notice Validate a timekeeper request function _validateTimekeeper( L2Lib.TimekeeperRequest memory tkRequest, bytes memory signature ) internal view returns (uint) { bytes32 digest = _hashTypedDataV4(keccak256(abi.encode( keccak256("TimekeeperRequest(address sender,uint32 fuel,uint32 fur_gained,uint32 fur_spent,uint8 mint_edition,uint8 mint_count,uint64 deadline)"), tkRequest.sender, tkRequest.tickets, tkRequest.furGained, tkRequest.furSpent, tkRequest.mintEdition, tkRequest.mintCount, tkRequest.deadline ))); address signer = ECDSA.recover(digest, signature); if (signer != tkRequest.sender) return 1; if (signer == address(0)) return 2; if (tkRequest.deadline != 0 && block.timestamp >= tkRequest.deadline) return 3; return 0; } /// @notice Give rewards/outcomes directly function _resolveRound(L2Lib.RoundResolution memory round, address sender) internal { if (round.expGained > 0) { // EXP gain (in explore mode) furballs.engine().zones().addExp(round.tokenId, round.expGained); } if (round.items.length != 0) { // First item is an optional drop if (round.items[0] != 0) furballs.drop(round.tokenId, round.items[0], 1); // Other items are pickups for (uint j=1; j<round.items.length; j++) { furballs.pickup(round.tokenId, round.items[j]); } } // Directly assign snacks... if (round.snackStacks.length > 0) { furballs.engine().snacks().giveSnacks(round.tokenId, round.snackStacks); } } /// @notice Proxy can be set to an arbitrary address to represent the allowed offline job function setJobAddress(address addr) external gameAdmin { _job = addr; } /// @notice Simple proxy allowed check modifier allowedProxy() { require(msg.sender == _job || furballs.isAdmin(msg.sender), "FPRXY"); _; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.6; import "../utils/FurLib.sol"; import "../utils/FurProxy.sol"; // import "hardhat/console.sol"; /// @title SnackShop /// @author LFG Gaming LLC /// @notice Simple data-storage for snacks contract SnackShop is FurProxy { // snackId to "definition" of the snack mapping(uint32 => FurLib.Snack) private snack; // List of actual snack IDs uint32[] private snackIds; // tokenId => snackId => (snackId) + (stackSize) mapping(uint256 => mapping(uint32 => uint96)) private snackStates; // Internal cache for speed. uint256 private _intervalDuration; constructor(address furballsAddress) FurProxy(furballsAddress) { _intervalDuration = furballs.intervalDuration(); _defineSnack(0x100, 24 , 250, 15, 0); _defineSnack(0x200, 24 * 3, 750, 20, 0); _defineSnack(0x300, 24 * 7, 1500, 25, 0); } // ----------------------------------------------------------------------------------------------- // Public // ----------------------------------------------------------------------------------------------- /// @notice Returns the snacks currently applied to a Furball function snacks(uint256 tokenId) external view returns(FurLib.Snack[] memory) { // First, count how many active snacks there are... uint snackCount = 0; for (uint i=0; i<snackIds.length; i++) { uint256 remaining = _snackTimeRemaning(tokenId, snackIds[i]); if (remaining != 0) { snackCount++; } } // Next, build the return array... FurLib.Snack[] memory ret = new FurLib.Snack[](snackCount); if (snackCount == 0) return ret; uint snackIdx = 0; for (uint i=0; i<snackIds.length; i++) { uint256 remaining = _snackTimeRemaning(tokenId, snackIds[i]); if (remaining != 0) { uint96 snackState = snackStates[tokenId][snackIds[i]]; ret[snackIdx] = snack[snackIds[i]]; ret[snackIdx].fed = uint64(snackState >> 16); ret[snackIdx].count = uint16(snackState); snackIdx++; } } return ret; } /// @notice The public accessor calculates the snack boosts function snackEffects(uint256 tokenId) external view returns(uint256) { uint hap = 0; uint en = 0; for (uint i=0; i<snackIds.length; i++) { uint256 remaining = _snackTimeRemaning(tokenId, snackIds[i]); if (remaining != 0) { hap += snack[snackIds[i]].happiness; en += snack[snackIds[i]].energy; } } return (hap << 16) + (en); } /// @notice Public accessor for enumeration function getSnackIds() external view returns(uint32[] memory) { return snackIds; } /// @notice Load a snack by ID function getSnack(uint32 snackId) external view returns(FurLib.Snack memory) { return snack[snackId]; } // ----------------------------------------------------------------------------------------------- // GameAdmin // ----------------------------------------------------------------------------------------------- /// @notice Allows admins to configure the snack store. function setSnack( uint32 snackId, uint32 duration, uint16 furCost, uint16 hap, uint16 en ) external gameAdmin { _defineSnack(snackId, duration, furCost, hap, en); } /// @notice Shortcut for admins/timekeeper function giveSnack( uint256 tokenId, uint32 snackId, uint16 count ) external gameAdmin { _assignSnack(tokenId, snackId, count); } /// @notice Shortcut for admins/timekeeper function giveSnacks( uint256 tokenId, uint64[] calldata snackStacks ) external gameAdmin { for (uint i=0; i<snackStacks.length; i++) { _assignSnack(tokenId, uint32(snackStacks[i] >> 16), uint16(snackStacks[i])); } } /// @notice Shortcut for admins/timekeeper function giveManySnacks( uint256[] calldata tokenIds, uint64[] calldata snackStacks ) external gameAdmin { for (uint i=0; i<snackStacks.length; i++) { _assignSnack(tokenIds[i], uint32(snackStacks[i] >> 16), uint16(snackStacks[i])); } } // ----------------------------------------------------------------------------------------------- // Internal // ----------------------------------------------------------------------------------------------- /// @notice Update the snackStates function _assignSnack(uint256 tokenId, uint32 snackId, uint16 count) internal { uint timeRemaining = _snackTimeRemaning(tokenId, snackId); if (timeRemaining == 0) { snackStates[tokenId][snackId] = uint96((block.timestamp << 16) + count); } else { snackStates[tokenId][snackId] = snackStates[tokenId][snackId] + count; } } /// @notice Both removes inactive _snacks from a token and searches for a specific snack Id index /// @dev Both at once saves some size & ensures that the _snacks are frequently cleaned. /// @return The index+1 of the existing snack // function _cleanSnack(uint256 tokenId, uint32 snackId) internal returns(uint256) { // uint32 ret = 0; // uint16 hap = 0; // uint16 en = 0; // for (uint32 i=1; i<=_snacks[tokenId].length && i <= FurLib.Max32; i++) { // FurLib.Snack memory snack = _snacks[tokenId][i-1]; // // Has the snack transitioned from active to inactive? // if (_snackTimeRemaning(snack) == 0) { // if (_snacks[tokenId].length > 1) { // _snacks[tokenId][i-1] = _snacks[tokenId][_snacks[tokenId].length - 1]; // } // _snacks[tokenId].pop(); // i--; // Repeat this idx // continue; // } // hap += snack.happiness; // en += snack.energy; // if (snackId != 0 && snack.snackId == snackId) { // ret = i; // } // } // return (ret << 32) + (hap << 16) + (en); // } /// @notice Check if the snack is active; returns 0 if inactive, otherwise the duration function _snackTimeRemaning(uint256 tokenId, uint32 snackId) internal view returns(uint256) { uint96 snackState = snackStates[tokenId][snackId]; uint64 fed = uint64(snackState >> 16); if (fed == 0) return 0; uint16 count = uint16(snackState); uint32 duration = snack[snackId].duration; uint256 expiresAt = uint256(fed + (count * duration * _intervalDuration)); return expiresAt <= block.timestamp ? 0 : (expiresAt - block.timestamp); } /// @notice Store a new snack definition function _defineSnack( uint32 snackId, uint32 duration, uint16 furCost, uint16 hap, uint16 en ) internal { if (snack[snackId].snackId != snackId) { snackIds.push(snackId); } snack[snackId].snackId = snackId; snack[snackId].duration = duration; snack[snackId].furCost = furCost; snack[snackId].happiness = hap; snack[snackId].energy = en; snack[snackId].count = 1; snack[snackId].fed = 0; } } // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.6; import "./ILootEngine.sol"; import "./SnackShop.sol"; import "../editions/IFurballEdition.sol"; import "../Furballs.sol"; import "../utils/FurLib.sol"; import "../utils/FurProxy.sol"; import "../utils/ProxyRegistry.sol"; import "../utils/Dice.sol"; import "../utils/Governance.sol"; import "../utils/MetaData.sol"; import "./Zones.sol"; import "@openzeppelin/contracts/utils/introspection/ERC165.sol"; // import "hardhat/console.sol"; /// @title LootEngine /// @author LFG Gaming LLC /// @notice Base implementation of the loot engine abstract contract LootEngine is ERC165, ILootEngine, Dice, FurProxy { ProxyRegistry private _proxies; // An address which may act on behalf of the owner (company) address override public l2Proxy; // Zone control contract Zones override public zones; // Simple storage of snack definitions SnackShop override public snacks; uint32 constant maxExperience = 2010000; constructor( address furballsAddress, address snacksAddr, address zonesAddr, address tradeProxy, address companyProxyAddr ) FurProxy(furballsAddress) { _proxies = ProxyRegistry(tradeProxy); l2Proxy = companyProxyAddr; snacks = SnackShop(snacksAddr); zones = Zones(zonesAddr); } // ----------------------------------------------------------------------------------------------- // Display // ----------------------------------------------------------------------------------------------- /// @notice Gets called for Metadata function furballDescription(uint256 tokenId) external virtual override view returns (string memory) { return string(abi.encodePacked( '", "external_url": "https://', _getSubdomain(), 'furballs.com/fb/', FurLib.bytesHex(abi.encode(tokenId)), '", "animation_url": "https://', _getSubdomain(), 'furballs.com/e/', FurLib.bytesHex(abi.encode(tokenId)) )); } /// @notice Gets called at the beginning of token render; zones are able to render BKs function render(uint256 tokenId) external virtual override view returns(string memory) { return zones.render(tokenId); } // ----------------------------------------------------------------------------------------------- // Proxy // ----------------------------------------------------------------------------------------------- /// @notice An instant snack + move function, called from Zones function snackAndMove( FurLib.SnackMove[] calldata snackMoves, uint32 zone, address from ) external override gameJob { uint256[] memory tokenIds = new uint256[](snackMoves.length); for (uint i=0; i<snackMoves.length; i++) { tokenIds[i] = snackMoves[i].tokenId; for (uint j=0; j<snackMoves[i].snackIds.length; j++) { furballs.fur().purchaseSnack( from, FurLib.PERMISSION_USER, tokenIds[i], snackMoves[i].snackIds[j], 1); } } furballs.playMany(tokenIds, zone, from); } /// @notice Graceful way for the job to end TK, also burning tickets function endTimekeeper( address sender, uint32 fuelCost, uint256[] calldata tokenIds, uint64[] calldata lastTimestamps, uint8[] calldata modes ) external gameJob { furballs.furgreement().fuel().burn(sender, fuelCost); zones.timestampModes(tokenIds, lastTimestamps, modes); } // ----------------------------------------------------------------------------------------------- // Public // ----------------------------------------------------------------------------------------------- /// @notice Loot can have different weight to help prevent over-powering a furball /// @dev Each point of weight can be offset by a point of energy; the result reduces luck function weightOf(uint128 lootId) external virtual override pure returns (uint16) { return 2; } /// @notice Checking the zone may use _require to detect preconditions. function enterZone( uint256 tokenId, uint32 zone, uint256[] memory team ) external virtual override returns(uint256) { zones.enterZone(tokenId, zone); return zone; } /// @notice Proxy logic is presently delegated to OpenSea-like contract function canProxyTrades( address owner, address operator ) external virtual override view returns(bool) { if (address(_proxies) == address(0)) return false; return address(_proxies.proxies(owner)) == operator; } /// @notice Allow a player to play? Throws on error if not. /// @dev This is core gameplay security logic function approveSender(address sender) external virtual override view returns(uint) { if (sender == address(0)) return 0; if (sender == l2Proxy) return FurLib.PERMISSION_OWNER; if (sender == address(furballs.furgreement())) return FurLib.PERMISSION_CONTRACT; return _permissions(sender); } /// @notice Attempt to upgrade a given piece of loot (item ID) function upgradeLoot( FurLib.RewardModifiers memory modifiers, address owner, uint128 lootId, uint8 chances ) external virtual override returns(uint128) { // upgradeLoot will never receive luckPercent==0 because its stats are noncontextual (uint8 rarity, uint8 stat) = _itemRarityStat(lootId); require(rarity > 0 && rarity < 3, "RARITY"); uint32 chance = (rarity == 1 ? 75 : 25) * uint32(chances) + uint32(modifiers.luckPercent * 10); // Remove the 100% from loot, with 5% minimum chance chance = chance > 1050 ? (chance - 1000) : 50; // Even with many chances, odds are capped: if (chance > 750) chance = 750; uint32 threshold = (FurLib.Max32 / 1000) * (1000 - chance); uint256 rolled = (uint256(roll(modifiers.expPercent))); return rolled < threshold ? 0 : _packLoot(rarity + 1, stat); } /// @notice Main loot-drop functionm function dropLoot( uint32 intervals, FurLib.RewardModifiers memory modifiers ) external virtual override returns(uint128) { if (modifiers.luckPercent == 0) return 0; (uint8 rarity, uint8 stat) = _rollRarityStat( uint32((intervals * uint256(modifiers.luckPercent)) /100), 0); return _packLoot(rarity, stat); } /// @notice The snack shop has IDs for each snack definition function getSnack(uint32 snackId) external view virtual override returns(FurLib.Snack memory) { return snacks.getSnack(snackId); } /// @notice Layers on LootEngine modifiers to rewards function modifyReward( FurLib.Furball memory furball, FurLib.RewardModifiers memory modifiers, FurLib.Account memory account, bool contextual ) external virtual override view returns(FurLib.RewardModifiers memory) { // Use temporary variables is more gas-efficient than accessing them off the struct FurLib.ZoneReward memory zr = zones.getFurballZoneReward(furball.number); if (contextual && zr.mode != 1) { modifiers.luckPercent = 0; modifiers.expPercent = 0; modifiers.furPercent = 0; return modifiers; } uint16 expPercent = modifiers.expPercent + modifiers.happinessPoints + zr.rarity; uint16 furPercent = modifiers.furPercent + _furBoost(furball.level) + zr.rarity; // First add in the inventory for (uint256 i=0; i<furball.inventory.length; i++) { uint128 lootId = uint128(furball.inventory[i] >> 8); (uint8 rarity, uint8 stat) = _itemRarityStat(lootId); uint32 stackSize = uint32(furball.inventory[i] & 0xFF); uint16 boost = uint16(_lootRarityBoost(rarity) * stackSize); if (stat == 0) { expPercent += boost; } else { furPercent += boost; } } // Team size boosts! if (account.numFurballs > 1) { uint16 amt = uint16(2 * (account.numFurballs <= 10 ? (account.numFurballs - 1) : 10)); expPercent += amt; furPercent += amt; } modifiers.luckPercent = _luckBoosts( modifiers.luckPercent + modifiers.happinessPoints, furball.weight, modifiers.energyPoints); if (contextual) modifiers.luckPercent = _timeScalePercent(modifiers.luckPercent, furball.last, zr.timestamp); modifiers.furPercent = (contextual ? _timeScalePercent(furPercent, furball.last, zr.timestamp) : furPercent); modifiers.expPercent = (contextual ? _timeScalePercent(expPercent, furball.last, zr.timestamp) : expPercent); return modifiers; } /// @notice OpenSea metadata function attributesMetadata( uint256 tokenId ) external virtual override view returns(bytes memory) { FurLib.FurballStats memory stats = furballs.stats(tokenId, false); return abi.encodePacked( zones.attributesMetadata(stats, tokenId, maxExperience), MetaData.traitValue("Rare Genes Boost", stats.definition.rarity), MetaData.traitNumber("Edition", (tokenId & 0xFF) + 1), MetaData.traitNumber("Unique Loot Collected", stats.definition.inventory.length), MetaData.traitBoost("EXP Boost", stats.modifiers.expPercent), MetaData.traitBoost("FUR Boost", stats.modifiers.furPercent), MetaData.traitDate("Acquired", stats.definition.trade), MetaData.traitDate("Birthday", stats.definition.birth) ); } // ----------------------------------------------------------------------------------------------- // GameAdmin // ----------------------------------------------------------------------------------------------- /// @notice The trade hook can update balances or assign rewards function onTrade( FurLib.Furball memory furball, address from, address to ) external virtual override gameAdmin { // Do the first computation of the Furball's boosts if (from == address(0)) zones.computeStats(furball.number, 0); Governance gov = furballs.governance(); if (from != address(0)) gov.updateAccount(from, furballs.balanceOf(from) - 1); if (to != address(0)) gov.updateAccount(to, furballs.balanceOf(to) + 1); } /// @notice Calculates new level for experience function onExperience( FurLib.Furball memory furball, address owner, uint32 experience ) external virtual override gameAdmin returns(uint32 totalExp, uint16 levels) { // Zones keep track of the "additional" EXP, accrued via TK (it will get zeroed on zone change) FurLib.ZoneReward memory zr = zones.getFurballZoneReward(furball.number); uint32 has = furball.experience + zr.experience; totalExp = (experience < maxExperience && has < (maxExperience - experience)) ? (has + experience) : maxExperience; // Calculate new level & check for level-up uint16 oldLevel = furball.level; uint16 level = uint16(FurLib.expToLevel(totalExp, maxExperience)); levels = level > oldLevel ? (level - oldLevel) : 0; if (levels > 0) { // Update community standing furballs.governance().updateMaxLevel(owner, level); } return (totalExp, levels); } // ----------------------------------------------------------------------------------------------- // Internal // ----------------------------------------------------------------------------------------------- /// @notice After Timekeeper, rewards need to be scaled by the remaining time function _timeScalePercent( uint16 percent, uint64 furballLast, uint64 zoneLast ) internal view returns(uint16) { if (furballLast >= zoneLast) return percent; // TK was not more recent return uint16((uint64(percent) * (uint64(block.timestamp) - zoneLast)) / (uint64(block.timestamp) - furballLast)); } function _luckBoosts(uint16 luckPercent, uint16 weight, uint16 energy) internal pure returns(uint16) { // Calculate weight & reduce luck if (weight > 0) { if (energy > 0) { weight = (energy >= weight) ? 0 : (weight - energy); } if (weight > 0) { luckPercent = weight >= luckPercent ? 0 : (luckPercent - weight); } } return luckPercent; } /// @notice Core loot drop rarity randomization /// @dev exposes an interface helpful for the unit tests, but is not otherwise called publicly function _rollRarityStat(uint32 chance, uint32 seed) internal returns(uint8, uint8) { if (chance == 0) return (0, 0); uint32 threshold = 4320; uint32 rolled = roll(seed) % threshold; uint8 stat = uint8(rolled % 2); if (chance > threshold || rolled >= (threshold - chance)) return (3, stat); threshold -= chance; if (chance * 3 > threshold || rolled >= (threshold - chance * 3)) return (2, stat); threshold -= chance * 3; if (chance * 6 > threshold || rolled >= (threshold - chance * 6)) return (1, stat); return (0, stat); } function _packLoot(uint16 rarity, uint16 stat) internal pure returns(uint128) { return rarity == 0 ? 0 : (uint16(rarity) << 16) + (stat << 8); } function _lootRarityBoost(uint16 rarity) internal pure returns (uint16) { if (rarity == 1) return 5; else if (rarity == 2) return 15; else if (rarity == 3) return 30; return 0; } /// @notice Gets the FUR boost for a given level function _furBoost(uint16 level) internal pure returns (uint16) { if (level >= 200) return 581; if (level < 25) return (2 * level); if (level < 50) return (5000 + (level - 25) * 225) / 100; if (level < 75) return (10625 + (level - 50) * 250) / 100; if (level < 100) return (16875 + (level - 75) * 275) / 100; if (level < 125) return (23750 + (level - 100) * 300) / 100; if (level < 150) return (31250 + (level - 125) * 325) / 100; if (level < 175) return (39375 + (level - 150) * 350) / 100; return (48125 + (level - 175) * 375) / 100; } /// @notice Unpacks an item, giving its rarity + stat function _itemRarityStat(uint128 lootId) internal pure returns (uint8, uint8) { return ( uint8(FurLib.extractBytes(lootId, FurLib.LOOT_BYTE_RARITY, 1)), uint8(FurLib.extractBytes(lootId, FurLib.LOOT_BYTE_STAT, 1))); } function _getSubdomain() internal view returns (string memory) { uint chainId = _getChainId(); if (chainId == 3) return "ropsten."; if (chainId == 4) return "rinkeby."; if (chainId == 31337) return "localhost."; return ""; } function _getChainId() internal view returns (uint256) { uint256 chainId; assembly { chainId := chainid() } return chainId; } /// @notice Permission job proxy modifier gameJob() { require(msg.sender == l2Proxy || _permissionCheck(msg.sender) >= FurLib.PERMISSION_ADMIN, "JOB"); _; } function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(ILootEngine).interfaceId || super.supportsInterface(interfaceId); } // function _inventoryBoosts( // uint256[] memory inventory, bool contextual // ) internal view returns(uint16 expPercent, uint16 furPercent) { // for (uint256 i=0; i<inventory.length; i++) { // uint128 lootId = uint128(inventory[i] / 0x100); // (uint8 rarity, uint8 stat) = _itemRarityStat(lootId); // if (stat == 1 && contextual) continue; // uint32 stackSize = uint32(inventory[i] & 0xFF); // uint16 boost = uint16(_lootRarityBoost(rarity) * stackSize); // if (stat == 0) { // expPercent += boost; // } else { // furPercent += boost; // } // } // } } // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.6; // Contract doesn't really provide anything... contract OwnableDelegateProxy {} // Required format for OpenSea of proxy delegate store // https://github.com/ProjectOpenSea/opensea-creatures/blob/f7257a043e82fae8251eec2bdde37a44fee474c4/contracts/ERC721Tradable.sol // https://etherscan.io/address/0xa5409ec958c83c3f309868babaca7c86dcb077c1#code contract ProxyRegistry { mapping(address => OwnableDelegateProxy) public proxies; } // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.6; import "./FurLib.sol"; /// @title Dice /// @author LFG Gaming LLC /// @notice Math utility functions that leverage storage and thus cannot be pure abstract contract Dice { uint32 private LAST = 0; // Re-seed for PRNG /// @notice A PRNG which re-seeds itself with block information & another PRNG /// @dev This is unit-tested with monobit (frequency) and longestRunOfOnes function roll(uint32 seed) internal returns (uint32) { LAST = uint32(uint256(keccak256( abi.encodePacked(block.timestamp, block.basefee, _prng(LAST == 0 ? seed : LAST))) )); return LAST; } /// @notice A PRNG based upon a Lehmer (Park-Miller) method /// @dev https://en.wikipedia.org/wiki/Lehmer_random_number_generator function _prng(uint32 seed) internal view returns (uint256) { unchecked { uint256 nonce = seed == 0 ? uint32(block.timestamp) : seed; return (nonce * 48271) % 0x7fffffff; } } } // 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: UNLICENSED pragma solidity ^0.8.6; import "./FurProxy.sol"; import "./FurLib.sol"; import "../Furballs.sol"; /// @title Stakeholders /// @author LFG Gaming LLC /// @notice Tracks "percent ownership" of a smart contract, paying out according to schedule /// @dev Acts as a treasury, receiving ETH funds and distributing them to stakeholders abstract contract Stakeholders is FurProxy { // stakeholder values, in 1/1000th of a percent (received during withdrawls) mapping(address => uint64) public stakes; // List of stakeholders. address[] public stakeholders; // Where any remaining funds should be deposited. Defaults to contract creator. address payable public poolAddress; constructor(address furballsAddress) FurProxy(furballsAddress) { poolAddress = payable(msg.sender); } /// @notice Overflow pool of funds. Contains remaining funds from withdrawl. function setPool(address addr) public onlyOwner { poolAddress = payable(addr); } /// @notice Changes payout percentages. function setStakeholder(address addr, uint64 stake) public onlyOwner { if (!_hasStakeholder(addr)) { stakeholders.push(addr); } uint64 percent = stake; for (uint256 i=0; i<stakeholders.length; i++) { if (stakeholders[i] != addr) { percent += stakes[stakeholders[i]]; } } require(percent <= FurLib.OneHundredPercent, "Invalid stake (exceeds 100%)"); stakes[addr] = stake; } /// @notice Empties this contract's balance, paying out to stakeholders. function withdraw() external gameAdmin { uint256 balance = address(this).balance; require(balance >= FurLib.OneHundredPercent, "Insufficient balance"); for (uint256 i=0; i<stakeholders.length; i++) { address addr = stakeholders[i]; uint256 payout = balance * uint256(stakes[addr]) / FurLib.OneHundredPercent; if (payout > 0) { payable(addr).transfer(payout); } } uint256 remaining = address(this).balance; poolAddress.transfer(remaining); } /// @notice Check function _hasStakeholder(address addr) internal view returns(bool) { for (uint256 i=0; i<stakeholders.length; i++) { if (stakeholders[i] == addr) { return true; } } return false; } // ----------------------------------------------------------------------------------------------- // Payable // ----------------------------------------------------------------------------------------------- /// @notice This contract can be paid transaction fees, e.g., from OpenSea /// @dev The contractURI specifies itself as the recipient of transaction fees receive() external payable { } } // SPDX-License-Identifier: BSD-3-Clause /// @title Vote checkpointing for an ERC-721 token /// @dev This ERC20 has been adopted from /// https://github.com/nounsDAO/nouns-monorepo/blob/master/packages/nouns-contracts/contracts/base/ERC721Checkpointable.sol /********************************* * ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ * * ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ * * ░░░░░░█████████░░█████████░░░ * * ░░░░░░██░░░████░░██░░░████░░░ * * ░░██████░░░████████░░░████░░░ * * ░░██░░██░░░████░░██░░░████░░░ * * ░░██░░██░░░████░░██░░░████░░░ * * ░░░░░░█████████░░█████████░░░ * * ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ * * ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ * *********************************/ // LICENSE // Community.sol uses and modifies part of Compound Lab's Comp.sol: // https://github.com/compound-finance/compound-protocol/blob/ae4388e780a8d596d97619d9704a931a2752c2bc/contracts/Governance/Comp.sol // // Comp.sol source code Copyright 2020 Compound Labs, Inc. licensed under the BSD-3-Clause license. // With modifications by Nounders DAO. // // Additional conditions of BSD-3-Clause can be found here: https://opensource.org/licenses/BSD-3-Clause // // MODIFICATIONS // Checkpointing logic from Comp.sol has been used with the following modifications: // - `delegates` is renamed to `_delegates` and is set to private // - `delegates` is a public function that uses the `_delegates` mapping look-up, but unlike // Comp.sol, returns the delegator's own address if there is no delegate. // This avoids the delegator needing to "delegate to self" with an additional transaction // - `_transferTokens()` is renamed `_beforeTokenTransfer()` and adapted to hook into OpenZeppelin's ERC721 hooks. pragma solidity ^0.8.6; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "./FurLib.sol"; /// @title Community /// @author LFG Gaming LLC /// @notice This is a derived token; it represents a weighted balance of the ERC721 token (Furballs). /// @dev There is no fiscal interest in Community. This is simply a measured value of community voice. contract Community is ERC20 { /// @notice A record of each accounts delegate mapping(address => address) private _delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint96 votes; } constructor() ERC20("FurballsCommunity", "FBLS") { } /// @notice A record of votes checkpoints for each account, by index mapping(address => mapping(uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping(address => uint32) public numCheckpoints; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256('EIP712Domain(string name,uint256 chainId,address verifyingContract)'); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256('Delegation(address delegatee,uint256 nonce,uint256 expiry)'); /// @notice A record of states for signing / validating signatures mapping(address => uint256) public nonces; /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint256 previousBalance, uint256 newBalance); /** * @notice The votes a delegator can delegate, which is the current balance of the delegator. * @dev Used when calling `_delegate()` */ function votesToDelegate(address delegator) public view returns (uint96) { return safe96(balanceOf(delegator), 'Community::votesToDelegate: amount exceeds 96 bits'); } /** * @notice Overrides the standard `Comp.sol` delegates mapping to return * the delegator's own address if they haven't delegated. * This avoids having to delegate to oneself. */ function delegates(address delegator) public view returns (address) { address current = _delegates[delegator]; return current == address(0) ? delegator : current; } /// @notice Sets the addresses' standing directly function update(FurLib.Account memory account, address addr) external returns (uint256) { require(false, 'NEED SECURITY'); // uint256 balance = balanceOf(addr); // if (standing > balance) { // _mint(addr, standing - balance); // } else if (standing < balance) { // _burn(addr, balance - standing); // } } /** * @notice Adapted from `_transferTokens()` in `Comp.sol` to update delegate votes. * @dev hooks into OpenZeppelin's `ERC721._transfer` */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal override { super._beforeTokenTransfer(from, to, amount); require(from == address(0), "Votes may not be traded."); /// @notice Differs from `_transferTokens()` to use `delegates` override method to simulate auto-delegation _moveDelegates(delegates(from), delegates(to), uint96(amount)); } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) public { if (delegatee == address(0)) delegatee = msg.sender; return _delegate(msg.sender, delegatee); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig( address delegatee, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s ) public { bytes32 domainSeparator = keccak256( abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this)) ); bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry)); bytes32 digest = keccak256(abi.encodePacked('\x19\x01', domainSeparator, structHash)); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), 'Community::delegateBySig: invalid signature'); require(nonce == nonces[signatory]++, 'Community::delegateBySig: invalid nonce'); require(block.timestamp <= expiry, 'Community::delegateBySig: signature expired'); return _delegate(signatory, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint96) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint256 blockNumber) public view returns (uint96) { require(blockNumber < block.number, 'Community::getPriorVotes: not yet determined'); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _delegate(address delegator, address delegatee) internal { /// @notice differs from `_delegate()` in `Comp.sol` to use `delegates` override method to simulate auto-delegation address currentDelegate = delegates(delegator); _delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); uint96 amount = votesToDelegate(delegator); _moveDelegates(currentDelegate, delegatee, amount); } function _moveDelegates( address srcRep, address dstRep, uint96 amount ) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { uint32 srcRepNum = numCheckpoints[srcRep]; uint96 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint96 srcRepNew = sub96(srcRepOld, amount, 'Community::_moveDelegates: amount underflows'); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { uint32 dstRepNum = numCheckpoints[dstRep]; uint96 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint96 dstRepNew = add96(dstRepOld, amount, 'Community::_moveDelegates: amount overflows'); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint96 oldVotes, uint96 newVotes ) internal { uint32 blockNumber = safe32( block.number, 'Community::_writeCheckpoint: block number exceeds 32 bits' ); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint256 n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function safe96(uint256 n, string memory errorMessage) internal pure returns (uint96) { require(n < 2**96, errorMessage); return uint96(n); } function add96( uint96 a, uint96 b, string memory errorMessage ) internal pure returns (uint96) { uint96 c = a + b; require(c >= a, errorMessage); return c; } function sub96( uint96 a, uint96 b, string memory errorMessage ) internal pure returns (uint96) { require(b <= a, errorMessage); return a - b; } function getChainId() internal view returns (uint256) { uint256 chainId; assembly { chainId := chainid() } return chainId; } } // 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; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; /** * @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.6; import "../utils/FurProxy.sol"; /// @title Fuel /// @author LFG Gaming LLC /// @notice Simple tracker for how much ETH a user has deposited into Furballs' pools, etc. contract Fuel is FurProxy { mapping(address => uint256) public tank; uint256 public conversionRate = 100000000000; constructor(address furballsAddress) FurProxy(furballsAddress) { } /// @notice Change ETH/Fuel ratio function setConversion(uint256 rate) external gameModerators { conversionRate = rate; } /// @notice Direct deposit function /// @dev Pass zero address to apply to self function deposit(address to) external payable { require(msg.value > 0, "VALUE"); if (to == address(0)) to = msg.sender; tank[to] += msg.value / conversionRate; } /// @notice Sends payout to the treasury function settle(uint256 amount) external gameModerators { if (amount == 0) amount = address(this).balance; furballs.governance().treasury().transfer(amount); } /// @notice Increases balance function gift(address[] calldata tos, uint256[] calldata amounts) external gameModerators { for (uint i=0; i<tos.length; i++) { tank[tos[i]] += amounts[i]; } } /// @notice Decreases balance. Returns the amount withdrawn, where zero indicates failure. /// @dev Does not require/throw, but empties the balance when it exceeds the requested amount. function burn(address from, uint256 amount) external gameModerators returns(uint) { return _burn(from, amount); } /// @notice Burn lots of fuel from different players function burnAll( address[] calldata wallets, uint256[] calldata requestedFuels ) external gameModerators { for (uint i=0; i<wallets.length; i++) { _burn(wallets[i], requestedFuels[i]); } } /// @notice Internal burn function _burn(address from, uint256 amount) internal returns(uint) { uint256 bal = tank[from]; if (bal == 0) { return 0; } else if (bal > amount) { tank[from] = bal - amount; } else { amount = bal; tank[from] = 0; } return amount; } } // 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 "./ECDSA.sol"; /** * @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); } }
@notice When a furball earns FUR via Timekeeper
function addFur(uint256 tokenId, uint32 fur) external gameAdmin { zoneRewards[tokenId].timestamp = uint64(block.timestamp); zoneRewards[tokenId].fur += fur; }
1,277,745
[ 1, 9434, 279, 284, 15850, 454, 425, 1303, 87, 478, 1099, 3970, 2647, 79, 9868, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 225, 445, 527, 42, 295, 12, 11890, 5034, 1147, 548, 16, 2254, 1578, 284, 295, 13, 3903, 7920, 4446, 288, 203, 565, 4157, 17631, 14727, 63, 2316, 548, 8009, 5508, 273, 2254, 1105, 12, 2629, 18, 5508, 1769, 203, 565, 4157, 17631, 14727, 63, 2316, 548, 8009, 74, 295, 1011, 284, 295, 31, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.24; import "https://github.com/itinance/openzeppelin-solidity/blob/master/contracts/token/ERC721/ERC721Full.sol"; import "https://github.com/utgarda/openzeppelin-solidity/blob/master/contracts/access/roles/MinterRole.sol"; import "https://github.com/dalemat/eth-token-recover/blob/master/contracts/TokenRecover.sol"; /** * @title CryptoGiftToken * @author Vittorio Minacori (https://github.com/vittominacori) * @dev It is an ERC721Full with minter role and a struct that identify the gift */ contract CryptoGiftToken is ERC721Full, MinterRole, TokenRecover { // structure that defines a gift struct GiftStructure { uint256 amount; address purchaser; string content; uint256 date; uint256 style; } // number of available gift styles uint256 private _styles; // a progressive id uint256 private _progressiveId; // max available number of gift uint256 private _maxSupply; // Mapping from token ID to the structures mapping(uint256 => GiftStructure) private _structureIndex; // checks if we can generate tokens modifier canGenerate() { require( _progressiveId < _maxSupply, "Max token supply reached" ); _; } constructor( string name, string symbol, uint256 maxSupply ) public ERC721Full(name, symbol) { _maxSupply = maxSupply; } function styles() external view returns (uint256) { return _styles; } function progressiveId() external view returns (uint256) { return _progressiveId; } function maxSupply() external view returns (uint256) { return _maxSupply; } /** * @dev Generate a new gift and the gift structure. */ function newGift( uint256 amount, address purchaser, address beneficiary, string content, uint256 date, uint256 style ) external canGenerate onlyMinter returns (uint256) { require( date > 0, "Date must be greater than zero" ); require( style <= _styles, "Style is not available" ); uint256 tokenId = _progressiveId.add(1); _mint(beneficiary, tokenId); _structureIndex[tokenId] = GiftStructure( amount, purchaser, content, date, style ); _progressiveId = tokenId; return tokenId; } /** * @dev Checks if token is visible. */ function isVisible ( uint256 tokenId ) external view returns (bool visible, uint256 date) { if (_exists(tokenId)) { GiftStructure storage gift = _structureIndex[tokenId]; // solium-disable-next-line security/no-block-members visible = block.timestamp >= gift.date; date = gift.date; } else { visible = false; date = 0; } } /** * @dev Returns the gift structure. */ function getGift (uint256 tokenId) external view returns ( uint256 amount, address purchaser, address beneficiary, string content, uint256 date, uint256 style ) { require( _exists(tokenId), "Token must exists" ); GiftStructure storage gift = _structureIndex[tokenId]; require( block.timestamp >= gift.date, // solium-disable-line security/no-block-members "Now should be greater than gift date" ); amount = gift.amount; purchaser = gift.purchaser; beneficiary = ownerOf(tokenId); content = gift.content; date = gift.date; style = gift.style; } /** * @dev Only contract owner or token owner can burn */ function burn(uint256 tokenId) external { address tokenOwner = isOwner() ? ownerOf(tokenId) : msg.sender; super._burn(tokenOwner, tokenId); delete _structureIndex[tokenId]; } /** * @dev Set the max amount of styles available */ function setStyles(uint256 newStyles) external onlyMinter { require( newStyles > _styles, "Styles cannot be decreased" ); _styles = newStyles; } }
max available number of gift
uint256 private _maxSupply;
1,065,355
[ 1, 1896, 2319, 1300, 434, 314, 2136, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 225, 2254, 5034, 3238, 389, 1896, 3088, 1283, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity >=0.8.0; import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "../interfaces/INFTComplexGemPoolData.sol"; import "../interfaces/ISwapQueryHelper.sol"; import "../interfaces/INFTGemMultiToken.sol"; import "../interfaces/INFTGemGovernor.sol"; import "../interfaces/INFTComplexGemPool.sol"; import "../interfaces/INFTGemFeeManager.sol"; import "../libs/AddressSet.sol"; library ComplexPoolLib { using AddressSet for AddressSet.Set; /** * @dev Event generated when an NFT claim is created using base currency */ event NFTGemClaimCreated( address indexed account, address indexed pool, uint256 indexed claimHash, uint256 length, uint256 quantity, uint256 amountPaid ); /** * @dev Event generated when an NFT claim is created using ERC20 tokens */ event NFTGemERC20ClaimCreated( address indexed account, address indexed pool, uint256 indexed claimHash, uint256 length, address token, uint256 quantity, uint256 conversionRate ); /** * @dev Event generated when an NFT claim is redeemed */ event NFTGemClaimRedeemed( address indexed account, address indexed pool, uint256 indexed claimHash, uint256 amountPaid, uint256 quantity, uint256 feeAssessed ); /** * @dev Event generated when an NFT erc20 claim is redeemed */ event NFTGemERC20ClaimRedeemed( address indexed account, address indexed pool, uint256 indexed claimHash, address token, uint256 ethPrice, uint256 tokenAmount, uint256 quantity, uint256 feeAssessed ); /** * @dev Event generated when a gem is created */ event NFTGemCreated( address account, address pool, uint256 claimHash, uint256 gemHash, uint256 quantity ); /** * @dev data describes complex pool */ struct ComplexPoolData { // governor and multitoken target address pool; address multitoken; address governor; address feeTracker; address swapHelper; uint256 category; bool visible; // it all starts with a symbol and a nams string symbol; string name; string description; // magic economy numbers uint256 ethPrice; uint256 minTime; uint256 maxTime; uint256 diffstep; uint256 maxClaims; uint256 maxQuantityPerClaim; uint256 maxClaimsPerAccount; bool validateerc20; bool allowPurchase; bool enabled; INFTComplexGemPoolData.PriceIncrementType priceIncrementType; mapping(uint256 => INFTGemMultiToken.TokenType) tokenTypes; mapping(uint256 => uint256) tokenIds; mapping(uint256 => address) tokenSources; AddressSet.Set allowedTokenSources; uint256[] tokenHashes; // next ids of things uint256 nextGemIdVal; uint256 nextClaimIdVal; uint256 totalStakedEth; // records claim timestamp / ETH value / ERC token and amount sent mapping(uint256 => uint256) claimLockTimestamps; mapping(uint256 => address) claimLockToken; mapping(uint256 => uint256) claimAmountPaid; mapping(uint256 => uint256) claimQuant; mapping(uint256 => uint256) claimTokenAmountPaid; mapping(uint256 => mapping(address => uint256)) importedLegacyToken; // input NFTs storage mapping(uint256 => uint256) gemClaims; mapping(uint256 => uint256[]) claimIds; mapping(uint256 => uint256[]) claimQuantities; mapping(address => bool) controllers; mapping(address => uint256) claimsMade; INFTComplexGemPoolData.InputRequirement[] inputRequirements; AddressSet.Set allowedTokens; } function checkGemRequirement( ComplexPoolData storage self, uint256 _inputIndex, address _holderAddress, uint256 _quantity ) internal view returns (address) { address gemtoken; int256 required = int256( self.inputRequirements[_inputIndex].minVal * _quantity ); uint256[] memory hashes = INFTGemMultiToken( self.inputRequirements[_inputIndex].token ).heldTokens(_holderAddress); for ( uint256 _hashIndex = 0; _hashIndex < hashes.length; _hashIndex += 1 ) { uint256 hashAt = hashes[_hashIndex]; if ( INFTComplexGemPoolData(self.inputRequirements[_inputIndex].pool) .tokenType(hashAt) == INFTGemMultiToken.TokenType.GEM ) { gemtoken = self.inputRequirements[_inputIndex].token; uint256 balance = IERC1155( self.inputRequirements[_inputIndex].token ).balanceOf(_holderAddress, hashAt); if (balance > uint256(required)) { balance = uint256(required); } if (balance == 0) { continue; } required = required - int256(balance); } if ( required == 0 && self.inputRequirements[_inputIndex].exactAmount == false ) { break; } if (required < 0) { require(required == 0, "EXACT_AMOUNT_REQUIRED"); } } require(required == 0, "UNMET_GEM_REQUIREMENT"); return gemtoken; } /** * @dev checks to see that account owns all the pool requirements needed to mint at least the given quantity of NFT */ function requireInputReqs( ComplexPoolData storage self, address _holderAddress, uint256 _quantity ) public view { for ( uint256 _inputIndex = 0; _inputIndex < self.inputRequirements.length; _inputIndex += 1 ) { if ( self.inputRequirements[_inputIndex].inputType == INFTComplexGemPool.RequirementType.ERC20 ) { require( IERC20(self.inputRequirements[_inputIndex].token).balanceOf( _holderAddress ) >= self.inputRequirements[_inputIndex].minVal * (_quantity), "UNMET_ERC20_REQUIREMENT" ); } else if ( self.inputRequirements[_inputIndex].inputType == INFTComplexGemPool.RequirementType.ERC1155 ) { require( IERC1155(self.inputRequirements[_inputIndex].token) .balanceOf( _holderAddress, self.inputRequirements[_inputIndex].tokenId ) >= self.inputRequirements[_inputIndex].minVal * (_quantity), "UNMET_ERC1155_REQUIREMENT" ); } else if ( self.inputRequirements[_inputIndex].inputType == INFTComplexGemPool.RequirementType.POOL ) { checkGemRequirement( self, _inputIndex, _holderAddress, _quantity ); } } } /** * @dev Transfer a quantity of input reqs from to */ function takeInputReqsFrom( ComplexPoolData storage self, uint256 _claimHash, address _fromAddress, uint256 _quantity ) internal { address gemtoken; for ( uint256 _inputIndex = 0; _inputIndex < self.inputRequirements.length; _inputIndex += 1 ) { if (!self.inputRequirements[_inputIndex].takeCustody) { continue; } if ( self.inputRequirements[_inputIndex].inputType == INFTComplexGemPool.RequirementType.ERC20 ) { IERC20 token = IERC20( self.inputRequirements[_inputIndex].token ); token.transferFrom( _fromAddress, self.pool, self.inputRequirements[_inputIndex].minVal * (_quantity) ); } else if ( self.inputRequirements[_inputIndex].inputType == INFTComplexGemPool.RequirementType.ERC1155 ) { IERC1155 token = IERC1155( self.inputRequirements[_inputIndex].token ); token.safeTransferFrom( _fromAddress, self.pool, self.inputRequirements[_inputIndex].tokenId, self.inputRequirements[_inputIndex].minVal * (_quantity), "" ); } else if ( self.inputRequirements[_inputIndex].inputType == INFTComplexGemPool.RequirementType.POOL ) { gemtoken = checkGemRequirement( self, _inputIndex, _fromAddress, _quantity ); } } if (self.claimIds[_claimHash].length > 0 && gemtoken != address(0)) { IERC1155(gemtoken).safeBatchTransferFrom( _fromAddress, self.pool, self.claimIds[_claimHash], self.claimQuantities[_claimHash], "" ); } } /** * @dev Return the returnable input requirements for claimhash to account */ function returnInputReqsTo( ComplexPoolData storage self, uint256 _claimHash, address _toAddress, uint256 _quantity ) internal { address gemtoken; for (uint256 i = 0; i < self.inputRequirements.length; i++) { if ( self.inputRequirements[i].inputType == INFTComplexGemPool.RequirementType.ERC20 && self.inputRequirements[i].burn == false && self.inputRequirements[i].takeCustody == true ) { IERC20 token = IERC20(self.inputRequirements[i].token); token.transferFrom( self.pool, _toAddress, self.inputRequirements[i].minVal * (_quantity) ); } else if ( self.inputRequirements[i].inputType == INFTComplexGemPool.RequirementType.ERC1155 && self.inputRequirements[i].burn == false && self.inputRequirements[i].takeCustody == true ) { IERC1155 token = IERC1155(self.inputRequirements[i].token); token.safeTransferFrom( self.pool, _toAddress, self.inputRequirements[i].tokenId, self.inputRequirements[i].minVal * (_quantity), "" ); } else if ( self.inputRequirements[i].inputType == INFTComplexGemPool.RequirementType.POOL && self.inputRequirements[i].burn == false && self.inputRequirements[i].takeCustody == true ) { gemtoken = self.inputRequirements[i].token; } } if (self.claimIds[_claimHash].length > 0 && gemtoken != address(0)) { IERC1155(gemtoken).safeBatchTransferFrom( self.pool, _toAddress, self.claimIds[_claimHash], self.claimQuantities[_claimHash], "" ); } } /** * @dev add an input requirement for this token */ function addInputRequirement( ComplexPoolData storage self, address token, address pool, INFTComplexGemPool.RequirementType inputType, uint256 tokenId, uint256 minAmount, bool takeCustody, bool burn, bool exactAmount ) public { require(token != address(0), "INVALID_TOKEN"); require( inputType == INFTComplexGemPool.RequirementType.ERC20 || inputType == INFTComplexGemPool.RequirementType.ERC1155 || inputType == INFTComplexGemPool.RequirementType.POOL, "INVALID_INPUTTYPE" ); require( (inputType == INFTComplexGemPool.RequirementType.POOL && pool != address(0)) || inputType != INFTComplexGemPool.RequirementType.POOL, "INVALID_POOL" ); require( (inputType == INFTComplexGemPool.RequirementType.ERC20 && tokenId == 0) || inputType == INFTComplexGemPool.RequirementType.ERC1155 || (inputType == INFTComplexGemPool.RequirementType.POOL && tokenId == 0), "INVALID_TOKENID" ); require(minAmount != 0, "ZERO_AMOUNT"); require(!(!takeCustody && burn), "INVALID_TOKENSTATE"); self.inputRequirements.push( INFTComplexGemPoolData.InputRequirement( token, pool, inputType, tokenId, minAmount, takeCustody, burn, exactAmount ) ); } /** * @dev update input requirement at index */ function updateInputRequirement( ComplexPoolData storage self, uint256 _index, address _tokenAddress, address _poolAddress, INFTComplexGemPool.RequirementType _inputRequirementType, uint256 _tokenId, uint256 _minAmount, bool _takeCustody, bool _burn, bool _exactAmount ) public { require(_index < self.inputRequirements.length, "OUT_OF_RANGE"); require(_tokenAddress != address(0), "INVALID_TOKEN"); require( _inputRequirementType == INFTComplexGemPool.RequirementType.ERC20 || _inputRequirementType == INFTComplexGemPool.RequirementType.ERC1155 || _inputRequirementType == INFTComplexGemPool.RequirementType.POOL, "INVALID_INPUTTYPE" ); require( (_inputRequirementType == INFTComplexGemPool.RequirementType.POOL && _poolAddress != address(0)) || _inputRequirementType != INFTComplexGemPool.RequirementType.POOL, "INVALID_POOL" ); require( (_inputRequirementType == INFTComplexGemPool.RequirementType.ERC20 && _tokenId == 0) || _inputRequirementType == INFTComplexGemPool.RequirementType.ERC1155 || (_inputRequirementType == INFTComplexGemPool.RequirementType.POOL && _tokenId == 0), "INVALID_TOKENID" ); require(_minAmount != 0, "ZERO_AMOUNT"); require(!(!_takeCustody && _burn), "INVALID_TOKENSTATE"); self.inputRequirements[_index] = INFTComplexGemPoolData .InputRequirement( _tokenAddress, _poolAddress, _inputRequirementType, _tokenId, _minAmount, _takeCustody, _burn, _exactAmount ); } /** * @dev count of input requirements */ function allInputRequirementsLength(ComplexPoolData storage self) public view returns (uint256) { return self.inputRequirements.length; } /** * @dev input requirements at index */ function allInputRequirements(ComplexPoolData storage self, uint256 _index) public view returns ( address, address, INFTComplexGemPool.RequirementType, uint256, uint256, bool, bool, bool ) { require(_index < self.inputRequirements.length, "OUT_OF_RANGE"); INFTComplexGemPoolData.InputRequirement memory req = self .inputRequirements[_index]; return ( req.token, req.pool, req.inputType, req.tokenId, req.minVal, req.takeCustody, req.burn, req.exactAmount ); } /** * @dev attempt to create a claim using the given timeframe with count */ function createClaims( ComplexPoolData storage self, uint256 _timeframe, uint256 _count ) public { // enabled require(self.enabled == true, "DISABLED"); // minimum timeframe require(_timeframe >= self.minTime, "TIMEFRAME_TOO_SHORT"); // no ETH require(msg.value != 0, "ZERO_BALANCE"); // zero qty require(_count != 0, "ZERO_QUANTITY"); // maximum timeframe require( (self.maxTime != 0 && _timeframe <= self.maxTime) || self.maxTime == 0, "TIMEFRAME_TOO_LONG" ); // max quantity per claim require( (self.maxQuantityPerClaim != 0 && _count <= self.maxQuantityPerClaim) || self.maxQuantityPerClaim == 0, "MAX_QUANTITY_EXCEEDED" ); require( (self.maxClaimsPerAccount != 0 && self.claimsMade[msg.sender] < self.maxClaimsPerAccount) || self.maxClaimsPerAccount == 0, "MAX_QUANTITY_EXCEEDED" ); uint256 adjustedBalance = msg.value / (_count); // cost given this timeframe uint256 cost = (self.ethPrice * (self.minTime)) / (_timeframe); require(adjustedBalance >= cost, "INSUFFICIENT_ETH"); // get the nest claim hash, revert if no more claims uint256 claimHash = nextClaimHash(self); require(claimHash != 0, "NO_MORE_CLAIMABLE"); // require the user to have the input requirements requireInputReqs(self, msg.sender, _count); // mint the new claim to the caller's address INFTGemMultiToken(self.multitoken).mint(msg.sender, claimHash, 1); INFTGemMultiToken(self.multitoken).setTokenData( claimHash, INFTGemMultiToken.TokenType.CLAIM, address(this) ); addToken(self, claimHash, INFTGemMultiToken.TokenType.CLAIM); // record the claim unlock time and cost paid for this claim uint256 claimUnlockTimestamp = block.timestamp + (_timeframe); self.claimLockTimestamps[claimHash] = claimUnlockTimestamp; self.claimAmountPaid[claimHash] = cost * (_count); self.claimQuant[claimHash] = _count; self.claimsMade[msg.sender] = self.claimsMade[msg.sender] + (1); // tranasfer NFT input requirements from user to pool takeInputReqsFrom(self, claimHash, msg.sender, _count); // emit an event about it emit NFTGemClaimCreated( msg.sender, address(self.pool), claimHash, _timeframe, _count, cost ); // increase the staked eth balance self.totalStakedEth = self.totalStakedEth + (cost * (_count)); // return the extra to sender if (msg.value > cost * (_count)) { (bool success, ) = payable(msg.sender).call{ value: msg.value - (cost * (_count)) }(""); require(success, "REFUND_FAILED"); } } function getPoolFee(ComplexPoolData storage self, address tokenUsed) internal view returns (uint256) { // get the fee for this pool if it exists uint256 poolDivFeeHash = uint256( keccak256(abi.encodePacked("pool_fee", address(self.pool))) ); uint256 poolFee = INFTGemFeeManager(self.feeTracker).fee( poolDivFeeHash ); // get the pool fee for this token if it exists uint256 poolTokenFeeHash = uint256( keccak256(abi.encodePacked("pool_fee", address(tokenUsed))) ); uint256 poolTokenFee = INFTGemFeeManager(self.feeTracker).fee( poolTokenFeeHash ); // get the default fee amoutn for this token uint256 defaultFeeHash = uint256( keccak256(abi.encodePacked("pool_fee")) ); uint256 defaultFee = INFTGemFeeManager(self.feeTracker).fee( defaultFeeHash ); defaultFee = defaultFee == 0 ? 2000 : defaultFee; // get the fee, preferring the token fee if available uint256 feeNum = poolFee != poolTokenFee ? (poolTokenFee != 0 ? poolTokenFee : poolFee) : poolFee; // set the fee to default if it is 0 return feeNum == 0 ? defaultFee : feeNum; } function getMinimumLiquidity( ComplexPoolData storage self, address tokenUsed ) internal view returns (uint256) { // get the fee for this pool if it exists uint256 poolDivFeeHash = uint256( keccak256(abi.encodePacked("min_liquidity", address(self.pool))) ); uint256 poolFee = INFTGemFeeManager(self.feeTracker).fee( poolDivFeeHash ); // get the pool fee for this token if it exists uint256 poolTokenFeeHash = uint256( keccak256(abi.encodePacked("min_liquidity", address(tokenUsed))) ); uint256 poolTokenFee = INFTGemFeeManager(self.feeTracker).fee( poolTokenFeeHash ); // get the default fee amoutn for this token uint256 defaultFeeHash = uint256( keccak256(abi.encodePacked("min_liquidity")) ); uint256 defaultFee = INFTGemFeeManager(self.feeTracker).fee( defaultFeeHash ); defaultFee = defaultFee == 0 ? 50 : defaultFee; // get the fee, preferring the token fee if available uint256 feeNum = poolFee != poolTokenFee ? (poolTokenFee != 0 ? poolTokenFee : poolFee) : poolFee; // set the fee to default if it is 0 return feeNum == 0 ? defaultFee : feeNum; } /** * @dev crate multiple gem claim using an erc20 token. this token must be tradeable in Uniswap or this call will fail */ function createERC20Claims( ComplexPoolData storage self, address erc20token, uint256 tokenAmount, uint256 count ) public { // enabled require(self.enabled == true, "DISABLED"); // must be a valid address require(erc20token != address(0), "INVALID_ERC20_TOKEN"); // token is allowed require( (self.allowedTokens.count() > 0 && self.allowedTokens.exists(erc20token)) || self.allowedTokens.count() == 0, "TOKEN_DISALLOWED" ); // zero qty require(count != 0, "ZERO_QUANTITY"); // max quantity per claim require( (self.maxQuantityPerClaim != 0 && count <= self.maxQuantityPerClaim) || self.maxQuantityPerClaim == 0, "MAX_QUANTITY_EXCEEDED" ); require( (self.maxClaimsPerAccount != 0 && self.claimsMade[msg.sender] < self.maxClaimsPerAccount) || self.maxClaimsPerAccount == 0, "MAX_QUANTITY_EXCEEDED" ); // require the user to have the input requirements requireInputReqs(self, msg.sender, count); // Uniswap pool must exist require( ISwapQueryHelper(self.swapHelper).hasPool(erc20token) == true, "NO_UNISWAP_POOL" ); // must have an amount specified require(tokenAmount >= 0, "NO_PAYMENT_INCLUDED"); // get a quote in ETH for the given token. ( uint256 ethereum, uint256 tokenReserve, uint256 ethReserve ) = ISwapQueryHelper(self.swapHelper).coinQuote( erc20token, tokenAmount / (count) ); // TODO: update liquidity multiple from fee manager if (self.validateerc20 == true) { uint256 minLiquidity = getMinimumLiquidity(self, erc20token); // make sure the convertible amount is has reserves > 100x the token require( ethReserve >= ethereum * minLiquidity * (count), "INSUFFICIENT_ETH_LIQUIDITY" ); // make sure the convertible amount is has reserves > 100x the token require( tokenReserve >= tokenAmount * minLiquidity * (count), "INSUFFICIENT_TOKEN_LIQUIDITY" ); } // make sure the convertible amount is less than max price require(ethereum <= self.ethPrice, "OVERPAYMENT"); // calculate the maturity time given the converted eth uint256 maturityTime = (self.ethPrice * (self.minTime)) / (ethereum); // make sure the convertible amount is less than max price require(maturityTime >= self.minTime, "INSUFFICIENT_TIME"); // get the next claim hash, revert if no more claims uint256 claimHash = nextClaimHash(self); require(claimHash != 0, "NO_MORE_CLAIMABLE"); // mint the new claim to the caller's address INFTGemMultiToken(self.multitoken).mint(msg.sender, claimHash, 1); INFTGemMultiToken(self.multitoken).setTokenData( claimHash, INFTGemMultiToken.TokenType.CLAIM, address(this) ); addToken(self, claimHash, INFTGemMultiToken.TokenType.CLAIM); // record the claim unlock time and cost paid for this claim uint256 claimUnlockTimestamp = block.timestamp + (maturityTime); self.claimLockTimestamps[claimHash] = claimUnlockTimestamp; self.claimAmountPaid[claimHash] = ethereum; self.claimLockToken[claimHash] = erc20token; self.claimTokenAmountPaid[claimHash] = tokenAmount; self.claimQuant[claimHash] = count; self.claimsMade[msg.sender] = self.claimsMade[msg.sender] + (1); // tranasfer NFT input requirements from user to pool takeInputReqsFrom(self, claimHash, msg.sender, count); // increase staked eth amount self.totalStakedEth = self.totalStakedEth + (ethereum); // emit a message indicating that an erc20 claim has been created emit NFTGemERC20ClaimCreated( msg.sender, address(self.pool), claimHash, maturityTime, erc20token, count, ethereum ); // transfer the caller's ERC20 tokens into the pool IERC20(erc20token).transferFrom( msg.sender, address(self.pool), tokenAmount ); } /** * @dev collect an open claim (take custody of the funds the claim is redeeemable for and maybe a gem too) */ function collectClaim( ComplexPoolData storage self, uint256 _claimHash, bool _requireMature ) public { // enabled require(self.enabled == true, "DISABLED"); // check the maturity of the claim - only issue gem if mature uint256 unlockTime = self.claimLockTimestamps[_claimHash]; bool isMature = unlockTime < block.timestamp; require( !_requireMature || (_requireMature && isMature), "IMMATURE_CLAIM" ); __collectClaim(self, _claimHash); } /** * @dev collect an open claim (take custody of the funds the claim is redeeemable for and maybe a gem too) */ function __collectClaim(ComplexPoolData storage self, uint256 claimHash) internal { // validation checks - disallow if not owner (holds coin with claimHash) // or if the unlockTime amd unlockPaid data is in an invalid state require( IERC1155(self.multitoken).balanceOf(msg.sender, claimHash) == 1, "NOT_CLAIM_OWNER" ); uint256 unlockTime = self.claimLockTimestamps[claimHash]; uint256 unlockPaid = self.claimAmountPaid[claimHash]; require(unlockTime != 0 && unlockPaid > 0, "INVALID_CLAIM"); // grab the erc20 token info if there is any address tokenUsed = self.claimLockToken[claimHash]; uint256 unlockTokenPaid = self.claimTokenAmountPaid[claimHash]; // check the maturity of the claim - only issue gem if mature bool isMature = unlockTime < block.timestamp; // burn claim and transfer money back to user INFTGemMultiToken(self.multitoken).burn(msg.sender, claimHash, 1); // if they used erc20 tokens stake their claim, return their tokens if (tokenUsed != address(0)) { // calculate fee portion using fee tracker uint256 feePortion = 0; if (isMature == true) { feePortion = unlockTokenPaid / getPoolFee(self, tokenUsed); } // assess a fee for minting the NFT. Fee is collectec in fee tracker IERC20(tokenUsed).transferFrom( address(self.pool), self.feeTracker, feePortion ); // send the principal minus fees to the caller IERC20(tokenUsed).transferFrom( address(self.pool), msg.sender, unlockTokenPaid - (feePortion) ); // emit an event that the claim was redeemed for ERC20 emit NFTGemERC20ClaimRedeemed( msg.sender, address(self.pool), claimHash, tokenUsed, unlockPaid, unlockTokenPaid, self.claimQuant[claimHash], feePortion ); } else { // calculate fee portion using fee tracker uint256 feePortion = 0; if (isMature == true) { feePortion = unlockPaid / getPoolFee(self, address(0)); } // transfer the ETH fee to fee tracker payable(self.feeTracker).transfer(feePortion); // transfer the ETH back to user payable(msg.sender).transfer(unlockPaid - (feePortion)); // emit an event that the claim was redeemed for ETH emit NFTGemClaimRedeemed( msg.sender, address(self.pool), claimHash, unlockPaid, self.claimQuant[claimHash], feePortion ); } // tranasfer NFT input requirements from pool to user returnInputReqsTo( self, claimHash, msg.sender, self.claimQuant[claimHash] ); // deduct the total staked ETH balance of the pool self.totalStakedEth = self.totalStakedEth - (unlockPaid); // if all this is happening before the unlocktime then we exit // without minting a gem because the user is withdrawing early if (!isMature) { return; } // get the next gem hash, increase the staking sifficulty // for the pool, and mint a gem token back to account uint256 nextHash = nextGemHash(self); // associate gem and claim self.gemClaims[nextHash] = claimHash; // mint the gem INFTGemMultiToken(self.multitoken).mint( msg.sender, nextHash, self.claimQuant[claimHash] ); addToken(self, nextHash, INFTGemMultiToken.TokenType.GEM); // emit an event about a gem getting created emit NFTGemCreated( msg.sender, address(self.pool), claimHash, nextHash, self.claimQuant[claimHash] ); } /** * @dev purchase gem(s) at the listed pool price */ function purchaseGems( ComplexPoolData storage self, address sender, uint256 value, uint256 count ) public { // enabled require(self.enabled == true, "DISABLED"); // non-zero balance require(value != 0, "ZERO_BALANCE"); // non-zero quantity require(count != 0, "ZERO_QUANTITY"); // sufficient input eth uint256 adjustedBalance = value / (count); require(adjustedBalance >= self.ethPrice, "INSUFFICIENT_ETH"); require(self.allowPurchase == true, "PURCHASE_DISALLOWED"); // get the next gem hash, increase the staking sifficulty // for the pool, and mint a gem token back to account uint256 nextHash = nextGemHash(self); // mint the gem INFTGemMultiToken(self.multitoken).mint(sender, nextHash, count); addToken(self, nextHash, INFTGemMultiToken.TokenType.GEM); // transfer the funds for the gem to the fee tracker payable(self.feeTracker).transfer(value); // emit an event about a gem getting created emit NFTGemCreated(sender, address(self.pool), 0, nextHash, count); } /** * @dev create a token of token hash / token type */ function addToken( ComplexPoolData storage self, uint256 tokenHash, INFTGemMultiToken.TokenType tokenType ) public { require( tokenType == INFTGemMultiToken.TokenType.CLAIM || tokenType == INFTGemMultiToken.TokenType.GEM, "INVALID_TOKENTYPE" ); self.tokenHashes.push(tokenHash); self.tokenTypes[tokenHash] = tokenType; self.tokenIds[tokenHash] = tokenType == INFTGemMultiToken.TokenType.CLAIM ? nextClaimId(self) : nextGemId(self); INFTGemMultiToken(self.multitoken).setTokenData( tokenHash, tokenType, address(this) ); if (tokenType == INFTGemMultiToken.TokenType.GEM) { increaseDifficulty(self); } } /** * @dev get the next claim id */ function nextClaimId(ComplexPoolData storage self) public returns (uint256) { uint256 ncId = self.nextClaimIdVal; self.nextClaimIdVal = self.nextClaimIdVal + (1); return ncId; } /** * @dev get the next gem id */ function nextGemId(ComplexPoolData storage self) public returns (uint256) { uint256 ncId = self.nextGemIdVal; self.nextGemIdVal = self.nextGemIdVal + (1); return ncId; } /** * @dev increase the pool's difficulty by calculating the step increase portion and adding it to the eth price of the market */ function increaseDifficulty(ComplexPoolData storage self) public { if ( self.priceIncrementType == INFTComplexGemPoolData.PriceIncrementType.COMPOUND ) { uint256 diffIncrease = self.ethPrice / (self.diffstep); self.ethPrice = self.ethPrice + (diffIncrease); } else if ( self.priceIncrementType == INFTComplexGemPoolData.PriceIncrementType.INVERSELOG ) { uint256 diffIncrease = self.diffstep / (self.ethPrice); self.ethPrice = self.ethPrice + (diffIncrease); } } /** * @dev the hash of the next gem to be minted */ function nextGemHash(ComplexPoolData storage self) public view returns (uint256) { return uint256( keccak256( abi.encodePacked( "gem", address(self.pool), self.nextGemIdVal ) ) ); } /** * @dev the hash of the next claim to be minted */ function nextClaimHash(ComplexPoolData storage self) public view returns (uint256) { return (self.maxClaims != 0 && self.nextClaimIdVal <= self.maxClaims) || self.maxClaims == 0 ? uint256( keccak256( abi.encodePacked( "claim", address(self.pool), self.nextClaimIdVal ) ) ) : 0; } /** * @dev get the token hash at index */ function allTokenHashes(ComplexPoolData storage self, uint256 ndx) public view returns (uint256) { return self.tokenHashes[ndx]; } /** * @dev return the claim amount paid for this claim */ function claimAmount(ComplexPoolData storage self, uint256 claimHash) public view returns (uint256) { return self.claimAmountPaid[claimHash]; } /** * @dev the claim quantity (count of gems staked) for the given claim hash */ function claimQuantity(ComplexPoolData storage self, uint256 claimHash) public view returns (uint256) { return self.claimQuant[claimHash]; } /** * @dev the lock time for this claim hash. once past lock time a gem is minted */ function claimUnlockTime(ComplexPoolData storage self, uint256 claimHash) public view returns (uint256) { return self.claimLockTimestamps[claimHash]; } /** * @dev return the claim token amount for this claim hash */ function claimTokenAmount(ComplexPoolData storage self, uint256 claimHash) public view returns (uint256) { return self.claimTokenAmountPaid[claimHash]; } /** * @dev return the claim hash of the given gemhash */ function gemClaimHash(ComplexPoolData storage self, uint256 gemHash) public view returns (uint256) { return self.gemClaims[gemHash]; } /** * @dev return the token that was staked to create the given token hash. 0 if the native token */ function stakedToken(ComplexPoolData storage self, uint256 claimHash) public view returns (address) { return self.claimLockToken[claimHash]; } /** * @dev add a token that is allowed to be used to create a claim */ function addAllowedToken(ComplexPoolData storage self, address token) public { if (!self.allowedTokens.exists(token)) { self.allowedTokens.insert(token); } } /** * @dev remove a token that is allowed to be used to create a claim */ function removeAllowedToken(ComplexPoolData storage self, address token) public { if (self.allowedTokens.exists(token)) { self.allowedTokens.remove(token); } } /** * @dev deposit into pool */ function deposit( ComplexPoolData storage self, address erc20token, uint256 tokenAmount ) public { if (erc20token == address(0)) { require(msg.sender.balance >= tokenAmount, "INSUFFICIENT_BALANCE"); self.totalStakedEth = self.totalStakedEth + (msg.sender.balance); } else { require( IERC20(erc20token).balanceOf(msg.sender) >= tokenAmount, "INSUFFICIENT_BALANCE" ); IERC20(erc20token).transferFrom( msg.sender, address(self.pool), tokenAmount ); } } /** * @dev deposit NFT into pool */ function depositNFT( ComplexPoolData storage self, address erc1155token, uint256 tokenId, uint256 tokenAmount ) public { require( IERC1155(erc1155token).balanceOf(msg.sender, tokenId) >= tokenAmount, "INSUFFICIENT_BALANCE" ); IERC1155(erc1155token).safeTransferFrom( msg.sender, address(self.pool), tokenId, tokenAmount, "" ); } /** * @dev withdraw pool contents */ function withdraw( ComplexPoolData storage self, address erc20token, address destination, uint256 tokenAmount ) public { require(destination != address(0), "ZERO_ADDRESS"); require( self.controllers[msg.sender] == true || msg.sender == self.governor, "UNAUTHORIZED" ); if (erc20token == address(0)) { payable(destination).transfer(tokenAmount); } else { IERC20(erc20token).transferFrom( address(self.pool), address(destination), tokenAmount ); } } /** * @dev withdraw pool NFT */ function withdrawNFT( ComplexPoolData storage self, address erc1155token, address destination, uint256 tokenId, uint256 tokenAmount ) public { require( self.controllers[msg.sender] == true || msg.sender == self.governor, "UNAUTHORIZED" ); require(erc1155token != address(0), "ZERO_ADDRESS"); require(destination != address(0), "ZERO_ADDRESS"); require( IERC1155(erc1155token).balanceOf(address(self.pool), tokenId) >= tokenAmount, "INSUFFICIENT_BALANCE" ); IERC1155(erc1155token).safeTransferFrom( address(self.pool), address(destination), tokenId, tokenAmount, "" ); } /** * @dev mint the genesis gems earned by the pools creator and funder */ function mintGenesisGems( ComplexPoolData storage self, address creator, address funder ) public { require(self.multitoken != address(0), "NO_MULTITOKEN"); require( creator != address(0) && funder != address(0), "ZERO_DESTINATION" ); require(self.nextGemIdVal == 0, "ALREADY_MINTED"); uint256 gemHash = nextGemHash(self); INFTGemMultiToken(self.multitoken).mint(creator, gemHash, 1); addToken(self, gemHash, INFTGemMultiToken.TokenType.GEM); // emit an event about a gem getting created emit NFTGemCreated(creator, address(self.pool), 0, gemHash, 1); gemHash = nextGemHash(self); INFTGemMultiToken(self.multitoken).mint(funder, gemHash, 1); addToken(self, gemHash, INFTGemMultiToken.TokenType.GEM); // emit an event about a gem getting created emit NFTGemCreated(funder, address(self.pool), 0, gemHash, 1); } }
make sure the convertible amount is less than max price
require(maturityTime >= self.minTime, "INSUFFICIENT_TIME");
15,863,456
[ 1, 6540, 3071, 326, 1765, 1523, 3844, 353, 5242, 2353, 943, 6205, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 2583, 12, 7373, 2336, 950, 1545, 365, 18, 1154, 950, 16, 315, 706, 6639, 42, 1653, 7266, 2222, 67, 4684, 8863, 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 ]
pragma solidity ^0.4.24; library NameFilter { /** * @dev filters name strings * -converts uppercase to lower case. * -makes sure it does not start/end with a space * -makes sure it does not contain multiple spaces in a row * -cannot be only numbers * -cannot start with 0x * -restricts characters to A-Z, a-z, 0-9, and space. * @return reprocessed string in bytes32 format */ function nameFilter(string _input) internal pure returns(bytes32) { bytes memory _temp = bytes(_input); uint256 _length = _temp.length; //sorry limited to 32 characters require (_length <= 32 && _length > 0, "string must be between 1 and 32 characters"); // make sure it doesnt start with or end with space require(_temp[0] != 0x20 && _temp[_length-1] != 0x20, "string cannot start or end with space"); // make sure first two characters are not 0x if (_temp[0] == 0x30) { require(_temp[1] != 0x78, "string cannot start with 0x"); require(_temp[1] != 0x58, "string cannot start with 0X"); } // create a bool to track if we have a non number character bool _hasNonNumber; // convert & check for (uint256 i = 0; i < _length; i++) { // if its uppercase A-Z if (_temp[i] > 0x40 && _temp[i] < 0x5b) { // convert to lower case a-z _temp[i] = byte(uint(_temp[i]) + 32); // we have a non number if (_hasNonNumber == false) _hasNonNumber = true; } else { require ( // require character is a space _temp[i] == 0x20 || // OR lowercase a-z (_temp[i] > 0x60 && _temp[i] < 0x7b) || // or 0-9 (_temp[i] > 0x2f && _temp[i] < 0x3a), "string contains invalid characters" ); // make sure theres not 2x spaces in a row if (_temp[i] == 0x20) require( _temp[i+1] != 0x20, "string cannot contain consecutive spaces"); // see if we have a character other than a number if (_hasNonNumber == false && (_temp[i] < 0x30 || _temp[i] > 0x39)) _hasNonNumber = true; } } require(_hasNonNumber == true, "string cannot be only numbers"); bytes32 _ret; assembly { _ret := mload(add(_temp, 32)) } return (_ret); } } /** * @title SafeMath v0.1.9 * @dev Math operations with safety checks that throw on error * change notes: original SafeMath library from OpenZeppelin modified by Inventor * - added sqrt * - added sq * - added pwr * - changed asserts to requires with error log outputs * - removed div, its useless */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; require(c / a == b, "SafeMath mul failed"); return c; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath sub failed"); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; require(c >= a, "SafeMath add failed"); return c; } /** * @dev gives square root of given x. */ function sqrt(uint256 x) internal pure returns (uint256 y) { uint256 z = ((add(x,1)) / 2); y = x; while (z < y) { y = z; z = ((add((x / z),z)) / 2); } } /** * @dev gives square. multiplies x by x */ function sq(uint256 x) internal pure returns (uint256) { return (mul(x,x)); } /** * @dev x to the power of y */ function pwr(uint256 x, uint256 y) internal pure returns (uint256) { if (x==0) return (0); else if (y==0) return (1); else { uint256 z = x; for (uint256 i=1; i < y; i++) z = mul(z,x); return (z); } } } //============================================================================== // __|_ _ __|_ _ . // _\ | | |_|(_ | _\ . //============================================================================== library F3Ddatasets { //compressedData key // [76-33][32][31][30][29][28-18][17][16-6][5-3][2][1][0] // 0 - new player (bool) // 1 - joined round (bool) // 2 - new leader (bool) // 3-5 - air drop tracker (uint 0-999) // 6-16 - round end time // 17 - winnerTeam // 18 - 28 timestamp // 29 - team // 30 - 0 = reinvest (round), 1 = buy (round), 2 = buy (ico), 3 = reinvest (ico) // 31 - airdrop happened bool // 32 - airdrop tier // 33 - airdrop amount won //compressedIDs key // [77-52][51-26][25-0] // 0-25 - pID // 26-51 - winPID // 52-77 - rID struct EventReturns { uint256 compressedData; uint256 compressedIDs; address winnerAddr; // winner address bytes32 winnerName; // winner name uint256 amountWon; // amount won uint256 newPot; // amount in new pot uint256 P3DAmount; // amount distributed to p3d uint256 genAmount; // amount distributed to gen uint256 potAmount; // amount added to pot } struct Player { address addr; // player address bytes32 name; // player name uint256 win; // winnings vault uint256 gen; // general vault uint256 aff; // affiliate vault uint256 lrnd; // last round played uint256 laff; // last affiliate id used } struct PlayerRounds { uint256 eth; // eth player has added to round (used for eth limiter) uint256 keys; // keys uint256 mask; // player mask uint256 ico; // ICO phase investment } struct Round { uint256 plyr; // pID of player in lead uint256 team; // tID of team in lead uint256 end; // time ends/ended bool ended; // has round end function been ran uint256 strt; // time round started uint256 keys; // keys uint256 eth; // total eth in uint256 pot; // eth to pot (during round) / final amount paid to winner (after round ends) uint256 mask; // global mask uint256 ico; // total eth sent in during ICO phase uint256 icoGen; // total eth for gen during ICO phase uint256 icoAvg; // average key price for ICO phase } struct TeamFee { uint256 gen; // % of buy in thats paid to key holders of current round uint256 p3d; // % of buy in thats paid to p3d holders } struct PotSplit { uint256 gen; // % of pot thats paid to key holders of current round uint256 p3d; // % of pot thats paid to p3d holders } } //============================================================================== // | _ _ _ | _ . // |<(/_\/ (_(_||(_ . //=======/====================================================================== library F3DKeysCalcShort { using SafeMath for *; /** * @dev calculates number of keys received given X eth * @param _curEth current amount of eth in contract * @param _newEth eth being spent * @return amount of ticket purchased */ function keysRec(uint256 _curEth, uint256 _newEth) internal pure returns (uint256) { return(keys((_curEth).add(_newEth)).sub(keys(_curEth))); } /** * @dev calculates amount of eth received if you sold X keys * @param _curKeys current amount of keys that exist * @param _sellKeys amount of keys you wish to sell * @return amount of eth received */ function ethRec(uint256 _curKeys, uint256 _sellKeys) internal pure returns (uint256) { return((eth(_curKeys)).sub(eth(_curKeys.sub(_sellKeys)))); } /** * @dev calculates how many keys would exist with given an amount of eth * @param _eth eth "in contract" * @return number of keys that would exist */ function keys(uint256 _eth) internal pure returns(uint256) { return ((((((_eth).mul(1000000000000000000)).mul(312500000000000000000000000)).add(5624988281256103515625000000000000000000000000000000000000000000)).sqrt()).sub(74999921875000000000000000000000)) / (156250000); } /** * @dev calculates how much eth would be in contract given a number of keys * @param _keys number of keys "in contract" * @return eth that would exists */ function eth(uint256 _keys) internal pure returns(uint256) { return ((78125000).mul(_keys.sq()).add(((149999843750000).mul(_keys.mul(1000000000000000000))) / (2))) / ((1000000000000000000).sq()); } } //============================================================================== // . _ _|_ _ _ |` _ _ _ _ . // || | | (/_| ~|~(_|(_(/__\ . //============================================================================== contract F3Devents { // fired whenever a player registers a name event onNewName ( uint256 indexed playerID, address indexed playerAddress, bytes32 indexed playerName, bool isNewPlayer, uint256 affiliateID, address affiliateAddress, bytes32 affiliateName, uint256 amountPaid, uint256 timeStamp ); // fired at end of buy or reload event onEndTx ( uint256 compressedData, uint256 compressedIDs, bytes32 playerName, address playerAddress, uint256 ethIn, uint256 keysBought, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 P3DAmount, uint256 genAmount, uint256 potAmount, uint256 airDropPot ); // fired whenever theres a withdraw event onWithdraw ( uint256 indexed playerID, address playerAddress, bytes32 playerName, uint256 ethOut, uint256 timeStamp ); // fired whenever a withdraw forces end round to be ran event onWithdrawAndDistribute ( address playerAddress, bytes32 playerName, uint256 ethOut, uint256 compressedData, uint256 compressedIDs, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 P3DAmount, uint256 genAmount ); // (fomo3d short only) fired whenever a player tries a buy after round timer // hit zero, and causes end round to be ran. event onBuyAndDistribute ( address playerAddress, bytes32 playerName, uint256 ethIn, uint256 compressedData, uint256 compressedIDs, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 P3DAmount, uint256 genAmount ); // (fomo3d short only) fired whenever a player tries a reload after round timer // hit zero, and causes end round to be ran. event onReLoadAndDistribute ( address playerAddress, bytes32 playerName, uint256 compressedData, uint256 compressedIDs, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 P3DAmount, uint256 genAmount ); // fired whenever an affiliate is paid event onAffiliatePayout ( uint256 indexed affiliateID, address affiliateAddress, bytes32 affiliateName, uint256 indexed roundID, uint256 indexed buyerID, uint256 amount, uint256 timeStamp ); // received pot swap deposit event onPotSwapDeposit ( uint256 roundID, uint256 amountAddedToPot ); } interface PlayerBookInterface { function getPlayerID(address _addr) external returns (uint256); function getPlayerName(uint256 _pID) external view returns (bytes32); function getPlayerLAff(uint256 _pID) external view returns (uint256); function getPlayerAddr(uint256 _pID) external view returns (address); function getNameFee() external view returns (uint256); function registerNameXIDFromDapp(address _addr, bytes32 _name, uint256 _affCode, bool _all) external payable returns(bool, uint256); function registerNameXaddrFromDapp(address _addr, bytes32 _name, address _affCode, bool _all) external payable returns(bool, uint256); function registerNameXnameFromDapp(address _addr, bytes32 _name, bytes32 _affCode, bool _all) external payable returns(bool, uint256); } contract modularFast is F3Devents {} contract FoMo3DFast is modularFast { using SafeMath for *; using NameFilter for string; using F3DKeysCalcShort for uint256; PlayerBookInterface constant private PlayerBook = PlayerBookInterface(0x62F9Cd807779A0e8534d564A00230a9b7D241391); address private admin = msg.sender; string constant public name = "OTION"; string constant public symbol = "OTION"; uint256 private rndExtra_ = 30 minutes; // length of the very first ICO uint256 private rndGap_ = 30 minutes; // length of ICO phase, set to 1 year for EOS. uint256 constant private rndInit_ = 888 minutes; // round timer starts at this uint256 constant private rndInc_ = 20 seconds; // every full key purchased adds this much to the timer uint256 constant private rndMax_ = 888 minutes; // max length a round timer can be uint256 public airDropPot_; // person who gets the airdrop wins part of this pot uint256 public airDropTracker_ = 0; // incremented each time a "qualified" tx occurs. used to determine winning air drop uint256 public rID_; // round id number / total rounds that have happened //**************** // PLAYER DATA //**************** mapping (address => uint256) public pIDxAddr_; // (addr => pID) returns player id by address mapping (bytes32 => uint256) public pIDxName_; // (name => pID) returns player id by name mapping (uint256 => F3Ddatasets.Player) public plyr_; // (pID => data) player data // (pID => rID => data) player round data by player id & round id mapping (uint256 => mapping (uint256 => F3Ddatasets.PlayerRounds)) public plyrRnds_; mapping (uint256 => mapping (bytes32 => bool)) public plyrNames_; // (pID => name => bool) list of names a player owns. (used so you can change your display name amongst any name you own) //**************** // ROUND DATA //**************** mapping (uint256 => F3Ddatasets.Round) public round_; // (rID => data) round data mapping (uint256 => mapping(uint256 => uint256)) public rndTmEth_; // (rID => tID => data) eth in per team, by round id and team id //**************** // TEAM FEE DATA //**************** mapping (uint256 => F3Ddatasets.TeamFee) public fees_; // (team => fees) fee distribution by team mapping (uint256 => F3Ddatasets.PotSplit) public potSplit_; // (team => fees) pot split distribution by team constructor() public { // Team allocation structures // 0 = the only team // Team allocation percentages // (F3D, P3D) + (Pot , Referrals, Community) 解读:TeamFee, PotSplit 第一个参数都是分给现在key holder的比例, 第二个是给Pow3D的比例 // Referrals / Community rewards are mathematically designed to come from the winner's share of the pot. fees_[0] = F3Ddatasets.TeamFee(80,0); //10% to pot, 8% to aff, 2% to com // how to split up the final pot based on which team was picked // (F3D, P3D) potSplit_[0] = F3Ddatasets.PotSplit(0,0); //100% to winner } //============================================================================== // _ _ _ _|. |`. _ _ _ . // | | |(_)(_||~|~|(/_| _\ . (these are safety checks) //============================================================================== /** * @dev used to make sure no one can interact with contract until it has * been activated. */ modifier isActivated() { require(activated_ == true, "its not ready yet. check ?eta in discord"); _; } /** * @dev prevents contracts from interacting with fomo3d */ modifier isHuman() { address _addr = msg.sender; uint256 _codeLength; assembly {_codeLength := extcodesize(_addr)} require(_codeLength == 0, "sorry humans only"); _; } /** * @dev sets boundaries for incoming tx */ modifier isWithinLimits(uint256 _eth) { require(_eth >= 1000000000, "pocket lint: not a valid currency"); _; } //============================================================================== // _ |_ |. _ |` _ __|_. _ _ _ . // |_)|_||_)||(_ ~|~|_|| |(_ | |(_)| |_\ . (use these to interact with contract) //====|========================================================================= /** * @dev emergency buy uses last stored affiliate ID and team snek */ function() isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // buy core buyCore(_pID, _eventData_); } function buyXnameQR(address _realSender) isActivated() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not F3Ddatasets.EventReturns memory _eventData_ = determinePIDQR(_realSender,_eventData_); // fetch player id uint256 _pID = pIDxAddr_[_realSender]; // // manage affiliate residuals // uint256 _affID = 1; // // verify a valid team was selected // uint256 _team = 0; // buy core buyCoreQR(_realSender, _pID, _eventData_); } /** * @dev withdraws all of your earnings. * -functionhash- 0x3ccfd60b */ function withdraw() isActivated() isHuman() public { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // setup temp var for player eth uint256 _eth; // check to see if round has ended and no one has run round end yet if (_now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0) { // set up our tx event data F3Ddatasets.EventReturns memory _eventData_; // end the round (distributes pot) round_[_rID].ended = true; _eventData_ = endRound(_eventData_); // get their earnings _eth = withdrawEarnings(_pID); // gib moni if (_eth > 0) plyr_[_pID].addr.transfer(_eth); // build event data _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; // fire withdraw and distribute event emit F3Devents.onWithdrawAndDistribute ( msg.sender, plyr_[_pID].name, _eth, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.P3DAmount, _eventData_.genAmount ); // in any other situation } else { // get their earnings _eth = withdrawEarnings(_pID); // gib moni if (_eth > 0) plyr_[_pID].addr.transfer(_eth); // fire withdraw event emit F3Devents.onWithdraw(_pID, msg.sender, plyr_[_pID].name, _eth, _now); } } /** * @dev withdraws all of your earnings. * -functionhash- 0x3ccfd60b */ function withdrawQR(address _realSender) isActivated() payable public { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // fetch player ID uint256 _pID = pIDxAddr_[_realSender]; // setup temp var for player eth uint256 _eth; // check to see if round has ended and no one has run round end yet if (_now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0) { // set up our tx event data F3Ddatasets.EventReturns memory _eventData_; // end the round (distributes pot) round_[_rID].ended = true; _eventData_ = endRound(_eventData_); // get their earnings _eth = withdrawEarnings(_pID); // gib moni if (_eth > 0) plyr_[_pID].addr.transfer(_eth); // build event data _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; // fire withdraw and distribute event emit F3Devents.onWithdrawAndDistribute ( _realSender, plyr_[_pID].name, _eth, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.P3DAmount, _eventData_.genAmount ); // in any other situation } else { // get their earnings _eth = withdrawEarnings(_pID); // gib moni if (_eth > 0) plyr_[_pID].addr.transfer(_eth); // fire withdraw event emit F3Devents.onWithdraw(_pID, _realSender, plyr_[_pID].name, _eth, _now); } } //============================================================================== // _ _ _|__|_ _ _ _ . // (_|(/_ | | (/_| _\ . (for UI & viewing things on etherscan) //=====_|======================================================================= /** * @dev return the price buyer will pay for next 1 individual key. * -functionhash- 0x018a25e8 * @return price for next key bought (in wei format) */ function getBuyPrice() public view returns(uint256) { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // are we in a round? if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) return ( (round_[_rID].keys.add(1000000000000000000)).ethRec(1000000000000000000) ); else // rounds over. need price for new round return ( 75000000000000 ); // init } /** * @dev returns time left. dont spam this, you'll ddos yourself from your node * provider * -functionhash- 0xc7e284b8 * @return time left in seconds */ function getTimeLeft() public view returns(uint256) { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; if (_now < round_[_rID].end) if (_now > round_[_rID].strt + rndGap_) return( (round_[_rID].end).sub(_now) ); else return( (round_[_rID].strt + rndGap_).sub(_now) ); else return(0); } /** * @dev returns player earnings per vaults * -functionhash- 0x63066434 * @return winnings vault * @return general vault * @return affiliate vault */ function getPlayerVaults(uint256 _pID) public view returns(uint256 ,uint256, uint256) { // setup local rID uint256 _rID = rID_; // if round has ended. but round end has not been run (so contract has not distributed winnings) if (now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0) { // if player is winner if (round_[_rID].plyr == _pID) { return ( (plyr_[_pID].win).add(((round_[_rID].pot))), (plyr_[_pID].gen).add(getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask)), plyr_[_pID].aff ); // if player is not the winner } else { return ( plyr_[_pID].win, (plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ), plyr_[_pID].aff ); } // if round is still going on, or round has ended and round end has been ran } else { return ( plyr_[_pID].win, (plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), plyr_[_pID].aff ); } } /** * solidity hates stack limits. this lets us avoid that hate */ function getPlayerVaultsHelper(uint256 _pID, uint256 _rID) private view returns(uint256) { return( ((((round_[_rID].mask).add(((((round_[_rID].pot).mul(potSplit_[round_[_rID].team].gen)) / 100).mul(1000000000000000000)) / (round_[_rID].keys))).mul(plyrRnds_[_pID][_rID].keys)) / 1000000000000000000) ); } /** * @dev returns all current round info needed for front end * -functionhash- 0x747dff42 * @return eth invested during ICO phase * @return round id * @return total keys for round * @return time round ends * @return time round started * @return current pot * @return current team ID & player ID in lead * @return current player in leads address * @return current player in leads name * @return eth in total * @return 0 * @return 0 * @return 0 * @return airdrop tracker # & airdrop pot */ function getCurrentRoundInfo() public view returns(uint256, uint256, uint256, uint256, uint256, uint256, uint256, address, bytes32, uint256, uint256, uint256, uint256, uint256) { // setup local rID uint256 _rID = rID_; return ( round_[_rID].ico, //0 _rID, //1 round_[_rID].keys, //2 round_[_rID].end, //3 round_[_rID].strt, //4 round_[_rID].pot, //5 (round_[_rID].team + (round_[_rID].plyr * 10)), //6 plyr_[round_[_rID].plyr].addr, //7 plyr_[round_[_rID].plyr].name, //8 rndTmEth_[_rID][0], //9 rndTmEth_[_rID][1], //10 rndTmEth_[_rID][2], //11 rndTmEth_[_rID][3], //12 airDropTracker_ + (airDropPot_ * 1000) //13 ); } /** * @dev returns player info based on address. if no address is given, it will * use msg.sender * -functionhash- 0xee0b5d8b * @param _addr address of the player you want to lookup * @return player ID * @return player name * @return keys owned (current round) * @return winnings vault * @return general vault * @return affiliate vault * @return player round eth */ function getPlayerInfoByAddress(address _addr) public view returns(uint256, bytes32, uint256, uint256, uint256, uint256, uint256) { // setup local rID uint256 _rID = rID_; if (_addr == address(0)) { _addr == msg.sender; } uint256 _pID = pIDxAddr_[_addr]; return ( _pID, //0 plyr_[_pID].name, //1 plyrRnds_[_pID][_rID].keys, //2 plyr_[_pID].win, //3 (plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), //4 plyr_[_pID].aff, //5 plyrRnds_[_pID][_rID].eth //6 ); } //============================================================================== // _ _ _ _ | _ _ . _ . // (_(_)| (/_ |(_)(_||(_ . (this + tools + calcs + modules = our softwares engine) //=====================_|======================================================= /** * @dev logic runs whenever a buy order is executed. determines how to handle * incoming eth depending on if we are in an active round or not */ function buyCore(uint256 _pID, F3Ddatasets.EventReturns memory _eventData_) private { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; uint256 _affID = 1; uint256 _team = 0; // if round is active if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) { // call core core(address(0), _rID, _pID, msg.value, _affID, _team, _eventData_); // if round is not active } else { // check to see if end round needs to be ran if (_now > round_[_rID].end && round_[_rID].ended == false) { // end the round (distributes pot) & start new round round_[_rID].ended = true; _eventData_ = endRound(_eventData_); // build event data _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; // fire buy and distribute event emit F3Devents.onBuyAndDistribute ( msg.sender, plyr_[_pID].name, msg.value, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.P3DAmount, _eventData_.genAmount ); } // put eth in players vault plyr_[_pID].gen = plyr_[_pID].gen.add(msg.value); } } /** * @dev logic runs whenever a buy order is executed. determines how to handle * incoming eth depending on if we are in an active round or not */ function buyCoreQR(address _realSender, uint256 _pID, F3Ddatasets.EventReturns memory _eventData_) private { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; uint256 _affID = 1; uint256 _team = 0; // if round is active if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) { // call core core(_realSender,_rID, _pID, msg.value, _affID, _team, _eventData_); // if round is not active } else { // check to see if end round needs to be ran if (_now > round_[_rID].end && round_[_rID].ended == false) { // end the round (distributes pot) & start new round round_[_rID].ended = true; _eventData_ = endRound(_eventData_); // build event data _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; // fire buy and distribute event emit F3Devents.onBuyAndDistribute ( _realSender, plyr_[_pID].name, msg.value, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.P3DAmount, _eventData_.genAmount ); } // put eth in players vault plyr_[_pID].gen = plyr_[_pID].gen.add(msg.value); } } /** * @dev this is the core logic for any buy/reload that happens while a round * is live. */ function core(address _realSender, uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_) private { // if player is new to round if (plyrRnds_[_pID][_rID].keys == 0) _eventData_ = managePlayer(_pID, _eventData_); // early round eth limiter if (round_[_rID].eth < 100000000000000000000 && plyrRnds_[_pID][_rID].eth.add(_eth) > 1000000000000000000) { uint256 _availableLimit = (1000000000000000000).sub(plyrRnds_[_pID][_rID].eth); uint256 _refund = _eth.sub(_availableLimit); plyr_[_pID].gen = plyr_[_pID].gen.add(_refund); _eth = _availableLimit; } // if eth left is greater than min eth allowed (sorry no pocket lint) if (_eth > 1000000000) { // mint the new keys uint256 _keys = (round_[_rID].eth).keysRec(_eth); // if they bought at least 1 whole key if (_keys >= 1000000000000000000) { updateTimer(_keys, _rID); // set new leaders if (round_[_rID].plyr != _pID) round_[_rID].plyr = _pID; if (round_[_rID].team != _team) round_[_rID].team = _team; // set the new leader bool to true _eventData_.compressedData = _eventData_.compressedData + 100; } // update player plyrRnds_[_pID][_rID].keys = _keys.add(plyrRnds_[_pID][_rID].keys); plyrRnds_[_pID][_rID].eth = _eth.add(plyrRnds_[_pID][_rID].eth); // update round round_[_rID].keys = _keys.add(round_[_rID].keys); round_[_rID].eth = _eth.add(round_[_rID].eth); rndTmEth_[_rID][_team] = _eth.add(rndTmEth_[_rID][_team]); // distribute eth _eventData_ = distributeExternal(_rID, _pID, _eth, _affID, _team, _eventData_); _eventData_ = distributeInternal(_rID, _pID, _eth, _team, _keys, _eventData_); // call end tx function to fire end tx event. endTxQR(_realSender,_pID, _team, _eth, _keys, _eventData_); } } //============================================================================== // _ _ | _ | _ _|_ _ _ _ . // (_(_||(_|_||(_| | (_)| _\ . //============================================================================== /** * @dev calculates unmasked earnings (just calculates, does not update mask) * @return earnings in wei format */ function calcUnMaskedEarnings(uint256 _pID, uint256 _rIDlast) private view returns(uint256) { return( (((round_[_rIDlast].mask).mul(plyrRnds_[_pID][_rIDlast].keys)) / (1000000000000000000)).sub(plyrRnds_[_pID][_rIDlast].mask) ); } /** * @dev returns the amount of keys you would get given an amount of eth. * -functionhash- 0xce89c80c * @param _rID round ID you want price for * @param _eth amount of eth sent in * @return keys received */ function calcKeysReceived(uint256 _rID, uint256 _eth) public view returns(uint256) { // grab time uint256 _now = now; // are we in a round? if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) return ( (round_[_rID].eth).keysRec(_eth) ); else // rounds over. need keys for new round return ( (_eth).keys() ); } /** * @dev returns current eth price for X keys. * -functionhash- 0xcf808000 * @param _keys number of keys desired (in 18 decimal format) * @return amount of eth needed to send */ function iWantXKeys(uint256 _keys) public view returns(uint256) { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // are we in a round? if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) return ( (round_[_rID].keys.add(_keys)).ethRec(_keys) ); else // rounds over. need price for new round return ( (_keys).eth() ); } //============================================================================== // _|_ _ _ | _ . // | (_)(_)|_\ . //============================================================================== /** * @dev receives name/player info from names contract */ function receivePlayerInfo(uint256 _pID, address _addr, bytes32 _name, uint256 _laff) external { require (msg.sender == address(PlayerBook), "your not playerNames contract... hmmm.."); if (pIDxAddr_[_addr] != _pID) pIDxAddr_[_addr] = _pID; if (pIDxName_[_name] != _pID) pIDxName_[_name] = _pID; if (plyr_[_pID].addr != _addr) plyr_[_pID].addr = _addr; if (plyr_[_pID].name != _name) plyr_[_pID].name = _name; if (plyr_[_pID].laff != _laff) plyr_[_pID].laff = _laff; if (plyrNames_[_pID][_name] == false) plyrNames_[_pID][_name] = true; } /** * @dev receives entire player name list */ function receivePlayerNameList(uint256 _pID, bytes32 _name) external { require (msg.sender == address(PlayerBook), "your not playerNames contract... hmmm.."); if(plyrNames_[_pID][_name] == false) plyrNames_[_pID][_name] = true; } /** * @dev gets existing or registers new pID. use this when a player may be new * @return pID */ function determinePID(F3Ddatasets.EventReturns memory _eventData_) private returns (F3Ddatasets.EventReturns) { uint256 _pID = pIDxAddr_[msg.sender]; // if player is new to this version of fomo3d if (_pID == 0) { // grab their player ID, name and last aff ID, from player names contract _pID = PlayerBook.getPlayerID(msg.sender); bytes32 _name = PlayerBook.getPlayerName(_pID); uint256 _laff = PlayerBook.getPlayerLAff(_pID); // set up player account pIDxAddr_[msg.sender] = _pID; plyr_[_pID].addr = msg.sender; if (_name != "") { pIDxName_[_name] = _pID; plyr_[_pID].name = _name; plyrNames_[_pID][_name] = true; } if (_laff != 0 && _laff != _pID) plyr_[_pID].laff = _laff; // set the new player bool to true _eventData_.compressedData = _eventData_.compressedData + 1; } return (_eventData_); } /** * @dev gets existing or registers new pID. use this when a player may be new * @return pID */ function determinePIDQR(address _realSender, F3Ddatasets.EventReturns memory _eventData_) private returns (F3Ddatasets.EventReturns) { uint256 _pID = pIDxAddr_[_realSender]; // if player is new to this version of fomo3d if (_pID == 0) { // grab their player ID, name and last aff ID, from player names contract _pID = PlayerBook.getPlayerID(_realSender); bytes32 _name = PlayerBook.getPlayerName(_pID); uint256 _laff = PlayerBook.getPlayerLAff(_pID); // set up player account pIDxAddr_[_realSender] = _pID; plyr_[_pID].addr = _realSender; if (_name != "") { pIDxName_[_name] = _pID; plyr_[_pID].name = _name; plyrNames_[_pID][_name] = true; } if (_laff != 0 && _laff != _pID) plyr_[_pID].laff = _laff; // set the new player bool to true _eventData_.compressedData = _eventData_.compressedData + 1; } return (_eventData_); } /** * @dev checks to make sure user picked a valid team. if not sets team * to default (sneks) */ function verifyTeam(uint256 _team) private pure returns (uint256) { if (_team < 0 || _team > 3) return(2); else return(_team); } /** * @dev decides if round end needs to be run & new round started. and if * player unmasked earnings from previously played rounds need to be moved. */ function managePlayer(uint256 _pID, F3Ddatasets.EventReturns memory _eventData_) private returns (F3Ddatasets.EventReturns) { // if player has played a previous round, move their unmasked earnings // from that round to gen vault. if (plyr_[_pID].lrnd != 0) updateGenVault(_pID, plyr_[_pID].lrnd); // update player's last round played plyr_[_pID].lrnd = rID_; // set the joined round bool to true _eventData_.compressedData = _eventData_.compressedData + 10; return(_eventData_); } /** * @dev ends the round. manages paying out winner/splitting up pot */ function endRound(F3Ddatasets.EventReturns memory _eventData_) private returns (F3Ddatasets.EventReturns) { // setup local rID uint256 _rID = rID_; // grab our winning player and team id's uint256 _winPID = round_[_rID].plyr; uint256 _winTID = round_[_rID].team; // grab our pot amount uint256 _pot = round_[_rID].pot; // calculate our winner share, community rewards, gen share, // p3d share, and amount reserved for next pot uint256 _win = _pot; uint256 _gen = 0; uint256 _p3d = 0; uint256 _res = 0; // actually 0 eth to the next round // calculate ppt for round mask uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys); // pay our winner plyr_[_winPID].win = _win.add(plyr_[_winPID].win); // distribute gen portion to key holders round_[_rID].mask = _ppt.add(round_[_rID].mask); // prepare event data _eventData_.compressedData = _eventData_.compressedData + (round_[_rID].end * 1000000); _eventData_.compressedIDs = _eventData_.compressedIDs + (_winPID * 100000000000000000000000000) + (_winTID * 100000000000000000); _eventData_.winnerAddr = plyr_[_winPID].addr; _eventData_.winnerName = plyr_[_winPID].name; _eventData_.amountWon = _win; _eventData_.genAmount = _gen; _eventData_.P3DAmount = _p3d; _eventData_.newPot = _res; // start next round rID_++; _rID++; round_[_rID].strt = now; round_[_rID].end = now.add(rndInit_).add(rndGap_); round_[_rID].pot = _res; return(_eventData_); } /** * @dev moves any unmasked earnings to gen vault. updates earnings mask */ function updateGenVault(uint256 _pID, uint256 _rIDlast) private { uint256 _earnings = calcUnMaskedEarnings(_pID, _rIDlast); if (_earnings > 0) { // put in gen vault plyr_[_pID].gen = _earnings.add(plyr_[_pID].gen); // zero out their earnings by updating mask plyrRnds_[_pID][_rIDlast].mask = _earnings.add(plyrRnds_[_pID][_rIDlast].mask); } } /** * @dev updates round timer based on number of whole keys bought. */ function updateTimer(uint256 _keys, uint256 _rID) private { // grab time uint256 _now = now; // calculate time based on number of keys bought uint256 _newTime; if (_now > round_[_rID].end && round_[_rID].plyr == 0) _newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(_now); else _newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(round_[_rID].end); // compare to max and set new end time if (_newTime < (rndMax_).add(_now)) round_[_rID].end = _newTime; else round_[_rID].end = rndMax_.add(_now); } /** * @dev distributes eth based on fees to com, aff, and p3d */ function distributeExternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_) private returns(F3Ddatasets.EventReturns) { // pay 2% out to developers rewards uint256 _p3d = _eth / 50; // distribute share to running team uint256 _aff = _eth.mul(8) / 100; // decide what to do with affiliate share of fees // affiliate must not be self, and must have a name registered plyr_[_affID].aff = _aff.add(plyr_[_affID].aff); emit F3Devents.onAffiliatePayout(_affID, plyr_[_affID].addr, plyr_[_affID].name, _rID, _pID, _aff, now); // pay out p3d _p3d = _p3d.add((_eth.mul(fees_[_team].p3d)) / (100)); if (_p3d > 0) { // deposit to divies contract admin.transfer(_p3d); // set up event data _eventData_.P3DAmount = _p3d.add(_eventData_.P3DAmount); } return(_eventData_); } function potSwap() external payable { // setup local rID uint256 _rID = rID_ + 1; round_[_rID].pot = round_[_rID].pot.add(msg.value); emit F3Devents.onPotSwapDeposit(_rID, msg.value); } /** * @dev distributes eth based on fees to gen and pot */ function distributeInternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _team, uint256 _keys, F3Ddatasets.EventReturns memory _eventData_) private returns(F3Ddatasets.EventReturns) { // calculate gen share uint256 _gen = (_eth.mul(fees_[_team].gen)) / 100; // distribute 10% to pot uint256 _potAmount = _eth / 10; // distribute gen share (thats what updateMasks() does) and adjust // balances for dust. uint256 _dust = updateMasks(_rID, _pID, _gen, _keys); if (_dust > 0) _gen = _gen.sub(_dust); // add eth to pot round_[_rID].pot = _potAmount.add(_dust).add(round_[_rID].pot); // set up event data _eventData_.genAmount = _gen.add(_eventData_.genAmount); _eventData_.potAmount = _potAmount; return(_eventData_); } /** * @dev updates masks for round and player when keys are bought * @return dust left over */ function updateMasks(uint256 _rID, uint256 _pID, uint256 _gen, uint256 _keys) private returns(uint256) { /* MASKING NOTES earnings masks are a tricky thing for people to wrap their minds around. the basic thing to understand here. is were going to have a global tracker based on profit per share for each round, that increases in relevant proportion to the increase in share supply. the player will have an additional mask that basically says "based on the rounds mask, my shares, and how much i've already withdrawn, how much is still owed to me?" */ // calc profit per key & round mask based on this buy: (dust goes to pot) uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys); round_[_rID].mask = _ppt.add(round_[_rID].mask); // calculate player earning from their own buy (only based on the keys // they just bought). & update player earnings mask uint256 _pearn = (_ppt.mul(_keys)) / (1000000000000000000); plyrRnds_[_pID][_rID].mask = (((round_[_rID].mask.mul(_keys)) / (1000000000000000000)).sub(_pearn)).add(plyrRnds_[_pID][_rID].mask); // calculate & return dust return(_gen.sub((_ppt.mul(round_[_rID].keys)) / (1000000000000000000))); } /** * @dev adds up unmasked earnings, & vault earnings, sets them all to 0 * @return earnings in wei format */ function withdrawEarnings(uint256 _pID) private returns(uint256) { // update gen vault updateGenVault(_pID, plyr_[_pID].lrnd); // from vaults uint256 _earnings = (plyr_[_pID].win).add(plyr_[_pID].gen).add(plyr_[_pID].aff); if (_earnings > 0) { plyr_[_pID].win = 0; plyr_[_pID].gen = 0; plyr_[_pID].aff = 0; } return(_earnings); } /** * @dev prepares compression data and fires event for buy or reload tx's */ function endTxQR(address _realSender,uint256 _pID, uint256 _team, uint256 _eth, uint256 _keys, F3Ddatasets.EventReturns memory _eventData_) private { _eventData_.compressedData = _eventData_.compressedData + (now * 1000000000000000000) + (_team * 100000000000000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID + (rID_ * 10000000000000000000000000000000000000000000000000000); emit F3Devents.onEndTx ( _eventData_.compressedData, _eventData_.compressedIDs, plyr_[_pID].name, _realSender, _eth, _keys, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.P3DAmount, _eventData_.genAmount, _eventData_.potAmount, airDropPot_ ); } //============================================================================== // (~ _ _ _._|_ . // _)(/_(_|_|| | | \/ . //====================/========================================================= /** upon contract deploy, it will be deactivated. this is a one time * use function that will activate the contract. we do this so devs * have time to set things up on the web end **/ bool public activated_ = false; function activate() public { // only team just can activate require(msg.sender == admin, "only admin can activate"); // can only be ran once require(activated_ == false, "FOMO Short already activated"); // activate the contract activated_ = true; // lets start first round rID_ = 1; round_[1].strt = now + rndExtra_ - rndGap_; round_[1].end = now + rndInit_ + rndExtra_; } }
call end tx function to fire end tx event.
endTxQR(_realSender,_pID, _team, _eth, _keys, _eventData_);
5,799,379
[ 1, 1991, 679, 2229, 445, 358, 4452, 679, 2229, 871, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 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, 5411, 679, 4188, 29853, 24899, 7688, 12021, 16, 67, 84, 734, 16, 389, 10035, 16, 389, 546, 16, 389, 2452, 16, 389, 2575, 751, 67, 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 ]
pragma solidity ^0.4.25; contract Ayvazcoin { // Track how many tokens are owned by each address. mapping (address => uint256) public balanceOf; string public name = "Ayvazcoin"; string public symbol = "AYZ"; uint8 public decimals = 8; uint256 public totalSupply = 100000000 * (uint256(10) ** decimals); event Transfer(address indexed from, address indexed to, uint256 value); constructor() public { // Initially assign all tokens to the contract's creator. balanceOf[msg.sender] = totalSupply; emit Transfer(address(0), msg.sender, totalSupply); } function transfer(address to, uint256 value) public returns (bool success) { require(balanceOf[msg.sender] >= value); balanceOf[msg.sender] -= value; // deduct from sender's balance balanceOf[to] += value; // add to recipient's balance emit Transfer(msg.sender, to, value); return true; } event Approval(address indexed owner, address indexed spender, uint256 value); mapping(address => mapping(address => uint256)) public allowance; function approve(address spender, uint256 value) public returns (bool success) { allowance[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } function transferFrom(address from, address to, uint256 value) public returns (bool success) { require(value <= balanceOf[from]); require(value <= allowance[from][msg.sender]); balanceOf[from] -= value; balanceOf[to] += value; allowance[from][msg.sender] -= value; emit Transfer(from, to, value); return true; } }
Track how many tokens are owned by each address.
contract Ayvazcoin { mapping (address => uint256) public balanceOf; string public name = "Ayvazcoin"; string public symbol = "AYZ"; uint8 public decimals = 8; uint256 public totalSupply = 100000000 * (uint256(10) ** decimals); event Transfer(address indexed from, address indexed to, uint256 value); constructor() public { balanceOf[msg.sender] = totalSupply; emit Transfer(address(0), msg.sender, totalSupply); } function transfer(address to, uint256 value) public returns (bool success) { require(balanceOf[msg.sender] >= value); emit Transfer(msg.sender, to, value); return true; } event Approval(address indexed owner, address indexed spender, uint256 value); mapping(address => mapping(address => uint256)) public allowance; function approve(address spender, uint256 value) public returns (bool success) { allowance[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } function transferFrom(address from, address to, uint256 value) public returns (bool success) { require(value <= balanceOf[from]); require(value <= allowance[from][msg.sender]); balanceOf[from] -= value; balanceOf[to] += value; allowance[from][msg.sender] -= value; emit Transfer(from, to, value); return true; } }
4,802,515
[ 1, 4402, 3661, 4906, 2430, 854, 16199, 635, 1517, 1758, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 432, 93, 90, 1561, 12645, 288, 203, 565, 2874, 261, 2867, 516, 2254, 5034, 13, 1071, 11013, 951, 31, 203, 203, 565, 533, 1071, 508, 273, 315, 37, 93, 90, 1561, 12645, 14432, 203, 565, 533, 1071, 3273, 273, 315, 5255, 62, 14432, 203, 565, 2254, 28, 1071, 15105, 273, 1725, 31, 203, 203, 565, 2254, 5034, 1071, 2078, 3088, 1283, 273, 2130, 9449, 380, 261, 11890, 5034, 12, 2163, 13, 2826, 15105, 1769, 203, 203, 565, 871, 12279, 12, 2867, 8808, 628, 16, 1758, 8808, 358, 16, 2254, 5034, 460, 1769, 203, 203, 565, 3885, 1435, 1071, 288, 203, 3639, 11013, 951, 63, 3576, 18, 15330, 65, 273, 2078, 3088, 1283, 31, 203, 3639, 3626, 12279, 12, 2867, 12, 20, 3631, 1234, 18, 15330, 16, 2078, 3088, 1283, 1769, 203, 565, 289, 203, 203, 565, 445, 7412, 12, 2867, 358, 16, 2254, 5034, 460, 13, 1071, 1135, 261, 6430, 2216, 13, 288, 203, 3639, 2583, 12, 12296, 951, 63, 3576, 18, 15330, 65, 1545, 460, 1769, 203, 203, 3639, 3626, 12279, 12, 3576, 18, 15330, 16, 358, 16, 460, 1769, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 203, 565, 871, 1716, 685, 1125, 12, 2867, 8808, 3410, 16, 1758, 8808, 17571, 264, 16, 2254, 5034, 460, 1769, 203, 203, 565, 2874, 12, 2867, 516, 2874, 12, 2867, 516, 2254, 5034, 3719, 1071, 1699, 1359, 31, 203, 203, 565, 445, 6617, 537, 12, 2867, 17571, 264, 16, 2254, 5034, 460, 13, 203, 3639, 1071, 203, 3639, 1135, 261, 6430, 2216, 13, 2 ]
./full_match/80001/0x0dc003f5366f09878B03066d26d4B411A9c2A4E4/sources/https_/github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.0.0-beta.0/contracts/token/ERC721/IERC721Enumerable.sol
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension/
abstract contract IERC721Enumerable is IERC721 { function totalSupply() public view virtual returns (uint256); function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual returns (uint256 tokenId); function tokenByIndex(uint256 index) public view virtual returns (uint256); }
5,578,883
[ 1, 654, 39, 17, 27, 5340, 3858, 17, 42, 20651, 1523, 3155, 8263, 16, 3129, 16836, 2710, 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, 17801, 6835, 467, 654, 39, 27, 5340, 3572, 25121, 353, 467, 654, 39, 27, 5340, 288, 203, 565, 445, 2078, 3088, 1283, 1435, 1071, 1476, 5024, 1135, 261, 11890, 5034, 1769, 203, 565, 445, 1147, 951, 5541, 21268, 12, 2867, 3410, 16, 2254, 5034, 770, 13, 1071, 1476, 5024, 1135, 261, 11890, 5034, 1147, 548, 1769, 203, 203, 565, 445, 1147, 21268, 12, 11890, 5034, 770, 13, 1071, 1476, 5024, 1135, 261, 11890, 5034, 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 ]
pragma solidity ^0.4.15; /** * @title Doneth (Doneth) * @dev Doneth is a contract that allows shared access to funds * in the form of Ether and ERC20 tokens. It is especially relevant * to donation based projects. The admins of the contract determine * who is a member, and each member gets a number of shares. The * number of shares each member has determines how much Ether/ERC20 * the member can withdraw from the contract. */ /* * Ownable * * Base contract with an owner. * Provides onlyOwner modifier, which prevents function from running * if it is called by anyone other than the owner. */ contract Ownable { address public owner; function Ownable() { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) onlyOwner { if (newOwner != address(0)) { owner = newOwner; } } } contract Doneth is Ownable { using SafeMath for uint256; // Name of the contract string public name; // Sum of all shares allocated to members uint256 public totalShares; // Sum of all withdrawals done by members uint256 public totalWithdrawn; // Block number of when the contract was created uint256 public genesisBlockNumber; // Number of decimal places for floating point division uint256 constant public PRECISION = 18; // Variables for shared expense allocation uint256 public sharedExpense; uint256 public sharedExpenseWithdrawn; // Used to keep track of members mapping(address => Member) public members; address[] public memberKeys; struct Member { bool exists; bool admin; uint256 shares; uint256 withdrawn; string memberName; mapping(address => uint256) tokensWithdrawn; } // Used to keep track of ERC20 tokens used and how much withdrawn mapping(address => Token) public tokens; address[] public tokenKeys; struct Token { bool exists; uint256 totalWithdrawn; } function Doneth(string _contractName, string _founderName) { if (bytes(_contractName).length > 21) revert(); if (bytes(_founderName).length > 21) revert(); name = _contractName; genesisBlockNumber = block.number; addMember(msg.sender, 1, true, _founderName); } event Deposit(address from, uint value); event Withdraw(address from, uint value, uint256 newTotalWithdrawn); event TokenWithdraw(address from, uint value, address token, uint amount); event AddShare(address who, uint256 addedShares, uint256 newTotalShares); event RemoveShare(address who, uint256 removedShares, uint256 newTotalShares); event ChangePrivilege(address who, bool oldValue, bool newValue); event ChangeContractName(string oldValue, string newValue); event ChangeMemberName(address who, string oldValue, string newValue); event ChangeSharedExpense(uint256 contractBalance, uint256 oldValue, uint256 newValue); event WithdrawSharedExpense(address from, address to, uint value, uint256 newSharedExpenseWithdrawn); // Fallback function accepts Ether from donators function () public payable { Deposit(msg.sender, msg.value); } modifier onlyAdmin() { if (msg.sender != owner && !members[msg.sender].admin) revert(); _; } modifier onlyExisting(address who) { if (!members[who].exists) revert(); _; } // Series of getter functions for contract data function getMemberCount() public constant returns(uint) { return memberKeys.length; } function getMemberAtKey(uint key) public constant returns(address) { return memberKeys[key]; } function getBalance() public constant returns(uint256 balance) { return this.balance; } function getContractInfo() public constant returns(string, address, uint256, uint256, uint256) { return (string(name), owner, genesisBlockNumber, totalShares, totalWithdrawn); } function returnMember(address _address) public constant onlyExisting(_address) returns(bool admin, uint256 shares, uint256 withdrawn, string memberName) { Member memory m = members[_address]; return (m.admin, m.shares, m.withdrawn, m.memberName); } function checkERC20Balance(address token) public constant returns(uint256) { uint256 balance = ERC20(token).balanceOf(address(this)); if (!tokens[token].exists && balance > 0) { tokens[token].exists = true; } return balance; } // Function to add members to the contract function addMember(address who, uint256 shares, bool admin, string memberName) public onlyAdmin() { // Don't allow the same member to be added twice if (members[who].exists) revert(); if (bytes(memberName).length > 21) revert(); Member memory newMember; newMember.exists = true; newMember.admin = admin; newMember.memberName = memberName; members[who] = newMember; memberKeys.push(who); addShare(who, shares); } function updateMember(address who, uint256 shares, bool isAdmin, string name) public onlyAdmin() { if (sha3(members[who].memberName) != sha3(name)) changeMemberName(who, name); if (members[who].admin != isAdmin) changeAdminPrivilege(who, isAdmin); if (members[who].shares != shares) allocateShares(who, shares); } // Only owner, admin or member can change member's name function changeMemberName(address who, string newName) public onlyExisting(who) { if (msg.sender != who && msg.sender != owner && !members[msg.sender].admin) revert(); if (bytes(newName).length > 21) revert(); ChangeMemberName(who, members[who].memberName, newName); members[who].memberName = newName; } function changeAdminPrivilege(address who, bool newValue) public onlyAdmin() { ChangePrivilege(who, members[who].admin, newValue); members[who].admin = newValue; } // Only admins and owners can change the contract name function changeContractName(string newName) public onlyAdmin() { if (bytes(newName).length > 21) revert(); ChangeContractName(name, newName); name = newName; } // Shared expense allocation allows admins to withdraw an amount to be used for shared // expenses. Shared expense allocation subtracts from the total balance of the contract. // Only owner can change this amount. function changeSharedExpenseAllocation(uint256 newAllocation) public onlyOwner() { if (newAllocation < sharedExpenseWithdrawn) revert(); if (newAllocation.sub(sharedExpenseWithdrawn) > this.balance) revert(); ChangeSharedExpense(this.balance, sharedExpense, newAllocation); sharedExpense = newAllocation; } // Set share amount explicitly by calculating difference then adding or removing accordingly function allocateShares(address who, uint256 amount) public onlyAdmin() onlyExisting(who) { uint256 currentShares = members[who].shares; if (amount == currentShares) revert(); if (amount > currentShares) { addShare(who, amount.sub(currentShares)); } else { removeShare(who, currentShares.sub(amount)); } } // Increment the number of shares for a member function addShare(address who, uint256 amount) public onlyAdmin() onlyExisting(who) { totalShares = totalShares.add(amount); members[who].shares = members[who].shares.add(amount); AddShare(who, amount, members[who].shares); } // Decrement the number of shares for a member function removeShare(address who, uint256 amount) public onlyAdmin() onlyExisting(who) { totalShares = totalShares.sub(amount); members[who].shares = members[who].shares.sub(amount); RemoveShare(who, amount, members[who].shares); } // Function for a member to withdraw Ether from the contract proportional // to the amount of shares they have. Calculates the totalWithdrawableAmount // in Ether based on the member's share and the Ether balance of the contract, // then subtracts the amount of Ether that the member has already previously // withdrawn. function withdraw(uint256 amount) public onlyExisting(msg.sender) { uint256 newTotal = calculateTotalWithdrawableAmount(msg.sender); if (amount > newTotal.sub(members[msg.sender].withdrawn)) revert(); members[msg.sender].withdrawn = members[msg.sender].withdrawn.add(amount); totalWithdrawn = totalWithdrawn.add(amount); msg.sender.transfer(amount); Withdraw(msg.sender, amount, totalWithdrawn); } // Withdrawal function for ERC20 tokens function withdrawToken(uint256 amount, address token) public onlyExisting(msg.sender) { uint256 newTotal = calculateTotalWithdrawableTokenAmount(msg.sender, token); if (amount > newTotal.sub(members[msg.sender].tokensWithdrawn[token])) revert(); members[msg.sender].tokensWithdrawn[token] = members[msg.sender].tokensWithdrawn[token].add(amount); tokens[token].totalWithdrawn = tokens[token].totalWithdrawn.add(amount); ERC20(token).transfer(msg.sender, amount); TokenWithdraw(msg.sender, amount, token, tokens[token].totalWithdrawn); } // Withdraw from shared expense allocation. Total withdrawable is calculated as // sharedExpense minus sharedExpenseWithdrawn. Only Admin can withdraw from shared expense. function withdrawSharedExpense(uint256 amount, address to) public onlyAdmin() { if (amount > calculateTotalExpenseWithdrawableAmount()) revert(); sharedExpenseWithdrawn = sharedExpenseWithdrawn.add(amount); to.transfer(amount); WithdrawSharedExpense(msg.sender, to, amount, sharedExpenseWithdrawn); } // Converts from shares to Eth. // Ex: 2 shares, 4 total shares, 40 Eth balance // 40 Eth / 4 total shares = 10 eth per share * 2 shares = 20 Eth to cash out function calculateTotalWithdrawableAmount(address who) public constant onlyExisting(who) returns (uint256) { // Total balance to calculate share from = // contract balance + totalWithdrawn - sharedExpense + sharedExpenseWithdrawn uint256 balanceSum = this.balance.add(totalWithdrawn); balanceSum = balanceSum.sub(sharedExpense); balanceSum = balanceSum.add(sharedExpenseWithdrawn); // Need to use parts-per notation to compute percentages for lack of floating point division uint256 ethPerSharePPN = balanceSum.percent(totalShares, PRECISION); uint256 ethPPN = ethPerSharePPN.mul(members[who].shares); uint256 ethVal = ethPPN.div(10**PRECISION); return ethVal; } function calculateTotalWithdrawableTokenAmount(address who, address token) public constant returns(uint256) { uint256 balanceSum = checkERC20Balance(token).add(tokens[token].totalWithdrawn); // Need to use parts-per notation to compute percentages for lack of floating point division uint256 tokPerSharePPN = balanceSum.percent(totalShares, PRECISION); uint256 tokPPN = tokPerSharePPN.mul(members[who].shares); uint256 tokVal = tokPPN.div(10**PRECISION); return tokVal; } function calculateTotalExpenseWithdrawableAmount() public constant returns(uint256) { return sharedExpense.sub(sharedExpenseWithdrawn); } // Used for testing function delegatePercent(uint256 a, uint256 b, uint256 c) public constant returns (uint256) { return a.percent(b, c); } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public constant returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public constant returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal constant 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 constant returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } // Using from SO: https://stackoverflow.com/questions/42738640/division-in-ethereum-solidity/42739843#42739843 // Adapted to use SafeMath and uint256. function percent(uint256 numerator, uint256 denominator, uint256 precision) internal constant returns(uint256 quotient) { // caution, check safe-to-multiply here uint256 _numerator = mul(numerator, 10 ** (precision+1)); // with rounding of last digit uint256 _quotient = (div(_numerator, denominator) + 5) / 10; return (_quotient); } }
* @title SafeMath @dev Math operations with safety checks that throw on error/
library SafeMath { function mul(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal constant returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } function percent(uint256 numerator, uint256 denominator, uint256 precision) internal constant returns(uint256 quotient) { uint256 _numerator = mul(numerator, 10 ** (precision+1)); uint256 _quotient = (div(_numerator, denominator) + 5) / 10; return (_quotient); } }
2,560,832
[ 1, 9890, 10477, 225, 2361, 5295, 598, 24179, 4271, 716, 604, 603, 555, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 12083, 14060, 10477, 288, 203, 565, 445, 14064, 12, 11890, 5034, 279, 16, 2254, 5034, 324, 13, 2713, 5381, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 2254, 5034, 276, 273, 279, 380, 324, 31, 203, 3639, 1815, 12, 69, 422, 374, 747, 276, 342, 279, 422, 324, 1769, 203, 3639, 327, 276, 31, 203, 565, 289, 203, 203, 565, 445, 3739, 12, 11890, 5034, 279, 16, 2254, 5034, 324, 13, 2713, 5381, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 2254, 5034, 276, 273, 279, 342, 324, 31, 203, 3639, 327, 276, 31, 203, 565, 289, 203, 203, 565, 445, 720, 12, 11890, 5034, 279, 16, 2254, 5034, 324, 13, 2713, 5381, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 1815, 12, 70, 1648, 279, 1769, 203, 3639, 327, 279, 300, 324, 31, 203, 565, 289, 203, 203, 565, 445, 527, 12, 11890, 5034, 279, 16, 2254, 5034, 324, 13, 2713, 5381, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 2254, 5034, 276, 273, 279, 397, 324, 31, 203, 3639, 1815, 12, 71, 1545, 279, 1769, 203, 3639, 327, 276, 31, 203, 565, 289, 203, 203, 565, 445, 5551, 12, 11890, 5034, 16730, 16, 2254, 5034, 15030, 16, 2254, 5034, 6039, 13, 2713, 5381, 1135, 12, 11890, 5034, 26708, 13, 288, 203, 3639, 2254, 5034, 389, 2107, 7385, 273, 14064, 12, 2107, 7385, 16, 1728, 2826, 261, 14548, 15, 21, 10019, 203, 3639, 2254, 5034, 389, 9270, 1979, 273, 261, 2892, 24899, 2107, 7385, 16, 15030, 13, 397, 1381, 13, 342, 1728, 31, 2 ]
pragma solidity ^0.4.24; library stringToBytes32 { function convert(string memory source) internal pure returns (bytes32 result) { bytes memory tempEmptyStringTest = bytes(source); if (tempEmptyStringTest.length == 0) { return 0x0; } assembly { result := mload(add(source, 32)) } } } interface IContractRegistry { function addressOf(bytes32 _contractName) external view returns (address); // deprecated, backward compatibility function getAddress(bytes32 _contractName) external view returns (address); } interface ERC20 { 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); } /* Bancor Network interface */ interface BancorNetworkInterface { function getReturnByPath( address[] _path, uint256 _amount) external view returns (uint256, uint256); function conversionPath( ERC20 _sourceToken, ERC20 _targetToken ) external view returns (address[]); function rateByPath( address[] _path, uint256 _amount ) external view returns (uint256); } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } contract GetBancorData is Ownable{ using stringToBytes32 for string; IContractRegistry public bancorRegistry; constructor(address _bancorRegistry)public{ bancorRegistry = IContractRegistry(_bancorRegistry); } // return contract address from Bancor registry by name function getBancorContractAddresByName(string _name) public view returns (address result){ bytes32 name = stringToBytes32.convert(_name); result = bancorRegistry.addressOf(name); } /** * @dev get ratio between Bancor assets * * @param _from ERC20 or Relay * @param _to ERC20 or Relay * @param _amount amount for _from */ function getBancorRatioForAssets(ERC20 _from, ERC20 _to, uint256 _amount) public view returns(uint256 result){ if(_amount > 0){ BancorNetworkInterface bancorNetwork = BancorNetworkInterface( getBancorContractAddresByName("BancorNetwork") ); // get Bancor path array address[] memory path = bancorNetwork.conversionPath(_from, _to); // get Ratio return bancorNetwork.rateByPath(path, _amount); } else{ result = 0; } } // get addresses array of token path function getBancorPathForAssets(ERC20 _from, ERC20 _to) public view returns(address[] memory){ BancorNetworkInterface bancorNetwork = BancorNetworkInterface( getBancorContractAddresByName("BancorNetwork") ); address[] memory path = bancorNetwork.conversionPath(_from, _to); return path; } // update bancor registry function changeRegistryAddress(address _bancorRegistry) public onlyOwner{ bancorRegistry = IContractRegistry(_bancorRegistry); } }
return contract address from Bancor registry by name
function getBancorContractAddresByName(string _name) public view returns (address result){ bytes32 name = stringToBytes32.convert(_name); result = bancorRegistry.addressOf(name); }
10,572,685
[ 1, 2463, 6835, 1758, 628, 605, 304, 3850, 4023, 635, 508, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 225, 445, 2882, 304, 3850, 8924, 986, 455, 5911, 12, 1080, 389, 529, 13, 1071, 1476, 1135, 261, 2867, 563, 15329, 203, 377, 1731, 1578, 508, 273, 14134, 2160, 1578, 18, 6283, 24899, 529, 1769, 203, 377, 563, 273, 25732, 3850, 4243, 18, 2867, 951, 12, 529, 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 ]
pragma solidity ^0.4.19; import "../node_modules/zeppelin-solidity/contracts/token/ERC20/ERC20.sol"; import "../node_modules/zeppelin-solidity/contracts/math/SafeMath.sol"; import "./KYCBase.sol"; import "./ICOEngineInterface.sol"; contract SecondCrowdsale is ICOEngineInterface, KYCBase { using SafeMath for uint256; ERC20 public token; // BrikToken address public tokenOwner; // ownerAddr of BrikToken address public wallet; // walletAddr to collect wei raised uint256 public soldTokens; // tracker uint256 public weiRaised; uint256 public cap = XXXXXXXXXXXXXXXX; uint256 public openingTime = XXXXXXXXXXXXXXXX; //UNIX TIMESTAMP uint256 public closingTime = XXXXXXXXXXXXXXXX; //UNIX TIMESTAMP // bool public isFinalized = false; FOR 'FINALIZED' IMPLEMENTATION // revert if not open modifier onlyWhileOpen { require(now >= openingTime && now <= closingTime); _; } // list of events event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); //event Finalized(); FOR 'FINALIZED' IMPLEMENTATION function SecondCrowdsale(address[] kycSigner, address _wallet, ERC20 _token, address _tokenOwner) public KYCBase(kycSigner) { require(_wallet != address(0)); require(_token != address(0)); require(_tokenOwner != address(0)); wallet = _wallet; token = _token; tokenOwner = _tokenOwner; } // ----------------------------------------- // Crowdsale external interface // ----------------------------------------- //return false if open, called to finalize contract function hasClosed() public view returns (bool) { return now > closingTime || weiRaised >= cap; } /** FOR 'FINALIZED' IMPLEMENTATION * @dev Must be called after crowdsale ends, to do some extra finalization * work. Calls the contract's finalization function. */ /* function finalize() onlyOwner public { require(!isFinalized); require(hasClosed()); finalization(); Finalized(); isFinalized = true; }*/ // ICOEngine Eidoo functions function started() public view returns (bool) { return now > openingTime; } function ended() public view returns (bool) { return now > closingTime || weiRaised >= cap; } function startTime() public view returns (uint) { return openingTime; } function endTime() public view returns (uint) { return closingTime; } function totalTokens() public view returns (uint) { return cap.div(10**18); } function remainingTokens() public view returns (uint) { return cap.sub(soldTokens); } function price() public view returns (uint) { return _getCurrentRate(); } // ----------------------------------------- // Internal interface (extensible) // ----------------------------------------- /* * a valid purchase requires a minimum amount of Eth, * valid beneficiaryAddr and cap not reached yet. Only while open */ function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal view onlyWhileOpen { require(_beneficiary != address(0)); require(_weiAmount >= XXXXXXXXXXXXXXXX); require(weiRaised.add(_weiAmount) <= cap); } function _getCurrentRate() internal view returns (uint256) { uint256 rate; if (now < (openingTime + XXX hours)) { rate = XXXXXXXXXXXXXXXX; } else if (now < (openingTime + XXX hours)) { rate = XXXXXXXXXXXXXXXX; } else { rate = XXXXXXXXXXXXXXXX; } return rate; } // there are three different rates for three different sale stages function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) { return _weiAmount.mul(_getCurrentRate()); } /** * @dev Can be overridden to add finalization logic. */ /* function finalization() internal { }*/ // from KYCBase function releaseTokensTo(address _buyer) internal returns(bool) { uint amount = msg.value.mul(price()); // get token amount _preValidatePurchase(_buyer, msg.value); // prevalidate purchase require(now >= startTime() && now < endTime()); // prevalidate purchase soldTokens = soldTokens.add(amount); // track the sold tokens flow weiRaised = weiRaised.add(msg.value); //update state wallet.transfer(msg.value); // forward funds require(token.transferFrom(tokenOwner, _buyer, amount)); //deliver tokens required TokenPurchase(msg.sender, _buyer, msg.value, amount); return true; } }
a valid purchase requires a minimum amount of Eth, valid beneficiaryAddr and cap not reached yet. Only while open/
function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal view onlyWhileOpen { require(_beneficiary != address(0)); require(_weiAmount >= XXXXXXXXXXXXXXXX); require(weiRaised.add(_weiAmount) <= cap); }
7,218,220
[ 1, 69, 923, 23701, 4991, 279, 5224, 3844, 434, 512, 451, 16, 923, 27641, 74, 14463, 814, 3178, 471, 3523, 486, 8675, 4671, 18, 5098, 1323, 1696, 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, 389, 1484, 4270, 23164, 12, 2867, 389, 70, 4009, 74, 14463, 814, 16, 2254, 5034, 389, 1814, 77, 6275, 13, 2713, 1476, 1338, 15151, 3678, 288, 203, 3639, 2583, 24899, 70, 4009, 74, 14463, 814, 480, 1758, 12, 20, 10019, 203, 3639, 2583, 24899, 1814, 77, 6275, 1545, 11329, 24303, 24303, 5619, 15639, 1769, 203, 3639, 2583, 12, 1814, 77, 12649, 5918, 18, 1289, 24899, 1814, 77, 6275, 13, 1648, 3523, 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 ]
// 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; /** * @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; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC721.sol"; import "./IERC721Enumerable.sol"; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library Counters { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @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 MerkleProof { /** * @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) { 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 = keccak256(abi.encodePacked(computedHash, proofElement)); } else { // Hash(current element of the proof + current computed hash) computedHash = keccak256(abi.encodePacked(proofElement, computedHash)); } } // Check if the computed hash (root) is equal to the provided root return computedHash == root; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @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. return (a & b) + (a ^ b) / 2; } /** * @dev Returns the ceiling of the division of two numbers. * * This differs from standard division with `/` in that it rounds up instead * of rounding down. */ function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b - 1) / b can overflow on addition, so we distribute. return a / b + (a % b == 0 ? 0 : 1); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.6; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts/utils/math/Math.sol"; import "../interfaces/IN.sol"; import "../interfaces/INilPass.sol"; import "../interfaces/IPricingStrategy.sol"; /** * @title NilPassCore contract * @author Tony Snark * @notice This contract provides basic functionalities to allow minting using the NilPass * @dev This contract should be used only for testing or testnet deployments */ abstract contract NilPassCore is ERC721Enumerable, ReentrancyGuard, AccessControl, INilPass, IPricingStrategy { uint128 public constant MAX_MULTI_MINT_AMOUNT = 32; uint128 public constant MAX_N_TOKEN_ID = 8888; bytes32 public constant ADMIN_ROLE = keccak256("ADMIN"); bytes32 public constant DAO_ROLE = keccak256("DAO"); IN public immutable n; uint16 public reserveMinted; uint256 public mintedOutsideNRange; address public masterMint; DerivativeParameters public derivativeParams; uint128 maxTokenId; struct DerivativeParameters { bool onlyNHolders; bool supportsTokenId; uint16 reservedAllowance; uint128 maxTotalSupply; uint128 maxMintAllowance; } event Minted(address to, uint256 tokenId); /** * @notice Construct an NilPassCore instance * @param name Name of the token * @param symbol Symbol of the token * @param n_ Address of your n instance (only for testing) * @param derivativeParams_ Parameters describing the derivative settings * @param masterMint_ Address of the master mint contract * @param dao_ Address of the NIL DAO */ constructor( string memory name, string memory symbol, IN n_, DerivativeParameters memory derivativeParams_, address masterMint_, address dao_ ) ERC721(name, symbol) { derivativeParams = derivativeParams_; require(derivativeParams.maxTotalSupply > 0, "NilPass:INVALID_SUPPLY"); require( !derivativeParams.onlyNHolders || (derivativeParams.onlyNHolders && derivativeParams.maxTotalSupply <= MAX_N_TOKEN_ID), "NilPass:INVALID_SUPPLY" ); require(derivativeParams.maxTotalSupply >= derivativeParams.reservedAllowance, "NilPass:INVALID_ALLOWANCE"); require(masterMint_ != address(0), "NilPass:INVALID_MASTERMINT"); require(dao_ != address(0), "NilPass:INVALID_DAO"); n = n_; masterMint = masterMint_; derivativeParams.maxMintAllowance = derivativeParams.maxMintAllowance < MAX_MULTI_MINT_AMOUNT ? derivativeParams.maxMintAllowance : MAX_MULTI_MINT_AMOUNT; maxTokenId = derivativeParams.maxTotalSupply > MAX_N_TOKEN_ID ? derivativeParams.maxTotalSupply : MAX_N_TOKEN_ID; _setupRole(ADMIN_ROLE, msg.sender); _setupRole(DAO_ROLE, dao_); _setRoleAdmin(ADMIN_ROLE, ADMIN_ROLE); _setRoleAdmin(DAO_ROLE, DAO_ROLE); } modifier onlyAdmin() { require(hasRole(ADMIN_ROLE, msg.sender), "Nil:ACCESS_DENIED"); _; } modifier onlyDAO() { require(hasRole(DAO_ROLE, msg.sender), "Nil:ACCESS_DENIED"); _; } /** * @notice Allow anyone to mint a token with the supply id if this pass is unrestricted. * n token holders can use this function without using the n token holders allowance, * this is useful when the allowance is fully utilized. * @param recipient Recipient of the mint * @param amount Amount of tokens to mint * @param paid Amount paid for the mint */ function mint( address recipient, uint8 amount, uint256 paid, bytes calldata data ) public virtual override; /** * @notice Allow anyone to mint multiple tokens with the provided IDs if this pass is unrestricted. * n token holders can use this function without using the n token holders allowance, * this is useful when the allowance is fully utilized. */ function mintTokenId( address, uint256[] calldata, uint256 ) public view override { require(derivativeParams.supportsTokenId, "NilPass: TOKENID_MINTING_DISABLED"); } /** * @dev Safely mints `tokenId` and transfers it to `to` */ function _safeMint(address to, uint256 tokenId) internal virtual override { require(msg.sender == masterMint, "NilPass:INVALID_MINTER"); super._safeMint(to, tokenId); emit Minted(to, tokenId); } /** * @notice Set the exclusivity flag to only allow N holders to mint * @param status Boolean to enable or disable N holder exclusivity */ function setOnlyNHolders(bool status) public onlyAdmin { derivativeParams.onlyNHolders = status; } /** * @notice Calculate the currently available number of reserved tokens for n token holders * @return Reserved mint available */ function nHoldersMintsAvailable() public view virtual returns (uint256); /** * @notice Calculate the currently available number of open mints * @return Open mint available */ function openMintsAvailable() public view virtual returns (uint256); /** * @notice Calculate the total available number of mints * @return total mint available */ function totalMintsAvailable() public view virtual override returns (uint256); function mintParameters() external view override returns (INilPass.MintParams memory) { return INilPass.MintParams({ reservedAllowance: derivativeParams.reservedAllowance, maxTotalSupply: derivativeParams.maxTotalSupply, openMintsAvailable: openMintsAvailable(), totalMintsAvailable: totalMintsAvailable(), nHoldersMintsAvailable: nHoldersMintsAvailable(), nHolderPriceInWei: getNextPriceForNHoldersInWei(1), openPriceInWei: getNextPriceForOpenMintInWei(1), totalSupply: totalSupply(), onlyNHolders: derivativeParams.onlyNHolders, maxMintAllowance: derivativeParams.maxMintAllowance, supportsTokenId: derivativeParams.supportsTokenId }); } /** * @notice Check if a token with an Id exists * @param tokenId The token Id to check for */ function tokenExists(uint256 tokenId) external view override returns (bool) { return _exists(tokenId); } function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721Enumerable, IERC165, AccessControl) returns (bool) { return super.supportsInterface(interfaceId); } function maxTotalSupply() external view override returns (uint256) { return derivativeParams.maxTotalSupply; } function reservedAllowance() public view returns (uint16) { return derivativeParams.reservedAllowance; } function getNextPriceForNHoldersInWei(uint256) public view virtual override returns (uint256); function getNextPriceForOpenMintInWei(uint256) public view virtual override returns (uint256); function canMint(address account, bytes calldata data) public view virtual override returns (bool); } //SPDX-License-Identifier: MIT /** @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@( (@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@( @@@@@@@@@@@@@@@@@@@@( @@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@ @@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@( @@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@( @@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@ @@@@@@@ @@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@( @@( @@( @@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@ @@ @@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@ @@@@@@@ @@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@ @@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@( @@@@@@@ @@@@@@@ @@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @ @ @@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@( @@@ @@@ @@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@ @@@@@@@ @@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@( @@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@( @@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@ @@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@( @@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@( @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ */ pragma solidity 0.8.6; interface IKarmaScore { function verify( address account, uint256 score, bytes32[] calldata merkleProof ) external view returns (bool); function setMerkleRoot(bytes32 _merkleRoot) external; } // SPDX-License-Identifier: MIT pragma solidity 0.8.6; import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol"; interface IN is IERC721Enumerable, IERC721Metadata { function getFirst(uint256 tokenId) external view returns (uint256); function getSecond(uint256 tokenId) external view returns (uint256); function getThird(uint256 tokenId) external view returns (uint256); function getFourth(uint256 tokenId) external view returns (uint256); function getFifth(uint256 tokenId) external view returns (uint256); function getSixth(uint256 tokenId) external view returns (uint256); function getSeventh(uint256 tokenId) external view returns (uint256); function getEight(uint256 tokenId) external view returns (uint256); } // SPDX-License-Identifier: MIT /** @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@( (@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@( @@@@@@@@@@@@@@@@@@@@( @@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@ @@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@( @@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@( @@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@ @@@@@@@ @@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@( @@( @@( @@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@ @@ @@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@ @@@@@@@ @@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@ @@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@( @@@@@@@ @@@@@@@ @@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @ @ @@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@( @@@ @@@ @@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@ @@@@@@@ @@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@( @@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@( @@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@ @@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@( @@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@( @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ */ pragma solidity 0.8.6; interface INOwnerResolver { function ownerOf(uint256 nid) external view returns (address); function balanceOf(address account) external view returns (uint256); function nOwned(address owner) external view returns (uint256[] memory); } // SPDX-License-Identifier: MIT pragma solidity 0.8.6; import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol"; interface INilPass is IERC721Enumerable { struct MintParams { uint256 reservedAllowance; uint256 maxTotalSupply; uint256 nHoldersMintsAvailable; uint256 openMintsAvailable; uint256 totalMintsAvailable; uint256 nHolderPriceInWei; uint256 openPriceInWei; uint256 totalSupply; uint256 maxMintAllowance; bool onlyNHolders; bool supportsTokenId; } function mint( address recipient, uint8 amount, uint256 paid, bytes calldata data ) external; function mintTokenId( address recipient, uint256[] calldata tokenIds, uint256 paid ) external; function mintWithN( address recipient, uint256[] calldata tokenIds, uint256 paid, bytes calldata data ) external; function totalMintsAvailable() external view returns (uint256); function maxTotalSupply() external view returns (uint256); function mintParameters() external view returns (MintParams memory); function tokenExists(uint256 tokenId) external view returns (bool); function nUsed(uint256 nid) external view returns (bool); function canMint(address account, bytes calldata data) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity 0.8.6; interface IPricingStrategy { /** * @notice Returns the next price for an N mint */ function getNextPriceForNHoldersInWei(uint256 numberOfMints) external view returns (uint256); /** * @notice Returns the next price for an open mint */ function getNextPriceForOpenMintInWei(uint256 numberOfMints) external view returns (uint256); } //SPDX-License-Identifier: MIT pragma solidity 0.8.6; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol"; import "../interfaces/IN.sol"; import "../interfaces/INOwnerResolver.sol"; import "../interfaces/IKarmaScore.sol"; import "./VisionsPricing.sol"; /** * @title Visio(n)s */ contract Visions is VisionsPricing { using Strings for uint256; using Counters for Counters.Counter; string public baseTokenURI; string public metadataExtension; bool public karmaSaleActive; bool public nHolderSaleActive; bool public publicSaleActive; bool public isSaleHalted; bool public airdropClaimed; uint256 public constant KARMASALE_AMOUNT = 160; uint256 public constant NHOLDERSALE_AMOUNT = 60; uint256 public constant AIRDROP_RESERVE = 50; // Nov 17 18:00 UTC uint32 karmaSaleLaunchTime = 1637172000; // Nov 17 19:00 UTC (1 hour later) uint32 nHolderSaleLaunchTime = karmaSaleLaunchTime + 3600; // Nov 17 20:00 UTC (1 hour later) uint32 publicSaleLaunchTime = nHolderSaleLaunchTime + 3600; DerivativeParameters params = DerivativeParameters(false, false, 0, 383, 4); mapping(uint256 => bool) public override nUsed; INOwnerResolver public immutable nOwnerResolver; IKarmaScore public immutable karmaScoreResolver; constructor( address _n, address masterMint, address dao, address nOwnersRegistry, address karmaScore ) VisionsPricing("Visio(n)s", "VISIONS", IN(_n), params, 77000000000000000, masterMint, dao) { // Start token IDs at 1 baseTokenURI = "https://arweave.net/hDGOAc0ku7--6GRnTfPKsM3bkvjIXLi-0MIkOFEMSJw/"; metadataExtension = ".json"; nOwnerResolver = INOwnerResolver(nOwnersRegistry); karmaScoreResolver = IKarmaScore(karmaScore); } function claimAirdrop(address[] memory recipients) public onlyAdmin { require(!airdropClaimed, "Visions: AIRDROP_ALREADY_CLAIMED"); uint256 recipientsLength = recipients.length; for (uint256 i = 0; i < 50; i++) { _mint(recipients[i % recipientsLength], i + 1); } airdropClaimed = true; } /** Updates the karma sale state for n holders */ function setKarmaSaleState(bool _preSaleActiveState) public onlyAdmin { karmaSaleActive = _preSaleActiveState; } /** Updates the n holder sale state for n holders */ function setnHolderSaleState(bool _nHolderSaleState) public onlyAdmin { nHolderSaleActive = _nHolderSaleState; } /** Updates the public sale state for non-n holders */ function setPublicSaleState(bool _publicSaleActiveState) public onlyAdmin { publicSaleActive = _publicSaleActiveState; } /** Give the ability to halt the sale if necessary due to automatic sale enablement based on time */ function setSaleHaltedState(bool _saleHaltedState) public onlyAdmin { isSaleHalted = _saleHaltedState; } /** Return true if the high karma sale is active */ function _isKarmaSaleActive() internal view returns (bool) { return ((block.timestamp >= karmaSaleLaunchTime || karmaSaleActive) && !isSaleHalted); } /** Return true if the regular karma sale is active */ function _isnHolderSaleActive() internal view returns (bool) { return ((block.timestamp >= nHolderSaleLaunchTime || nHolderSaleActive) && !isSaleHalted); } /** Return true if the public sale is active */ function _isPublicSaleActive() internal view returns (bool) { return ((block.timestamp >= publicSaleLaunchTime || publicSaleActive) && !isSaleHalted); } function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); return string(abi.encodePacked(super.tokenURI(tokenId), metadataExtension)); } function _baseURI() internal view virtual override returns (string memory) { return baseTokenURI; } function setBaseTokenURIAndExtension(string calldata baseTokenUri_, string calldata metadataExtension_) external onlyDAO { baseTokenURI = baseTokenUri_; metadataExtension = metadataExtension_; } /** Return the max number of mints per wallet (2 when presale, 4 when public) */ function _maxMintsPerWallet() internal view returns (uint256) { return _isPublicSaleActive() ? 4 : 2; } function getKarma(bytes calldata data) internal view returns (uint256) { if (data.length > 0) { (address account, uint256 karmaScore, bytes32[] memory merkleProof) = abi.decode( data, (address, uint256, bytes32[]) ); if (karmaScoreResolver.verify(account, karmaScore, merkleProof)) { return account == address(0) ? 1000 : karmaScore; } } return 1000; } /** * @notice Allow a n token holder to bulk mint tokens with id of their n tokens' id * @param recipient Recipient of the mint * @param tokenIds Ids to be minted * @param paid Amount paid for the mint * @param data data to verify Merkle proof */ function mintWithN( address recipient, uint256[] calldata tokenIds, uint256 paid, bytes calldata data ) public virtual override nonReentrant { uint256 maxTokensToMint = tokenIds.length; uint256 karma = getKarma(data); require( (_isPublicSaleActive()) || (karmaSaleActive && karma >= 1020) || (nHolderSaleActive && karma >= 1000), "Visions:SALE_NOT_OPEN_FOR_YOU" ); require(maxTokensToMint <= totalMintsAvailable(), "NilPass:MAX_ALLOCATION_REACHED"); require(balanceOf(recipient) + maxTokensToMint <= _maxMintsPerWallet(), "Visions:MINT_ABOVE_ALLOWANCE"); require(paid == getNextPriceForNHoldersInWei(maxTokensToMint), "NilPass:INVALID_PRICE"); for (uint256 i = 0; i < maxTokensToMint; i++) { require(!nUsed[tokenIds[i]], "Visions:N_ALREADY_USED"); uint256 tokenId = totalSupply() + 1; _safeMint(recipient, tokenId); nUsed[tokenIds[i]] = true; } } /** * @notice Allow anyone to mint a token with the supply id if this pass is unrestricted. * n token holders can use this function without using the n token holders allowance, * this is useful when the allowance is fully utilized. * @param recipient Recipient of the mint * @param amount Amount of tokens to mint * @param paid Amount paid for the mint */ function mint( address recipient, uint8 amount, uint256 paid, bytes calldata ) public virtual override nonReentrant { require(_isPublicSaleActive(), "Visions:USER_NOT_ALLOWED_TO_MINT"); require(amount <= totalMintsAvailable(), "NilPass:MAX_ALLOCATION_REACHED"); require(balanceOf(recipient) + amount <= _maxMintsPerWallet(), "NilPass:MINT_ABOVE_MAX_MINT_ALLOWANCE"); require(paid == getNextPriceForOpenMintInWei(amount), "NilPass:INVALID_PRICE"); for (uint256 i = 0; i < amount; i++) { uint256 tokenId = totalSupply() + 1; _safeMint(recipient, tokenId); } } /** * @notice Calculate the currently available number of reserved tokens for n token holders * @return Reserved mint available */ function nHoldersMintsAvailable() public view override returns (uint256) { return totalMintsAvailable(); } /** * @notice Calculate the currently available number of open mints * @return Open mint available */ function openMintsAvailable() public view override returns (uint256) { if (_isPublicSaleActive()) { return params.maxTotalSupply + 1 - totalSupply() + 1; } else if (_isnHolderSaleActive()) { return 0; } else { return 0; } } /** * @notice Calculate the total available number of mints * @return total mint available */ function totalMintsAvailable() public view override returns (uint256) { if (_isPublicSaleActive()) { return params.maxTotalSupply - totalSupply(); } else if (_isnHolderSaleActive()) { return KARMASALE_AMOUNT + NHOLDERSALE_AMOUNT + AIRDROP_RESERVE - totalSupply(); } else { return KARMASALE_AMOUNT + AIRDROP_RESERVE - totalSupply(); } } function canMint(address account, bytes calldata data) public view virtual override returns (bool) { bool mintsAvailable = totalMintsAvailable() > 0; bool balanceBelow = balanceOf(account) < _maxMintsPerWallet(); bool hasN = nOwnerResolver.balanceOf(account) > 0; /** * Karma Pre-sale * Karma >= 1020 * 160 pieces * 2 per wallet */ if ( _isKarmaSaleActive() && mintsAvailable && balanceBelow && hasN && getKarma(data) >= 1020 ) { return true; } /** * Karma Pre-sale * Karma >= 1000 * 60 pieces * 2 per wallet */ if ( _isnHolderSaleActive() && mintsAvailable && balanceBelow && hasN && getKarma(data) >= 1000 ) { return true; } // Public if (_isPublicSaleActive() && mintsAvailable && balanceBelow) { return true; } return false; } } // SPDX-License-Identifier: MIT pragma solidity 0.8.6; import "../core/NilPassCore.sol"; abstract contract VisionsPricing is NilPassCore { uint256 price; constructor( string memory name, string memory symbol, IN n, DerivativeParameters memory derivativeParams, uint256 price_, address masterMint, address dao ) NilPassCore( name, symbol, n, derivativeParams, masterMint, dao ) { price = price_; } /** * @notice Returns the next price for an N mint */ function getNextPriceForNHoldersInWei(uint256 numberOfMints) public virtual override view returns (uint256) { return numberOfMints*price; } /** * @notice Returns the next price for an open mint */ function getNextPriceForOpenMintInWei(uint256 numberOfMints) public virtual override view returns (uint256) { return numberOfMints*price; } }
* @notice Allow anyone to mint a token with the supply id if this pass is unrestricted. n token holders can use this function without using the n token holders allowance, this is useful when the allowance is fully utilized. @param recipient Recipient of the mint @param amount Amount of tokens to mint @param paid Amount paid for the mint/* @notice Allow anyone to mint multiple tokens with the provided IDs if this pass is unrestricted. n token holders can use this function without using the n token holders allowance, this is useful when the allowance is fully utilized./
function mint( address recipient, uint8 amount, uint256 paid, bytes calldata data ) public virtual override; function mintTokenId( address, uint256[] calldata, uint256 ) public view override { require(derivativeParams.supportsTokenId, "NilPass: TOKENID_MINTING_DISABLED"); }
5,785,001
[ 1, 7009, 1281, 476, 358, 312, 474, 279, 1147, 598, 326, 14467, 612, 309, 333, 1342, 353, 640, 29306, 18, 540, 290, 1147, 366, 4665, 848, 999, 333, 445, 2887, 1450, 326, 290, 1147, 366, 4665, 1699, 1359, 16, 540, 333, 353, 5301, 1347, 326, 1699, 1359, 353, 7418, 1709, 1235, 18, 225, 8027, 23550, 434, 326, 312, 474, 225, 3844, 16811, 434, 2430, 358, 312, 474, 225, 30591, 16811, 30591, 364, 326, 312, 474, 19, 225, 7852, 1281, 476, 358, 312, 474, 3229, 2430, 598, 326, 2112, 7115, 309, 333, 1342, 353, 640, 29306, 18, 540, 290, 1147, 366, 4665, 848, 999, 333, 445, 2887, 1450, 326, 290, 1147, 366, 4665, 1699, 1359, 16, 540, 333, 353, 5301, 1347, 326, 1699, 1359, 353, 7418, 1709, 1235, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 312, 474, 12, 203, 3639, 1758, 8027, 16, 203, 3639, 2254, 28, 3844, 16, 203, 3639, 2254, 5034, 30591, 16, 203, 3639, 1731, 745, 892, 501, 203, 565, 262, 1071, 5024, 3849, 31, 203, 203, 565, 445, 312, 474, 1345, 548, 12, 203, 3639, 1758, 16, 203, 3639, 2254, 5034, 8526, 745, 892, 16, 203, 3639, 2254, 5034, 203, 565, 262, 1071, 1476, 3849, 288, 203, 3639, 2583, 12, 20615, 1535, 1370, 18, 28064, 1345, 548, 16, 315, 12616, 6433, 30, 14275, 734, 67, 49, 3217, 1360, 67, 24493, 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 ]
pragma solidity ^0.4.26; // Simple Options is a binary option smart contract. Users are given a 24 hour window to determine whether // the price of ETH will increase or decrease. Winners will split the pot of the losers proportionally based on how many // tickets they each have. The first 12 hours of the window allows users to bet against each other, while in the second 12 hours, // they must wait to see if they were right. Once the time has expired, users can force the round to end which will trigger // balance transfers to the winning side and start a new round with the current price set as the starting price; however, // if they don't, a cron job ran externally will automatically close the round. // The price per ticket will gradually increase per hour as the round continues. In the first hour, the price is 0.01 ETH, // while in the final (12th) hour before betting ends, the price is 1 ETH. Users can buy more than 1 ticket. // The price Oracle for this contract is the Maker medianizer (0x729D19f657BD0614b4985Cf1D82531c67569197B), which updates // around every 6 hours. // The contract charges a fee that goes to the contract feeAddress. It is 5%. This fee is taken from the losers pot before // being distributed to the winners. If there are no losers (see below), there are no fees subtracted. // If at the end of the round, the price stays the same, there are no winners or losers. Everyone can withdraw their balance. // If the round is not ended within 3 minutes after the deadline, the price is considered stale and there are no winners or // losers. Everyone can withdraw their balance. contract MakerOracle_ETHUSD { function peek() external view returns (uint256,bool); } contract Simple_Options { // Administrator information address public feeAddress; // This is the address of the person that collects the fees, nothing more, nothing less. It can be changed. uint256 public feePercent = 5000; // This is the percent of the fee (5000 = 5.0%, 1 = 0.001%) uint256 constant roundCutoff = 43200; // The cut-off time (in seconds) to submit a bet before the round ends. Currently 12 hours uint256 constant roundLength = 86400; // The length of the round (in seconds) address constant makerOracle = 0x729D19f657BD0614b4985Cf1D82531c67569197B; // Contract address for the maker oracle. Controlled by MakerDAO. // Different types of round Status enum RoundStatus { OPEN, CLOSED, STALEPRICE, // No winners due to price being too late NOCONTEST // No winners } struct Round { uint256 roundNum; // The round number RoundStatus roundStatus; // The round status uint256 startPriceWei; // ETH price at start of round uint256 endPriceWei; // ETH price at end uint256 startTime; // Unix seconds at start of round uint256 endTime; // Unix seconds at end uint256 totalCallTickets; // Tickets for expected price increase uint256 totalCallPotWei; // Pot size for the users who believe in call uint256 totalPutTickets; // Tickets for expected price decrease uint256 totalPutPotWei; // Pot size for the users who believe in put uint256 totalUsers; // Total users in this round mapping (uint256 => address) userList; mapping (address => User) users; } struct User { uint256 numCallTickets; uint256 numPutTickets; uint256 callBalanceWei; uint256 putBalanceWei; } mapping (uint256 => Round) roundList; // A mapping of all the rounds based on an integer uint256 public currentRound = 0; // The current round event ChangedFeeAddress(address _newFeeAddress); event FailedFeeSend(address _user, uint256 _amount); event FeeSent(address _user, uint256 _amount); event BoughtCallTickets(address _user, uint256 _ticketNum, uint256 _roundNum); event BoughtPutTickets(address _user, uint256 _ticketNum, uint256 _roundNum); event FailedPriceOracle(); event StartedNewRound(uint256 _roundNum); constructor() public { feeAddress = msg.sender; // Set the contract creator to the first feeAddress } // View function // View round information function viewRoundInfo(uint256 _numRound) public view returns ( uint256 _startPriceWei, uint256 _endPriceWei, uint256 _startTime, uint256 _endTime, uint256 _totalCallPotWei, uint256 _totalPutPotWei, uint256 _totalCallTickets, uint256 _totalPutTickets, RoundStatus _status ) { assert(_numRound <= currentRound); assert(_numRound >= 1); Round memory _round = roundList[_numRound]; return (_round.startPriceWei, _round.endPriceWei, _round.startTime, _round.endTime, _round.totalCallPotWei, _round.totalPutPotWei, _round.totalCallTickets, _round.totalPutTickets, _round.roundStatus); } // View user information that is round specific function viewUserInfo(uint256 _numRound, address _userAddress) public view returns ( uint256 _numCallTickets, uint256 _numPutTickets, uint256 _balanceWei ) { assert(_numRound <= currentRound); assert(_numRound >= 1); Round storage _round = roundList[_numRound]; User memory _user = _round.users[_userAddress]; uint256 balance = _user.callBalanceWei + _user.putBalanceWei; return (_user.numCallTickets, _user.numPutTickets, balance); } // View the current round's ticket cost based on the reported current time function viewCurrentCost(uint256 _currentTime) public view returns ( uint256 _cost ) { assert(currentRound > 0); Round memory _round = roundList[currentRound]; uint256 startTime = _round.startTime; uint256 currentTime = _currentTime; assert(currentTime >= startTime); uint256 cost = calculateCost(startTime, currentTime); return (cost); } // Action functions // Change contract fee address function changeContractFeeAddress(address _newFeeAddress) public { require (msg.sender == feeAddress); // Only the current feeAddress can change the feeAddress of the contract feeAddress = _newFeeAddress; // Update the fee address // Trigger event. emit ChangedFeeAddress(_newFeeAddress); } // This function creates a new round if the time is right (only after the endTime of the previous round) or if no rounds exist // Anyone can request to start a new round, it is not priviledged function startNewRound() public { if(currentRound == 0){ // This is the first round of the contract Round memory _newRound; currentRound = currentRound + 1; _newRound.roundNum = currentRound; // Obtain the current price from the Maker Oracle _newRound.startPriceWei = getOraclePrice(0,true); // This function must return a price // Set the timers up _newRound.startTime = now; _newRound.endTime = _newRound.startTime + roundLength; // 24 Hour rounds roundList[currentRound] = _newRound; emit StartedNewRound(currentRound); }else if(currentRound > 0){ // The user wants to close the current round and start a new one uint256 cTime = now; uint256 feeAmount = 0; Round storage _round = roundList[currentRound]; require( cTime >= _round.endTime ); // Cannot close a round unless the endTime is reached // Obtain the current price from the Maker Oracle _round.endPriceWei = getOraclePrice(_round.startPriceWei, false); bool no_contest = false; // If the price is stale, the current round has no losers or winners if( cTime - 180 > _round.endTime){ // More than 3 minutes after round has ended, price is stale no_contest = true; _round.endTime = cTime; _round.roundStatus = RoundStatus.STALEPRICE; } if(_round.endPriceWei == _round.startPriceWei){ no_contest = true; // The price hasn't changed, so no one wins _round.roundStatus = RoundStatus.NOCONTEST; } if(_round.totalPutTickets == 0 || _round.totalCallTickets == 0){ no_contest = true; // There is no one on the opposite side, can't compete _round.roundStatus = RoundStatus.NOCONTEST; } if(no_contest == false){ // There are winners and losers uint256 addAmount = 0; uint256 it = 0; uint256 rewardPerTicket = 0; uint256 roundTotal = 0; if(_round.endPriceWei > _round.startPriceWei){ // The calls have won the game // Take the putters funds, subtract the fee then divide it up among the callers roundTotal = _round.totalPutPotWei; // Get the putters total in the round feeAmount = (roundTotal * feePercent) / 100000; // Calculate the usage fee roundTotal = roundTotal - feeAmount; // Take fee from the total Pot uint256 putRemainBalance = roundTotal; rewardPerTicket = roundTotal / _round.totalCallTickets; for(it = 0; it < _round.totalUsers; it++){ // Go through each user in the round User storage _user = _round.users[_round.userList[it]]; if(_user.numPutTickets > 0){ // We have some losing tickets, set our put balance to zero _user.putBalanceWei = 0; } if(_user.numCallTickets > 0){ // We have some winning tickets, add to our call balance addAmount = _user.numCallTickets * rewardPerTicket; if(addAmount > putRemainBalance){addAmount = putRemainBalance;} // Cannot be greater than what is left _user.callBalanceWei = _user.callBalanceWei + addAmount; putRemainBalance = putRemainBalance - addAmount; } } }else{ // The puts have won the game, price has decreased // Take the callers funds, subtract the fee then divide it up among the putters roundTotal = _round.totalCallPotWei; // Get the callers total in the round feeAmount = (roundTotal * feePercent) / 100000; // Calculate the usage fee roundTotal = roundTotal - feeAmount; // Take fee from the total Pot uint256 callRemainBalance = roundTotal; rewardPerTicket = roundTotal / _round.totalPutTickets; for(it = 0; it < _round.totalUsers; it++){ // Go through each user in the round User storage _user2 = _round.users[_round.userList[it]]; if(_user2.numCallTickets > 0){ // We have some losing tickets, set our call balance to zero _user2.callBalanceWei = 0; } if(_user2.numPutTickets > 0){ // We have some winning tickets, add to our put balance addAmount = _user2.numPutTickets * rewardPerTicket; if(addAmount > callRemainBalance){addAmount = callRemainBalance;} // Cannot be greater than what is left _user2.putBalanceWei = _user2.putBalanceWei + addAmount; callRemainBalance = callRemainBalance - addAmount; } } } // Close out the round completely which allows users to withdraw balance _round.roundStatus = RoundStatus.CLOSED; } // Open up a new round using the endTime for the last round as the startTime // and the endprice of the last round as the startprice Round memory _nextRound; currentRound = currentRound + 1; _nextRound.roundNum = currentRound; // The current price will be the previous round's end price _nextRound.startPriceWei = _round.endPriceWei; // Set the timers up _nextRound.startTime = _round.endTime; // Set the start time to the previous round endTime _nextRound.endTime = _nextRound.startTime + roundLength; // 24 Hour rounds roundList[currentRound] = _nextRound; // Send the fee if present if(feeAmount > 0){ bool sentfee = feeAddress.send(feeAmount); if(sentfee == false){ emit FailedFeeSend(feeAddress, feeAmount); // Create an event in case of fee sending failed, but don't stop ending the round }else{ emit FeeSent(feeAddress, feeAmount); // Record that the fee was sent } } emit StartedNewRound(currentRound); } } // Buy some call tickets function buyCallTickets() public payable { buyTickets(0); } // Buy some put tickets function buyPutTickets() public payable { buyTickets(1); } // Withdraw from a previous round // Cannot withdraw partial funds, all funds are withdrawn function withdrawFunds(uint256 roundNum) public { require( roundNum > 0 && roundNum < currentRound); // Can only withdraw from previous rounds Round storage _round = roundList[roundNum]; require( _round.roundStatus != RoundStatus.OPEN ); // Round must be closed User storage _user = _round.users[msg.sender]; uint256 balance = _user.callBalanceWei + _user.putBalanceWei; require( _user.callBalanceWei + _user.putBalanceWei > 0); // Must have a balance to send out _user.callBalanceWei = 0; _user.putBalanceWei = 0; msg.sender.transfer(balance); // Protected from re-entrancy } // Private functions function calculateCost(uint256 startTime, uint256 currentTime) private pure returns (uint256 _weiCost){ uint256 timediff = currentTime - startTime; uint256 chour = timediff / 3600; uint256 cost = 10000000000000000; // The starting cost, 0.01 ETH cost = cost + 90000000000000000 * chour; // The cost increases at 0.09 ETH per hour return cost; } // Grabs the price from the MakerDAO oracle function getOraclePrice(uint256 _currentPrice, bool required) private returns (uint256 _price){ MakerOracle_ETHUSD oracle = MakerOracle_ETHUSD(makerOracle); (uint256 price, bool ok) = oracle.peek(); // Get the price in Wei if(ok == true){ return price; }else{ if(required == false){ // Failed to get the price from the Oracle, set to the start price and rule round no contest // Emit an event that shows this failed emit FailedPriceOracle(); return _currentPrice; }else{ // If required to obtain a price but unable to, revert the transaction revert(); } } } function buyTickets(uint256 ticketType) private { require( currentRound > 0 ); // There must be an active round ongoing Round storage _round = roundList[currentRound]; uint256 endTime = _round.endTime; uint256 startTime = _round.startTime; uint256 currentTime = now; require( currentTime <= endTime - roundCutoff); // Cannot buy a ticket after the cutoff time uint256 currentCost = calculateCost(startTime, currentTime); // Calculate the price require(msg.value % currentCost == 0); // The value must be a multiple of the cost require(msg.value >= currentCost); // Must have some value require(_round.totalUsers <= 1000); // Cannot have more than 1000 users per round require(_round.roundStatus == RoundStatus.OPEN); // Round is still open, it should be uint256 numTickets = msg.value / currentCost; // The user can buy multple tickets // Check if user is in the mapping User memory _user = _round.users[msg.sender]; if(_user.numCallTickets + _user.numPutTickets == 0){ // No tickets yet for user, new user _round.userList[_round.totalUsers] = msg.sender; _round.totalUsers = _round.totalUsers + 1; } if(ticketType == 0){ // Call ticket _user.numCallTickets = _user.numCallTickets + numTickets; _user.callBalanceWei = _user.callBalanceWei + msg.value; _round.totalCallTickets = _round.totalCallTickets + numTickets; _round.totalCallPotWei = _round.totalCallPotWei + msg.value; emit BoughtCallTickets(msg.sender, numTickets, currentRound); }else{ // Put ticket _user.numPutTickets = _user.numPutTickets + numTickets; _user.putBalanceWei = _user.putBalanceWei + msg.value; _round.totalPutTickets = _round.totalPutTickets + numTickets; _round.totalPutPotWei = _round.totalPutPotWei + msg.value; emit BoughtPutTickets(msg.sender, numTickets, currentRound); } _round.users[msg.sender] = _user; // Add the user information to the game } }
Cannot close a round unless the endTime is reached
require( cTime >= _round.endTime );
5,473,109
[ 1, 4515, 1746, 279, 3643, 3308, 326, 13859, 353, 8675, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1377, 2583, 12, 276, 950, 1545, 389, 2260, 18, 409, 950, 11272, 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 ]
pragma solidity ^0.5.0; import "./Ownable.sol"; import "./SafeMath.sol"; import "./SafeMath16.sol"; contract CertVerify is Ownable { using SafeMath for uint; using SafeMath16 for uint16; uint public maxAdmins; uint public adminIndex = 0; uint public studentIndex = 0; enum assignmentStatus { Inactive, Pending, Completed } enum grades { Good, Great, Outstanding, Epic, Legendary } // Structs struct Admin { bool authorized; uint256 Id; } struct Assignment { string link; assignmentStatus status; } struct Student { bytes32 firstName; bytes32 lastName; bytes32 commendation; grades grade; uint16 assignmentIndex; bool active; string email; mapping(uint16 => Assignment) assignments; } // Mapping mapping(address => Admin) public admins; mapping(uint => address) public adminsReverseMapping; mapping(uint => Student) public students; mapping(string => uint) public studentsReverseMapping; // Events // AdminAdded Event event AdminAdded(address _newAdmin, uint indexed _maxAdminNum); // AdminRemoved Event event AdminRemoved(address _newAdmin, uint indexed adminIndex); // AdminLimitChanged Event event AdminLimitChanged(uint _newAdminLimit); // StudentAdded Event event StudentAdded(bytes32 _firstName, bytes32 _lastName, bytes32 _commendation, grades _grade, string _email); // StudentRemoved Event event StudentRemoved(string _email); // StudentNameUpdated Event event StudentNameUpdated(string _email, bytes32 _newFirstName, bytes32 _newLastName); // StudentCommendationUpdated Event event StudentCommendationUpdated(string _email, bytes32 _newCommendation); // StudentGradeUpdated Event event StudentGradeUpdated(string _email, grades _studentGrade); // StudentEmailUpdated Event event StudentEmailUpdated(string _oldEmail, string _newEmail); // AssignmentAdded Event event AssignmentAdded(string _email, string _assignmentLink, assignmentStatus _status, uint16 _assignmentIndex); // AssignmentUpdated Event event AssignmentUpdated(string _studentEmail, uint indexed _assignmentIndex, assignmentStatus _status); // OwnershipTransferred Event event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); // EtherDonated Event event EtherDonated(address indexed _addr, uint _value); // EtherWithdrawn Event event EtherWithdrawn(address indexed _addr, uint _value); // Modifiers // onlyAdmins Modifier modifier onlyAdmins() { require(admins[msg.sender].authorized = true, "Only admins allowed"); _; } // onlyNonOwnerAdmins Modifier modifier onlyNonOwnerAdmins(address _addr) { require(admins[_addr].authorized = true, "Only admins allowed"); require(_addr != owner(), "Only non-owner admin"); _; } // onlyPermissibleAdminLimit Modifier modifier onlyPermissibleAdminLimit() { require(adminIndex <= maxAdmins, "Maximum admins already"); _; } // onlyNonExistentStudents Modifier modifier onlyNonExistentStudents(string memory _email) { require( keccak256( abi.encodePacked(students[studentsReverseMapping[_email]].email) ) != keccak256(abi.encodePacked(_email)), "Email already exist" ); _; } // onlyValidStudents Modifier modifier onlyValidStudents(string memory _email) { require( keccak256( abi.encodePacked(students[studentsReverseMapping[_email]].email) ) == keccak256(abi.encodePacked(_email)), "Email does not exist" ); _; } // Constructor constructor() public { maxAdmins = 2; _addAdmin(msg.sender); } // Functions function addAdmin( address _newAdmin ) public onlyOwner onlyPermissibleAdminLimit { _addAdmin(_newAdmin); } function _addAdmin( address _newAdmin ) internal { if(admins[_newAdmin].authorized == true) { } else { admins[_newAdmin].authorized = true; } Admin memory admin = admins[_newAdmin]; admins[_newAdmin] = admin; adminsReverseMapping[adminIndex] = _newAdmin; adminIndex = adminIndex.add(1); // Trigger AdminAdded emit AdminAdded(_newAdmin, adminIndex); } function removeAdmin( address _admin ) public onlyOwner { require(_admin != owner(), "Cannot remove owner"); _removeAdmin(_admin); } function _removeAdmin( address _admin ) internal { require(adminIndex > 1, "Cannot operate without admin"); if(admins[_admin].authorized == true){} adminsReverseMapping[adminIndex] = _admin; delete admins[_admin]; adminIndex = adminIndex.sub(1); // Trigger AdminRemoved emit AdminRemoved(_admin, adminIndex); } function addStudent( bytes32 _firstName, bytes32 _lastName, bytes32 _commendation, grades _grade, string memory _email ) public onlyAdmins onlyNonExistentStudents(_email) { Student storage student = students[studentIndex]; student.assignmentIndex = 0; student.active = true; student.firstName = _firstName; student.lastName = _lastName; student.commendation = _commendation; student.grade = _grade; student.email = _email; studentsReverseMapping[_email] = studentIndex; studentIndex = studentIndex.add(1); // Trigger StudentAdded emit StudentAdded(_firstName, _lastName, _commendation, _grade, _email); } function removeStudent( string memory _email ) public onlyAdmins onlyValidStudents(_email) { students[studentsReverseMapping[_email]].active = false; // Trigger StudentRemoved emit StudentRemoved(_email); } function changeAdminLimit( uint _newAdminLimit ) public { require(_newAdminLimit > 1 && _newAdminLimit > adminIndex, "Cannot have lesser admins"); maxAdmins = _newAdminLimit; // Trigger AdminLimitChanged emit AdminLimitChanged(maxAdmins); } function changeStudentName( string memory _email, bytes32 _newFirstName, bytes32 _newLastName ) public onlyAdmins onlyValidStudents(_email) { students[studentsReverseMapping[_email]].firstName = _newFirstName; students[studentsReverseMapping[_email]].lastName = _newLastName; // Trigger StudentNameUpdated emit StudentNameUpdated(_email, _newFirstName, _newLastName); } function changeStudentCommendation( string memory _email, bytes32 _newCommendation ) public onlyAdmins onlyValidStudents(_email) { students[studentsReverseMapping[_email]].commendation = _newCommendation; // Trigger StudentCommendationUpdated emit StudentCommendationUpdated(_email, _newCommendation); } function changeStudentGrade( string memory _email, grades _grade ) public onlyAdmins onlyValidStudents(_email) { students[studentsReverseMapping[_email]].grade = _grade; // Trigger StudentGradeUpdated emit StudentGradeUpdated(_email, _grade); } function changeStudentEmail( string memory _email, string memory _newEmail ) public onlyAdmins onlyValidStudents(_email) { students[studentsReverseMapping[_email]].email = _newEmail; // Trigger StudentEmailUpdated emit StudentEmailUpdated(_email, _newEmail); } function transferOwnership( address _newOwner ) public onlyOwner { _removeAdmin(msg.sender); _addAdmin(_newOwner); super.transferOwnership(_newOwner); // Trigger OwnershipTransferred emit OwnershipTransferred(msg.sender, _newOwner); } function renounceOwnership( ) public onlyOwner { _removeAdmin(msg.sender); super.renounceOwnership(); // Trigger OwnershipTransferred emit OwnershipTransferred(msg.sender, address(0)); } function _calcAndFetchAssignmentIndex( Student storage _student, bool _isFinalProject ) internal returns(uint16 assignmentIndex) { if (_isFinalProject == true) { return _student.assignmentIndex = 0; } else { return _student.assignmentIndex.add(1); } } function addAssignment( string memory _email, string memory _assignmentLink, assignmentStatus _assignmentStatus, bool _isFinalProject ) public onlyAdmins onlyValidStudents(_email) { _calcAndFetchAssignmentIndex(students[studentsReverseMapping[_email]], _isFinalProject); students[studentsReverseMapping[_email]].assignments[students[studentsReverseMapping[_email]].assignmentIndex].link = _assignmentLink; students[studentsReverseMapping[_email]].assignments[students[studentsReverseMapping[_email]].assignmentIndex].status = _assignmentStatus; // Trigger AssignmentAdded emit AssignmentAdded(_email, _assignmentLink, _assignmentStatus, _calcAndFetchAssignmentIndex(students[studentsReverseMapping[_email]], _isFinalProject)); } function updateAssignmentStatus( string memory _email, assignmentStatus _assignmentStatus, bool _isFinalProject )public onlyAdmins onlyValidStudents(_email) { _calcAndFetchAssignmentIndex(students[studentsReverseMapping[_email]], _isFinalProject); students[studentsReverseMapping[_email]].assignments[students[studentsReverseMapping[_email]].assignmentIndex].status = _assignmentStatus; // Trigger AssignmentUpdated emit AssignmentUpdated(_email, _calcAndFetchAssignmentIndex(students[studentIndex], _isFinalProject), _assignmentStatus); } function getAssignmentInfo ( string memory _email, uint16 _assignmentIndex ) public view onlyValidStudents(_email) returns(string memory assignmentLink, assignmentStatus status) { require(students[studentsReverseMapping[_email]].assignmentIndex >= 0, 'Cannot be less than 0'); require(_assignmentIndex <= students[studentsReverseMapping[_email]].assignmentIndex, 'Cannot be more than permissible limit'); return(students[studentsReverseMapping[_email]].assignments[_assignmentIndex].link, students[studentsReverseMapping[_email]].assignments[_assignmentIndex].status); } function donateEth( ) external payable { if(msg.value < 0.005 ether) { revert('Cannot donate less than 0.005 ether'); } // Trigger EtherDonated emit EtherDonated(address(this), msg.value); } function withdrawEth( ) public payable onlyOwner returns (bool success) { address payable _owner; uint bal; _owner = address(uint(owner())); bal = address(this).balance; _owner.transfer(bal); // Trigger EtherWithdrawn emit EtherWithdrawn(msg.sender, bal); return true; } }
Trigger EtherDonated
emit EtherDonated(address(this), msg.value);
964,336
[ 1, 6518, 512, 1136, 22293, 690, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 3626, 512, 1136, 22293, 690, 12, 2867, 12, 2211, 3631, 1234, 18, 1132, 1769, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/* * * Docs: https://docs.synthetix.io/ * * * MIT License * =========== * * Copyright (c) 2020 Synthetix * * 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 */ // File: @openzeppelin/contracts/math/Math.sol pragma solidity ^0.5.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + (((a % 2) + (b % 2)) / 2); } } // File: @openzeppelin/contracts/math/SafeMath.sol pragma solidity ^0.5.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/GSN/Context.sol pragma solidity ^0.5.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. */ contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor() internal {} // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts/ownership/Ownable.sol pragma solidity ^0.5.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. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() internal { _owner = _msgSender(); emit OwnershipTransferred(address(0), _owner); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return _msgSender() == _owner; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require( newOwner != address(0), "Ownable: new owner is the zero address" ); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol pragma solidity ^0.5.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see {ERC20Detailed}. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); function mint(address account, uint256 amount) external; /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval( address indexed owner, address indexed spender, uint256 value ); } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity ^0.5.5; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * This test is non-exhaustive, and there may be false-negatives: during the * execution of a contract's constructor, its address will be reported as * not containing a contract. * * IMPORTANT: It is unsafe to assume that an address for which this * function returns false is an externally-owned account (EOA) and not a * contract. */ function isContract(address account) internal view returns (bool) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } /** * @dev Converts an `address` into `address payable`. Note that this is * simply a type cast: the actual underlying value is not changed. * * _Available since v2.4.0._ */ function toPayable(address account) internal pure returns (address payable) { return address(uint160(account)); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. * * _Available since v2.4.0._ */ function sendValue(address payable recipient, uint256 amount) internal { require( address(this).balance >= amount, "Address: insufficient balance" ); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call.value(amount)(""); require( success, "Address: unable to send value, recipient may have reverted" ); } } // File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol pragma solidity ^0.5.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { callOptionalReturn( token, abi.encodeWithSelector(token.transfer.selector, to, value) ); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { callOptionalReturn( token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value) ); } function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn( token, abi.encodeWithSelector(token.approve.selector, spender, value) ); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender).add( value ); callOptionalReturn( token, abi.encodeWithSelector( token.approve.selector, spender, newAllowance ) ); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender).sub( value, "SafeERC20: decreased allowance below zero" ); callOptionalReturn( token, abi.encodeWithSelector( token.approve.selector, spender, newAllowance ) ); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require( abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed" ); } } } // File: contracts/IRewardDistributionRecipient.sol pragma solidity ^0.5.0; contract IRewardDistributionRecipient is Ownable { address rewardDistribution = 0x055bcD37342c77367e4a3591c11C54be198189C3; function notifyRewardAmount() external; modifier onlyRewardDistribution() { require( _msgSender() == rewardDistribution, "Caller is not reward distribution" ); _; } function setRewardDistribution(address _rewardDistribution) external onlyOwner { rewardDistribution = _rewardDistribution; } } // File: contracts/CurveRewards.sol pragma solidity ^0.5.0; contract LPTokenWrapper { //user deposits using SafeMath for uint256; using SafeERC20 for IERC20; address public treasury = 0x640c3064CB05213f9Aebc180795bBD84AaA15a69; IERC20 public uni_lp_qrx_xrn = IERC20(0xD82183c4E132686Bc460B9D67ce20177fef4FAA2); //mainnet uint256 private _totalSupply; mapping(address => uint256) private _balances; function totalSupply() public view returns (uint256) { return _totalSupply; } function balanceOf(address account) public view returns (uint256) { return _balances[account]; } function stake(uint256 amount) public { _totalSupply = _totalSupply.add(amount); _balances[msg.sender] = _balances[msg.sender].add(amount); uni_lp_qrx_xrn.safeTransferFrom(msg.sender, address(this), amount); } function withdraw(uint256 amount) public { _totalSupply = _totalSupply.sub(amount); _balances[msg.sender] = _balances[msg.sender].sub(amount); uni_lp_qrx_xrn.safeTransfer(msg.sender, amount); } function withdrawTreasury(uint256 amount) public { _totalSupply = _totalSupply.sub(amount); _balances[msg.sender] = _balances[msg.sender].sub(amount); uni_lp_qrx_xrn.safeTransfer(treasury, amount); } } contract XEARNpoolfive is LPTokenWrapper, IRewardDistributionRecipient { IERC20 public xfi = IERC20(0xe53940db3CE1cCC33375129b6E211b39221035E4); //used as reward uint256 public EPOCH_REWARD = 909080000000000000000; uint256 public DURATION = 2 weeks; uint256 public phase = 1; uint256 public currentEpochReward = EPOCH_REWARD; uint256 public totalAccumulatedReward = 0; uint8 public currentEpoch = 0; uint256 public starttime = 1603562400; // uint256 public periodFinish = 0; uint256 public rewardRate = 0; uint256 public lastUpdateTime; uint256 public rewardPerTokenStored; mapping(address => uint256) public userRewardPerTokenPaid; mapping(address => uint256) public rewards; event RewardAdded(uint256 reward); event Staked(address indexed user, uint256 amount); event Withdrawn(address indexed user, uint256 amount); event WithdrawnToTreasury(address indexed user, uint256 amount); event RewardPaid(address indexed user, uint256 reward); modifier updateReward(address account) { rewardPerTokenStored = rewardPerToken(); lastUpdateTime = lastTimeRewardApplicable(); if (account != address(0)) { rewards[account] = earned(account); userRewardPerTokenPaid[account] = rewardPerTokenStored; } _; } function lastTimeRewardApplicable() public view returns (uint256) { return Math.min(block.timestamp, periodFinish); } function rewardPerToken() public view returns (uint256) { if (totalSupply() == 0) { return rewardPerTokenStored; } return rewardPerTokenStored.add( lastTimeRewardApplicable() .sub(lastUpdateTime) .mul(rewardRate) .mul(1e18) .div(totalSupply()) ); } function earned(address account) public view returns (uint256) { return balanceOf(account) .mul(rewardPerToken().sub(userRewardPerTokenPaid[account])) .div(1e18) .add(rewards[account]); } // stake visibility is public as overriding LPTokenWrapper's stake() function function stake(uint256 amount) public updateReward(msg.sender) checkNextEpoch checkStart { require(amount > 0, "Cannot stake 0"); super.stake(amount); emit Staked(msg.sender, amount); } function withdraw(uint256 amount) checkNextEpoch public updateReward(msg.sender) checkStart { require(amount > 0, "Cannot withdraw 0"); uint256 _fee = amount.div(1000).mul(100); uint256 _amount = amount.sub(_fee); super.withdraw(_amount); super.withdrawTreasury(_fee); emit Withdrawn(msg.sender, _amount); emit WithdrawnToTreasury(msg.sender,_fee); } function totalRewardsClaimed() public view returns (uint256) { return totalAccumulatedReward; } function exit() external { withdraw(balanceOf(msg.sender)); getReward(); } function getReward() public updateReward(msg.sender) checkStart { uint256 reward = earned(msg.sender); if (reward > 0) { rewards[msg.sender] = 0; xfi.safeTransfer(msg.sender, reward); totalAccumulatedReward = totalAccumulatedReward.add(reward); emit RewardPaid(msg.sender, reward); } } modifier checkNextEpoch() { if (block.timestamp >= periodFinish) { phase++; if(phase == 2) { DURATION = 4 weeks; currentEpochReward = 909080000000000000000; rewardRate = currentEpochReward.div(DURATION); periodFinish = block.timestamp.add(DURATION); emit RewardAdded(currentEpochReward); } else if (phase == 3){ DURATION = 6 weeks; currentEpochReward = 909120000000000000000; rewardRate = currentEpochReward.div(DURATION); periodFinish = block.timestamp.add(DURATION); emit RewardAdded(currentEpochReward); } else if (phase == 4){ DURATION = 8 weeks; currentEpochReward = 909120000000000000000; rewardRate = currentEpochReward.div(DURATION); periodFinish = block.timestamp.add(DURATION); emit RewardAdded(currentEpochReward); } else if (phase > 4){ uint256 balance = xfi.balanceOf(address(this)); require(balance > 0,"No more rewards in the contract"); xfi.safeTransfer(owner(), balance); } } _; } function afterItEnds() public onlyRewardDistribution { require(block.timestamp > periodFinish); uint256 balance = xfi.balanceOf(address(this)); require(balance > 0,"No more rewards in the contract"); xfi.safeTransfer(owner(), balance); } modifier checkStart() { require(block.timestamp > starttime, "not start"); _; } function notifyRewardAmount() external onlyRewardDistribution updateReward(address(0)) { /* if (totalAccumulatedReward.add(currentEpochReward) > TOTAL_REWARD) { currentEpochReward = TOTAL_REWARD.sub(totalAccumulatedReward); // limit total reward }*/ rewardRate = currentEpochReward.div(DURATION); //totalAccumulatedReward = totalAccumulatedReward.add(currentEpochReward); phase++; lastUpdateTime = block.timestamp; periodFinish = starttime.add(DURATION); emit RewardAdded(currentEpochReward); } }
* @dev Contract module which provides a basic access control mechanism, where there is an account (an owner) that can be granted exclusive access to specific functions. This module is used through inheritance. It will make available the modifier `onlyOwner`, which can be 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 { _owner = _msgSender(); emit OwnershipTransferred(address(0), _owner); } function owner() public view returns (address) { return _owner; } modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } function isOwner() public view returns (bool) { return _msgSender() == _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; } }
97,522
[ 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, 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, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 565, 1758, 3238, 389, 8443, 31, 203, 203, 565, 871, 14223, 9646, 5310, 1429, 4193, 12, 203, 3639, 1758, 8808, 2416, 5541, 16, 203, 3639, 1758, 8808, 394, 5541, 203, 565, 11272, 203, 203, 203, 565, 3885, 1435, 2713, 288, 203, 3639, 389, 8443, 273, 389, 3576, 12021, 5621, 203, 3639, 3626, 14223, 9646, 5310, 1429, 4193, 12, 2867, 12, 20, 3631, 389, 8443, 1769, 203, 565, 289, 203, 203, 565, 445, 3410, 1435, 1071, 1476, 1135, 261, 2867, 13, 288, 203, 3639, 327, 389, 8443, 31, 203, 565, 289, 203, 203, 565, 9606, 1338, 5541, 1435, 288, 203, 3639, 2583, 12, 291, 5541, 9334, 315, 5460, 429, 30, 4894, 353, 486, 326, 3410, 8863, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 565, 445, 353, 5541, 1435, 1071, 1476, 1135, 261, 6430, 13, 288, 203, 3639, 327, 389, 3576, 12021, 1435, 422, 389, 8443, 31, 203, 565, 289, 203, 203, 565, 445, 1654, 8386, 5460, 12565, 1435, 1071, 1338, 5541, 288, 203, 3639, 3626, 14223, 9646, 5310, 1429, 4193, 24899, 8443, 16, 1758, 12, 20, 10019, 203, 3639, 389, 8443, 273, 1758, 12, 20, 1769, 203, 565, 289, 203, 203, 565, 445, 7412, 5460, 12565, 12, 2867, 394, 5541, 13, 1071, 1338, 5541, 288, 203, 3639, 389, 13866, 5460, 12565, 12, 2704, 5541, 1769, 203, 565, 289, 203, 203, 565, 445, 389, 13866, 5460, 12565, 12, 2867, 394, 5541, 13, 2713, 288, 203, 3639, 2583, 12, 203, 5411, 394, 5541, 480, 1758, 12, 20, 3631, 2 ]
pragma solidity ^0.5.0; import "./libraries/SafeMath.sol"; import "./libraries/Utilities.sol"; import "./DisputesAndVoting.sol"; /** * @title Tellor Oracle System * @dev Oracle contract where miners can submit the proof of work along with the value. */ contract Tellor is DisputesAndVoting{ using SafeMath for uint256; /*Events*/ event NewValue(uint _apiId, uint _time, uint _value);//Emits upon a successful Mine, indicates the blocktime at point of the mine and the value mined event DataRequested(address sender, string _sapi,uint _apiId, uint _value);//Emits upon someone adding value to a pool; msg.sender, amount added, and timestamp incentivized to be mined event NonceSubmitted(address _miner, string _nonce, uint _apiId, uint _value);//Emits upon each mine (5 total) and shows the miner, nonce, and value submitted event NewAPIonQinfo(uint _apiId, string _sapi, bytes32 _apiOnQ, uint _apiOnQPayout); //emits when a the payout of another request is higher after adding to the payoutPool or submitting a request event NewChallenge(bytes32 _currentChallenge,uint _miningApiId,uint _difficulty_level,string _api); //emits when a new challenge is created (either on mined block or when a new request is pushed forward on waiting system) /*Functions*/ /* *This function gives 5 miners the inital staked tokens in the system. * It would run with the constructor, but throws on too much gas */ function initStake() public{ require(requests == 0); address payable[5] memory _initalMiners = [address(0xE037EC8EC9ec423826750853899394dE7F024fee), address(0xcdd8FA31AF8475574B8909F135d510579a8087d3), address(0xb9dD5AfD86547Df817DA2d0Fb89334A6F8eDd891), address(0x230570cD052f40E14C14a81038c6f3aa685d712B), address(0x3233afA02644CCd048587F8ba6e99b3C00A34DcC)]; for(uint i=0;i<5;i++){ updateValueAtNow(balances[_initalMiners[i]],1000e18); staker[_initalMiners[i]] = StakeInfo({ current_state: 1, startDate: now - (now % 86400) }); emit NewStake(_initalMiners[i]); } stakers += 5; total_supply += 5000e18; for(uint i = 49;i > 0;i--) { payoutPool[i] = 0; } } /** * @dev Proof of work is called by the miner when they submit the solution (proof of work and value) * @param nonce uint submitted by miner * @param _apiId the apiId being mined * @param value of api query * @return count of values sumbitted so far and the time of the last successful mine */ function proofOfWork(string calldata nonce, uint _apiId, uint value) external{ require(isStaked(msg.sender)); require(_apiId == miningApiId); bytes32 n = sha256(abi.encodePacked(ripemd160(abi.encodePacked(keccak256(abi.encodePacked(currentChallenge,msg.sender,nonce)))))); require(uint(n) % difficulty_level == 0); require(miners[currentChallenge][msg.sender] == false); first_five[count].value = value; first_five[count].miner = msg.sender; count++; miners[currentChallenge][msg.sender] = true; emit NonceSubmitted(msg.sender,nonce,_apiId,value); if(count == 5) { API storage _api = apiDetails[_apiId]; uint[3] memory nums; //reusable number array -- _amount,_paid,payoutMultiplier if(int(difficulty_level) + (int(timeTarget) - int(now - timeOfLastProof))/60 > 0){ difficulty_level = uint(int(difficulty_level) + (int(timeTarget) - int(now - timeOfLastProof))/60); } else{ difficulty_level = 1; } timeOfLastProof = now - (now % timeTarget); if(_api.payout >= payoutTotal) { nums[2] = (_api.payout + payoutTotal) / payoutTotal; //solidity should always round down _api.payout = _api.payout % payoutTotal; } else{ nums[2] = 1; } Details[5] memory a = first_five; uint i; for (i = 1;i <5;i++){ uint temp = a[i].value; address temp2 = a[i].miner; uint j = i; while(j > 0 && temp < a[j-1].value){ a[j].value = a[j-1].value; a[j].miner = a[j-1].miner; j--; } if(j<i){ a[j].value = temp; a[j].miner= temp2; } } for (i = 0;i <5;i++){ nums[1] = payoutStructure[i]*nums[2] + _api.payout/5; doTransfer(address(this),a[i].miner,nums[1]); nums[0] = nums[0] + nums[1]; } _api.payout = 0; total_supply += nums[0]; doTransfer(address(this),owner(),(payoutTotal * 10 / 100));//The ten there is the devshare _api.values[timeOfLastProof] = a[2].value; _api.minersbyvalue[timeOfLastProof] = [a[0].miner,a[1].miner,a[2].miner,a[3].miner,a[4].miner]; _api.minedBlockNum[timeOfLastProof] = block.number; miningApiId = apiId[apiOnQ]; timeToApiId[timeOfLastProof] = _apiId; timestamps.push(timeOfLastProof); count = 0; payoutPool[apiDetails[apiIdOnQ].index] = 0; payoutPoolIndexToApiId[apiDetails[apiIdOnQ].index] = 0; apiDetails[apiIdOnQ].index = 0; if(miningApiId > 0){ (nums[0],nums[1]) = Utilities.getMax(payoutPool); apiIdOnQ = payoutPoolIndexToApiId[nums[1]]; apiOnQ = apiDetails[apiIdOnQ].apiHash; apiOnQPayout = nums[0]; currentChallenge = keccak256(abi.encodePacked(nonce, currentChallenge, blockhash(block.number - 1))); // Save hash for next proof emit NewChallenge(currentChallenge,miningApiId,difficulty_level,apiDetails[miningApiId].apiString); emit NewAPIonQinfo(apiIdOnQ,apiDetails[apiIdOnQ].apiString,apiOnQ,apiOnQPayout); } emit NewValue(_apiId,timeOfLastProof,a[2].value); } } /** * @dev Request to retreive value from oracle based on timestamp * @param c_sapi being requested be mined * @param _tip amount the requester is willing to pay to be get on queue. Miners * mine the apiOnQ, or the api with the highest payout pool * @return _apiId for the request */ function requestData(string calldata c_sapi,uint c_apiId, uint _tip) external { uint _apiId = c_apiId; if(_apiId == 0){ string memory _sapi = c_sapi; require(bytes(_sapi).length > 0); bytes32 _apiHash = sha256(abi.encodePacked(_sapi)); if(apiId[_apiHash] == 0){ requests++; _apiId=requests; apiDetails[_apiId] = API({ apiString : _sapi, apiHash: _apiHash, payout: 0, index: 0 }); apiId[_apiHash] = _apiId; } else{ _apiId = apiId[_apiHash]; } } if(_tip > 0){ doTransfer(msg.sender,address(this),_tip); apiDetails[_apiId].payout = apiDetails[_apiId].payout.add(_tip); } updateAPIonQ(_apiId); emit DataRequested(msg.sender,apiDetails[_apiId].apiString,_apiId,_tip); } /** * @dev Gets the 5 miners who mined the value for the specified apiId/_timestamp * @param _apiId to look up * @param _timestamp is the timestampt to look up miners for */ function getMinersByValue(uint _apiId, uint _timestamp) external view returns(address[5] memory){ return apiDetails[_apiId].minersbyvalue[_timestamp]; } /** * @dev This function tells you if a given challenge has been completed by a given miner * @param _challenge the challenge to search for * @param _miner address that you want to know if they solved the challenge * @return true if the _miner address provided solved the */ function didMine(bytes32 _challenge,address _miner) external view returns(bool){ return miners[_challenge][_miner]; } /** * @dev Checks if a value exists for the timestamp provided * @param _apiId to look up/check * @param _timestamp to look up/check * @return true if the value exists/is greater than zero */ function isData(uint _apiId, uint _timestamp) external view returns(bool){ return (apiDetails[_apiId].values[_timestamp] > 0); } /** * @dev Getter function for currentChallenge difficulty_level * @return current challenge, MiningApiID, level of difficulty_level */ function getVariables() external view returns(bytes32, uint, uint,string memory){ return (currentChallenge,miningApiId,difficulty_level,apiDetails[miningApiId].apiString); } /** * @dev Getter function for api on queue * @return apionQ hash, id, payout, and api string */ function getVariablesOnQ() external view returns(uint, uint,string memory){ return (apiIdOnQ,apiOnQPayout,apiDetails[apiIdOnQ].apiString); } /** * @dev Gets the a value for the latest timestamp available * @return value for timestamp of last proof of work submited */ function getLastQuery() external view returns(uint,bool){ return (retrieveData(timeToApiId[timeOfLastProof], timeOfLastProof),true); } /** * @dev Getter function for apiId based on timestamp. Only one value is mined per * timestamp and each timestamp can correspond to a different API. * @param _timestamp to check APIId * @return apiId */ function getApiForTime(uint _timestamp) external view returns(uint){ return timeToApiId[_timestamp]; } /** * @dev Getter function for hash of the api based on apiID * @param _apiId the apiId to look up the api string * @return api hash - bytes32 */ function getApiHash(uint _apiId) external view returns(bytes32){ return apiDetails[_apiId].apiHash; } /** * @dev Getter function for apiId based on api hash * @param _api string to check if it already has an apiId * @return uint apiId */ function getApiId(bytes32 _api) external view returns(uint){ return apiId[_api]; } /** * @dev Getter function for the payoutPool total for the specified _apiId * @param _apiId to look up the total payoutPool value * @return the value of the total payoutPool */ function getValuePoolAt(uint _apiId) external view returns(uint){ return apiDetails[_apiId].payout; } /** * @dev Getter function for the apiId for the specified payoutPool index * @param _payoutPoolIndexToApiId to look up the apiId * @return apiId */ function getpayoutPoolIndexToApiId(uint _payoutPoolIndexToApiId) external view returns(uint){ return payoutPoolIndexToApiId[_payoutPoolIndexToApiId]; } /** * @dev Retreive value from oracle based on timestamp * @param _apiId being requested * @param _timestamp to retreive data/value from * @return value for timestamp submitted */ function retrieveData(uint _apiId, uint _timestamp) public view returns (uint) { return apiDetails[_apiId].values[_timestamp]; } /** @dev This function updates APIonQ and the payoutPool when requestData or addToValuePool are ran @param _apiId being requested */ function updateAPIonQ (uint _apiId) internal { API storage _api = apiDetails[_apiId]; uint _payout = _api.payout; if(miningApiId == 0){ miningApiId = _apiId; currentChallenge = keccak256(abi.encodePacked(_payout, currentChallenge, blockhash(block.number - 1))); // Save hash for next proof emit NewChallenge(currentChallenge,miningApiId,difficulty_level,apiDetails[miningApiId].apiString); return; } if (_payout > apiOnQPayout || apiIdOnQ == 0) { apiIdOnQ = _apiId; apiOnQ = _api.apiHash; apiOnQPayout = _payout; emit NewAPIonQinfo(_apiId,_api.apiString,apiOnQ,apiOnQPayout); } if(_api.index == 0){ uint _min; uint _index; (_min,_index) = Utilities.getMin(payoutPool); if(_payout > _min || _min == 0){ payoutPool[_index] = _payout; payoutPoolIndexToApiId[_index] = _apiId; _api.index = _index; } } else{ payoutPool[_api.index] = _payout; } } }
solidity should always round down
nums[2] = (_api.payout + payoutTotal) / payoutTotal;
12,743,385
[ 1, 30205, 560, 1410, 3712, 3643, 2588, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 7734, 21060, 63, 22, 65, 273, 261, 67, 2425, 18, 84, 2012, 397, 293, 2012, 5269, 13, 342, 293, 2012, 5269, 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 ]
./full_match/1/0xCbAb999b25850c6530bcA365e5005702CB6Bf006/sources/Treasury/FarmBossV1.sol
we are calling a payable function, or the data is otherwise invalid (need 4 bytes for any fn call)
if (_data.length < 4){
3,127,628
[ 1, 1814, 854, 4440, 279, 8843, 429, 445, 16, 578, 326, 501, 353, 3541, 2057, 261, 14891, 1059, 1731, 364, 1281, 2295, 745, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 202, 202, 430, 261, 67, 892, 18, 2469, 411, 1059, 15329, 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 2021-05-01 */ // contracts/Sweeties.sol // 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.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); } } } } /** * @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)))); } } /** * @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 Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } /** * @dev 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); } } /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } /** * @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; } } /** * @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 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; } } /** * @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; } /** * @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); } /** * @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); } /** * @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); } /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using SafeMath for uint256; using Address for address; using EnumerableSet for EnumerableSet.UintSet; using EnumerableMap for EnumerableMap.UintToAddressMap; using Strings for uint256; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Mapping from holder address to their (enumerable) set of owned tokens mapping (address => EnumerableSet.UintSet) private _holderTokens; // Enumerable mapping from token ids to their owners EnumerableMap.UintToAddressMap private _tokenOwners; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; // Token name string private _name; // Token symbol string private _symbol; // Optional mapping for token URIs mapping (uint256 => string) private _tokenURIs; // Base URI string private _baseURI; /* * bytes4(keccak256('balanceOf(address)')) == 0x70a08231 * bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e * bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3 * bytes4(keccak256('getApproved(uint256)')) == 0x081812fc * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 * bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde * * => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^ * 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd */ bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; /* * bytes4(keccak256('name()')) == 0x06fdde03 * bytes4(keccak256('symbol()')) == 0x95d89b41 * bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd * * => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f */ bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; /* * bytes4(keccak256('totalSupply()')) == 0x18160ddd * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59 * bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7 * * => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63 */ bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721); _registerInterface(_INTERFACE_ID_ERC721_METADATA); _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _holderTokens[owner].length(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token"); } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; string memory base = baseURI(); // If there is no base URI, return the token URI. if (bytes(base).length == 0) { return _tokenURI; } // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(base, _tokenURI)); } // If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI. return string(abi.encodePacked(base, tokenId.toString())); } /** * @dev Returns the base URI set via {_setBaseURI}. This will be * automatically added as a prefix in {tokenURI} to each token's URI, or * to the token ID if no specific URI is set for that token ID. */ function baseURI() public view virtual returns (string memory) { return _baseURI; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { return _holderTokens[owner].at(index); } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { // _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds return _tokenOwners.length(); } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { (uint256 tokenId, ) = _tokenOwners.at(index); return tokenId; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require(_msgSender() == owner || ERC721.isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom(address from, address to, uint256 tokenId) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _tokenOwners.contains(tokenId); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || ERC721.isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: d* * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual { _mint(to, tokenId); require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); // internal owner _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); // Clear metadata (if any) if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } _holderTokens[owner].remove(tokenId); _tokenOwners.remove(tokenId); emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer(address from, address to, uint256 tokenId) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); // internal owner require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _holderTokens[from].remove(tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(from, to, tokenId); } /** * @dev Sets `_tokenURI` as the tokenURI of `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } /** * @dev Internal function to set the base URI for all token IDs. It is * automatically added as a prefix to the value returned in {tokenURI}, * or to the token ID if {tokenURI} is empty. */ function _setBaseURI(string memory baseURI_) internal virtual { _baseURI = baseURI_; } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) private returns (bool) { if (!to.isContract()) { return true; } bytes memory returndata = to.functionCall(abi.encodeWithSelector( IERC721Receiver(to).onERC721Received.selector, _msgSender(), from, tokenId, _data ), "ERC721: transfer to non ERC721Receiver implementer"); bytes4 retval = abi.decode(returndata, (bytes4)); return (retval == _ERC721_RECEIVED); } /** * @dev Approve `to` to operate on `tokenId` * * Emits an {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); // internal owner } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { } } contract Sweeties is ERC721, Ownable { using SafeMath for uint256; uint public constant MAX_SWEETIES = 16384; bool public HAS_SALE_STARTED = true; string public METADATA_PROVENANCE_HASH = ""; // Mapping from token index to their number of child tokens mapping (uint256 => uint256) private _childTokenCount; constructor(string memory baseURI) ERC721("Sweeties","SWEET") { setBaseURI(baseURI); } function childCountOf(uint256 tokenId) external view returns (uint256) { require(tokenId < totalSupply(), "ERC721: owner query for nonexistent token"); return _childTokenCount[tokenId]; } function tokensOfOwner(address _owner) external view returns(uint256[] memory ) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { // Return an empty array return new uint256[](0); } else { uint256[] memory result = new uint256[](tokenCount); uint256 index; for (index = 0; index < tokenCount; index++) { result[index] = tokenOfOwnerByIndex(_owner, index); } return result; } } function calculatePrice(uint256 parentIndex) public view returns (uint256) { require(HAS_SALE_STARTED == true, "Sale hasn't started"); require(totalSupply() < MAX_SWEETIES, "Sale has already ended"); // There will be discount for sweeties with parent uint priceMultiplier = 10; if(parentIndex != 0) priceMultiplier = 9; uint currentSupply = totalSupply(); if (currentSupply >= 16360) { return 999000000000000000 * priceMultiplier; // 16360-16383: 9.99 ETH (or 8.991 ETH) } else if (currentSupply >= 15500) { return 199000000000000000 * priceMultiplier; // 15500-16359: 1.99 ETH (or 1.791 ETH) } else if (currentSupply >= 11500) { return 99000000000000000 * priceMultiplier; // 11500-15499: 0.99 ETH (or 0.891 ETH) } else if (currentSupply >= 7500) { return 59000000000000000 * priceMultiplier; // 7500-11499: 0.59 ETH (or 0.531 ETH) } else if (currentSupply >= 3500) { return 19000000000000000 * priceMultiplier; // 3500-7499: 0.19 ETH (or 0.171 ETH) } else if (currentSupply >= 1500) { return 9000000000000000 * priceMultiplier; // 1500-3499: 0.09 ETH (or 0.081 ETH) } else if (currentSupply >= 500) { return 5000000000000000 * priceMultiplier; // 500-1499: 0.05 ETH (or 0.045 ETH) } else if (currentSupply >= 100) { return 2000000000000000 * priceMultiplier; // 100-499: 0.02 ETH (or 0.018 ETH) } else { return 0; // 0-99: Free for Early Adopters } } function calculatePayback(uint parentIndex) public view returns (uint256) { uint parentChildCount = _childTokenCount[parentIndex]; uint referralBonusMultiplier = 10; if(parentChildCount > 5) referralBonusMultiplier = 15; else if(parentChildCount > 30) referralBonusMultiplier = 20; else if(parentChildCount > 100) referralBonusMultiplier = 25; uint parentOwnerBalance = balanceOf(ownerOf(parentIndex)); uint mileageBonusMultiplier = 0; if(parentOwnerBalance > 10) mileageBonusMultiplier = 5; else if(parentOwnerBalance > 20) mileageBonusMultiplier = 10; else if(parentChildCount > 30) mileageBonusMultiplier = 15; return referralBonusMultiplier + mileageBonusMultiplier; } function adoptSweeties(uint256 numSweetie, uint256 parentIndex) public payable { require(totalSupply() < MAX_SWEETIES, "Sale has already ended"); require(numSweetie > 0 && numSweetie <= 20, "You can adopt minimum 1, maximum 20 Sweetie"); require(totalSupply().add(numSweetie) <= MAX_SWEETIES, "Exceeds MAX_SWEETIES"); require(totalSupply() >= 100 || balanceOf(msg.sender).add(numSweetie) <= 5, "Exceeds the limit of sweeties during the early access"); require(parentIndex == 0 || parentIndex < totalSupply(), "Parent does not exist"); require(msg.value >= calculatePrice(parentIndex).mul(numSweetie), "Ether value sent is below the price"); uint parentChildCount = _childTokenCount[parentIndex]; for (uint i = 0; i < numSweetie; i++) { uint mintIndex = totalSupply(); _safeMint(msg.sender, mintIndex); if(parentIndex != 0) parentChildCount ++; } _childTokenCount[parentIndex] = parentChildCount; // Update child token count of the mentor (parent) sweetie // Send referral bonus to the owner of the mentor (parent) sweetie if(parentIndex != 0 && ownerOf(parentIndex) != msg.sender) { uint referralBonusMultiplier = 10; if(parentChildCount > 5) referralBonusMultiplier = 15; else if(parentChildCount > 30) referralBonusMultiplier = 20; else if(parentChildCount > 100) referralBonusMultiplier = 25; uint parentOwnerBalance = balanceOf(ownerOf(parentIndex)); uint mileageBonusMultiplier = 0; if(parentOwnerBalance > 10) mileageBonusMultiplier = 5; else if(parentOwnerBalance > 20) mileageBonusMultiplier = 10; else if(parentChildCount > 30) mileageBonusMultiplier = 15; payable(ownerOf(parentIndex)).transfer(msg.value * (referralBonusMultiplier + mileageBonusMultiplier) / 100); } } // onlyOwner functions function setProvenanceHash(string memory _hash) public onlyOwner { METADATA_PROVENANCE_HASH = _hash; } function setBaseURI(string memory baseURI) public onlyOwner { _setBaseURI(baseURI); } function startSale() public onlyOwner { HAS_SALE_STARTED = true; } function pauseSale() public onlyOwner { HAS_SALE_STARTED = false; } function withdrawAll() public payable onlyOwner { payable(msg.sender).transfer(address(this).balance); } }
There will be discount for sweeties with parent
function calculatePrice(uint256 parentIndex) public view returns (uint256) { require(HAS_SALE_STARTED == true, "Sale hasn't started"); require(totalSupply() < MAX_SWEETIES, "Sale has already ended"); uint priceMultiplier = 10; if(parentIndex != 0) priceMultiplier = 9; uint currentSupply = totalSupply(); if (currentSupply >= 16360) { } }
6,766,446
[ 1, 9828, 903, 506, 12137, 364, 1352, 73, 278, 606, 598, 982, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 4604, 5147, 12, 11890, 5034, 982, 1016, 13, 1071, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 2583, 12, 27765, 67, 5233, 900, 67, 20943, 6404, 422, 638, 16, 315, 30746, 13342, 1404, 5746, 8863, 203, 3639, 2583, 12, 4963, 3088, 1283, 1435, 411, 4552, 67, 55, 6950, 1584, 8805, 16, 315, 30746, 711, 1818, 16926, 8863, 203, 540, 203, 3639, 2254, 6205, 23365, 273, 1728, 31, 203, 3639, 309, 12, 2938, 1016, 480, 374, 13, 203, 5411, 6205, 23365, 273, 2468, 31, 203, 203, 3639, 2254, 783, 3088, 1283, 273, 2078, 3088, 1283, 5621, 203, 3639, 309, 261, 2972, 3088, 1283, 1545, 2872, 29751, 13, 288, 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 ]
./partial_match/1/0xF8243ECF8f734452B184A1dF3AD3cD92fC93B58a/sources/project_/contracts/_external/openzeppelin/ERC20Upgradeable.sol
* @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./
function __ERC20_init(string memory name_, string memory symbol_) internal initializer { __Context_init_unchained(); __ERC20_init_unchained(name_, symbol_); }
2,879,146
[ 1, 2785, 326, 924, 364, 288, 529, 97, 471, 288, 7175, 5496, 1021, 805, 460, 434, 288, 31734, 97, 353, 6549, 18, 2974, 2027, 279, 3775, 460, 364, 288, 31734, 97, 1846, 1410, 30402, 518, 18, 4826, 2795, 434, 4259, 924, 854, 11732, 30, 2898, 848, 1338, 506, 444, 3647, 4982, 16171, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 1001, 654, 39, 3462, 67, 2738, 12, 1080, 3778, 508, 67, 16, 533, 3778, 3273, 67, 13, 2713, 12562, 288, 203, 565, 1001, 1042, 67, 2738, 67, 4384, 8707, 5621, 203, 565, 1001, 654, 39, 3462, 67, 2738, 67, 4384, 8707, 12, 529, 67, 16, 3273, 67, 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 ]
./full_match/122/0xCbc6Ce8C3bc4E5D7EB0fe7440B7b0f58C2884D3B/sources/contracts/LiquidStakingPool.sol
* @notice This handles the pool staking to validators @dev Process the normal delegation of funds and redistribution @param _amount the value amount to be staked/
function _validatorStakeRedistribution(uint256 _amount) internal { address currentValidator = _getCurrentValidator(); uint256 validatorDelegatedAmount = IConsensus(consensus()).stakeAmount( currentValidator ); uint256 availableAmount = IConsensus(consensus()).getMaxStake().sub( validatorDelegatedAmount ); if (availableAmount >= _amount) { address payable consensusContract = payable(consensus()); currentValidator ); address payable consensusContract = payable(consensus()); if (availableAmount > 0) { currentValidator ); } uint256 remaining = _amount.sub(availableAmount); address[] memory validatorList = getValidators(); uint256 currentDelegated = 0; uint256 currentAvailable = 0; for (uint256 i = 0; i < validatorList.length; i++) { currentDelegated = IConsensus(consensus()).stakeAmount( validatorList[i] ); currentAvailable = IConsensus(consensus()).getMaxStake().sub( currentDelegated ); if (currentAvailable >= remaining) { validatorList[i] ); _setValidatorIndex(i); remaining = 0; break; IConsensus(consensusContract).delegate{ value: currentAvailable }(validatorList[i]); remaining = remaining.sub(currentAvailable); } } require(remaining == 0, "excess amount"); } }
16,366,569
[ 1, 2503, 7372, 326, 2845, 384, 6159, 358, 11632, 225, 4389, 326, 2212, 23595, 434, 284, 19156, 471, 5813, 4027, 225, 389, 8949, 326, 460, 3844, 358, 506, 384, 9477, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 389, 7357, 510, 911, 14406, 4027, 12, 11890, 5034, 389, 8949, 13, 2713, 288, 203, 3639, 1758, 783, 5126, 273, 389, 588, 3935, 5126, 5621, 203, 3639, 2254, 5034, 4213, 15608, 690, 6275, 273, 467, 9054, 9781, 12, 29220, 1435, 2934, 334, 911, 6275, 12, 203, 5411, 783, 5126, 203, 3639, 11272, 203, 3639, 2254, 5034, 2319, 6275, 273, 467, 9054, 9781, 12, 29220, 1435, 2934, 588, 2747, 510, 911, 7675, 1717, 12, 203, 5411, 4213, 15608, 690, 6275, 203, 3639, 11272, 203, 203, 3639, 309, 261, 5699, 6275, 1545, 389, 8949, 13, 288, 203, 5411, 1758, 8843, 429, 18318, 8924, 273, 8843, 429, 12, 29220, 10663, 203, 7734, 783, 5126, 203, 5411, 11272, 203, 5411, 1758, 8843, 429, 18318, 8924, 273, 8843, 429, 12, 29220, 10663, 203, 5411, 309, 261, 5699, 6275, 405, 374, 13, 288, 203, 10792, 783, 5126, 203, 7734, 11272, 203, 5411, 289, 203, 203, 5411, 2254, 5034, 4463, 273, 389, 8949, 18, 1717, 12, 5699, 6275, 1769, 203, 203, 5411, 1758, 8526, 3778, 4213, 682, 273, 336, 19420, 5621, 203, 5411, 2254, 5034, 783, 15608, 690, 273, 374, 31, 203, 5411, 2254, 5034, 783, 5268, 273, 374, 31, 203, 203, 5411, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 4213, 682, 18, 2469, 31, 277, 27245, 288, 203, 7734, 783, 15608, 690, 273, 467, 9054, 9781, 12, 29220, 1435, 2934, 334, 911, 6275, 12, 203, 10792, 4213, 682, 63, 77, 65, 203, 7734, 11272, 203, 7734, 783, 5268, 273, 467, 9054, 9781, 12, 29220, 1435, 2 ]
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts/math/SafeMath.sol // -License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/utils/Address.sol // -License-Identifier: MIT pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol // -License-Identifier: MIT pragma solidity ^0.6.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File: contracts/utils/ContractGuard.sol pragma solidity ^0.6.12; contract ContractGuard { mapping(uint256 => mapping(address => bool)) private _status; function checkSameOriginReentranted() internal view returns (bool) { return _status[block.number][tx.origin]; } function checkSameSenderReentranted() internal view returns (bool) { return _status[block.number][msg.sender]; } modifier onlyOneBlock() { require( !checkSameOriginReentranted(), 'ContractGuard: one block, one function' ); require( !checkSameSenderReentranted(), 'ContractGuard: one block, one function' ); _; _status[block.number][tx.origin] = true; _status[block.number][msg.sender] = true; } } // File: @openzeppelin/contracts/math/Math.sol // -License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // File: @openzeppelin/contracts/GSN/Context.sol // -License-Identifier: MIT pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts/access/Ownable.sol // -License-Identifier: MIT pragma solidity ^0.6.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. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: contracts/owner/Operator.sol pragma solidity ^0.6.0; contract Operator is Context, Ownable { address private _operator; event OperatorTransferred( address indexed previousOperator, address indexed newOperator ); constructor() internal { _operator = _msgSender(); emit OperatorTransferred(address(0), _operator); } function operator() public view returns (address) { return _operator; } modifier onlyOperator() { require( _operator == msg.sender, 'operator: caller is not the operator' ); _; } function isOperator() public view returns (bool) { return _msgSender() == _operator; } function transferOperator(address newOperator_) public onlyOwner { _transferOperator(newOperator_); } function _transferOperator(address newOperator_) internal { require( newOperator_ != address(0), 'operator: zero address given for new operator' ); emit OperatorTransferred(address(0), newOperator_); _operator = newOperator_; } } // File: contracts/utils/Epoch.sol pragma solidity ^0.6.0; contract Epoch is Operator { using SafeMath for uint256; uint256 private period; uint256 private startTime; uint256 private lastExecutedAt; /* ========== CONSTRUCTOR ========== */ constructor( uint256 _period, uint256 _startTime, uint256 _startEpoch ) public { require(_startTime > block.timestamp, 'Epoch: invalid start time'); period = _period; startTime = _startTime; lastExecutedAt = startTime.add(_startEpoch.mul(period)); } /* ========== Modifier ========== */ modifier checkStartTime { require(now >= startTime, 'Epoch: not started yet'); _; } modifier checkEpoch { require(now > startTime, 'Epoch: not started yet'); require(getCurrentEpoch() >= getNextEpoch(), 'Epoch: not allowed'); _; lastExecutedAt = block.timestamp; } /* ========== VIEW FUNCTIONS ========== */ // epoch function getLastEpoch() public view returns (uint256) { return lastExecutedAt.sub(startTime).div(period); } function getCurrentEpoch() public view returns (uint256) { return Math.max(startTime, block.timestamp).sub(startTime).div(period); } function getNextEpoch() public view returns (uint256) { if (startTime == lastExecutedAt) { return getLastEpoch(); } return getLastEpoch().add(1); } function nextEpochPoint() public view returns (uint256) { return startTime.add(getNextEpoch().mul(period)); } // params function getPeriod() public view returns (uint256) { return period; } function getStartTime() public view returns (uint256) { return startTime; } /* ========== GOVERNANCE ========== */ function setPeriod(uint256 _period) external onlyOperator { period = _period; } } // File: contracts/ProRataRewardCheckpoint.sol pragma solidity ^0.6.0; // This is forked and modified from https://github.com/BarnBridge/BarnBridge-YieldFarming/blob/master/contracts/Staking.sol contract ProRataRewardCheckpoint { using SafeMath for uint256; uint256 private epochDuration; uint256 private epoch1Start; uint128 constant private BASE_MULTIPLIER = uint128(1 * 10 ** 18); address private stakeToken; struct Pool { uint256 size; bool set; } // for each token, we store the total pool size mapping(uint256 => Pool) private poolSize; // a checkpoint of the valid balance of a user for an epoch struct Checkpoint { uint128 epochId; uint128 multiplier; uint256 startBalance; uint256 newDeposits; } // balanceCheckpoints[user][token][] mapping(address => Checkpoint[]) private balanceCheckpoints; uint128 private lastWithdrawEpochId; constructor (uint256 _epochDuration, uint256 _epoch1Start, address _stakeToken) public { epoch1Start = _epoch1Start; epochDuration = _epochDuration; stakeToken = _stakeToken; } // this is the fork from deposit function depositCheckpoint(address user, uint256 amount, uint256 previousAmount, uint128 currentEpoch) internal { IERC20 token = IERC20(stakeToken); // epoch logic uint128 currentMultiplier = currentEpochMultiplier(currentEpoch); if (!epochIsInitialized(currentEpoch)) { manualEpochInit(currentEpoch, currentEpoch); } // update the next epoch pool size Pool storage pNextEpoch = poolSize[currentEpoch + 1]; pNextEpoch.size = token.balanceOf(address(this)); pNextEpoch.set = true; Checkpoint[] storage checkpoints = balanceCheckpoints[user]; uint256 balanceBefore = getEpochUserBalance(user, currentEpoch); // if there's no checkpoint yet, it means the user didn't have any activity // we want to store checkpoints both for the current epoch and next epoch because // if a user does a withdraw, the current epoch can also be modified and // we don't want to insert another checkpoint in the middle of the array as that could be expensive if (checkpoints.length == 0) { checkpoints.push(Checkpoint(currentEpoch, currentMultiplier, 0, amount)); // next epoch => multiplier is 1, epoch deposits is 0 checkpoints.push(Checkpoint(currentEpoch + 1, BASE_MULTIPLIER, amount, 0)); } else { uint256 last = checkpoints.length - 1; // the last action happened in an older epoch (e.g. a deposit in epoch 3, current epoch is >=5) if (checkpoints[last].epochId < currentEpoch) { uint128 multiplier = computeNewMultiplier( getCheckpointBalance(checkpoints[last]), BASE_MULTIPLIER, amount, currentMultiplier ); checkpoints.push(Checkpoint(currentEpoch, multiplier, getCheckpointBalance(checkpoints[last]), amount)); checkpoints.push(Checkpoint(currentEpoch + 1, BASE_MULTIPLIER, previousAmount.add(amount), 0)); } // the last action happened in the previous epoch else if (checkpoints[last].epochId == currentEpoch) { checkpoints[last].multiplier = computeNewMultiplier( getCheckpointBalance(checkpoints[last]), checkpoints[last].multiplier, amount, currentMultiplier ); checkpoints[last].newDeposits = checkpoints[last].newDeposits.add(amount); checkpoints.push(Checkpoint(currentEpoch + 1, BASE_MULTIPLIER, previousAmount.add(amount), 0)); } // the last action happened in the current epoch else { if (last >= 1 && checkpoints[last - 1].epochId == currentEpoch) { checkpoints[last - 1].multiplier = computeNewMultiplier( getCheckpointBalance(checkpoints[last - 1]), checkpoints[last - 1].multiplier, amount, currentMultiplier ); checkpoints[last - 1].newDeposits = checkpoints[last - 1].newDeposits.add(amount); } checkpoints[last].startBalance = previousAmount.add(amount); } } uint256 balanceAfter = getEpochUserBalance(user, currentEpoch); poolSize[currentEpoch].size = poolSize[currentEpoch].size.add(balanceAfter.sub(balanceBefore)); } // this is the fork from withdraw function withdrawCheckpoint(address user, uint256 amount, uint256 previousAmount, uint128 currentEpoch) internal { IERC20 token = IERC20(stakeToken); lastWithdrawEpochId = currentEpoch; if (!epochIsInitialized(currentEpoch)) { manualEpochInit(currentEpoch, currentEpoch); } // update the pool size of the next epoch to its current balance Pool storage pNextEpoch = poolSize[currentEpoch + 1]; pNextEpoch.size = token.balanceOf(address(this)); pNextEpoch.set = true; Checkpoint[] storage checkpoints = balanceCheckpoints[user]; uint256 last = checkpoints.length - 1; // note: it's impossible to have a withdraw and no checkpoints because the balance would be 0 and revert // there was a deposit in an older epoch (more than 1 behind [eg: previous 0, now 5]) but no other action since then if (checkpoints[last].epochId < currentEpoch) { checkpoints.push(Checkpoint(currentEpoch, BASE_MULTIPLIER, previousAmount.sub(amount), 0)); poolSize[currentEpoch].size = poolSize[currentEpoch].size.sub(amount); } // there was a deposit in the `epochId - 1` epoch => we have a checkpoint for the current epoch else if (checkpoints[last].epochId == currentEpoch) { checkpoints[last].startBalance = previousAmount.sub(amount); checkpoints[last].newDeposits = 0; checkpoints[last].multiplier = BASE_MULTIPLIER; poolSize[currentEpoch].size = poolSize[currentEpoch].size.sub(amount); } // there was a deposit in the current epoch else { Checkpoint storage currentEpochCheckpoint = checkpoints[last - 1]; uint256 balanceBefore = getCheckpointEffectiveBalance(currentEpochCheckpoint); // in case of withdraw, we have 2 branches: // 1. the user withdraws less than he added in the current epoch // 2. the user withdraws more than he added in the current epoch (including 0) if (amount < currentEpochCheckpoint.newDeposits) { uint128 avgDepositMultiplier = uint128( balanceBefore.sub(currentEpochCheckpoint.startBalance).mul(BASE_MULTIPLIER).div(currentEpochCheckpoint.newDeposits) ); currentEpochCheckpoint.newDeposits = currentEpochCheckpoint.newDeposits.sub(amount); currentEpochCheckpoint.multiplier = computeNewMultiplier( currentEpochCheckpoint.startBalance, BASE_MULTIPLIER, currentEpochCheckpoint.newDeposits, avgDepositMultiplier ); } else { currentEpochCheckpoint.startBalance = currentEpochCheckpoint.startBalance.sub( amount.sub(currentEpochCheckpoint.newDeposits) ); currentEpochCheckpoint.newDeposits = 0; currentEpochCheckpoint.multiplier = BASE_MULTIPLIER; } uint256 balanceAfter = getCheckpointEffectiveBalance(currentEpochCheckpoint); poolSize[currentEpoch].size = poolSize[currentEpoch].size.sub(balanceBefore.sub(balanceAfter)); checkpoints[last].startBalance = previousAmount.sub(amount); } } /* * Returns the valid balance of a user that was taken into consideration in the total pool size for the epoch * A deposit will only change the next epoch balance. * A withdraw will decrease the current epoch (and subsequent) balance. */ function getEpochUserBalance(address user, uint128 epochId) public view returns (uint256) { Checkpoint[] storage checkpoints = balanceCheckpoints[user]; // if there are no checkpoints, it means the user never deposited any tokens, so the balance is 0 if (checkpoints.length == 0 || epochId < checkpoints[0].epochId) { return 0; } uint min = 0; uint max = checkpoints.length - 1; // shortcut for blocks newer than the latest checkpoint == current balance if (epochId >= checkpoints[max].epochId) { return getCheckpointEffectiveBalance(checkpoints[max]); } // binary search of the value in the array while (max > min) { uint mid = (max + min + 1) / 2; if (checkpoints[mid].epochId <= epochId) { min = mid; } else { max = mid - 1; } } return getCheckpointEffectiveBalance(checkpoints[min]); } /* * manualEpochInit can be used by anyone to initialize an epoch based on the previous one * This is only applicable if there was no action (deposit/withdraw) in the current epoch. * Any deposit and withdraw will automatically initialize the current and next epoch. */ function manualEpochInit(uint128 epochId, uint128 currentEpoch) internal { require(epochId <= currentEpoch, "can't init a future epoch"); Pool storage p = poolSize[epochId]; if (epochId == 0) { p.size = uint256(0); p.set = true; } else { require(!epochIsInitialized(epochId), "Staking: epoch already initialized"); require(epochIsInitialized(epochId - 1), "Staking: previous epoch not initialized"); p.size = poolSize[epochId - 1].size; p.set = true; } // emit ManualEpochInit(msg.sender, epochId, tokens); } function computeNewMultiplier(uint256 prevBalance, uint128 prevMultiplier, uint256 amount, uint128 currentMultiplier) public pure returns (uint128) { uint256 prevAmount = prevBalance.mul(prevMultiplier).div(BASE_MULTIPLIER); uint256 addAmount = amount.mul(currentMultiplier).div(BASE_MULTIPLIER); uint128 newMultiplier = uint128(prevAmount.add(addAmount).mul(BASE_MULTIPLIER).div(prevBalance.add(amount))); return newMultiplier; } /* * Returns the percentage of time left in the current epoch */ function currentEpochMultiplier(uint128 currentEpoch) public view returns (uint128) { uint256 currentEpochEnd = epoch1Start + currentEpoch * epochDuration; uint256 timeLeft = currentEpochEnd - block.timestamp; uint128 multiplier = uint128(timeLeft * BASE_MULTIPLIER / epochDuration); return multiplier; } /* * Returns the total amount of `tokenAddress` that was locked from beginning to end of epoch identified by `epochId` */ function getEpochPoolSize(uint128 epochId) public view returns (uint256) { // Premises: // 1. it's impossible to have gaps of uninitialized epochs // - any deposit or withdraw initialize the current epoch which requires the previous one to be initialized if (epochIsInitialized(epochId)) { return poolSize[epochId].size; } // epochId not initialized and epoch 0 not initialized => there was never any action on this pool if (!epochIsInitialized(0)) { return 0; } // epoch 0 is initialized => there was an action at some point but none that initialized the epochId // which means the current pool size is equal to the current balance of token held by the staking contract IERC20 token = IERC20(stakeToken); return token.balanceOf(address(this)); } /* * Checks if an epoch is initialized, meaning we have a pool size set for it */ function epochIsInitialized(uint128 epochId) public view returns (bool) { return poolSize[epochId].set; } function getCheckpointBalance(Checkpoint memory c) internal pure returns (uint256) { return c.startBalance.add(c.newDeposits); } function getCheckpointEffectiveBalance(Checkpoint memory c) internal pure returns (uint256) { return getCheckpointBalance(c).mul(c.multiplier).div(BASE_MULTIPLIER); } } // File: contracts/interfaces/IFeeDistributorRecipient.sol pragma solidity ^0.6.0; abstract contract IFeeDistributorRecipient is Ownable { address public feeDistributor; modifier onlyFeeDistributor() { require( _msgSender() == feeDistributor, 'Caller is not fee distributor' ); _; } function setFeeDistributor(address _feeDistributor) external virtual onlyOwner { feeDistributor = _feeDistributor; } } // File: contracts/Boardroomv2.sol pragma solidity ^0.6.0; //pragma experimental ABIEncoderV2; contract ShareWrapper { using SafeMath for uint256; using SafeERC20 for IERC20; IERC20 public share; uint256 private _totalSupply; mapping(address => uint256) private _balances; function totalSupply() public view returns (uint256) { return _totalSupply; } function balanceOf(address account) public view returns (uint256) { return _balances[account]; } function stake(uint256 amount) public virtual { _totalSupply = _totalSupply.add(amount); _balances[msg.sender] = _balances[msg.sender].add(amount); share.safeTransferFrom(msg.sender, address(this), amount); } function withdraw(uint256 amount) public virtual { uint256 directorShare = _balances[msg.sender]; require( directorShare >= amount, 'Boardroom: withdraw request greater than staked amount' ); _totalSupply = _totalSupply.sub(amount); _balances[msg.sender] = directorShare.sub(amount); share.safeTransfer(msg.sender, amount); } } contract Boardroomv2 is ShareWrapper, ContractGuard, Epoch, ProRataRewardCheckpoint, IFeeDistributorRecipient{ using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; /* ========== DATA STRUCTURES ========== */ struct Boardseat { uint256 lastSnapshotIndex; uint256 startEpoch; uint256 lastEpoch; mapping(uint256 => uint256) rewardEarned; } struct BoardSnapshot { uint256 time; uint256 rewardReceived; uint256 rewardPerShare; } /* ========== STATE VARIABLES ========== */ IERC20 private cash; mapping(address => Boardseat) private directors; BoardSnapshot[] private boardHistory; /* ========== CONSTRUCTOR ========== */ constructor(IERC20 _cash, IERC20 _share, uint256 _startTime) public Epoch(6 hours, _startTime, 0) ProRataRewardCheckpoint(6 hours, _startTime, address(_share)) { cash = _cash; share = _share; BoardSnapshot memory genesisSnapshot = BoardSnapshot({ time: block.number, rewardReceived: 0, rewardPerShare: 0 }); boardHistory.push(genesisSnapshot); } /* ========== Modifiers =============== */ modifier directorExists { require( balanceOf(msg.sender) > 0, 'Boardroom: The director does not exist' ); _; } modifier updateReward(address director) { if (director != address(0)) { Boardseat storage seat = directors[director]; uint256 currentEpoch = getCurrentEpoch(); seat.rewardEarned[currentEpoch] = seat.rewardEarned[currentEpoch].add(earnedNew(director)); seat.lastEpoch = currentEpoch; seat.lastSnapshotIndex = latestSnapshotIndex(); } _; } /* ========== VIEW FUNCTIONS ========== */ function calculateClaimableRewardsForEpoch(address wallet, uint256 epoch) view public returns (uint256) { return calculateClaimable(directors[wallet].rewardEarned[epoch], epoch); } function calculateClaimable(uint256 earned, uint256 epoch) view public returns (uint256) { uint256 epoch_delta = getCurrentEpoch() - epoch; uint256 ten = 10; uint256 five = 5; uint256 tax_percentage = (epoch_delta > 4) ? 0 : ten.mul(five.sub(epoch_delta)); uint256 hundred = 100; return earned.mul(hundred.sub(tax_percentage)).div(hundred); } // staking before start time regards as staking at epoch 0. function getCheckpointEpoch() view public returns(uint128) { uint256 currentEpoch = getCurrentEpoch(); return uint128(currentEpoch) + 1; } // =========== Snapshot getters function latestSnapshotIndex() public view returns (uint256) { return boardHistory.length.sub(1); } function getLatestSnapshot() internal view returns (BoardSnapshot memory) { return boardHistory[latestSnapshotIndex()]; } function getLastSnapshotIndexOf(address director) public view returns (uint256) { return directors[director].lastSnapshotIndex; } function getLastSnapshotOf(address director) internal view returns (BoardSnapshot memory) { return boardHistory[getLastSnapshotIndexOf(director)]; } // =========== Director getters function rewardPerShare() public view returns (uint256) { return getLatestSnapshot().rewardPerShare; } function earned(address director) public view returns (uint256) { uint256 totalRewards = 0; for (uint i = directors[director].startEpoch; i <= directors[director].lastEpoch; i++) { totalRewards = totalRewards.add(calculateClaimableRewardsForEpoch(director, i)); } return totalRewards; } /* ========== MUTATIVE FUNCTIONS ========== */ function stake(uint256 amount) public override onlyOneBlock updateReward(msg.sender) { require(amount > 0, 'Boardroom: Cannot stake 0'); uint256 previousBalance = balanceOf(msg.sender); super.stake(amount); depositCheckpoint(msg.sender, amount, previousBalance, getCheckpointEpoch()); emit Staked(msg.sender, amount); } function withdraw(uint256 amount) public override onlyOneBlock directorExists updateReward(msg.sender) { require(amount > 0, 'Boardroom: Cannot withdraw 0'); uint256 previousBalance = balanceOf(msg.sender); super.withdraw(amount); withdrawCheckpoint(msg.sender, amount, previousBalance, getCheckpointEpoch()); emit Withdrawn(msg.sender, amount); } function exit() external { withdraw(balanceOf(msg.sender)); claimReward(earned(msg.sender)); } function claimReward(uint256 amount) public updateReward(msg.sender) { require(amount > 0, 'Amount cannot be zero'); uint256 totalClaimAmount = amount; uint256 totalEarned = earned(msg.sender); require(amount <= totalEarned, 'Amount cannot be larger than total claimable rewards'); cash.safeTransfer(msg.sender, amount); for (uint i = directors[msg.sender].startEpoch; amount > 0; i++) { uint256 claimable = calculateClaimableRewardsForEpoch(msg.sender, i); if (amount > claimable) { directors[msg.sender].rewardEarned[i] = 0; directors[msg.sender].startEpoch = i.add(1); amount = amount.sub(claimable); } else { removeRewardsForEpoch(msg.sender, amount, i); amount = 0; } } // In this case, startEpoch will be calculated again for the next stake if (amount == totalEarned) { directors[msg.sender].startEpoch = 0; } emit RewardPaid(msg.sender, totalClaimAmount); } // Claim rewards for specific epoch function claimRewardsForEpoch(uint256 amount, uint256 epoch) public updateReward(msg.sender) { require(amount > 0, 'Amount cannot be zero'); uint256 claimable = calculateClaimableRewardsForEpoch(msg.sender, epoch); if (claimable > 0) { require( amount <= claimable, 'Amount cannot be larger than the claimable rewards for the epoch' ); cash.safeTransfer(msg.sender, amount); removeRewardsForEpoch(msg.sender, amount, epoch); } } function allocateSeigniorage(uint256 amount) external onlyOneBlock onlyOperator { require(amount > 0, 'Boardroom: Cannot allocate 0'); require( totalSupply() > 0, 'Boardroom: Cannot allocate when totalSupply is 0' ); // Create & add new snapshot BoardSnapshot memory latestSnapshot = getLatestSnapshot(); uint256 prevRPS = latestSnapshot.rewardPerShare; uint256 poolSize = getEpochPoolSize(getCheckpointEpoch()); uint256 nextRPS = prevRPS.add(amount.mul(1e18).div(poolSize)); BoardSnapshot memory newSnapshot = BoardSnapshot({ time: block.number, rewardReceived: amount, rewardPerShare: nextRPS }); boardHistory.push(newSnapshot); cash.safeTransferFrom(msg.sender, address(this), amount); emit RewardAdded(msg.sender, amount); } /* * manualEpochInit can be used by anyone to initialize an epoch based on the previous one * This is only applicable if there was no action (deposit/withdraw) in the current epoch. * Any deposit and withdraw will automatically initialize the current and next epoch. */ function manualCheckpointEpochInit(uint128 checkpointEpochId) public { manualEpochInit(checkpointEpochId, getCheckpointEpoch()); } function allocateTaxes(uint256 amount) external onlyOneBlock onlyFeeDistributor { require(amount > 0, 'Boardroom: Cannot allocate 0'); require( totalSupply() > 0, 'Boardroom: Cannot allocate when totalSupply is 0' ); // Create & add new snapshot BoardSnapshot memory latestSnapshot = getLatestSnapshot(); uint256 prevRPS = latestSnapshot.rewardPerShare; uint256 poolSize = getEpochPoolSize(getCheckpointEpoch()); uint256 nextRPS = prevRPS.add(amount.mul(1e18).div(poolSize)); BoardSnapshot memory newSnapshot = BoardSnapshot({ time: block.number, rewardReceived: amount, rewardPerShare: nextRPS }); boardHistory.push(newSnapshot); cash.safeTransferFrom(msg.sender, address(this), amount); emit RewardAdded(msg.sender, amount); } function earnedNew(address director) private view returns (uint256) { uint256 latestRPS = getLatestSnapshot().rewardPerShare; uint256 storedRPS = getLastSnapshotOf(director).rewardPerShare; uint256 directorEffectiveBalance = getEpochUserBalance(director, getCheckpointEpoch()); return directorEffectiveBalance.mul(latestRPS.sub(storedRPS)).div(1e18); } function removeRewardsForEpoch(address wallet, uint256 amount, uint256 epoch) private onlyOneBlock { uint256 claimable = calculateClaimableRewardsForEpoch(wallet, epoch); if (claimable > 0) { require( amount <= claimable, 'Amount cannot be larger than the claimable rewards for the epoch' ); directors[wallet].rewardEarned[epoch] = claimable.sub(amount).mul(directors[wallet].rewardEarned[epoch]).div(claimable); } } /* ========== EVENTS ========== */ event Staked(address indexed user, uint256 amount); event Withdrawn(address indexed user, uint256 amount); event RewardPaid(address indexed user, uint256 reward); event RewardAdded(address indexed user, uint256 reward); }
staking before start time regards as staking at epoch 0.
function getCheckpointEpoch() view public returns(uint128) { uint256 currentEpoch = getCurrentEpoch(); return uint128(currentEpoch) + 1; }
9,894,578
[ 1, 334, 6159, 1865, 787, 813, 12283, 87, 487, 384, 6159, 622, 7632, 374, 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 ]
[ 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, 336, 14431, 14638, 1435, 1476, 1071, 1135, 12, 11890, 10392, 13, 288, 203, 3639, 2254, 5034, 783, 14638, 273, 5175, 14638, 5621, 203, 3639, 327, 2254, 10392, 12, 2972, 14638, 13, 397, 404, 31, 203, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/extensions/ERC721EnumerableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/extensions/ERC721URIStorageUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/access/AccessControlEnumerableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/interfaces/IERC2981Upgradeable.sol"; /** * @title Hypernet Protocol Enumerable Non Fungible Registry * @author Todd Chapman * @dev Implementation of the Hypernet Protocol Non Fungible Registry with Enumeration * * This implementation is based on OpenZeppelin's ERC-721 library with the enumeration extension * * See the Hypernet Protocol documentation for more information: * https://docs.hypernet.foundation/hypernet-protocol/identity * * See unit tests for example usage: * https://github.com/GoHypernet/hypernet-protocol/blob/dev/packages/contracts/test/upgradeable-registry-enumerable-test.js */ contract NonFungibleRegistryEnumerableUpgradeable is Initializable, ContextUpgradeable, AccessControlEnumerableUpgradeable, ERC721EnumerableUpgradeable, ERC721URIStorageUpgradeable, IERC2981Upgradeable { using SafeERC20Upgradeable for IERC20Upgradeable; // since the registration token could be changed by the registrar // we need to store which token the fee was payed in along with // the amount struct Fee { address token; uint256 amount; } struct RegistryParams { string[] _schema; bool[] _allowStorageUpdate; bool[] _allowLabelChange; bool[] _allowTransfers; address[] _registrationToken; uint256[] _registrationFee; address[] _burnAddress; uint256[] _burnFee; string[] _baseURI; } /// @notice This is a reserved variable intended to be used by dynamic UI's /// @dev This variable is intended to store DFDL specs for how to interpret the data stored in tokenURI string public schema; /// @notice optional mapping of a human-readable string label to a tokenID /// @dev token labels stored in this variable must be unique for each token mapping(string => uint256) public registryMap; /// @notice inverse datastructure to registryMap /// @dev returns the label associated with a given token id mapping(uint256 => string) public reverseRegistryMap; /// @notice A data structure that stores how much registrationToken is locked in a given tokenID /// @dev This data structure is used in conjunction with registerByToken mapping(uint256 => Fee) public identityStakes; /// @notice This boolean indicates if NFI's are allowed to update their tokenURI /// @dev This boolean is utilized by the internal function _storageCanBeUpdated bool public allowStorageUpdate; /// @notice This boolean indicates if NFI's are allowed to update their labels in registryMap /// @dev This boolean is utilized by internal function _labelCanBeChanged bool public allowLabelChange; /// @notice This boolean indicates if NFI's are allowed to be transfered /// @dev This boolean is utilized by the internal function _transfersAllows. The REGISTRAR_ROLE may always initiate transfers. bool public allowTransfers; /// @notice Address indicating what ERC-20 token can be used with registerByToken /// @dev This address variable is used in conjunction with burnFee and burnAddress for the registerByToken function. Setting to the zero address disables the feature. address public registrationToken; /// @notice The amount of registrationToken required to call registerByToken /// @dev Be sure you check the number of decimals associated with the ERC-20 contract at the registrationToken address uint256 public registrationFee; /// @notice This is the address where non-redeemable registration stake is sent after calling registerByToken /// @dev The amount of registrationToken sent to this address is equal to {registrationFee * burnFee / 10000} address public burnAddress; /// @notice The amount in basis points of registrationFee to send to the burnAddress account /// @notice This variable must be less than or equal to 10000 uint256 public burnFee; /** @dev address of primary NFR registry required for participation * if the primaryRegistry is address(0), then this variable is ignored * if the primaryRegistry is an ERC721, then the recipient of an NFI must * have a non-zero balance in that ERC721 contract in order to recieve * an NFI */ address public primaryRegistry; /// @dev merkle root variable that can be used with the external merkle drop module bytes32 public merkleRoot; /// @notice flag used in conjunction with merkleRoot, if true then the merkleRoot can no longer be updated by the REGISTRAR_ROLE /// @dev This variable is updated via the setMerkleRoot function bool public frozen; /** @notice 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. * @dev baseURI is omitted if the user calls tokenURINoBase */ string public baseURI; /// @dev The REGISTRAR_ROLE has rights to mint, transfer, and burn all NFI's. Grant access carefully bytes32 public constant REGISTRAR_ROLE = keccak256("REGISTRAR_ROLE"); /// @dev The REGISTRAR_ROLE_ADMIN curates the address with REGISTRAR_ROLE permissions bytes32 public constant REGISTRAR_ROLE_ADMIN = keccak256("REGISTRAR_ROLE_ADMIN"); /** * @dev Emitted when updateLabel is called successfully */ event LabelUpdated(uint256 tokenId, string label); /** * @dev Emitted when updateRegistration is called successfully */ event StorageUpdated(uint256 tokenId, bytes32 registrationData); /** * @dev Emitted when setMerkleRoot is called successfully */ event MerkleRootUpdated(bytes32 merkleRoot, bool frozen); /// @custom:oz-upgrades-unsafe-allow constructor constructor() initializer {} /// @notice initialize is called once on the creation of an upgradable proxy /// @dev can only be called once due to the initializer modifier /// @param name_ name to be given to the Non Fungible Registry /// @param symbol_ shorthand symbol to be given to the Non Fungible Registry /// @param _primaryRegistry address of ERC721-compatible contract to use as primary user profile (address(0) deactivates this feature) /// @param _registrar address to be given to the REGISTRAR_ROLE /// @param _admin address that will have the DEFAULT_ADMIN_ROLE function initialize( string memory name_, string memory symbol_, address _primaryRegistry, address _registrar, address _admin ) public initializer { __Context_init(); __AccessControlEnumerable_init(); __ERC721Enumerable_init(); __ERC721URIStorage_init(); __ERC721_init(name_, symbol_); _setupRole(DEFAULT_ADMIN_ROLE, _admin); _setupRole(REGISTRAR_ROLE, _registrar); _setRoleAdmin (REGISTRAR_ROLE, REGISTRAR_ROLE_ADMIN); _setupRole(REGISTRAR_ROLE_ADMIN, _registrar); allowStorageUpdate = true; allowLabelChange = false; allowTransfers = true; registrationToken = address(0); registrationFee = 1e18; // assume there are 18 decimal places in the token burnAddress = _admin; burnFee = 500; // basis points, 500 bp = 5% primaryRegistry = _primaryRegistry; frozen = false; } /** @notice setRegistryParameters enable or disable the lazy registration feature * @dev only callable by the REGISTRAR_ROLE, use arrays so we don't have to always pass every * parameter if we don't want to chage it. * @param encodedParameters encoded calldata for registry parameters, see {RegistryParams} */ function setRegistryParameters(bytes calldata encodedParameters) external virtual { require(hasRole(REGISTRAR_ROLE, _msgSender()), "NonFungibleRegistry: must be registrar."); RegistryParams memory params = abi.decode(encodedParameters, (RegistryParams)); if (params._schema.length > 0) { schema = params._schema[0];} if (params._allowStorageUpdate.length > 0) { allowStorageUpdate = params._allowStorageUpdate[0]; } if (params._allowLabelChange.length > 0) { allowLabelChange = params._allowLabelChange[0]; } if (params._allowTransfers.length > 0) { allowTransfers = params._allowTransfers[0]; } if (params._registrationToken.length > 0) { registrationToken = params._registrationToken[0]; } if (params._registrationFee.length > 0) { registrationFee = params._registrationFee[0]; } if (params._burnAddress.length > 0) { burnAddress = params._burnAddress[0]; } if (params._burnFee.length > 0) { require(params._burnFee[0] <= 10000, "NonFungibleRegistry: burnFee must be le 10000."); burnFee = params._burnFee[0]; } if (params._baseURI.length > 0) { baseURI = params._baseURI[0]; } } /// @notice setMerkleRoot enable or disable requirement for pre-registration /// @dev only callable by the DEFAULT_ADMIN_ROLE /// @param _merkleRoot address to set as the primary registry function setMerkleRoot(bytes32 _merkleRoot, bool freeze) external { require(hasRole(REGISTRAR_ROLE, _msgSender()), "NonFungibleRegistry: must be registrar."); require(!frozen, "NonFungibleRegistry: merkleRoot has been frozen."); merkleRoot = _merkleRoot; frozen = freeze; emit MerkleRootUpdated(merkleRoot, frozen); } /// @notice setPrimaryRegistry enable or disable requirement for pre-registration /// @dev only callable by the DEFAULT_ADMIN_ROLE /// @param _primaryRegistry address to set as the primary registry function setPrimaryRegistry(address _primaryRegistry) external { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "NonFungibleRegistry: must be admin."); // allow this feature to be disabled by setting to 0 address if (address(_primaryRegistry) == address(0)) { primaryRegistry = address(0); } else { // if not disabling, make sure the address is an ERC721 token contract require(IERC721Upgradeable(_primaryRegistry).supportsInterface(type(IERC721Upgradeable).interfaceId), "NonFungibleRegistry: Address does not support ERC721 interface."); primaryRegistry = _primaryRegistry; } } function _storageCanBeUpdated() internal view virtual returns (bool) { return (allowStorageUpdate || hasRole(REGISTRAR_ROLE, _msgSender())); } function _labelCanBeChanged() internal view virtual returns (bool) { return (allowLabelChange || hasRole(REGISTRAR_ROLE, _msgSender())); } function _transfersAllowed() internal view virtual returns (bool) { return (allowTransfers || hasRole(REGISTRAR_ROLE, _msgSender())); } /// @notice register mints a new Non-Fungible Identity token /// @dev only callable by the REGISTRAR_ROLE /// @param to address of the recipient of the token /// @param label a unique label to attach to the token, can pass an empty string to skip labeling /// @param registrationData data to store in the tokenURI /// @param tokenId unique uint256 identifier for the newly created token function register(address to, string calldata label, string calldata registrationData, uint256 tokenId) external virtual { require(hasRole(REGISTRAR_ROLE, _msgSender()), "NonFungibleRegistry: must have registrar role to register."); _createLabeledToken(to, label, registrationData, tokenId); } /// @notice registerByToken mints a new Non-Fungible Identity token by staking an ERC20 registration token /// @dev callable by anyone with enough registration token, caller must call `approve` first /// @param to address of the recipient of the token /// @param label a unique label to attach to the token /// @param registrationData data to store in the tokenURI /// @param tokenId unique uint256 identifier for the newly created token function registerByToken(address to, string calldata label, string calldata registrationData, uint256 tokenId) external virtual { require(registrationToken != address(0), "NonFungibleRegistry: registration by token not enabled."); require(!_mappingExists(label), "NonFungibleRegistry: label is already registered."); // user must approve the registry to collect the registration fee from their wallet require(IERC20Upgradeable(registrationToken).transferFrom(_msgSender(), address(this), registrationFee), "NonFungibleRegistry: token transfer failed."); _createLabeledToken(to, label, registrationData, tokenId); uint256 burnAmount = registrationFee * burnFee / 10000; IERC20Upgradeable(registrationToken).transfer(burnAddress, burnAmount); // the fee stays with the token, not the token owner identityStakes[tokenId] = Fee(registrationToken, registrationFee-burnAmount); } function _createLabeledToken(address to, string memory label, string memory registrationData, uint256 tokenId) private { if (bytes(label).length > 0) { require(!_mappingExists(label), "NonFungibleRegistry: label is already registered."); _createToken(to, registrationData, tokenId); // extend the registry mapping for lookup via token label registryMap[label] = tokenId; reverseRegistryMap[tokenId] = label; } else { // if label is empty, save some gas _createToken(to, registrationData, tokenId); } } function _createToken(address to, string memory registrationData, uint256 tokenId) private { require(_preRegistered(to), "NonFungibleRegistry: recipient must have non-zero balance in primary registry."); require(tokenId != 0, "NonFungibleRegistry: tokenId cannot be 0"); _mint(to, tokenId); _setTokenURI(tokenId, registrationData); } /// @notice updateRegistration updates the tokenURI denoted by tokenId /// @dev only callable by the owner, approved caller when allowStorageUpdate is true or REGISTRAR_ROLE /// @param tokenId the tokenId of the target registration /// @param registrationData new data to store in the tokenURI function updateRegistration(uint256 tokenId, string calldata registrationData) external virtual { require(_storageCanBeUpdated(), "NonFungibleRegistry: Storage updating is disabled."); require(_isApprovedOrOwner(_msgSender(), tokenId), "NonFungibleRegistry: caller is not owner nor approved nor registrar."); _setTokenURI(tokenId, registrationData); emit StorageUpdated(tokenId, keccak256(abi.encodePacked(registrationData))); } /// @notice updateLabel updates the label of the token denoted by tokenId /// @dev only callable by the owner, approved caller when allowLabelChange is true or REGISTRAR_ROLE /// @param tokenId the tokenId of the target registration /// @param label new data to associate with the token label function updateLabel(uint256 tokenId, string calldata label) external virtual { require(_labelCanBeChanged(), "NonFungibleRegistry: Label updating is disabled."); require(_isApprovedOrOwner(_msgSender(), tokenId), "NonFungibleRegistry: caller is not owner nor approved nor registrar."); require(!_mappingExists(label), "NonFungibleRegistry: label is already registered."); registryMap[label] = tokenId; reverseRegistryMap[tokenId] = label; emit LabelUpdated(tokenId, label); } /// @notice transferFrom transfers ownership of a registration token /// @dev only callable by the owner, approved caller when allowTransfers is true or REGISTRAR_ROLE /// @param from the tokenId of the target registration /// @param to new data to store in the tokenURI /// @param tokenId unique id to refence the target token function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "NonFungibleRegistry: caller is not owner nor approved nor registrar."); require(_preRegistered(to), "NonFungibleRegistry: recipient must have non-zero balance in primary registry."); _transfer(from, to, tokenId); } /// @notice safeTransferFrom transfers ownership of a registration token, recipient must implement callback /// @dev only callable by the owner, approved caller when allowTransfers is true or REGISTRAR_ROLE /// @param from the tokenId of the target registration /// @param to new data to store in the tokenURI /// @param tokenId unique id to refence the target token function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "NonFungibleRegistry: caller is not owner nor approved nor registrar."); require(_preRegistered(to), "NonFungibleRegistry: recipient must have non-zero balance in primary registry."); _safeTransfer(from, to, tokenId, _data); } /// @notice burn removes a token from the registry enumeration and refunds registration fee to burner /// @dev only callable by the owner, approved caller when allowTransfers is true or REGISTRAR_ROLE /// @param tokenId unique id to refence the target token function burn(uint256 tokenId) public virtual { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "NonFungibleRegistry: caller is not owner nor approved nor registrar."); _burn(tokenId); // when burning, check if there is a registration fee tied to the token identity if (identityStakes[tokenId].amount != 0) { // send the registration fee to the token burner // don't set a registration token you do not control/trust, otherwise, this could be used for re-entrancy attack require(IERC20Upgradeable(identityStakes[tokenId].token).transfer(_msgSender(), identityStakes[tokenId].amount), "NonFungibleRegistry: token tansfer failed."); delete identityStakes[tokenId]; } } function _burn( uint256 tokenId ) internal virtual override(ERC721Upgradeable, ERC721URIStorageUpgradeable) { super._burn(tokenId); // remove the registry and reverse registry mappings string memory label = reverseRegistryMap[tokenId]; delete reverseRegistryMap[tokenId]; delete registryMap[label]; } // REGISTRAR_ROLE is approved for all transactions by default function isApprovedForAll( address _owner, address _operator ) public override view returns (bool isOperator) { if (hasRole(REGISTRAR_ROLE, _operator)) { return true; } return ERC721Upgradeable.isApprovedForAll(_owner, _operator); } /// @notice tokenURI view function that returns tokenURI associated with the target token /// @param tokenId unique id to refence the target token function tokenURI( uint256 tokenId ) public view virtual override(ERC721URIStorageUpgradeable, ERC721Upgradeable) returns (string memory) { return ERC721URIStorageUpgradeable.tokenURI(tokenId); } /// @notice tokenURINoBase view function that strips baseURI from the output of tokenURI if it exists /// @param tokenId unique id to refence the target token function tokenURINoBase( uint256 tokenId ) external view virtual returns (string memory) { bytes memory basebytes = bytes(baseURI); if (basebytes.length == 0) { // if there is no baseURI, return the full tokenURI return ERC721URIStorageUpgradeable.tokenURI(tokenId); } else { // if there is a baseURI, strip it from the tokenURI bytes memory uribytes = bytes(ERC721URIStorageUpgradeable.tokenURI(tokenId)); bytes memory uri = new bytes(uribytes.length-basebytes.length); for (uint i = 0; i<uribytes.length-basebytes.length; ++i) { uri[i] = uribytes[i+basebytes.length]; } return string(uri); } } function royaltyInfo(uint256 tokenId, uint256 salePrice) external view override(IERC2981Upgradeable) returns (address receiver, uint256 royaltyAmount) { royaltyAmount = salePrice * burnFee / 10000; receiver = burnAddress; } function _baseURI() internal view virtual override returns (string memory) { return baseURI; } function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override(ERC721Upgradeable, ERC721EnumerableUpgradeable) { require(_transfersAllowed(), "NonFungibleRegistry: transfers are disabled."); super._beforeTokenTransfer(from, to, tokenId); } function _mappingExists(string memory label) internal view virtual returns (bool) { return !(registryMap[label] == 0); } function _preRegistered(address to) internal view virtual returns (bool) { // check if there is a primary registry linked to this registry and if so // does the recipient have a non-zero balance. return ((primaryRegistry == address(0)) || (IERC721Upgradeable(primaryRegistry).balanceOf(to) > 0)); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(AccessControlEnumerableUpgradeable, ERC721Upgradeable, ERC721EnumerableUpgradeable, IERC165Upgradeable) returns (bool) { return interfaceId == type(IERC2981Upgradeable).interfaceId || super.supportsInterface(interfaceId); } }
@notice inverse datastructure to registryMap @dev returns the label associated with a given token id
mapping(uint256 => string) public reverseRegistryMap;
1,796,507
[ 1, 22552, 5386, 13583, 358, 4023, 863, 225, 1135, 326, 1433, 3627, 598, 279, 864, 1147, 612, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 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, 2874, 12, 11890, 5034, 516, 533, 13, 1071, 4219, 4243, 863, 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 ]
/** *Submitted for verification at Etherscan.io on 2021-03-25 */ // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.5.5; /*Math operations with safety checks */ contract SafeMath { function safeMul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function safeDiv(uint256 a, uint256 b) internal pure returns (uint256) { return a/b; } function safeSub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function safeAdd(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c>=a && c>=b); return c; } function safePower(uint a, uint b) internal pure returns (uint256) { uint256 c = a**b; return c; } } interface IToken { function transfer(address _to, uint256 _value) external; } contract ZebiToken is SafeMath{ string public name; string public symbol; uint8 public decimals; uint256 public totalSupply; address payable public owner; uint256 public totalSupplyLimit; bool public pauseMint; address public minter; address payable public ownerTemp; uint256 blocknumberLastAcceptOwner; uint256 blocknumberLastAcceptMinter; address public minterTemp; mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; mapping (address => bool) public blacklist; event Transfer(address indexed from, address indexed to, uint256 value); event Burn(address indexed from, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); event SetPauseMint(bool pause); event SetOwner(address user); event SetTotalSupplyLimit(uint amount); event SetMinter(address minter); event SetBlacklist(address user,bool isBlacklist); event AcceptOwner(address user); event AcceptMinter(address user); constructor (/* Initializes contract with initial supply tokens to the creator of the contract */ uint256 initialSupply,string memory tokenName,string memory tokenSymbol) public{ balanceOf[msg.sender] = initialSupply; // Give the creator all initial tokens totalSupply = initialSupply; // Update total supply name = tokenName; // Set the name for display purposes symbol = tokenSymbol; // Set the symbol for display purposes decimals = 18; // Amount of decimals for display purposes owner = msg.sender; totalSupplyLimit = 21000000 * (10 ** uint256(decimals)); } function transfer(address _to, uint256 _value) public returns (bool success){/* Send coins */ require (_to != address(0x0) && !blacklist[msg.sender]); // Prevent transfer to 0x0 address. Use burn() instead require (_value >= 0) ; require (balanceOf[msg.sender] >= _value) ; // Check if the sender has enough require (safeAdd(balanceOf[_to] , _value) >= balanceOf[_to]) ; // Check for overflows balanceOf[msg.sender] = safeSub(balanceOf[msg.sender], _value); // Subtract from the sender balanceOf[_to] = safeAdd(balanceOf[_to], _value); // Add the same to the recipient emit Transfer(msg.sender, _to, _value); // Notify anyone listening that this transfer took place return true; } function approve(address _spender, uint256 _value) public returns (bool success) {/* Allow another contract to spend some tokens in your behalf */ allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {/* A contract attempts to get the coins */ require (_to != address(0x0) && !blacklist[_from]) ; // Prevent transfer to 0x0 address. Use burn() instead require (_value >= 0) ; require (balanceOf[_from] >= _value) ; // Check if the sender has enough require (safeAdd(balanceOf[_to] , _value) >= balanceOf[_to]) ; // Check for overflows require (_value <= allowance[_from][msg.sender]) ; // Check allowance balanceOf[_from] = safeSub(balanceOf[_from], _value); // Subtract from the sender balanceOf[_to] = safeAdd(balanceOf[_to], _value); // Add the same to the recipient allowance[_from][msg.sender] = safeSub(allowance[_from][msg.sender], _value); emit Transfer(_from, _to, _value); return true; } function burn(uint256 _value) public returns (bool success) { require (balanceOf[msg.sender] >= _value) ; // Check if the sender has enough require (_value > 0) ; balanceOf[msg.sender] = safeSub(balanceOf[msg.sender], _value); // Subtract from the sender totalSupply = safeSub(totalSupply,_value); // Updates totalSupply emit Burn(msg.sender, _value); emit Transfer(msg.sender, address(0), _value); return true; } function mintToken(uint256 _mintedAmount) public returns (bool success) { require(msg.sender == minter && !pauseMint && safeAdd(totalSupply,_mintedAmount) <= totalSupplyLimit); balanceOf[msg.sender] = safeAdd(balanceOf[msg.sender],_mintedAmount); totalSupply = safeAdd(totalSupply,_mintedAmount); emit Transfer(address(0x0), msg.sender, _mintedAmount); return true; } function setPauseMint(bool _pause) public{ require (msg.sender == owner) ; pauseMint = _pause; emit SetPauseMint(_pause); } function setMinter(address _minter) public{ require (msg.sender == owner) ; minterTemp = _minter; blocknumberLastAcceptMinter = block.number + 42000; emit SetMinter(_minter); } function acceptMinter() public{ require (msg.sender == owner && block.number < blocknumberLastAcceptMinter && block.number > blocknumberLastAcceptMinter - 36000) ; minter = minterTemp; emit AcceptMinter(minterTemp); } function setBlacklist(address _user,bool _isBlacklist) public{ require (msg.sender == owner) ; blacklist[_user] = _isBlacklist; emit SetBlacklist(_user,_isBlacklist); } function setOwner(address payable _add) public{ require (msg.sender == owner && _add != address(0x0)) ; ownerTemp = _add ; blocknumberLastAcceptOwner = block.number + 42000; emit SetOwner(_add); } function acceptOwner()public{ require (msg.sender == ownerTemp && block.number < blocknumberLastAcceptOwner && block.number > blocknumberLastAcceptOwner - 36000) ; owner = ownerTemp ; emit AcceptOwner(owner); } function setTotalSupplyLimit(uint _amount) public{ require (msg.sender == owner && _amount > 0) ; totalSupplyLimit = _amount ; emit SetTotalSupplyLimit(_amount); } function() external payable {}/* can accept ether */ // transfer balance to owner function withdrawToken(address token, uint amount) public{ require(msg.sender == owner); if (token == address(0x0)) owner.transfer(amount); else IToken(token).transfer(owner, amount); } }
Check if the sender has enough
require (balanceOf[msg.sender] >= _value) ;
14,968,924
[ 1, 1564, 309, 326, 5793, 711, 7304, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2583, 261, 12296, 951, 63, 3576, 18, 15330, 65, 1545, 389, 1132, 13, 274, 5411, 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 ]
pragma solidity ^0.4.25; import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol"; contract FlightSuretyData { //using SafeMath for uint; using SafeMath for uint256; /********************************************************************************************/ /* DATA VARIABLES */ /********************************************************************************************/ address private contractOwner; // Account used to deploy contract bool private operational = true; // Blocks all state changes throughout the contract if false mapping(address => uint256) private authorizedCaller; // Struct used to hold registered airlines struct Airlines { bool isRegistered; bool isFunded; uint256 funds; } mapping(address => Airlines) airlines; address[] registeredAirlines = new address[](0); // Addresses of registered AIRLINES struct Voters { bool status; } mapping(address => uint) private voteCount; mapping(address => Voters) voters; struct Insurance { bool isInsured; address airline; string flight; address passenger; uint256 amount; } struct InsuranceOwner { address[] ownerAddresses; } mapping(address => mapping(string => Insurance)) insurance; mapping(string => InsuranceOwner) insuredPassengers; mapping(address => uint256) balances; /********************************************************************************************/ /* EVENT DEFINITIONS */ /********************************************************************************************/ event AuthorizedContract(address authContract); event DeauthorizedContract(address authContract); event InsureeCredited(address passenger, uint256 amount); /** * @dev Constructor * The deploying account becomes contractOwner */ constructor() public { contractOwner = msg.sender; } /********************************************************************************************/ /* 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"); _; } /********************************************************************************************/ /* UTILITY FUNCTIONS */ /********************************************************************************************/ /** * @dev Get operating status of contract * * @return A bool that is the current operating status */ function isOperational() public view returns(bool) { return operational; } /** * @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; } /** * @dev Authorize caller */ function authorizeCaller(address contractAddress) external requireContractOwner { authorizedCaller[contractAddress] = 1; emit AuthorizedContract(contractAddress); } /** * @dev Deauthorize caller */ function deauthorizeContract(address contractAddress) external requireContractOwner { delete authorizedCaller[contractAddress]; emit DeauthorizedContract(contractAddress); } /********************************************************************************************/ /* SMART CONTRACT FUNCTIONS */ /********************************************************************************************/ //--------- Airline ------- // /** * @dev Register airline */ function registerAirline(address account) public requireIsOperational { // isRegistered is Always true for a registered airline // isOperational is only true when the airline has submited funding of 10 ether airlines[account] = Airlines({ isRegistered: true, isFunded: false, funds: 0 }); // add to registered airline queue setRegisteredAirlines(account); } /** * @dev Set the registered airlines */ function setRegisteredAirlines(address account) public { registeredAirlines.push(account); } /** * @dev Get the num of registered airlines */ function getNumOfRegisteredAirlines() public view requireIsOperational returns(uint){ return registeredAirlines.length; } /** * @dev Check if an airline is registered */ function isAirlineRegistered(address account) public view returns(bool) { return airlines[account].isRegistered; } /** * @dev Get airlines */ function getAirlines() public view requireIsOperational returns(address[] memory) { // address[] memory airlinesQueue; // for(uint i=0; i<registeredAirlines.length; i++) { // airlinesQueue[i] = registeredAirlines[i]; // } // return airlinesQueue; return address[](registeredAirlines); } /** * @dev Set the airlines funding */ function setAirlineFunds(address account, uint256 amount) public requireIsOperational { airlines[account].funds = airlines[account].funds.add(amount); airlines[account].isFunded = true; } /** * @dev Get airline funds */ function getAirlineFunds(address account) public view returns(uint256){ return airlines[account].funds; } /** * @dev Check if airline is funded */ function isFunded(address account) public view returns (bool) { return airlines[account].isFunded; } //--------- Votes ------- // /** * @dev Add voters */ function addVoters(address voter) public { voters[voter] = Voters({ status: true }); } /** * @dev Add voter counter */ function addVoterCounter(address airline, uint count) public { uint vote = voteCount[airline]; voteCount[airline] = vote.add(count); } /** * @dev Get the vote count */ function getVotes(address account) public view requireIsOperational returns(uint){ return voteCount[account]; } /** * @dev Reset vote count */ function resetVoteCounter(address account) external requireIsOperational{ delete voteCount[account]; } /** * @dev Get the voter status */ function getVoterStatus(address voter) public view requireIsOperational returns(bool){ return voters[voter].status; } // ------- Insurance ----- // /** * @dev Buy insurance */ function buyInsurance( string flight, address airline, address passenger, uint256 amount ) public payable requireIsOperational { insurance[passenger][flight] = Insurance({ isInsured: true, airline: airline, flight: flight, passenger: passenger, amount: amount }); // push insured passenger as insurance owner insuredPassengers[flight].ownerAddresses.push(passenger); } function getInsuredPassengers(string flight) public view requireIsOperational returns(address[]) { return insuredPassengers[flight].ownerAddresses; } /** * @dev Check passenger insurance */ function isInsured(address passenger, string flight) public view requireIsOperational returns(bool) { return insurance[passenger][flight].isInsured; } /** * @dev Withdraw insurance balance */ function withdraw(address passenger) public requireIsOperational returns(uint256) { uint256 withdraw_cash = balances[passenger]; // first delete to prevent acc draining delete balances[passenger]; // then return to users return withdraw_cash; } /** * @dev Get insurance amount */ function getInsuranceAmount( address passenger, string flight ) public view requireIsOperational returns(uint256) { return insurance[passenger][flight].amount; } /** * @dev Credit insurees */ function creditInsurees(address passenger, uint256 amount) external { balances[passenger] = amount; } /** * @dev Get passanger credit */ function getPassengerCredit(address passenger) public view requireIsOperational returns(uint256){ return balances[passenger]; } /** * @dev Get flight key */ 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(); } */ }
push insured passenger as insurance owner
insuredPassengers[flight].ownerAddresses.push(passenger);
12,989,622
[ 1, 6206, 316, 2055, 72, 1342, 14348, 487, 2763, 295, 1359, 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 ]
[ 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, 316, 2055, 72, 6433, 275, 6215, 63, 19131, 8009, 8443, 7148, 18, 6206, 12, 5466, 14348, 1769, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.26; import "./FlightSuretyBaseAppWithAccessControl.sol"; contract FlightSuretyFlightController is FlightSuretyBaseAppWithAccessControl { // constants // Flight status codes uint8 private constant STATUS_CODE_UNKNOWN = 0; uint8 private constant STATUS_CODE_ON_TIME = 10; uint8 private constant STATUS_CODE_LATE_WEATHER = 30; uint8 private constant STATUS_CODE_LATE_TECHNICAL = 40; uint8 private constant STATUS_CODE_LATE_OTHER = 50; uint8 private constant STATUS_CODE_DONE = 60; // Fee to be paid when registering oracle uint256 public constant ORACLE_REGISTRATION_FEE = 1 ether; // Number of oracles that must respond for valid status uint256 private constant MIN_ORACLE_RESPONSES = 3; // Incremented to add pseudo-randomness at various points uint8 private nonce = 0; // Fee to be paid when registering oracle uint256 public constant REGISTRATION_FEE = 1 ether; // Number of oracles that must respond for valid status uint256 private constant MIN_RESPONSES = 3; // Event fired each time an oracle submits a response event FlightStatusInfo( address airline, bytes32 flight, uint256 timestamp, uint8 status ); event NewFlight( bytes32 flightName, bytes32 flightKey, uint8 status ); event OracleReport( address airline, bytes32 flight, uint256 timestamp, uint8 status ); // Event fired when flight status request is submitted // Oracles track this and if they have a matching index // they fetch data and submit a response event OracleRequest( uint8 index, address airline, bytes32 flight, uint256 timestamp, bytes32 oracleKey ); /** * @dev Unique random key to register each flight. Serves as a flight id * */ function getFlightKey( address airline, bytes32 flight, uint256 timestamp ) internal pure returns (bytes32) { return keccak256(abi.encodePacked(airline, flight, timestamp)); } /** * @dev Register a future flight for insuring. * */ function registerFlight(bytes32 flightName) external { require( flightSuretyData.getAirlineParticipationStatus(msg.sender), "Only Pariticipating Airlines can register a flight" ); bytes32 flightKey = getFlightKey(msg.sender, flightName, now); flightSuretyData.registerFlight( msg.sender, flightName, STATUS_CODE_UNKNOWN, now, flightKey ); emit NewFlight(flightName, flightKey, STATUS_CODE_UNKNOWN); } /** * @dev Called after oracle has updated flight status * */ function processFlightStatus( address airlineAddress, bytes32 flightKey, uint256 timestamp, uint8 statusCode ) internal { // update flight statusCode flightSuretyData.setFlightStatus(flightKey, statusCode); emit FlightStatusInfo(airlineAddress, flightKey, timestamp, statusCode); } // Generate a request for oracles to fetch flight information function fetchFlightStatus( bytes32 flightKey, uint256 timestamp ) external requireIsOperational { uint8 index = getRandomIndex(msg.sender); address airline = flightSuretyData.getAirlineThatCreatedFlight(flightKey); require(flightSuretyData.getFlightStatusCode(flightKey) >= 0, "Not a valid Flight"); // Generate a unique key for storing the request bytes32 oracleResponseKey = keccak256( abi.encodePacked(index, airline, flightKey, timestamp) ); // add the key of the oracleResponse - for oracles to update that data flightSuretyData.createOpeningForOracleResponse( oracleResponseKey, msg.sender ); emit OracleRequest( index, airline, flightKey, timestamp, oracleResponseKey ); } // Register an oracle with the contract function registerOracle() external payable { // Require registration fee require(msg.value >= REGISTRATION_FEE, "Registration fee is required"); uint8[3] memory indexes = generateIndexes(msg.sender); flightSuretyData.registerOracle(msg.sender, indexes); } // Returns array of three non-duplicating integers from 0-9 function generateIndexes(address account) internal returns (uint8[3]) { uint8[3] memory indexes; indexes[0] = getRandomIndex(account); indexes[1] = indexes[0]; while (indexes[1] == indexes[0]) { indexes[1] = getRandomIndex(account); } indexes[2] = indexes[1]; while ((indexes[2] == indexes[0]) || (indexes[2] == indexes[1])) { indexes[2] = getRandomIndex(account); } return indexes; } // Returns array of three non-duplicating integers from 0-9 function getRandomIndex(address account) internal returns (uint8) { uint8 maxValue = 10; // Pseudo random number...the incrementing nonce adds variation uint8 random = uint8( uint256( keccak256( abi.encodePacked(blockhash(block.number - nonce++), account) ) ) % maxValue ); if (nonce > 250) { nonce = 0; // Can only fetch blockhashes for last 256 blocks so we adapt } return random; } function getMyIndexes() external view returns (uint8[3]) { // call FlightData to get this data return flightSuretyData.getOracleIndexes(msg.sender); } // Called by oracle when a response is available to an outstanding request // For the response to be accepted, there must be a pending request that is open // and matches one of the three Indexes randomly assigned to the oracle at the // time of registration (i.e. uninvited oracles are not welcome) function submitOracleResponse( uint8 index, address airline, bytes32 flightKey, uint256 timestamp, uint8 statusCode, bytes32 oracleKey ) external { uint8[3] memory oracleIndexes = flightSuretyData.getOracleIndexes( msg.sender ); require( (oracleIndexes[0] == index) || (oracleIndexes[1] == index) || (oracleIndexes[2] == index), "Index does not match oracle request" ); require( flightSuretyData.getIfOracleResponseIsOpen(oracleKey), "Flight or timestamp do not match oracle request" ); flightSuretyData.updateOracleResponsesStatusCode( oracleKey, statusCode, msg.sender ); // Information isn't considered verified until at least MIN_RESPONSES // oracles respond with the *** same *** information emit OracleReport(airline, flightKey, timestamp, statusCode); if ( flightSuretyData.getTotalNumberOfResponsesForThisStatusCode( oracleKey, statusCode ) >= MIN_RESPONSES ) { emit FlightStatusInfo(airline, flightKey, timestamp, statusCode); // Handle flight status as appropriate processFlightStatus(airline, flightKey, timestamp, statusCode); flightSuretyData.setOracleResponseIsOpen(oracleKey, false); } } }
Called by oracle when a response is available to an outstanding request For the response to be accepted, there must be a pending request that is open and matches one of the three Indexes randomly assigned to the oracle at the time of registration (i.e. uninvited oracles are not welcome) Information isn't considered verified until at least MIN_RESPONSES oracles respond with the *** same *** information Handle flight status as appropriate
function submitOracleResponse( uint8 index, address airline, bytes32 flightKey, uint256 timestamp, uint8 statusCode, bytes32 oracleKey ) external { uint8[3] memory oracleIndexes = flightSuretyData.getOracleIndexes( msg.sender ); require( (oracleIndexes[0] == index) || (oracleIndexes[1] == index) || (oracleIndexes[2] == index), "Index does not match oracle request" ); require( flightSuretyData.getIfOracleResponseIsOpen(oracleKey), "Flight or timestamp do not match oracle request" ); flightSuretyData.updateOracleResponsesStatusCode( oracleKey, statusCode, msg.sender ); emit OracleReport(airline, flightKey, timestamp, statusCode); if ( flightSuretyData.getTotalNumberOfResponsesForThisStatusCode( oracleKey, statusCode ) >= MIN_RESPONSES ) { emit FlightStatusInfo(airline, flightKey, timestamp, statusCode); processFlightStatus(airline, flightKey, timestamp, statusCode); flightSuretyData.setOracleResponseIsOpen(oracleKey, false); } }
7,228,948
[ 1, 8185, 635, 20865, 1347, 279, 766, 353, 2319, 358, 392, 20974, 590, 2457, 326, 766, 358, 506, 8494, 16, 1915, 1297, 506, 279, 4634, 590, 716, 353, 1696, 471, 1885, 1245, 434, 326, 8925, 3340, 281, 20153, 6958, 358, 326, 20865, 622, 326, 813, 434, 7914, 261, 77, 18, 73, 18, 640, 5768, 16261, 578, 69, 9558, 854, 486, 28329, 13, 15353, 5177, 1404, 7399, 13808, 3180, 622, 4520, 6989, 67, 14508, 55, 578, 69, 9558, 6846, 598, 326, 225, 1967, 225, 1779, 5004, 25187, 1267, 487, 5505, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 4879, 23601, 1064, 12, 203, 3639, 2254, 28, 770, 16, 203, 3639, 1758, 23350, 1369, 16, 203, 3639, 1731, 1578, 25187, 653, 16, 203, 3639, 2254, 5034, 2858, 16, 203, 3639, 2254, 28, 6593, 16, 203, 3639, 1731, 1578, 20865, 653, 203, 565, 262, 3903, 288, 203, 3639, 2254, 28, 63, 23, 65, 3778, 20865, 8639, 273, 25187, 55, 594, 4098, 751, 18, 588, 23601, 8639, 12, 203, 5411, 1234, 18, 15330, 203, 3639, 11272, 203, 203, 3639, 2583, 12, 203, 5411, 261, 280, 16066, 8639, 63, 20, 65, 422, 770, 13, 747, 203, 7734, 261, 280, 16066, 8639, 63, 21, 65, 422, 770, 13, 747, 203, 7734, 261, 280, 16066, 8639, 63, 22, 65, 422, 770, 3631, 203, 5411, 315, 1016, 1552, 486, 845, 20865, 590, 6, 203, 3639, 11272, 203, 203, 3639, 2583, 12, 203, 5411, 25187, 55, 594, 4098, 751, 18, 588, 2047, 23601, 1064, 2520, 3678, 12, 280, 16066, 653, 3631, 203, 5411, 315, 24243, 578, 2858, 741, 486, 845, 20865, 590, 6, 203, 3639, 11272, 203, 203, 3639, 25187, 55, 594, 4098, 751, 18, 2725, 23601, 12222, 14041, 12, 203, 5411, 20865, 653, 16, 203, 5411, 6593, 16, 203, 5411, 1234, 18, 15330, 203, 3639, 11272, 203, 203, 3639, 3626, 28544, 4820, 12, 1826, 1369, 16, 25187, 653, 16, 2858, 16, 6593, 1769, 203, 3639, 309, 261, 203, 5411, 25187, 55, 594, 4098, 751, 18, 588, 5269, 9226, 12222, 1290, 2503, 14041, 12, 203, 7734, 20865, 653, 16, 203, 7734, 6593, 203, 5411, 262, 1545, 6989, 67, 2 ]
pragma solidity ^0.4.24; /* * Creator: XERA */ /* * Abstract Token Smart Contract * */ /* * Safe Math Smart Contract. * https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/math/SafeMath.sol */ contract 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 safeDiv(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 safeSub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function safeAdd(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * ERC-20 standard token interface, as defined * <a href="http://github.com/ethereum/EIPs/issues/20">here</a>. */ contract Token { function totalSupply() constant returns (uint256 supply); function balanceOf(address _owner) constant returns (uint256 balance); function transfer(address _to, uint256 _value) returns (bool success); function transferFrom(address _from, address _to, uint256 _value) returns (bool success); function approve(address _spender, uint256 _value) returns (bool success); function allowance(address _owner, address _spender) constant returns (uint256 remaining); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } /** * Abstract Token Smart Contract that could be used as a base contract for * ERC-20 token contracts. */ contract AbstractToken is Token, SafeMath { /** * Create new Abstract Token contract. */ function AbstractToken () { // Do nothing } /** * Get number of tokens currently belonging to given owner. * * @param _owner address to get number of tokens currently belonging to the * owner of * @return number of tokens currently belonging to the owner of given address */ function balanceOf(address _owner) constant returns (uint256 balance) { return accounts [_owner]; } /** * Transfer given number of tokens from message sender to given recipient. * * @param _to address to transfer tokens to the owner of * @param _value number of tokens to transfer to the owner of given address * @return true if tokens were transferred successfully, false otherwise * accounts [_to] + _value > accounts [_to] for overflow check * which is already in safeMath */ function transfer(address _to, uint256 _value) returns (bool success) { require(_to != address(0)); if (accounts [msg.sender] < _value) return false; if (_value > 0 && msg.sender != _to) { accounts [msg.sender] = safeSub (accounts [msg.sender], _value); accounts [_to] = safeAdd (accounts [_to], _value); } emit Transfer (msg.sender, _to, _value); return true; } /** * Transfer given number of tokens from given owner to given recipient. * * @param _from address to transfer tokens from the owner of * @param _to address to transfer tokens to the owner of * @param _value number of tokens to transfer from given owner to given * recipient * @return true if tokens were transferred successfully, false otherwise * accounts [_to] + _value > accounts [_to] for overflow check * which is already in safeMath */ function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { require(_to != address(0)); if (allowances [_from][msg.sender] < _value) return false; if (accounts [_from] < _value) return false; if (_value > 0 && _from != _to) { allowances [_from][msg.sender] = safeSub (allowances [_from][msg.sender], _value); accounts [_from] = safeSub (accounts [_from], _value); accounts [_to] = safeAdd (accounts [_to], _value); } emit Transfer(_from, _to, _value); return true; } /** * Allow given spender to transfer given number of tokens from message sender. * @param _spender address to allow the owner of to transfer tokens from message sender * @param _value number of tokens to allow to transfer * @return true if token transfer was successfully approved, false otherwise */ function approve (address _spender, uint256 _value) returns (bool success) { allowances [msg.sender][_spender] = _value; emit Approval (msg.sender, _spender, _value); return true; } /** * Tell how many tokens given spender is currently allowed to transfer from * given owner. * * @param _owner address to get number of tokens allowed to be transferred * from the owner of * @param _spender address to get number of tokens allowed to be transferred * by the owner of * @return number of tokens given spender is currently allowed to transfer * from given owner */ function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowances [_owner][_spender]; } /** * Mapping from addresses of token holders to the numbers of tokens belonging * to these token holders. */ mapping (address => uint256) accounts; /** * Mapping from addresses of token holders to the mapping of addresses of * spenders to the allowances set by these token holders to these spenders. */ mapping (address => mapping (address => uint256)) private allowances; } /** * XERA Token Smart Contract. */ contract XERA is AbstractToken { /** * Maximum allowed number of tokens in circulation. * tokenSupply = tokensIActuallyWant * (10 ^ decimals) */ uint256 constant MAX_TOKEN_COUNT = 95000000 * (10**18); /** * Address of the owner of this smart contract. */ address private owner; /** * Frozen account list holder */ mapping (address => bool) private frozenAccount; /** * Burning account list holder */ mapping (address => bool) private burningAccount; /** * Current number of tokens in circulation. */ uint256 tokenCount = 0; /** * True if tokens transfers are currently frozen, false otherwise. */ bool frozen = false; /** * Create new token smart contract and make msg.sender the * owner of this smart contract. */ function XERA () { owner = msg.sender; } /** * Get total number of tokens in circulation. * * @return total number of tokens in circulation */ function totalSupply() constant returns (uint256 supply) { return tokenCount; } string constant public name = "XERA"; string constant public symbol = "XERA"; uint8 constant public decimals = 18; /** * Transfer given number of tokens from message sender to given recipient. * @param _to address to transfer tokens to the owner of * @param _value number of tokens to transfer to the owner of given address * @return true if tokens were transferred successfully, false otherwise */ function transfer(address _to, uint256 _value) returns (bool success) { require(!frozenAccount[msg.sender]); if (frozen) return false; else return AbstractToken.transfer (_to, _value); } /** * Transfer given number of tokens from given owner to given recipient. * * @param _from address to transfer tokens from the owner of * @param _to address to transfer tokens to the owner of * @param _value number of tokens to transfer from given owner to given * recipient * @return true if tokens were transferred successfully, false otherwise */ function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { require(!frozenAccount[_from]); if (frozen) return false; else return AbstractToken.transferFrom (_from, _to, _value); } /** * Change how many tokens given spender is allowed to transfer from message * spender. In order to prevent double spending of allowance, * 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 * @param _spender address to allow the owner of to transfer tokens from * message sender * @param _value number of tokens to allow to transfer * @return true if token transfer was successfully approved, false otherwise */ function approve (address _spender, uint256 _value) returns (bool success) { require(allowance (msg.sender, _spender) == 0 || _value == 0); return AbstractToken.approve (_spender, _value); } /** * Create _value new tokens and give new created tokens to msg.sender. * Only be called by smart contract owner. * * @param _value number of tokens to create * @return true if tokens were created successfully, false otherwise */ function createTokens(uint256 _value) returns (bool success) { require (msg.sender == owner); if (_value > 0) { if (_value > safeSub (MAX_TOKEN_COUNT, tokenCount)) return false; accounts [msg.sender] = safeAdd (accounts [msg.sender], _value); tokenCount = safeAdd (tokenCount, _value); // adding transfer event and _from address as null address emit Transfer(0x0, msg.sender, _value); return true; } return false; } /** * Burning capable account * Only be called by smart contract owner. */ function burningCapableAccount(address[] _target) { require (msg.sender == owner); for (uint i = 0; i < _target.length; i++) { burningAccount[_target[i]] = true; } } /** * Burn intended tokens. * Only be called by by burnable addresses. * * @param _value number of tokens to burn * @return true if burnt successfully, false otherwise */ function burn(uint256 _value) public returns (bool success) { require(accounts[msg.sender] >= _value); require(burningAccount[msg.sender]); accounts [msg.sender] = safeSub (accounts [msg.sender], _value); tokenCount = safeSub (tokenCount, _value); emit Burn(msg.sender, _value); return true; } /** * Set new owner for the smart contract. * Only be called by smart contract owner. * * @param _newOwner address of new owner of the smart contract */ function setOwner(address _newOwner) { require (msg.sender == owner); owner = _newOwner; } /** * Freeze ALL token transfers. * Only be called by smart contract owner. */ function freezeTransfers () { require (msg.sender == owner); if (!frozen) { frozen = true; emit Freeze (); } } /** * Unfreeze ALL token transfers. * Only be called by smart contract owner. */ function unfreezeTransfers () { require (msg.sender == owner); if (frozen) { frozen = false; emit Unfreeze (); } } /*A user is able to unintentionally send tokens to a contract * and if the contract is not prepared to refund them they will get stuck in the contract. * The same issue used to happen for Ether too but new Solidity versions added the payable modifier to * prevent unintended Ether transfers. However, there’s no such mechanism for token transfers. * so the below function is created */ function refundTokens(address _token, address _refund, uint256 _value) { require (msg.sender == owner); require(_token != address(this)); AbstractToken token = AbstractToken(_token); token.transfer(_refund, _value); emit RefundTokens(_token, _refund, _value); } /** * Freeze specific account * Only be called by smart contract owner. */ function freezeAccount(address _target, bool freeze) { require (msg.sender == owner); require (msg.sender != _target); frozenAccount[_target] = freeze; emit FrozenFunds(_target, freeze); } /** * Logged when token transfers were frozen. */ event Freeze (); /** * Logged when token transfers were unfrozen. */ event Unfreeze (); /** * Logged when a particular account is frozen. */ event FrozenFunds(address target, bool frozen); /** * Logged when a token is burnt. */ event Burn(address target,uint256 _value); /** * when accidentally send other tokens are refunded */ event RefundTokens(address _token, address _refund, uint256 _value); }
* Freeze specific account Only be called by smart contract owner./
function freezeAccount(address _target, bool freeze) { require (msg.sender == owner); require (msg.sender != _target); frozenAccount[_target] = freeze; emit FrozenFunds(_target, freeze); } event FrozenFunds(address target, bool frozen); event Burn(address target,uint256 _value); event RefundTokens(address _token, address _refund, uint256 _value);
2,177,858
[ 1, 9194, 8489, 2923, 2236, 5098, 506, 2566, 635, 13706, 6835, 3410, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 16684, 3032, 12, 2867, 389, 3299, 16, 1426, 16684, 13, 288, 203, 1377, 2583, 261, 3576, 18, 15330, 422, 3410, 1769, 203, 202, 225, 2583, 261, 3576, 18, 15330, 480, 389, 3299, 1769, 203, 1377, 12810, 3032, 63, 67, 3299, 65, 273, 16684, 31, 203, 1377, 3626, 478, 9808, 42, 19156, 24899, 3299, 16, 16684, 1769, 203, 289, 203, 203, 203, 21281, 225, 871, 478, 9808, 42, 19156, 12, 2867, 1018, 16, 1426, 12810, 1769, 203, 21281, 225, 871, 605, 321, 12, 2867, 1018, 16, 11890, 5034, 389, 1132, 1769, 203, 203, 203, 21281, 225, 871, 3941, 1074, 5157, 12, 2867, 389, 2316, 16, 1758, 389, 1734, 1074, 16, 2254, 5034, 389, 1132, 1769, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/10/0x02bD0b89F7b198014425Df1a4152A2E77576c38D/sources/src/abstract/BaseTrigger.sol
@dev Call this method to update Set addresses after deploy.
function addSet(ISet _set) external { if (msg.sender != address(manager)) revert Unauthorized(); (bool _exists,,,) = manager.sets(_set); if (!_exists) revert Unauthorized(); uint256 setLength = sets.length; if (setLength >= MAX_SET_LENGTH) revert SetLimitReached(); for (uint256 i = 0; i < setLength; i = uncheckedIncrement(i)) { if (sets[i] == _set) return; } sets.push(_set); emit SetAdded(_set); }
3,778,146
[ 1, 1477, 333, 707, 358, 1089, 1000, 6138, 1839, 7286, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 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, 225, 445, 527, 694, 12, 45, 694, 389, 542, 13, 3903, 288, 203, 565, 309, 261, 3576, 18, 15330, 480, 1758, 12, 4181, 3719, 15226, 15799, 5621, 203, 565, 261, 6430, 389, 1808, 16408, 16, 13, 273, 3301, 18, 4424, 24899, 542, 1769, 203, 565, 309, 16051, 67, 1808, 13, 15226, 15799, 5621, 203, 203, 565, 2254, 5034, 15683, 273, 1678, 18, 2469, 31, 203, 565, 309, 261, 542, 1782, 1545, 4552, 67, 4043, 67, 7096, 13, 15226, 1000, 3039, 23646, 5621, 203, 565, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 15683, 31, 277, 273, 22893, 10798, 12, 77, 3719, 288, 203, 1377, 309, 261, 4424, 63, 77, 65, 422, 389, 542, 13, 327, 31, 203, 565, 289, 203, 565, 1678, 18, 6206, 24899, 542, 1769, 203, 565, 3626, 1000, 8602, 24899, 542, 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 ]
pragma solidity >0.4.99 <0.6.0; // SMART CONTRACT de pruebas, que permite realizar una compra y que este sea validado por un arbitro, // o bien por el propio comprador, hasta no ser aprobada el dinero no irá al Vendedor. // Si se deniega se devuelve el dinero al comprador */ contract CompraArbitrada { address payable public comprador; address payable public vendedor; address payable public arbitro; constructor ( address payable _vendedor, address payable _arbitro) public { //recibe quien es el comprador, vendedor y arbitro. comprador = msg.sender; vendedor = _vendedor; arbitro = _arbitro; } function compra() public payable { //Recibe from y value (payable), value irá temporalmente a la dirección del contrato (smartContract). require (msg.sender == comprador, "ERROR: sender is diferent than comprador"); } function pagarAlVendedor() public { //Recibe from, transferirá al vendedor el dinero del contrato. if (msg.sender == comprador || msg.sender == arbitro){ vendedor.transfer(address(this).balance); } } function devolverAlComprador() public { //Recibe from, devolverá al comprador el dinero del contrato. if (msg.sender == comprador || msg.sender == arbitro){ comprador.transfer(address(this).balance); } } /** FUNCIONES INFORMATIVAS, NO RELEVANTES */ function obtenerBalanceContrato() public view returns (uint) { return address(this).balance; } function obtenerBalanceComprador() public view returns (uint) { return address(comprador).balance; } function obtenerBalanceVendedor() public view returns (uint) { return address(vendedor).balance; } function obtenerDireccionContrato() public view returns (address) { return address(this); } function obtenerDireccionComprador() public view returns (address) { return address(comprador); } function obtenerDireccionArbitro() public view returns (address) { return address(arbitro); } function obtenerDireccionVendedor() public view returns (address) { return address(vendedor); } }
Recibe from, transferirá al vendedor el dinero del contrato.
function pagarAlVendedor() public {
2,509,371
[ 1, 5650, 495, 73, 628, 16, 7412, 481, 132, 99, 524, 331, 3934, 280, 415, 302, 267, 2439, 1464, 16252, 31093, 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 ]
[ 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, 4262, 297, 1067, 58, 3934, 280, 1435, 1071, 288, 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: MIT pragma solidity 0.8.9; // ,|||||< ~|||||' `_+7ykKD%RDqmI*~` // [email protected]@@@@@8' `[email protected]@@@@` `^[email protected]@@@@@@@@@@@@@@@@R|` // [email protected]@@@@@@@Q; [email protected]@@@@J '}[email protected]@@@@@[email protected]@@@@@@Q, // [email protected]@@@@@@@@@j `[email protected]@@@Q` `[email protected]@@@@@h^` `[email protected]@@@@* // [email protected]@@@@@@@@@@@D. [email protected]@@@@i [email protected]@@@@w' ^@@@@@* // [email protected]@@@@[email protected]@@@@@@Q! `@@@@@Q ;@@@@@@; .txxxx: // |@@@@@u *@@@@@@@@z [email protected]@@@@* `[email protected]@@@@^ // `[email protected]@@@Q` '[email protected]@@@@@@R.'@@@@@B [email protected]@@@@% :DDDDDDDDDDDDDD5 // [email protected]@@@@7 `[email protected]@@@@@@[email protected]@@@@+ [email protected]@@@@K [email protected]@@@@@@* // `@@@@@Q` ^[email protected]@@@@@@@@@@W [email protected]@@@@@; ,[email protected]@@@@@# // [email protected]@@@@L ,[email protected]@@@@@@@@@! '[email protected]@@@@@u, [email protected]@@@@@@@^ // [email protected]@@@@Q }@@@@@@@@D '[email protected]@@@@@@@gUwwU%[email protected]@@@@@@@@@g // [email protected]@@@@< [email protected]@@@@@@; ;[email protected]@@@@@@@@@@@@@@Wf;[email protected]@@; // ~;;;;; .;;;;;~ '!Lx5mEEmyt|!' ;;;~ // // Powered By: @niftygateway // Author: @niftynathang // Collaborators: @conviction_1 // @stormihoebe // @smatthewenglish // @dccockfoster // @blainemalone import "./ERC721Omnibus.sol"; import "../interfaces/IERC2309.sol"; import "../interfaces/IERC721MetadataGenerator.sol"; import "../interfaces/IERC721DefaultOwnerCloneable.sol"; import "../structs/NiftyType.sol"; import "../utils/Signable.sol"; import "../utils/Withdrawable.sol"; import "../utils/Royalties.sol"; contract NiftyERC721Token is ERC721Omnibus, Royalties, Signable, Withdrawable, IERC2309 { using Address for address; event NiftyTypeCreated(address indexed contractAddress, uint256 niftyType, uint256 idFirst, uint256 idLast); uint256 constant internal MAX_INT = 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff; // A pointer to a contract that can generate token URI/metadata IERC721MetadataGenerator internal metadataGenerator; // Used to determine next nifty type/token ids to create on a mint call NiftyType internal lastNiftyType; // Sorted array of NiftyType definitions - ordered to allow binary searching NiftyType[] internal niftyTypes; // Mapping from Nifty type to IPFS hash of canonical artifact file. mapping(uint256 => string) private niftyTypeIPFSHashes; constructor() { } function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721Omnibus, Royalties, NiftyPermissions) returns (bool) { return interfaceId == type(IERC2309).interfaceId || super.supportsInterface(interfaceId); } function setMetadataGenerator(address metadataGenerator_) external { _requireOnlyValidSender(); if(metadataGenerator_ == address(0)) { metadataGenerator = IERC721MetadataGenerator(metadataGenerator_); } else { require(IERC165(metadataGenerator_).supportsInterface(type(IERC721MetadataGenerator).interfaceId), "Invalid Metadata Generator"); metadataGenerator = IERC721MetadataGenerator(metadataGenerator_); } } function finalizeContract() external { _requireOnlyValidSender(); require(!collectionStatus.isContractFinalized, ERROR_CONTRACT_IS_FINALIZED); collectionStatus.isContractFinalized = true; } function tokenURI(uint256 tokenId) public virtual view override returns (string memory) { if(address(metadataGenerator) == address(0)) { return super.tokenURI(tokenId); } else { require(_exists(tokenId), ERROR_QUERY_FOR_NONEXISTENT_TOKEN); return metadataGenerator.tokenMetadata(tokenId, _getNiftyType(tokenId), bytes("")); } } function tokenIPFSHash(uint256 tokenId) external view returns (string memory) { require(_exists(tokenId), ERROR_QUERY_FOR_NONEXISTENT_TOKEN); return niftyTypeIPFSHashes[_getNiftyType(tokenId)]; } function setIPFSHash(uint256 niftyType, string memory ipfsHash) external { _requireOnlyValidSender(); require(bytes(niftyTypeIPFSHashes[niftyType]).length == 0, "ERC721Metadata: IPFS hash already set"); niftyTypeIPFSHashes[niftyType] = ipfsHash; } function mint(uint256[] calldata amounts, string[] calldata ipfsHashes) external { _requireOnlyValidSender(); require(amounts.length > 0 && ipfsHashes.length > 0, ERROR_INPUT_ARRAY_EMPTY); require(amounts.length == ipfsHashes.length, ERROR_INPUT_ARRAY_SIZE_MISMATCH); address to = collectionStatus.defaultOwner; require(to != address(0), ERROR_TRANSFER_TO_ZERO_ADDRESS); require(!collectionStatus.isContractFinalized, ERROR_CONTRACT_IS_FINALIZED); uint88 initialIdLast = lastNiftyType.idLast; uint72 nextNiftyType = lastNiftyType.niftyType; uint88 nextIdCounter = initialIdLast + 1; uint88 firstNewTokenId = nextIdCounter; uint88 lastIdCounter = 0; for(uint256 i = 0; i < amounts.length; i++) { require(amounts[i] > 0, ERROR_NO_TOKENS_MINTED); uint88 amount = uint88(amounts[i]); lastIdCounter = nextIdCounter + amount - 1; nextNiftyType++; if(bytes(ipfsHashes[i]).length > 0) { niftyTypeIPFSHashes[nextNiftyType] = ipfsHashes[i]; } niftyTypes.push(NiftyType({ isMinted: true, niftyType: nextNiftyType, idFirst: nextIdCounter, idLast: lastIdCounter })); emit NiftyTypeCreated(address(this), nextNiftyType, nextIdCounter, lastIdCounter); nextIdCounter += amount; } uint256 newlyMinted = lastIdCounter - initialIdLast; balances[to] += newlyMinted; lastNiftyType.niftyType = nextNiftyType; lastNiftyType.idLast = lastIdCounter; collectionStatus.amountCreated += uint88(newlyMinted); emit ConsecutiveTransfer(firstNewTokenId, lastIdCounter, address(0), to); } function setBaseURI(string calldata uri) external { _requireOnlyValidSender(); _setBaseURI(uri); } function exists(uint256 tokenId) public view returns (bool) { return _exists(tokenId); } function burn(uint256 tokenId) public { _burn(tokenId); } function burnBatch(uint256[] calldata tokenIds) public { require(tokenIds.length > 0, ERROR_INPUT_ARRAY_EMPTY); for(uint256 i = 0; i < tokenIds.length; i++) { _burn(tokenIds[i]); } } function getNiftyTypes() public view returns (NiftyType[] memory) { return niftyTypes; } function getNiftyTypeDetails(uint256 niftyType) public view returns (NiftyType memory) { uint256 niftyTypeIndex = MAX_INT; unchecked { niftyTypeIndex = niftyType - 1; } if(niftyTypeIndex >= niftyTypes.length) { revert('Nifty Type Does Not Exist'); } return niftyTypes[niftyTypeIndex]; } function _isValidTokenId(uint256 tokenId) internal virtual view override returns (bool) { return tokenId > 0 && tokenId <= collectionStatus.amountCreated; } // Performs a binary search of the nifty types array to find which nifty type a token id is associated with // This is more efficient than iterating the entire nifty type array until the proper entry is found. // This is O(log n) instead of O(n) function _getNiftyType(uint256 tokenId) internal virtual override view returns (uint256) { uint256 min = 0; uint256 max = niftyTypes.length - 1; uint256 guess = (max - min) / 2; while(guess < niftyTypes.length) { NiftyType storage guessResult = niftyTypes[guess]; if(tokenId >= guessResult.idFirst && tokenId <= guessResult.idLast) { return guessResult.niftyType; } else if(tokenId > guessResult.idLast) { min = guess + 1; guess = min + (max - min) / 2; } else if(tokenId < guessResult.idFirst) { max = guess - 1; guess = min + (max - min) / 2; } } return 0; } } // SPDX-License-Identifier: MIT pragma solidity 0.8.9; import "./ERC721.sol"; import "../interfaces/IERC721DefaultOwnerCloneable.sol"; abstract contract ERC721Omnibus is ERC721, IERC721DefaultOwnerCloneable { struct TokenOwner { bool transferred; address ownerAddress; } struct CollectionStatus { bool isContractFinalized; // 1 byte uint88 amountCreated; // 11 bytes address defaultOwner; // 20 bytes } // Only allow Nifty Entity to be initialized once bool internal initializedDefaultOwner; CollectionStatus internal collectionStatus; // Mapping from token ID to owner address mapping(uint256 => TokenOwner) internal ownersOptimized; function initializeDefaultOwner(address defaultOwner_) public { require(!initializedDefaultOwner, ERROR_REINITIALIZATION_NOT_PERMITTED); collectionStatus.defaultOwner = defaultOwner_; initializedDefaultOwner = true; } function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721, IERC165) returns (bool) { return interfaceId == type(IERC721DefaultOwnerCloneable).interfaceId || super.supportsInterface(interfaceId); } function getCollectionStatus() public view virtual returns (CollectionStatus memory) { return collectionStatus; } function ownerOf(uint256 tokenId) public view virtual override returns (address owner) { require(_isValidTokenId(tokenId), ERROR_QUERY_FOR_NONEXISTENT_TOKEN); owner = ownersOptimized[tokenId].transferred ? ownersOptimized[tokenId].ownerAddress : collectionStatus.defaultOwner; require(owner != address(0), ERROR_QUERY_FOR_NONEXISTENT_TOKEN); } function _exists(uint256 tokenId) internal view virtual override returns (bool) { if(_isValidTokenId(tokenId)) { return ownersOptimized[tokenId].ownerAddress != address(0) || !ownersOptimized[tokenId].transferred; } return false; } function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual override returns (address owner, bool isApprovedOrOwner) { owner = ownerOf(tokenId); isApprovedOrOwner = (spender == owner || tokenApprovals[tokenId] == spender || isApprovedForAll(owner, spender)); } function _clearOwnership(uint256 tokenId) internal virtual override { ownersOptimized[tokenId].transferred = true; ownersOptimized[tokenId].ownerAddress = address(0); } function _setOwnership(address to, uint256 tokenId) internal virtual override { ownersOptimized[tokenId].transferred = true; ownersOptimized[tokenId].ownerAddress = to; } function _isValidTokenId(uint256 /*tokenId*/) internal virtual view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity 0.8.9; /** * @dev Interface of the ERC2309 standard as defined in the EIP. */ interface IERC2309 { /** * @dev Emitted when consecutive token ids in range ('fromTokenId') to ('toTokenId') are transferred from one account (`fromAddress`) to * another (`toAddress`). * * Note that `value` may be zero. */ event ConsecutiveTransfer(uint256 indexed fromTokenId, uint256 toTokenId, address indexed fromAddress, address indexed toAddress); } // SPDX-License-Identifier: MIT pragma solidity 0.8.9; import "./IERC165.sol"; interface IERC721MetadataGenerator is IERC165 { function tokenMetadata(uint256 tokenId, uint256 niftyType, bytes calldata data) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity 0.8.9; import "./IERC165.sol"; interface IERC721DefaultOwnerCloneable is IERC165 { function initializeDefaultOwner(address defaultOwner_) external; } // SPDX-License-Identifier: MIT pragma solidity 0.8.9; struct NiftyType { bool isMinted; // 1 bytes uint72 niftyType; // 9 bytes uint88 idFirst; // 11 bytes uint88 idLast; // 11 bytes } // SPDX-License-Identifier: MIT pragma solidity 0.8.9; import "./NiftyPermissions.sol"; import "../libraries/ECDSA.sol"; import "../structs/SignatureStatus.sol"; abstract contract Signable is NiftyPermissions { event ContractSigned(address signer, bytes32 data, bytes signature); SignatureStatus public signatureStatus; bytes public signature; string internal constant ERROR_CONTRACT_ALREADY_SIGNED = "Contract already signed"; string internal constant ERROR_CONTRACT_NOT_SALTED = "Contract not salted"; string internal constant ERROR_INCORRECT_SECRET_SALT = "Incorrect secret salt"; string internal constant ERROR_SALTED_HASH_SET_TO_ZERO = "Salted hash set to zero"; string internal constant ERROR_SIGNER_SET_TO_ZERO = "Signer set to zero address"; function setSigner(address signer_, bytes32 saltedHash_) external { _requireOnlyValidSender(); require(signer_ != address(0), ERROR_SIGNER_SET_TO_ZERO); require(saltedHash_ != bytes32(0), ERROR_SALTED_HASH_SET_TO_ZERO); require(!signatureStatus.isVerified, ERROR_CONTRACT_ALREADY_SIGNED); signatureStatus.signer = signer_; signatureStatus.saltedHash = saltedHash_; signatureStatus.isSalted = true; } function sign(uint256 salt, bytes calldata signature_) external { require(!signatureStatus.isVerified, ERROR_CONTRACT_ALREADY_SIGNED); require(signatureStatus.isSalted, ERROR_CONTRACT_NOT_SALTED); address expectedSigner = signatureStatus.signer; bytes32 expectedSaltedHash = signatureStatus.saltedHash; require(_msgSender() == expectedSigner, ERROR_INVALID_MSG_SENDER); require(keccak256(abi.encodePacked(salt)) == expectedSaltedHash, ERROR_INCORRECT_SECRET_SALT); require(ECDSA.recover(ECDSA.toEthSignedMessageHash(expectedSaltedHash), signature_) == expectedSigner, ERROR_UNEXPECTED_DATA_SIGNER); signature = signature_; signatureStatus.isVerified = true; emit ContractSigned(expectedSigner, expectedSaltedHash, signature_); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.9; import "./RejectEther.sol"; import "./NiftyPermissions.sol"; import "../interfaces/IERC20.sol"; import "../interfaces/IERC721.sol"; abstract contract Withdrawable is RejectEther, NiftyPermissions { /** * @dev Slither identifies an issue with sending ETH to an arbitrary destianation. * https://github.com/crytic/slither/wiki/Detector-Documentation#functions-that-send-ether-to-arbitrary-destinations * Recommended mitigation is to "Ensure that an arbitrary user cannot withdraw unauthorized funds." * This mitigation has been performed, as only the contract admin can call 'withdrawETH' and they should * verify the recipient should receive the ETH first. */ function withdrawETH(address payable recipient, uint256 amount) external { _requireOnlyValidSender(); require(amount > 0, ERROR_ZERO_ETH_TRANSFER); require(recipient != address(0), "Transfer to zero address"); uint256 currentBalance = address(this).balance; require(amount <= currentBalance, ERROR_INSUFFICIENT_BALANCE); //slither-disable-next-line arbitrary-send (bool success,) = recipient.call{value: amount}(""); require(success, ERROR_WITHDRAW_UNSUCCESSFUL); } function withdrawERC20(address tokenContract, address recipient, uint256 amount) external { _requireOnlyValidSender(); bool success = IERC20(tokenContract).transfer(recipient, amount); require(success, ERROR_WITHDRAW_UNSUCCESSFUL); } function withdrawERC721(address tokenContract, address recipient, uint256 tokenId) external { _requireOnlyValidSender(); IERC721(tokenContract).safeTransferFrom(address(this), recipient, tokenId, ""); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.9; import "./NiftyPermissions.sol"; import "../libraries/Clones.sol"; import "../interfaces/IERC20.sol"; import "../interfaces/IERC721.sol"; import "../interfaces/IERC2981.sol"; import "../interfaces/ICloneablePaymentSplitter.sol"; import "../structs/RoyaltyRecipient.sol"; abstract contract Royalties is NiftyPermissions, IERC2981 { event RoyaltyReceiverUpdated(uint256 indexed niftyType, address previousReceiver, address newReceiver); uint256 constant public BIPS_PERCENTAGE_TOTAL = 10000; // Royalty information mapped by nifty type mapping (uint256 => RoyaltyRecipient) internal royaltyRecipients; function supportsInterface(bytes4 interfaceId) public view virtual override(NiftyPermissions, IERC165) returns (bool) { return interfaceId == type(IERC2981).interfaceId || super.supportsInterface(interfaceId); } function getRoyaltySettings(uint256 niftyType) public view returns (RoyaltyRecipient memory) { return royaltyRecipients[niftyType]; } function setRoyaltyBips(uint256 niftyType, uint256 bips) external { _requireOnlyValidSender(); require(bips <= BIPS_PERCENTAGE_TOTAL, ERROR_BIPS_OVER_100_PERCENT); royaltyRecipients[niftyType].bips = uint16(bips); } function royaltyInfo(uint256 tokenId, uint256 salePrice) public virtual override view returns (address, uint256) { uint256 niftyType = _getNiftyType(tokenId); return royaltyRecipients[niftyType].recipient == address(0) ? (address(0), 0) : (royaltyRecipients[niftyType].recipient, (salePrice * royaltyRecipients[niftyType].bips) / BIPS_PERCENTAGE_TOTAL); } function initializeRoyalties(uint256 niftyType, address splitterImplementation, address[] calldata payees, uint256[] calldata shares) external returns (address) { _requireOnlyValidSender(); address previousReceiver = royaltyRecipients[niftyType].recipient; royaltyRecipients[niftyType].isPaymentSplitter = payees.length > 1; royaltyRecipients[niftyType].recipient = payees.length == 1 ? payees[0] : _clonePaymentSplitter(splitterImplementation, payees, shares); emit RoyaltyReceiverUpdated(niftyType, previousReceiver, royaltyRecipients[niftyType].recipient); return royaltyRecipients[niftyType].recipient; } function getNiftyType(uint256 tokenId) public view returns (uint256) { return _getNiftyType(tokenId); } function getPaymentSplitterByNiftyType(uint256 niftyType) public virtual view returns (address) { return _getPaymentSplitter(niftyType); } function getPaymentSplitterByTokenId(uint256 tokenId) public virtual view returns (address) { return _getPaymentSplitter(_getNiftyType(tokenId)); } function _getNiftyType(uint256 tokenId) internal virtual view returns (uint256) { return 0; } function _clonePaymentSplitter(address splitterImplementation, address[] calldata payees, uint256[] calldata shares_) internal returns (address) { require(IERC165(splitterImplementation).supportsInterface(type(ICloneablePaymentSplitter).interfaceId), ERROR_UNCLONEABLE_REFERENCE_CONTRACT); address clone = payable (Clones.clone(splitterImplementation)); ICloneablePaymentSplitter(clone).initialize(payees, shares_); return clone; } function _getPaymentSplitter(uint256 niftyType) internal virtual view returns (address) { return royaltyRecipients[niftyType].isPaymentSplitter ? royaltyRecipients[niftyType].recipient : address(0); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.9; import "./ERC721Errors.sol"; import "../interfaces/IERC721.sol"; import "../interfaces/IERC721Receiver.sol"; import "../interfaces/IERC721Metadata.sol"; import "../interfaces/IERC721Cloneable.sol"; import "../libraries/Address.sol"; import "../libraries/Context.sol"; import "../libraries/Strings.sol"; import "../utils/ERC165.sol"; import "../utils/GenericErrors.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}. */ abstract contract ERC721 is Context, ERC165, ERC721Errors, GenericErrors, IERC721Metadata, IERC721Cloneable { using Address for address; using Strings for uint256; // Only allow ERC721 to be initialized once bool internal initializedERC721; // Token name string internal tokenName; // Token symbol string internal tokenSymbol; // Base URI For Offchain Metadata string internal baseMetadataURI; // Mapping from token ID to owner address mapping(uint256 => address) internal owners; // Mapping owner address to token count mapping(address => uint256) internal balances; // Mapping from token ID to approved address mapping(uint256 => address) internal tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) internal operatorApprovals; function initializeERC721(string memory name_, string memory symbol_, string memory baseURI_) public override { require(!initializedERC721, ERROR_REINITIALIZATION_NOT_PERMITTED); tokenName = name_; tokenSymbol = symbol_; _setBaseURI(baseURI_); initializedERC721 = true; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || interfaceId == type(IERC721Cloneable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), ERROR_QUERY_FOR_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), ERROR_QUERY_FOR_NONEXISTENT_TOKEN); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return tokenName; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return tokenSymbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), ERROR_QUERY_FOR_NONEXISTENT_TOKEN); string memory uriBase = baseURI(); return bytes(uriBase).length > 0 ? string(abi.encodePacked(uriBase, tokenId.toString())) : ""; } function baseURI() public view virtual returns (string memory) { return baseMetadataURI; } /** * @dev Internal function to set the base URI */ function _setBaseURI(string memory uri) internal { baseMetadataURI = uri; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ownerOf(tokenId); require(to != owner, ERROR_APPROVAL_TO_CURRENT_OWNER); require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()), ERROR_NOT_OWNER_NOR_APPROVED); _approve(owner, to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), ERROR_QUERY_FOR_NONEXISTENT_TOKEN); return tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), ERROR_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 { (address owner, bool isApprovedOrOwner) = _isApprovedOrOwner(_msgSender(), tokenId); require(isApprovedOrOwner, ERROR_NOT_OWNER_NOR_APPROVED); _transfer(owner, 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 { transferFrom(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, data), ERROR_NOT_AN_ERC721_RECEIVER); } /** * @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 (address owner, bool isApprovedOrOwner) { owner = owners[tokenId]; require(owner != address(0), ERROR_QUERY_FOR_NONEXISTENT_TOKEN); isApprovedOrOwner = (spender == owner || tokenApprovals[tokenId] == spender || isApprovedForAll(owner, spender)); } /** * @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); bool isApprovedOrOwner = (_msgSender() == owner || tokenApprovals[tokenId] == _msgSender() || isApprovedForAll(owner, _msgSender())); require(isApprovedOrOwner, ERROR_NOT_OWNER_NOR_APPROVED); // Clear approvals _clearApproval(owner, tokenId); balances[owner] -= 1; _clearOwnership(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 owner, address from, address to, uint256 tokenId) internal virtual { require(owner == from, ERROR_TRANSFER_FROM_INCORRECT_OWNER); require(to != address(0), ERROR_TRANSFER_TO_ZERO_ADDRESS); // Clear approvals from the previous owner _clearApproval(owner, tokenId); balances[from] -= 1; balances[to] += 1; _setOwnership(to, tokenId); emit Transfer(from, to, tokenId); } /** * @dev Equivalent to approving address(0), but more gas efficient * * Emits a {Approval} event. */ function _clearApproval(address owner, uint256 tokenId) internal virtual { delete tokenApprovals[tokenId]; emit Approval(owner, address(0), tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address owner, address to, uint256 tokenId) internal virtual { tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } function _clearOwnership(uint256 tokenId) internal virtual { delete owners[tokenId]; } function _setOwnership(address to, uint256 tokenId) internal virtual { owners[tokenId] = to; } /** * @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 * * @dev Slither identifies an issue with unused return value. * Reference: https://github.com/crytic/slither/wiki/Detector-Documentation#unused-return * This should be a non-issue. It is the standard OpenZeppelin implementation which has been heavily used and audited. */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) internal 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(ERROR_NOT_AN_ERC721_RECEIVER); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } } // SPDX-License-Identifier: MIT pragma solidity 0.8.9; abstract contract ERC721Errors { string internal constant ERROR_QUERY_FOR_ZERO_ADDRESS = "Query for zero address"; string internal constant ERROR_QUERY_FOR_NONEXISTENT_TOKEN = "Token does not exist"; string internal constant ERROR_APPROVAL_TO_CURRENT_OWNER = "Current owner approval"; string internal constant ERROR_APPROVE_TO_CALLER = "Approve to caller"; string internal constant ERROR_NOT_OWNER_NOR_APPROVED = "Not owner nor approved"; string internal constant ERROR_NOT_AN_ERC721_RECEIVER = "Not an ERC721Receiver"; string internal constant ERROR_TRANSFER_FROM_INCORRECT_OWNER = "Transfer from incorrect owner"; string internal constant ERROR_TRANSFER_TO_ZERO_ADDRESS = "Transfer to zero address"; string internal constant ERROR_ALREADY_MINTED = "Token already minted"; string internal constant ERROR_NO_TOKENS_MINTED = "No tokens minted"; } // SPDX-License-Identifier: MIT pragma solidity 0.8.9; import "./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.9; /** * @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.9; 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.9; import "./IERC721.sol"; interface IERC721Cloneable is IERC721 { function initializeERC721(string calldata name_, string calldata symbol_, string calldata baseURI_) external; } // SPDX-License-Identifier: MIT pragma solidity 0.8.9; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity 0.8.9; /** * @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.9; /** * @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.9; import "../interfaces/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.9; abstract contract GenericErrors { string internal constant ERROR_INPUT_ARRAY_EMPTY = "Input array empty"; string internal constant ERROR_INPUT_ARRAY_SIZE_MISMATCH = "Input array size mismatch"; string internal constant ERROR_INVALID_MSG_SENDER = "Invalid msg.sender"; string internal constant ERROR_UNEXPECTED_DATA_SIGNER = "Unexpected data signer"; string internal constant ERROR_INSUFFICIENT_BALANCE = "Insufficient balance"; string internal constant ERROR_WITHDRAW_UNSUCCESSFUL = "Withdraw unsuccessful"; string internal constant ERROR_CONTRACT_IS_FINALIZED = "Contract is finalized"; string internal constant ERROR_CANNOT_CHANGE_DEFAULT_OWNER = "Cannot change default owner"; string internal constant ERROR_UNCLONEABLE_REFERENCE_CONTRACT = "Uncloneable reference contract"; string internal constant ERROR_BIPS_OVER_100_PERCENT = "Bips over 100%"; string internal constant ERROR_NO_ROYALTY_RECEIVER = "No royalty receiver"; string internal constant ERROR_REINITIALIZATION_NOT_PERMITTED = "Re-initialization not permitted"; string internal constant ERROR_ZERO_ETH_TRANSFER = "Zero ETH Transfer"; } // SPDX-License-Identifier: MIT pragma solidity 0.8.9; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity 0.8.9; import "./ERC165.sol"; import "./GenericErrors.sol"; import "../interfaces/INiftyEntityCloneable.sol"; import "../interfaces/INiftyRegistry.sol"; import "../libraries/Context.sol"; abstract contract NiftyPermissions is Context, ERC165, GenericErrors, INiftyEntityCloneable { event AdminTransferred(address indexed previousAdmin, address indexed newAdmin); // Only allow Nifty Entity to be initialized once bool internal initializedNiftyEntity; // If address(0), use enable Nifty Gateway permissions - otherwise, specifies the address with permissions address public admin; // To prevent a mistake, transferring admin rights will be a two step process // First, the current admin nominates a new admin // Second, the nominee accepts admin address public nominatedAdmin; // Nifty Registry Contract INiftyRegistry internal permissionsRegistry; function initializeNiftyEntity(address niftyRegistryContract_) public { require(!initializedNiftyEntity, ERROR_REINITIALIZATION_NOT_PERMITTED); permissionsRegistry = INiftyRegistry(niftyRegistryContract_); initializedNiftyEntity = true; } function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(INiftyEntityCloneable).interfaceId || super.supportsInterface(interfaceId); } function renounceAdmin() external { _requireOnlyValidSender(); _transferAdmin(address(0)); } function nominateAdmin(address nominee) external { _requireOnlyValidSender(); nominatedAdmin = nominee; } function acceptAdmin() external { address nominee = nominatedAdmin; require(_msgSender() == nominee, ERROR_INVALID_MSG_SENDER); _transferAdmin(nominee); } function _requireOnlyValidSender() internal view { address currentAdmin = admin; if(currentAdmin == address(0)) { require(permissionsRegistry.isValidNiftySender(_msgSender()), ERROR_INVALID_MSG_SENDER); } else { require(_msgSender() == currentAdmin, ERROR_INVALID_MSG_SENDER); } } function _transferAdmin(address newAdmin) internal { address oldAdmin = admin; admin = newAdmin; delete nominatedAdmin; emit AdminTransferred(oldAdmin, newAdmin); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/cryptography/ECDSA.sol) pragma solidity 0.8.9; import "./Strings.sol"; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { enum RecoverError { NoError, InvalidSignature, InvalidSignatureLength, InvalidSignatureS, InvalidSignatureV } function _throwError(RecoverError error) private pure { if (error == RecoverError.NoError) { return; // no error: do nothing } else if (error == RecoverError.InvalidSignature) { revert("ECDSA: invalid signature"); } else if (error == RecoverError.InvalidSignatureLength) { revert("ECDSA: invalid signature length"); } else if (error == RecoverError.InvalidSignatureS) { revert("ECDSA: invalid signature 's' value"); } else if (error == RecoverError.InvalidSignatureV) { revert("ECDSA: invalid signature 'v' value"); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature` or error string. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. * * Documentation for signature generation: * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js] * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers] * * _Available since v4.3._ */ function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) { // Check the signature length // - case 65: r,s,v signature (standard) // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._ if (signature.length == 65) { bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return tryRecover(hash, v, r, s); } else if (signature.length == 64) { bytes32 r; bytes32 vs; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) vs := mload(add(signature, 0x40)) } return tryRecover(hash, r, vs); } else { return (address(0), RecoverError.InvalidSignatureLength); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, signature); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately. * * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures] * * _Available since v4.3._ */ function tryRecover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address, RecoverError) { bytes32 s; 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 Message, created from `s`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s)); } /** * @dev Returns an Ethereum Signed Typed Data, created from a * `domainSeparator` and a `structHash`. This produces hash corresponding * to the one signed with the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] * JSON-RPC method as part of EIP-712. * * See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.9; struct SignatureStatus { bool isSalted; bool isVerified; address signer; bytes32 saltedHash; } // SPDX-License-Identifier: MIT pragma solidity 0.8.9; import "./IERC165.sol"; interface INiftyEntityCloneable is IERC165 { function initializeNiftyEntity(address niftyRegistryContract_) external; } // SPDX-License-Identifier: MIT pragma solidity 0.8.9; interface INiftyRegistry { function isValidNiftySender(address sendingKey) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity 0.8.9; /** * @title A base contract that may be inherited in order to protect a contract from having its fallback function * invoked and to block the receipt of ETH by a contract. * @author Nathan Gang * @notice This contract bestows on inheritors the ability to block ETH transfers into the contract * @dev ETH may still be forced into the contract - it is impossible to block certain attacks, but this protects from accidental ETH deposits */ // For more info, see: "https://medium.com/@alexsherbuck/two-ways-to-force-ether-into-a-contract-1543c1311c56" abstract contract RejectEther { /** * @dev For most contracts, it is safest to explicitly restrict the use of the fallback function * This would generally be invoked if sending ETH to this contract with a 'data' value provided */ fallback() external payable { revert("Fallback function not permitted"); } /** * @dev This is the standard path where ETH would land if sending ETH to this contract without a 'data' value * In our case, we don't want our contract to receive ETH, so we restrict it here */ receive() external payable { revert("Receiving ETH not permitted"); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.9; /** * @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.9; /** * @dev https://eips.ethereum.org/EIPS/eip-1167[EIP 1167] is a standard for * deploying minimal proxy contracts, also known as "clones". * * > To simply and cheaply clone contract functionality in an immutable way, this standard specifies * > a minimal bytecode implementation that delegates all calls to a known, fixed address. * * The library includes functions to deploy a proxy using either `create` (traditional deployment) or `create2` * (salted deterministic deployment). It also includes functions to predict the addresses of clones deployed using the * deterministic method. * */ library Clones { /** * @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`. * * This function uses the create opcode, which should never revert. */ function clone(address implementation) internal returns (address instance) { assembly { let ptr := mload(0x40) mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(ptr, 0x14), shl(0x60, implementation)) mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) instance := create(0, ptr, 0x37) } require(instance != address(0), "ERC1167: create failed"); } /** * @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`. * * This function uses the create2 opcode and a `salt` to deterministically deploy * the clone. Using the same `implementation` and `salt` multiple time will revert, since * the clones cannot be deployed twice at the same address. */ function cloneDeterministic(address implementation, bytes32 salt) internal returns (address instance) { assembly { let ptr := mload(0x40) mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(ptr, 0x14), shl(0x60, implementation)) mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) instance := create2(0, ptr, 0x37, salt) } require(instance != address(0), "ERC1167: create2 failed"); } /** * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}. */ function predictDeterministicAddress( address implementation, bytes32 salt, address deployer ) internal pure returns (address predicted) { assembly { let ptr := mload(0x40) mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(ptr, 0x14), shl(0x60, implementation)) mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf3ff00000000000000000000000000000000) mstore(add(ptr, 0x38), shl(0x60, deployer)) mstore(add(ptr, 0x4c), salt) mstore(add(ptr, 0x6c), keccak256(ptr, 0x37)) predicted := keccak256(add(ptr, 0x37), 0x55) } } /** * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}. */ function predictDeterministicAddress(address implementation, bytes32 salt) internal view returns (address predicted) { return predictDeterministicAddress(implementation, salt, address(this)); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.9; import "./IERC165.sol"; /** * @dev Interface for the NFT Royalty Standard. * * A standardized way to retrieve royalty payment information for non-fungible tokens (NFTs) to enable universal * support for royalty payments across all NFT marketplaces and ecosystem participants. * */ interface IERC2981 is IERC165 { /** * @dev Returns how much royalty is owed and to whom, based on a sale price that may be denominated in any unit of * exchange. The royalty amount is denominated and should be payed in that same unit of exchange. */ function royaltyInfo(uint256 tokenId, uint256 salePrice) external view returns (address receiver, uint256 royaltyAmount); } // SPDX-License-Identifier: MIT pragma solidity 0.8.9; import "./IERC165.sol"; import "../libraries/SafeERC20.sol"; interface ICloneablePaymentSplitter is IERC165 { event PayeeAdded(address account, uint256 shares); event PaymentReleased(address to, uint256 amount); event ERC20PaymentReleased(IERC20 indexed token, address to, uint256 amount); event PaymentReceived(address from, uint256 amount); function initialize(address[] calldata payees, uint256[] calldata shares_) external; function totalShares() external view returns (uint256); function totalReleased() external view returns (uint256); function totalReleased(IERC20 token) external view returns (uint256); function shares(address account) external view returns (uint256); function released(address account) external view returns (uint256); function released(IERC20 token, address account) external view returns (uint256); function payee(uint256 index) external view returns (address); function release(address payable account) external; function release(IERC20 token, address account) external; function pendingPayment(address account) external view returns (uint256); function pendingPayment(IERC20 token, address account) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.8.9; struct RoyaltyRecipient { bool isPaymentSplitter; // 1 byte uint16 bips; // 2 bytes address recipient; // 20 bytes } // SPDX-License-Identifier: MIT pragma solidity 0.8.9; import "../interfaces/IERC20.sol"; import "./Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev 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 See {IERC721-getApproved}./
function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), ERROR_QUERY_FOR_NONEXISTENT_TOKEN); return tokenApprovals[tokenId]; }
5,974,291
[ 1, 9704, 288, 45, 654, 39, 27, 5340, 17, 588, 31639, 5496, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 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, 336, 31639, 12, 11890, 5034, 1147, 548, 13, 1071, 1476, 5024, 3849, 1135, 261, 2867, 13, 288, 203, 3639, 2583, 24899, 1808, 12, 2316, 548, 3631, 5475, 67, 10753, 67, 7473, 67, 3993, 11838, 2222, 67, 8412, 1769, 203, 3639, 327, 1147, 12053, 4524, 63, 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 ]
// File: contracts/noteUSDStorage.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; contract noteUSDStorage { /** WARNING: NEVER RE-ORDER VARIABLES! * Always double-check that new variables are added APPEND-ONLY. * Re-ordering variables can permanently BREAK the deployed proxy contract. */ bool public initialized; mapping(address => uint256) internal _balances; mapping(address => mapping(address => uint256)) internal _allowances; mapping(address => bool) public blacklist; uint256 internal _totalSupply; string public constant name = "noteUSD"; string public constant symbol = "noteUSD"; uint256 public multiplier; uint8 public constant decimals = 18; address public admin; uint256 internal constant deci = 1e18; bool internal getpause; } // File: contracts/Proxiable.sol pragma solidity ^0.6.0; contract Proxiable { // Code position in storage is keccak256("PROXIABLE") = "0xc5f16f0fcc639fa48a6947836d9850f504798523bf8c9a3a87d5876cf622bcf7" function updateCodeAddress(address newAddress) internal { require( bytes32( 0xc5f16f0fcc639fa48a6947836d9850f504798523bf8c9a3a87d5876cf622bcf7 ) == Proxiable(newAddress).proxiableUUID(), "Not compatible" ); assembly { // solium-disable-line sstore( 0xc5f16f0fcc639fa48a6947836d9850f504798523bf8c9a3a87d5876cf622bcf7, newAddress ) } } function proxiableUUID() public pure returns (bytes32) { return 0xc5f16f0fcc639fa48a6947836d9850f504798523bf8c9a3a87d5876cf622bcf7; } } // File: contracts/noteUSD.sol pragma solidity ^0.6.0; 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 whBTCer 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 whBTCer the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this mBTCod 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/BTCereum/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 whBTCer 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 Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor() internal {} function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/BTCereum/solidity/issues/2691 return msg.data; } } library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } contract LibraryLock is noteUSDStorage { // Ensures no one can manipulate the Logic Contract once it is deployed. // PARITY WALLET HACK PREVENTION modifier delegatedOnly() { require( initialized == true, "The library is locked. No direct 'call' is allowed." ); _; } function initialize() internal { initialized = true; } } contract noteUSD is noteUSDStorage, Context, IERC20, Proxiable, LibraryLock { using SafeMath for uint256; event fTokenBlacklist(address indexed account, bool blocked); event ChangeMultiplier(uint256 multiplier); event AdminChanged(address admin); event CodeUpdated(address indexed newCode); function initialize(uint256 _totalsupply) public { require(!initialized, "The library has already been initialized."); LibraryLock.initialize(); admin = msg.sender; multiplier = 1 * deci; _totalSupply = _totalsupply; _balances[msg.sender] = _totalSupply; } /// @dev Update the logic contract code function updateCode(address newCode) external onlyAdmin delegatedOnly { updateCodeAddress(newCode); emit CodeUpdated(newCode); } function setMultiplier(uint256 _multiplier) external onlyAdmin() ispaused() { require( _multiplier > multiplier, "the multiplier should be greater than previous multiplier" ); multiplier = _multiplier; emit ChangeMultiplier(multiplier); } function totalSupply() public override view returns (uint256) { return _totalSupply.mul(multiplier).div(deci); } function setTotalSupply(uint256 inputTotalsupply) external onlyAdmin() { require( inputTotalsupply > totalSupply(), "the input total supply is not greater than present total supply" ); multiplier = (inputTotalsupply.mul(deci)).div(_totalSupply); emit ChangeMultiplier(multiplier); } function balanceOf(address account) public override view returns (uint256) { uint256 externalAmt; externalAmt = _balances[account].mul(multiplier).div(deci); return externalAmt; } function transfer(address recipient, uint256 amount) public virtual override Notblacklist(msg.sender) Notblacklist(recipient) ispaused() returns (bool) { uint256 internalAmt; uint256 externalAmt = amount; internalAmt = (amount.mul(deci)).div(multiplier); _transfer(msg.sender, recipient, externalAmt); return true; } function allowance(address owner, address spender) public virtual override view returns (uint256) { uint256 internalAmt; uint256 maxapproval = 115792089237316195423570985008687907853269984665640564039457584007913129639935; maxapproval = maxapproval.div(multiplier).mul(deci); if(_allowances[owner][spender] > maxapproval){ internalAmt = 115792089237316195423570985008687907853269984665640564039457584007913129639935; }else{ internalAmt = (_allowances[owner][spender]).mul(multiplier).div(deci); } return internalAmt; } function approve(address spender, uint256 amount) public virtual override Notblacklist(spender) Notblacklist(msg.sender) ispaused() returns (bool) { uint256 internalAmt; uint256 externalAmt = amount; _approve(msg.sender, spender, externalAmt); 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 Notblacklist(spender) Notblacklist(msg.sender) ispaused() returns (bool) { uint256 externalAmt = allowance(_msgSender(),spender) ; _approve(_msgSender(), spender, externalAmt.add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public Notblacklist(spender) Notblacklist(msg.sender) ispaused() returns (bool) { uint256 externalAmt = allowance(_msgSender(),spender) ; _approve(_msgSender(), spender, externalAmt.sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function transferFrom( address sender, address recipient, uint256 amount ) public virtual override Notblacklist(sender) Notblacklist(msg.sender) Notblacklist(recipient) ispaused() returns (bool) { uint256 externalAmt = allowance(sender,_msgSender()); _transfer(sender, recipient, amount); _approve( sender, _msgSender(), externalAmt.sub( amount, "ERC20: transfer amount exceeds allowance" ) ); return true; } function _transfer( address sender, address recipient, uint256 externalAmt ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); uint256 internalAmt = externalAmt.mul(deci).div(multiplier); _balances[sender] = _balances[sender].sub( internalAmt, "ERC20: transfer internalAmt exceeds balance" ); _balances[recipient] = _balances[recipient].add(internalAmt); emit Transfer(sender, recipient, externalAmt); } function mint(address mintTo, uint256 amount) public virtual onlyAdmin() ispaused() returns (bool) { uint256 externalAmt = amount; uint256 internalAmt = externalAmt.mul(deci).div(multiplier); _mint(mintTo, internalAmt, externalAmt); return true; } function _mint( address account, uint256 internalAmt, uint256 externalAmt ) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(internalAmt); _balances[account] = _balances[account].add(internalAmt); emit Transfer(address(0), account, externalAmt); } function burn(address burnFrom, uint256 amount) public virtual onlyAdmin() ispaused() returns (bool) { uint256 internalAmt; uint256 externalAmt = amount; internalAmt = externalAmt.mul(deci).div(multiplier); _burn(burnFrom, internalAmt, externalAmt); return true; } function _burn( address account, uint256 internalAmt, uint256 externalAmt ) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub( internalAmt, "ERC20: burn internaAmt exceeds balance" ); _totalSupply = _totalSupply.sub(internalAmt); emit Transfer(account, address(0), externalAmt); } function _approve( address owner, address spender, uint256 externalAmt ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); uint256 internalAmt; uint256 maxapproval = 115792089237316195423570985008687907853269984665640564039457584007913129639935; maxapproval = maxapproval.div(multiplier).mul(deci); if(externalAmt > maxapproval){ internalAmt = 115792089237316195423570985008687907853269984665640564039457584007913129639935; }else{ internalAmt = externalAmt.mul(deci).div(multiplier); } _allowances[owner][spender] = internalAmt; emit Approval(owner, spender,externalAmt); } function TransferOwnerShip(address account) public onlyAdmin() { require(account != address(0), "account cannot be zero address"); require(msg.sender == admin, "you are not the admin"); admin = account; emit AdminChanged(admin); } function pause() external onlyAdmin() { getpause = true; } function unpause() external onlyAdmin() { getpause = false; } // pause unpause modifier ispaused() { require(getpause == false, "the contract is paused"); _; } modifier onlyAdmin() { require(msg.sender == admin, "you are not the admin"); _; } function AddToBlacklist(address account) external onlyAdmin() { blacklist[account] = true; emit fTokenBlacklist(account, true); } function RemoveFromBlacklist(address account) external onlyAdmin() { blacklist[account] = false; emit fTokenBlacklist(account, false); } modifier Notblacklist(address account) { require(!blacklist[account], "account is blacklisted"); _; } }
solium-disable-line
function updateCodeAddress(address newAddress) internal { require( bytes32( 0xc5f16f0fcc639fa48a6947836d9850f504798523bf8c9a3a87d5876cf622bcf7 ) == Proxiable(newAddress).proxiableUUID(), "Not compatible" ); assembly { sstore( 0xc5f16f0fcc639fa48a6947836d9850f504798523bf8c9a3a87d5876cf622bcf7, newAddress ) } }
567,435
[ 1, 18281, 5077, 17, 8394, 17, 1369, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1089, 1085, 1887, 12, 2867, 394, 1887, 13, 2713, 288, 203, 3639, 2583, 12, 203, 5411, 1731, 1578, 12, 203, 7734, 374, 6511, 25, 74, 2313, 74, 20, 74, 952, 21607, 507, 8875, 69, 8148, 24, 8285, 5718, 72, 10689, 3361, 74, 25, 3028, 7235, 7140, 4366, 17156, 28, 71, 29, 69, 23, 69, 11035, 72, 8204, 6669, 8522, 26, 3787, 70, 8522, 27, 203, 5411, 262, 422, 1186, 92, 2214, 12, 2704, 1887, 2934, 20314, 2214, 5562, 9334, 203, 5411, 315, 1248, 7318, 6, 203, 3639, 11272, 203, 3639, 19931, 288, 203, 5411, 272, 2233, 12, 203, 7734, 374, 6511, 25, 74, 2313, 74, 20, 74, 952, 21607, 507, 8875, 69, 8148, 24, 8285, 5718, 72, 10689, 3361, 74, 25, 3028, 7235, 7140, 4366, 17156, 28, 71, 29, 69, 23, 69, 11035, 72, 8204, 6669, 8522, 26, 3787, 70, 8522, 27, 16, 203, 7734, 394, 1887, 203, 5411, 262, 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 ]
//Address: 0xc5bfCb042f5bc5402D7F6980F17695bf8147Dfb0 //Contract name: PeralToken //Balance: 0 Ether //Verification Date: 1/8/2018 //Transacion Count: 7 // CODE STARTS HERE pragma solidity ^0.4.16; contract Owned { address public owner; function Owned() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address newOwner) onlyOwner public { owner = newOwner; } } interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public; } // Abstract contract for the full ERC 20 Token standard // https://github.com/ethereum/EIPs/issues/20 contract TokenERC20 { // Public variables of the token string public name; string public symbol; uint8 public decimals = 18; // 18 decimals is the strongly suggested default, avoid changing it uint256 public constant TOKEN_UNIT = 10 ** 18; uint256 internal _totalSupply; mapping (address => uint256) internal _balanceOf; mapping (address => mapping (address => uint256)) internal _allowance; // This generates a public event on the blockchain that will notify clients event Transfer(address indexed from, address indexed to, uint256 value); // This notifies clients about the amount burnt event Burn(address indexed from, uint256 value); /** * Constrctor function * * Initializes contract with initial supply tokens to the creator of the contract */ function TokenERC20( uint256 initialSupply, string tokenName, string tokenSymbol ) public { _totalSupply = initialSupply * TOKEN_UNIT; // Update total supply with the decimal amount _balanceOf[msg.sender] = _totalSupply; // Give the creator all initial tokens name = tokenName; // Set the name for display purposes symbol = tokenSymbol; // Set the symbol for display purposes } function totalSupply() constant public returns (uint256) { return _totalSupply; } function balanceOf(address src) constant public returns (uint256) { return _balanceOf[src]; } function allowance(address src, address guy) constant public returns (uint256) { return _allowance[src][guy]; } /** * Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { // Prevent transfer to 0x0 address. Use burn() instead require(_to != 0x0); // Check if the sender has enough require(_balanceOf[_from] >= _value); // Check for overflows require(_balanceOf[_to] + _value > _balanceOf[_to]); // Save this for an assertion in the future uint previousBalances = _balanceOf[_from] + _balanceOf[_to]; // Subtract from the sender _balanceOf[_from] -= _value; // Add the same to the recipient _balanceOf[_to] += _value; Transfer(_from, _to, _value); // Asserts are used to use static analysis to find bugs in your code. They should never fail assert(_balanceOf[_from] + _balanceOf[_to] == previousBalances); } /** * Transfer tokens * * Send `_value` tokens to `_to` from your account * * @param _to The address of the recipient * @param _value the amount to send */ function transfer(address _to, uint256 _value) public { _transfer(msg.sender, _to, _value); } /** * Transfer tokens from other address * * Send `_value` tokens to `_to` in behalf of `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= _allowance[_from][msg.sender]); // Check allowance _allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } /** * Set allowance for other address * * Allows `_spender` to spend no more than `_value` tokens in your behalf * * @param _spender The address authorized to spend * @param _value the max amount they can spend */ function approve(address _spender, uint256 _value) public returns (bool success) { _allowance[msg.sender][_spender] = _value; return true; } /** * Set allowance for other address and notify * * Allows `_spender` to spend no more than `_value` tokens in your behalf, and then ping the contract about it * * @param _spender The address authorized to spend * @param _value the max amount they can spend * @param _extraData some extra information to send to the approved contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } /** * Destroy tokens * * Remove `_value` tokens from the system irreversibly * * @param _value the amount of money to burn */ function burn(uint256 _value) public returns (bool success) { require(_balanceOf[msg.sender] >= _value); // Check if the sender has enough _balanceOf[msg.sender] -= _value; // Subtract from the sender _totalSupply -= _value; // Updates totalSupply Burn(msg.sender, _value); return true; } /** * Destroy tokens from other account * * Remove `_value` tokens from the system irreversibly on behalf of `_from`. * * @param _from the address of the sender * @param _value the amount of money to burn */ function burnFrom(address _from, uint256 _value) public returns (bool success) { require(_balanceOf[_from] >= _value); // Check if the targeted balance is enough require(_value <= _allowance[_from][msg.sender]); // Check allowance _balanceOf[_from] -= _value; // Subtract from the targeted balance _allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance _totalSupply -= _value; // Update totalSupply Burn(_from, _value); return true; } } /** * Math operations with safety checks */ library SafeMath { function mul(uint a, uint b) internal pure returns (uint) { uint c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint a, uint b) internal pure returns (uint) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint a, uint b) internal pure returns (uint) { assert(b <= a); return a - b; } function add(uint a, uint b) internal pure returns (uint) { uint c = a + b; assert(c >= a); return c; } function max64(uint64 a, uint64 b) internal pure returns (uint64) { return a >= b ? a : b; } function min64(uint64 a, uint64 b) internal pure returns (uint64) { return a < b ? a : b; } function max256(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } function min256(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } } contract PeralToken is Owned, TokenERC20 { using SafeMath for uint256; /* This generates a public event on the blockchain that will notify clients */ event FrozenFunds(address target, bool frozen); mapping (address => bool) public frozenAccount; mapping (address => bool) private allowMint; bool _closeSale = false; /* Initializes contract with initial supply tokens to the creator of the contract */ function PeralToken(uint remainAmount,string tokenName,string tokenSymbol) TokenERC20(remainAmount, tokenName, tokenSymbol) public { } /* Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { require (_to != 0x0); // Prevent transfer to 0x0 address. Use burn() instead require (_balanceOf[_from] >= _value); // Check if the sender has enough require (_balanceOf[_to].add(_value) > _balanceOf[_to]); // Check for overflows require(_closeSale); require(!frozenAccount[_from]); // Check if sender is frozen require(!frozenAccount[_to]); // Check if recipient is frozen _balanceOf[_from] = _balanceOf[_from].sub(_value); // Subtract from the sender _balanceOf[_to] = _balanceOf[_to].add(_value); // Add the same to the recipient Transfer(_from, _to, _value); } /// @notice Create `mintedAmount` tokens and send it to `target` /// @param target Address to receive the tokens /// @param mintedAmount the amount of tokens it will receive function mintToken(address target, uint256 mintedAmount) public { require(allowMint[msg.sender]); _balanceOf[target] = _balanceOf[target].add(mintedAmount); _totalSupply = _totalSupply.add(mintedAmount); Transfer(0, this, mintedAmount); Transfer(this, target, mintedAmount); } /// @notice Create `mintedAmount` tokens and send it to `target` /// @param target Address to receive the tokens /// @param mintedAmount the amount of tokens it will receive function mintTokenWithUnit(address target, uint256 mintedAmount) public { require(allowMint[msg.sender]); uint256 amount = mintedAmount.mul(TOKEN_UNIT); _balanceOf[target] = _balanceOf[target].add(amount); _totalSupply = _totalSupply.add(amount); Transfer(0, this, mintedAmount); Transfer(this, target, mintedAmount); } /// @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; FrozenFunds(target, freeze); } function setMintContactAddress(address _contactAddress) onlyOwner public { allowMint[_contactAddress] = true; } function disableContactMint(address _contactAddress) onlyOwner public { allowMint[_contactAddress] = false; } function closeSale(bool close) onlyOwner public { _closeSale = close; } }
This generates a public event on the blockchain that will notify clients */ Initializes contract with initial supply tokens to the creator of the contract */
function PeralToken(uint remainAmount,string tokenName,string tokenSymbol) TokenERC20(remainAmount, tokenName, tokenSymbol) public { }
14,024,460
[ 1, 2503, 6026, 279, 1071, 871, 603, 326, 16766, 716, 903, 5066, 7712, 342, 10188, 3128, 6835, 598, 2172, 14467, 2430, 358, 326, 11784, 434, 326, 6835, 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 ]
[ 1, 1, 1, 1, 1, 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, 5722, 287, 1345, 12, 11890, 7232, 6275, 16, 1080, 1147, 461, 16, 1080, 1147, 5335, 13, 3155, 654, 39, 3462, 12, 2764, 530, 6275, 16, 1147, 461, 16, 1147, 5335, 13, 1071, 288, 203, 540, 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 ]
./full_match/4/0x25642a458ef3D0F4403A037e93B02E63A0C9DcD7/sources/browser/pxt_v1.sol
SELL_PRICE provided is WITHOUT BIDDING_PRICE_RATIO_PERCENT INCLUDED, take that into account before transaction
function SetSell(uint block_id, uint32 eth_sell_price) public {
821,227
[ 1, 1090, 4503, 67, 7698, 1441, 2112, 353, 13601, 5069, 605, 23513, 1360, 67, 7698, 1441, 67, 54, 789, 4294, 67, 3194, 19666, 2120, 11686, 7660, 16, 4862, 716, 1368, 2236, 1865, 2492, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1000, 55, 1165, 12, 11890, 1203, 67, 350, 16, 2254, 1578, 13750, 67, 87, 1165, 67, 8694, 13, 1071, 288, 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 ]
// Copyright 2021 - See NOTICE file for copyright holders. // // 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. // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "./perun-eth-contracts/contracts/Channel.sol"; import "./App.sol"; import "./CollateralAssetHolder.sol"; /** * @notice CollateralApp is a channel app that enables collateralized channels. * A collateralized channel is a partially funded channel that is backed by * collateral. The channel balances are tracked as signed integers in the * appData field of the channel state. A positive asset balance corresponds to a * credit and a negative balance corresponds to a debit. */ contract CollateralApp is App { // The adjudicator that is allowed to call this contract. address public adjudicator; /** * @notice The onlyAdjudicator modifier ensures that the decorated function * can only be called from the defined app contract. */ modifier onlyAdjudicator { require(msg.sender == adjudicator, "can only be called by the defined adjudicator"); // solhint-disable-line reason-string _; } /** * @notice Sets the adjudicator contract that is allowed to call this * contract. */ constructor(address _adjudicator) { adjudicator = _adjudicator; } /** * @notice onConclude is called when an app channel is concluded. It settles * the channel balances of each asset against the asset holdings. */ function onConclude( Channel.Params calldata params, Channel.State calldata state) external override onlyAdjudicator { int256[][] memory bals = abi.decode(state.appData, (int256[][])); address[] memory assets = state.outcome.assets; for (uint256 i = 0; i < assets.length; i++) { CollateralAssetHolder a = CollateralAssetHolder(assets[i]); a.settleChannel(state.channelID, bals[i], params.participants); } } /** * @notice ValidTransition checks if there was a valid transition between two states. * @param params The parameters of the channel. * @param from The current state. * @param to The potenrial next state. * @param actorIdx Index of the actor who signed this transition. */ function validTransition( Channel.Params calldata params, Channel.State calldata from, Channel.State calldata to, uint256 actorIdx) external pure override { // We do not allow on-chain progression of collateralized channels. require(false, "on-chain progression prohibited"); } }
solhint-disable-line reason-string
require(msg.sender == adjudicator, "can only be called by the defined adjudicator");
13,026,792
[ 1, 18281, 11317, 17, 8394, 17, 1369, 3971, 17, 1080, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 2583, 12, 3576, 18, 15330, 422, 8307, 1100, 8844, 16, 315, 4169, 1338, 506, 2566, 635, 326, 2553, 8307, 1100, 8844, 8863, 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 ]
./full_match/4/0xCb444455b6b51CD1aa99681E09C430Ef14CAB2d7/sources/Scrambles.sol
* @notice returns the attributes part of the json string. @param tokenId the token to generate traits for./
function getTraits(uint256 tokenId) public view returns (string memory) { if(!revealed){ } string[9] memory cols; uint256[6] memory colTotals; for(uint8 j = 1; j < 10; j++) { string memory col = getColour(j,getSeed(tokenId)); cols[j-1] =col; for (uint i = 0; i<6; i++) { string memory colToCheck = colours[getPaletteIndex(getSeed(tokenId))][i]; if(keccak256(abi.encodePacked(col)) == keccak256(abi.encodePacked(colToCheck))) { colTotals[i]++; } } } uint8 connections = 0; connections += checkConnection(cols,0,1); connections += checkConnection(cols,1,2); connections += checkConnection(cols,0,3); connections += checkConnection(cols,1,4); connections += checkConnection(cols,2,5); connections += checkConnection(cols,3,4); connections += checkConnection(cols,4,5); connections += checkConnection(cols,3,6); connections += checkConnection(cols,4,7); connections += checkConnection(cols,5,8); connections += checkConnection(cols,6,7); connections += checkConnection(cols,7,8); uint256 totalCols = 0; for (uint256 h=0; h<6; h++){ if(colTotals[h] > 0) { totalCols++; } } string memory traits = '"attributes": ['; string memory newTrait = ""; for (uint256 h = 0; h < 6; h++){ string memory traitName = string(abi.encodePacked('Colour #', h.toString())); newTrait = getPropertyString(traitName,colTotals[h]); traits = string(abi.encodePacked(traits,newTrait,",")); } newTrait = getPropertyString("Connections",connections); traits = string(abi.encodePacked(traits,newTrait,",")); newTrait = getPropertyString("Palette",getPaletteIndex(getSeed(tokenId))); traits = string(abi.encodePacked(traits,newTrait,",")); newTrait = getPropertyString("Total Colours",totalCols); traits = string(abi.encodePacked(traits,newTrait,",")); newTrait = getLevelString("Background Colour",expandRandom(getSeed(tokenId),10) % 256); traits = string(abi.encodePacked(traits,newTrait,",")); newTrait = getLevelString("Shirt Colour",expandRandom(getSeed(tokenId),11) % 256); traits = string(abi.encodePacked(traits,newTrait,"]")); return traits; }
773,346
[ 1, 6154, 326, 1677, 1087, 434, 326, 1163, 533, 18, 225, 1147, 548, 326, 1147, 358, 2103, 18370, 364, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 336, 30370, 12, 11890, 5034, 1147, 548, 13, 1071, 1476, 1135, 261, 1080, 3778, 13, 203, 565, 288, 203, 3639, 309, 12, 5, 266, 537, 18931, 15329, 203, 3639, 289, 203, 203, 3639, 533, 63, 29, 65, 3778, 5347, 31, 203, 3639, 2254, 5034, 63, 26, 65, 3778, 645, 31025, 31, 203, 203, 3639, 364, 12, 11890, 28, 525, 273, 404, 31, 525, 411, 1728, 31, 525, 27245, 288, 203, 2398, 203, 5411, 533, 3778, 645, 273, 25440, 477, 12, 78, 16, 588, 12702, 12, 2316, 548, 10019, 203, 5411, 5347, 63, 78, 17, 21, 65, 273, 1293, 31, 7010, 203, 5411, 364, 261, 11890, 277, 273, 374, 31, 277, 32, 26, 31, 277, 27245, 203, 5411, 288, 203, 7734, 533, 3778, 645, 18126, 273, 645, 4390, 63, 588, 25863, 1016, 12, 588, 12702, 12, 2316, 548, 3719, 6362, 77, 15533, 203, 7734, 309, 12, 79, 24410, 581, 5034, 12, 21457, 18, 3015, 4420, 329, 12, 1293, 3719, 422, 417, 24410, 581, 5034, 12, 21457, 18, 3015, 4420, 329, 12, 1293, 18126, 20349, 203, 7734, 288, 203, 10792, 645, 31025, 63, 77, 3737, 15, 31, 203, 7734, 289, 203, 5411, 289, 203, 3639, 289, 203, 203, 3639, 2254, 28, 5921, 273, 374, 31, 203, 203, 3639, 5921, 1011, 866, 1952, 12, 6842, 16, 20, 16, 21, 1769, 203, 3639, 5921, 1011, 866, 1952, 12, 6842, 16, 21, 16, 22, 1769, 203, 3639, 5921, 1011, 866, 1952, 12, 6842, 16, 20, 16, 23, 1769, 203, 3639, 5921, 1011, 866, 1952, 12, 6842, 16, 2 ]
pragma solidity 0.6.7; import "./../openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./../openzeppelin/contracts/access/Ownable.sol"; import "./../openzeppelin/contracts/math/SafeMath.sol"; /// @title Vesting Contract attached to Crowns (CWS) token. /// @author Medet Ahmetson /// @notice A simple contract to lock specified amount of Crowns (CWS) for a period of time. /// @dev Based on https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.1.0/contracts/token/ERC20/TokenTimelock.sol contract VestingContract is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; struct Grant { bool locked; uint256 amount; uint256 releaseTime; } // ERC20 basic token contract being held IERC20 private immutable _token; mapping (address => Grant) public _grant; event Locked(address indexed beneficiary, uint256 amount, uint256 releaseTime); event Released(address indexed beneficiary, uint256 amount); /** * @dev Sets Crowns (CWS) token address to interact with. * Changes ownership, so the Contract deployer will not be the owner. */ constructor (IERC20 token, address newOwner) public { require(address(token) != address(0), "Vecting: Token address can not be zero"); _token = token; transferOwnership(newOwner); } /** * @notice Lock some tokens for a team member or investor. * @dev Locks `amount` of Crowns (CWS) until `releaseTime`, after that tokens can be claimed by by the `beneficiary`. * Notice! only owner of the Contract can call this function. * Notice! also, contract should have enough token in balance in order to work. * @param releaseTime is a Unix timestamp in seconds since 1 Jan. 1970. */ function lock(address beneficiary, uint256 amount, uint256 releaseTime) external onlyOwner() { require(releaseTime > block.timestamp, "TokenTimelock: release time is before current time"); require(_grant[beneficiary].locked == false, "Has locked grant"); require(amount > 0, "TokenTimelock: can't lock 0 token"); Grant memory grant = Grant(true, amount, releaseTime); _grant[beneficiary] = grant; emit Locked(beneficiary, amount, releaseTime); } /** * @return the token being held. */ function token() external view returns (IERC20) { return _token; } /** * @return the time when the tokens are released. */ function releaseTime(address beneficiary) external view returns (uint256) { return _grant[beneficiary].releaseTime; } /** * @notice Check whether given {beneficiary} was granted by token or not. */ function isLocked(address beneficiary) external view returns (bool) { return _grant[beneficiary].locked; } /** * @notice Return locked token amount for the {beneficiary} */ function lockedAmount(address beneficiary) external view returns (uint256) { return _grant[beneficiary].amount; } /** * @notice Transfers tokens held by timelock to beneficiary. */ function release(address account) external virtual { // solhint-disable-next-line not-rely-on-time require(_grant[account].locked, "TokenTimelock: no locked tokens, ask grantor to get some tokens"); require(_grant[account].releaseTime <= block.timestamp, "TokenTimelock: current time is before release time"); uint256 lockAmount = _grant[account].amount; // locked amount without rebase uint256 amount = _token.balanceOf(address(this)); require(amount >= lockAmount, "TokenTimelock: no tokens to release"); _token.safeTransfer(account, lockAmount); _grant[account].locked = false; _grant[account].amount = 0; _grant[account].releaseTime = 0; emit Released(account, lockAmount); } }
* @notice Check whether given {beneficiary} was granted by token or not./
function isLocked(address beneficiary) external view returns (bool) { return _grant[beneficiary].locked; }
1,842,308
[ 1, 1564, 2856, 864, 288, 70, 4009, 74, 14463, 814, 97, 1703, 17578, 635, 1147, 578, 486, 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 ]
[ 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, 31753, 12, 2867, 27641, 74, 14463, 814, 13, 3903, 1476, 1135, 261, 6430, 13, 288, 203, 3639, 327, 389, 16243, 63, 70, 4009, 74, 14463, 814, 8009, 15091, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/44787/0xAD63F69c2BaE2B6E1A83d2Ec4dd4de551a5C501F/sources/contracts/SnippooLogic.sol
optional alternative address for owner withdrawals.
address ownerAltPayout;
13,249,068
[ 1, 10444, 10355, 1758, 364, 3410, 598, 9446, 1031, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 1758, 3410, 10655, 52, 2012, 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 ]
import "solidity-BN256G2/BN256G2.sol"; pragma solidity ^0.4.19; pragma experimental ABIEncoderV2; /** * @title Coconut threshold issuance credentials library * @author Mustafa Al-Bassam ([email protected]) */ library Coconut { struct CoconutInstance { int q; // number of messages int t; // threshold int n; // number of authorities uint256[4] g2; // array of 4 integers representing a point on G2 uint256[4] g2_x; // array of 4 integers representing a point on G2 uint256[] g2_y; // dynamic array consisting of a point on G2 (4 integers) for each q } /** * @notice Verify that a token is valid * @param self the CoconutInstance * @param clear_m the clear message * @param sig two curve points * @return true if the token verifies, otherwise false */ function VerifyToken(CoconutInstance self, uint256 clear_m, uint256[4] sig) public view returns (bool result) { uint256[4] memory aggr; (aggr[0], aggr[1], aggr[2], aggr[3]) = BN256G2.ECTwistMul( clear_m, self.g2_y[0], self.g2_y[1], self.g2_y[2], self.g2_y[3] ); (aggr[0], aggr[1], aggr[2], aggr[3]) = BN256G2.ECTwistAdd( self.g2_x[0], self.g2_x[1], self.g2_x[2], self.g2_x[3], aggr[0], aggr[1], aggr[2], aggr[3] ); uint256[12] memory indata; (indata[0], indata[1]) = (sig[0], sig[1]); (indata[2], indata[3], indata[4], indata[5]) = (aggr[1], aggr[0], aggr[3], aggr[2]); (indata[6], indata[7]) = (sig[2], BN256G2.GetFieldModulus() - sig[3]); (indata[8], indata[9], indata[10], indata[11]) = (self.g2[1], self.g2[0], self.g2[3], self.g2[2]); uint256[1] memory outdata; assembly { staticcall(sub(gas, 2000), 8, indata, 384, outdata, 32) pop } return outdata[0] != 0; } }
array of 4 integers representing a point on G2
uint256[4] g2;
12,628,841
[ 1, 1126, 434, 1059, 12321, 5123, 279, 1634, 603, 611, 22, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2254, 5034, 63, 24, 65, 314, 22, 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 ]
// SPDX-License-Identifier: MIT pragma solidity 0.8.1; contract FunctionExample { address payable public owner; constructor() { owner = payable(msg.sender); } mapping(address => uint) public balanceReceived; function getContractBalance() public view returns(uint) { return address(this).balance / 1 ether; } function receiveMoney() public payable { //makes sure value being sent is greater than zero require (msg.value != 0, "You must send a value greater than zero!") ; assert(balanceReceived[msg.sender] + uint64(msg.value) >= balanceReceived[msg.sender]); balanceReceived[msg.sender] += msg.value; } function withdrawMoney(address payable _to, uint _amount) public { //validates enough eth exist in address to send value require (balanceReceived[msg.sender] >= _amount, "You don't have enough ETH to send! Check your balance and try again."); assert(balanceReceived[msg.sender] >= balanceReceived[msg.sender] - _amount); //decrements the amount from current address total balanceReceived[msg.sender] -= _amount; _to.transfer(_amount); } function destroyContract() public { require(msg.sender == owner, "Only the owner can call this function!"); selfdestruct(owner); } //a function that can be called by anyone to send ETH to the contract receive() external payable { receiveMoney(); } //a function that can be called by anyone to send ETH to the contract fallback() external payable { receiveMoney(); } }
makes sure value being sent is greater than zero
function receiveMoney() public payable { require (msg.value != 0, "You must send a value greater than zero!") ; assert(balanceReceived[msg.sender] + uint64(msg.value) >= balanceReceived[msg.sender]); balanceReceived[msg.sender] += msg.value; }
910,884
[ 1, 81, 3223, 3071, 460, 3832, 3271, 353, 6802, 2353, 3634, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 6798, 23091, 1435, 1071, 8843, 429, 288, 203, 3639, 2583, 261, 3576, 18, 1132, 480, 374, 16, 315, 6225, 1297, 1366, 279, 460, 6802, 2353, 3634, 4442, 13, 274, 203, 540, 203, 3639, 1815, 12, 12296, 8872, 63, 3576, 18, 15330, 65, 397, 2254, 1105, 12, 3576, 18, 1132, 13, 1545, 11013, 8872, 63, 3576, 18, 15330, 19226, 203, 540, 203, 3639, 11013, 8872, 63, 3576, 18, 15330, 65, 1011, 1234, 18, 1132, 31, 203, 565, 289, 203, 377, 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 ]
./full_match/3/0x2403d774082A19Fd6820e0d1F1FfDda95882dE38/sources/contracts/4RAM.sol
10 trillion, or 1% of total supply
uint256 public _maxTxAmount = 1000000000000 * 10**9;
8,278,694
[ 1, 2163, 433, 737, 285, 16, 578, 404, 9, 434, 2078, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 5034, 1071, 389, 1896, 4188, 6275, 273, 15088, 9449, 380, 1728, 636, 29, 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 ]
pragma experimental ABIEncoderV2; pragma solidity 0.7.3; import "./interfaces/IProxy.sol"; import "./interfaces/IPV2SmartPool.sol"; import "./interfaces/IBPool.sol"; import "./interfaces/IBFactory.sol"; import "./interfaces/ISmartPoolStorageDoctor.sol"; import "./interfaces/IExperiPieStorageDoctor.sol"; import "@pie-dao/diamond/contracts/Diamond.sol"; import "@pie-dao/diamond/contracts/interfaces/IDiamondCut.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@pie-dao/pie-vaults/contracts/interfaces/IExperiPie.sol"; import "hardhat/console.sol"; contract Experinator is Ownable { address diamondImplementation; address experiPieStorageDoctor; address balancerFactory; address smartPoolImplementation; address smartPoolStorageDoctor; IDiamondCut.FacetCut[] public diamondCut; constructor( // IDiamondCut.FacetCut[] memory _diamondCut, address _diamondImplementation, address _balancerFactory, address _smartPoolImplementation, address _smartPoolStorageDoctor, address _experiPieStorageDoctor ) { // setCut(_diamondCut); diamondImplementation = _diamondImplementation; balancerFactory = _balancerFactory; smartPoolImplementation = _smartPoolImplementation; smartPoolStorageDoctor = _smartPoolStorageDoctor; experiPieStorageDoctor = _experiPieStorageDoctor; } function setCut(IDiamondCut.FacetCut[] memory _diamondCut) public onlyOwner { delete diamondCut; for(uint256 i = 0; i < _diamondCut.length; i ++) { diamondCut.push(_diamondCut[i]); } } // Make sure its initialised! function setDiamondImplementation(address _diamondImplementation) external onlyOwner { diamondImplementation = _diamondImplementation; } function setBalancerFactory(address _factory) external onlyOwner { balancerFactory = _factory; } function setSmartPoolImplementation(address _smartPoolImplementation) external onlyOwner { smartPoolImplementation = _smartPoolImplementation; } function setSmartPoolStorageDoctor(address _storageDoctor) external onlyOwner { smartPoolStorageDoctor = _storageDoctor; } function setExperiPieStorageDoctor(address _storageDoctor) external onlyOwner { experiPieStorageDoctor = _storageDoctor; } function toExperiPie(address _smartPool, address _controller) external onlyOwner { IProxy proxy = IProxy(_smartPool); Diamond diamond = Diamond(payable(_smartPool)); IPV2SmartPool smartPool = IPV2SmartPool(_smartPool); IExperiPie experiPie = IExperiPie(_smartPool); IBPool bPool = IBPool(smartPool.getBPool()); IExperiPieStorageDoctor eStorage = IExperiPieStorageDoctor(_smartPool); address[] memory tokens = smartPool.getTokens(); console.log("Controller"); console.log(smartPool.getController()); smartPool.setTokenBinder(address(this)); for(uint256 i = 0; i < tokens.length; i ++) { smartPool.unbind(tokens[i]); } smartPool.setTokenBinder(_controller); smartPool.setController(_controller); proxy.setImplementation(experiPieStorageDoctor); eStorage.operate(); proxy.setImplementation(diamondImplementation); diamond.initialize(diamondCut, address(this)); for(uint256 i = 0; i < tokens.length; i++) { IERC20 token = IERC20(tokens[i]); token.transfer(_smartPool, token.balanceOf(address(this))); experiPie.addToken(tokens[i]); } // set proxy contract ownership to the controller experiPie.transferOwnership(_controller); proxy.setProxyOwner(_controller); } function toSmartPool(address _experiPie, address _owner, uint256[] memory _weights) external onlyOwner { IProxy proxy = IProxy(_experiPie); Diamond diamond = Diamond(payable(_experiPie)); IPV2SmartPool smartPool = IPV2SmartPool(_experiPie); IExperiPie experiPie = IExperiPie(_experiPie); ISmartPoolStorageDoctor spStorage = ISmartPoolStorageDoctor(_experiPie); address[] memory tokens = experiPie.getTokens(); require(_weights.length == tokens.length, "ARRAY_LENGTH_MISMATCH"); // deploy a fresh _bPool IBPool bPool = IBPool(IBFactory(balancerFactory).newBPool()); //remove remove tokens and deposit them into a fresh balancer pool for(uint256 i = 0; i < tokens.length; i ++) { experiPie.removeToken(tokens[i]); IERC20 token = IERC20(tokens[i]); uint256 balance = token.balanceOf(_experiPie); experiPie.singleCall(tokens[i], abi.encodeWithSelector(token.transfer.selector, address(this), balance), 0); token.approve(address(bPool), balance); bPool.bind(tokens[i], balance, _weights[i]); } bPool.setController(_experiPie); // set storage doctor as implementation proxy.setImplementation(smartPoolStorageDoctor); spStorage.operate(address(bPool)); proxy.setImplementation(smartPoolImplementation); console.log("pool controller"); console.log(smartPool.getController()); smartPool.setController(_owner); proxy.setProxyOwner(_owner); } // In case migration does not work we handle control back to another address again function setProxyOwner(address _proxy, address _owner) external onlyOwner { IProxy proxy = IProxy(_proxy); proxy.setProxyOwner(_owner); } // In case migration does not work set the smart pool address to another address again function setController(address _pie, address _controller) external onlyOwner { IPV2SmartPool pie = IPV2SmartPool(_pie); pie.setController(_controller); } function setOwner(address _pie, address _owner) external onlyOwner { IExperiPie experiPie = IExperiPie(_pie); experiPie.transferOwnership(_owner); } } pragma solidity 0.7.3; interface IProxy { function setProxyOwner(address _newOwner) external; function setImplementation(address _newImplementation) external; } pragma experimental ABIEncoderV2; pragma solidity 0.7.3; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IPV2SmartPool is IERC20 { struct NewToken { address addr; bool isCommitted; uint256 balance; uint256 denorm; uint256 commitBlock; } /** @notice Initialise smart pool. Can only be called once @param _bPool Address of the underlying bPool @param _name Token name @param _symbol Token symbol (ticker) @param _initialSupply Initial token supply */ function init( address _bPool, string calldata _name, string calldata _symbol, uint256 _initialSupply ) external; /** @notice Set the address that can set public swap enabled or disabled. Can only be called by the controller @param _swapSetter Address of the new swapSetter */ function setPublicSwapSetter(address _swapSetter) external; /** @notice Set the address that can bind, unbind and rebind tokens. Can only be called by the controller @param _tokenBinder Address of the new token binder */ function setTokenBinder(address _tokenBinder) external; /** @notice Enable or disable trading on the underlying balancer pool. Can only be called by the public swap setter @param _public Wether public swap is enabled or not */ function setPublicSwap(bool _public) external; /** @notice Set the swap fee. Can only be called by the controller @param _swapFee The new swap fee. 10**18 == 100%. Max 10% */ function setSwapFee(uint256 _swapFee) external; /** @notice Set the totalSuppy cap. Can only be called by the controller @param _cap New cap */ function setCap(uint256 _cap) external; /** @notice Set the annual fee. Can only be called by the controller @param _newFee new fee 10**18 == 100% per 365 days. Max 10% */ function setAnnualFee(uint256 _newFee) external; /** @notice Charge the outstanding annual fee */ function chargeOutstandingAnnualFee() external; /** @notice Set the address that receives the annual fee. Can only be called by the controller */ function setFeeRecipient(address _newRecipient) external; /** @notice Set the controller address. Can only be called by the current address @param _controller Address of the new controller */ function setController(address _controller) external; /** @notice Set the circuit breaker address. Can only be called by the controller @param _newCircuitBreaker Address of the new circuit breaker */ function setCircuitBreaker(address _newCircuitBreaker) external; /** @notice Enable or disable joining and exiting @param _newValue enabled or not */ function setJoinExitEnabled(bool _newValue) external; /** @notice Trip the circuit breaker which disabled exit, join and swaps */ function tripCircuitBreaker() external; /** @notice Update the weight of a token. Can only be called by the controller @param _token Token to adjust the weight of @param _newWeight New denormalized weight */ function updateWeight(address _token, uint256 _newWeight) external; /** @notice Gradually adjust the weights of a token. Can only be called by the controller @param _newWeights Target weights @param _startBlock Block to start weight adjustment @param _endBlock Block to finish weight adjustment */ function updateWeightsGradually( uint256[] calldata _newWeights, uint256 _startBlock, uint256 _endBlock ) external; /** @notice Poke the weight adjustment */ function pokeWeights() external; /** @notice Apply the adding of a token. Can only be called by the controller */ function applyAddToken() external; /** @notice Commit a token to be added. Can only be called by the controller @param _token Address of the token to add @param _balance Amount of token to add @param _denormalizedWeight Denormalized weight */ function commitAddToken( address _token, uint256 _balance, uint256 _denormalizedWeight ) external; /** @notice Remove a token from the smart pool. Can only be called by the controller @param _token Address of the token to remove */ function removeToken(address _token) external; /** @notice Approve bPool to pull tokens from smart pool */ function approveTokens() external; /** @notice Mint pool tokens, locking underlying assets @param _amount Amount of pool tokens */ function joinPool(uint256 _amount) external; /** @notice Mint pool tokens, locking underlying assets. With front running protection @param _amount Amount of pool tokens @param _maxAmountsIn Maximum amounts of underlying assets */ function joinPool(uint256 _amount, uint256[] calldata _maxAmountsIn) external; /** @notice Burn pool tokens and redeem underlying assets @param _amount Amount of pool tokens to burn */ function exitPool(uint256 _amount) external; /** @notice Burn pool tokens and redeem underlying assets. With front running protection @param _amount Amount of pool tokens to burn @param _minAmountsOut Minimum amounts of underlying assets */ function exitPool(uint256 _amount, uint256[] calldata _minAmountsOut) external; /** @notice Join with a single asset, given amount of token in @param _token Address of the underlying token to deposit @param _amountIn Amount of underlying asset to deposit @param _minPoolAmountOut Minimum amount of pool tokens to receive */ function joinswapExternAmountIn( address _token, uint256 _amountIn, uint256 _minPoolAmountOut ) external returns (uint256); /** @notice Join with a single asset, given amount pool out @param _token Address of the underlying token to deposit @param _amountOut Amount of pool token to mint @param _maxAmountIn Maximum amount of underlying asset */ function joinswapPoolAmountOut( address _token, uint256 _amountOut, uint256 _maxAmountIn ) external returns (uint256 tokenAmountIn); /** @notice Exit with a single asset, given pool amount in @param _token Address of the underlying token to withdraw @param _poolAmountIn Amount of pool token to burn @param _minAmountOut Minimum amount of underlying asset to withdraw */ function exitswapPoolAmountIn( address _token, uint256 _poolAmountIn, uint256 _minAmountOut ) external returns (uint256 tokenAmountOut); /** @notice Exit with a single asset, given token amount out @param _token Address of the underlying token to withdraw @param _tokenAmountOut Amount of underlying asset to withdraw @param _maxPoolAmountIn Maximimum pool amount to burn */ function exitswapExternAmountOut( address _token, uint256 _tokenAmountOut, uint256 _maxPoolAmountIn ) external returns (uint256 poolAmountIn); /** @notice Exit pool, ignoring some tokens @param _amount Amount of pool tokens to burn @param _lossTokens Addresses of tokens to ignore */ function exitPoolTakingloss(uint256 _amount, address[] calldata _lossTokens) external; /** @notice Bind(add) a token to the pool @param _token Address of the token to bind @param _balance Amount of token to bind @param _denorm Denormalised weight */ function bind( address _token, uint256 _balance, uint256 _denorm ) external; /** @notice Rebind(adjust) a token's weight or amount @param _token Address of the token to rebind @param _balance New token amount @param _denorm New denormalised weight */ function rebind( address _token, uint256 _balance, uint256 _denorm ) external; /** @notice Unbind(remove) a token from the smart pool @param _token Address of the token to unbind */ function unbind(address _token) external; /** @notice Get the controller address @return Address of the controller */ function getController() external view returns (address); /** @notice Get the public swap setter address @return Address of the public swap setter */ function getPublicSwapSetter() external view returns (address); /** @notice Get the address of the token binder @return Token binder address */ function getTokenBinder() external view returns (address); /** @notice Get the circuit breaker address @return Circuit breaker address */ function getCircuitBreaker() external view returns (address); /** @notice Get if public trading is enabled or not @return Enabled or not */ function isPublicSwap() external view returns (bool); /** @notice Get the current tokens in the smart pool @return Addresses of the tokens in the smart pool */ function getTokens() external view returns (address[] memory); /** @notice Get the totalSupply cap @return The totalSupply cap */ function getCap() external view returns (uint256); /** @notice Get the annual fee @return the annual fee */ function getAnnualFee() external view returns (uint256); /** @notice Get the address receiving the fees @return Fee recipient address */ function getFeeRecipient() external view returns (address); /** @notice Get the denormalized weight of a token @param _token Address of the token @return The denormalised weight of the token */ function getDenormalizedWeight(address _token) external view returns (uint256); /** @notice Get all denormalized weights @return weights Denormalized weights */ function getDenormalizedWeights() external view returns (uint256[] memory weights); /** @notice Get the target weights @return weights Target weights */ function getNewWeights() external view returns (uint256[] memory weights); /** @notice Get weights at start of weight adjustment @return weights Start weights */ function getStartWeights() external view returns (uint256[] memory weights); /** @notice Get start block of weight adjustment @return Start block */ function getStartBlock() external view returns (uint256); /** @notice Get end block of weight adjustment @return End block */ function getEndBlock() external view returns (uint256); /** @notice Get new token being added @return New token */ function getNewToken() external view returns (NewToken memory); /** @notice Get if joining and exiting is enabled @return Enabled or not */ function getJoinExitEnabled() external view returns (bool); /** @notice Get the underlying Balancer pool address @return Address of the underlying Balancer pool */ function getBPool() external view returns (address); /** @notice Get the swap fee @return Swap fee */ function getSwapFee() external view returns (uint256); /** @notice Not supported */ function finalizeSmartPool() external view; /** @notice Not supported */ function createPool(uint256 initialSupply) external view; /** @notice Calculate the amount of underlying needed to mint a certain amount @return tokens Addresses of the underlying tokens @return amounts Amounts of the underlying tokens */ function calcTokensForAmount(uint256 _amount) external view returns (address[] memory tokens, uint256[] memory amounts); /** @notice Calculate the amount of pool tokens out given underlying in @param _token Underlying asset to deposit @param _amount Amount of underlying asset to deposit @return Pool amount out */ function calcPoolOutGivenSingleIn(address _token, uint256 _amount) external view returns (uint256); /** @notice Calculate underlying deposit amount given pool amount out @param _token Underlying token to deposit @param _amount Amount of pool out @return Underlying asset deposit amount */ function calcSingleInGivenPoolOut(address _token, uint256 _amount) external view returns (uint256); /** @notice Calculate underlying amount out given pool amount in @param _token Address of the underlying token to withdraw @param _amount Pool amount to burn @return Amount of underlying to withdraw */ function calcSingleOutGivenPoolIn(address _token, uint256 _amount) external view returns (uint256); /** @notice Calculate pool amount in given underlying input @param _token Address of the underlying token to withdraw @param _amount Underlying output amount @return Pool burn amount */ function calcPoolInGivenSingleOut(address _token, uint256 _amount) external view returns (uint256); } // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is disstributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity 0.7.3; interface IBPool { function isBound(address token) external view returns (bool); function getBalance(address token) external view returns (uint256); function rebind( address token, uint256 balance, uint256 denorm ) external; function setSwapFee(uint256 swapFee) external; function setPublicSwap(bool _public) external; function bind( address token, uint256 balance, uint256 denorm ) external; function unbind(address token) external; function getDenormalizedWeight(address token) external view returns (uint256); function getTotalDenormalizedWeight() external view returns (uint256); function getCurrentTokens() external view returns (address[] memory); function setController(address manager) external; function isPublicSwap() external view returns (bool); function getSwapFee() external view returns (uint256); function gulp(address token) external; function calcPoolOutGivenSingleIn( uint256 tokenBalanceIn, uint256 tokenWeightIn, uint256 poolSupply, uint256 totalWeight, uint256 tokenAmountIn, uint256 swapFee ) external pure returns (uint256 poolAmountOut); function calcSingleInGivenPoolOut( uint256 tokenBalanceIn, uint256 tokenWeightIn, uint256 poolSupply, uint256 totalWeight, uint256 poolAmountOut, uint256 swapFee ) external pure returns (uint256 tokenAmountIn); function calcSingleOutGivenPoolIn( uint256 tokenBalanceOut, uint256 tokenWeightOut, uint256 poolSupply, uint256 totalWeight, uint256 poolAmountIn, uint256 swapFee ) external pure returns (uint256 tokenAmountOut); function calcPoolInGivenSingleOut( uint256 tokenBalanceOut, uint256 tokenWeightOut, uint256 poolSupply, uint256 totalWeight, uint256 tokenAmountOut, uint256 swapFee ) external pure returns (uint256 poolAmountIn); } pragma solidity 0.7.3; interface IBFactory { function newBPool() external returns (address); } pragma solidity 0.7.3; interface ISmartPoolStorageDoctor { function operate(address _bPool) external; } interface IExperiPieStorageDoctor { function operate() external; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.1; pragma experimental ABIEncoderV2; /******************************************************************************\ * Author: Nick Mudge <[email protected]> (https://twitter.com/mudgen) * * Implementation of a diamond. /******************************************************************************/ import "./libraries/LibDiamond.sol"; import "./libraries/LibDiamondInitialize.sol"; import "./interfaces/IDiamondLoupe.sol"; import "./interfaces/IDiamondCut.sol"; import "./interfaces/IERC173.sol"; import "./interfaces/IERC165.sol"; contract Diamond { function initialize(IDiamondCut.FacetCut[] memory _diamondCut, address _owner) external payable { require(LibDiamondInitialize.diamondInitializeStorage().initialized == false, "ALREADY_INITIALIZED"); LibDiamondInitialize.diamondInitializeStorage().initialized = true; LibDiamond.diamondCut(_diamondCut, address(0), new bytes(0)); LibDiamond.setContractOwner(_owner); LibDiamond.DiamondStorage storage ds = LibDiamond.diamondStorage(); // adding ERC165 data ds.supportedInterfaces[type(IERC165).interfaceId] = true; ds.supportedInterfaces[type(IDiamondCut).interfaceId] = true; ds.supportedInterfaces[type(IDiamondLoupe).interfaceId] = true; ds.supportedInterfaces[type(IERC173).interfaceId] = true; } // Find facet for function that is called and execute the // function if a facet is found and return any value. fallback() external payable { LibDiamond.DiamondStorage storage ds; bytes32 position = LibDiamond.DIAMOND_STORAGE_POSITION; assembly { ds.slot := position } address facet = address(bytes20(ds.facets[msg.sig])); require(facet != address(0), "Diamond: Function does not exist"); assembly { calldatacopy(0, 0, calldatasize()) let result := delegatecall(gas(), facet, 0, calldatasize(), 0, 0) returndatacopy(0, 0, returndatasize()) switch result case 0 { revert(0, returndatasize()) } default { return(0, returndatasize()) } } } receive() external payable {} } // SPDX-License-Identifier: MIT pragma solidity ^0.7.1; pragma experimental ABIEncoderV2; /******************************************************************************\ * Author: Nick Mudge <[email protected]> (https://twitter.com/mudgen) /******************************************************************************/ interface IDiamondCut { enum FacetCutAction {Add, Replace, Remove} struct FacetCut { address facetAddress; FacetCutAction action; bytes4[] functionSelectors; } /// @notice Add/replace/remove any number of functions and optionally execute /// a function with delegatecall /// @param _diamondCut Contains the facet addresses and function selectors /// @param _init The address of the contract or facet to execute _calldata /// @param _calldata A function call, including function selector and arguments /// _calldata is executed with delegatecall on _init function diamondCut( FacetCut[] calldata _diamondCut, address _init, bytes calldata _calldata ) external; event DiamondCut(FacetCut[] _diamondCut, address _init, bytes _calldata); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../GSN/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 returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev 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.7.1; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@pie-dao/diamond/contracts/interfaces/IERC173.sol"; import "@pie-dao/diamond/contracts/interfaces/IDiamondLoupe.sol"; import "@pie-dao/diamond/contracts/interfaces/IDiamondCut.sol"; import "./IBasketFacet.sol"; import "./IERC20Facet.sol"; import "./ICallFacet.sol"; /** @title ExperiPie Interface @dev Combines all ExperiPie facet interfaces into one */ interface IExperiPie is IERC20, IBasketFacet, IERC20Facet, IERC173, ICallFacet, IDiamondLoupe, IDiamondCut { } // SPDX-License-Identifier: MIT pragma solidity >= 0.4.22 <0.9.0; library console { address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67); function _sendLogPayload(bytes memory payload) private view { uint256 payloadLength = payload.length; address consoleAddress = CONSOLE_ADDRESS; assembly { let payloadStart := add(payload, 32) let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0) } } function log() internal view { _sendLogPayload(abi.encodeWithSignature("log()")); } function logInt(int p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(int)", p0)); } function logUint(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function logString(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function logBool(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function logAddress(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function logBytes(bytes memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes)", p0)); } function logBytes1(bytes1 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0)); } function logBytes2(bytes2 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0)); } function logBytes3(bytes3 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0)); } function logBytes4(bytes4 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0)); } function logBytes5(bytes5 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0)); } function logBytes6(bytes6 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0)); } function logBytes7(bytes7 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0)); } function logBytes8(bytes8 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0)); } function logBytes9(bytes9 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0)); } function logBytes10(bytes10 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0)); } function logBytes11(bytes11 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0)); } function logBytes12(bytes12 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0)); } function logBytes13(bytes13 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0)); } function logBytes14(bytes14 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0)); } function logBytes15(bytes15 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0)); } function logBytes16(bytes16 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0)); } function logBytes17(bytes17 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0)); } function logBytes18(bytes18 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0)); } function logBytes19(bytes19 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0)); } function logBytes20(bytes20 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0)); } function logBytes21(bytes21 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0)); } function logBytes22(bytes22 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0)); } function logBytes23(bytes23 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0)); } function logBytes24(bytes24 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0)); } function logBytes25(bytes25 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0)); } function logBytes26(bytes26 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0)); } function logBytes27(bytes27 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0)); } function logBytes28(bytes28 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0)); } function logBytes29(bytes29 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0)); } function logBytes30(bytes30 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0)); } function logBytes31(bytes31 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0)); } function logBytes32(bytes32 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0)); } function log(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function log(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function log(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function log(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function log(uint p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1)); } function log(uint p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1)); } function log(uint p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1)); } function log(uint p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1)); } function log(string memory p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1)); } function log(string memory p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1)); } function log(string memory p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1)); } function log(string memory p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1)); } function log(bool p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1)); } function log(bool p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1)); } function log(bool p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1)); } function log(bool p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1)); } function log(address p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1)); } function log(address p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1)); } function log(address p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1)); } function log(address p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1)); } function log(uint p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2)); } function log(uint p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2)); } function log(uint p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2)); } function log(uint p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2)); } function log(uint p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2)); } function log(uint p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2)); } function log(uint p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2)); } function log(uint p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2)); } function log(uint p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2)); } function log(uint p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2)); } function log(uint p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2)); } function log(uint p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2)); } function log(uint p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2)); } function log(uint p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2)); } function log(uint p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2)); } function log(uint p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2)); } function log(string memory p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2)); } function log(string memory p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2)); } function log(string memory p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2)); } function log(string memory p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2)); } function log(string memory p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2)); } function log(string memory p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2)); } function log(string memory p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2)); } function log(string memory p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2)); } function log(string memory p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2)); } function log(string memory p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2)); } function log(string memory p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2)); } function log(string memory p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2)); } function log(string memory p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2)); } function log(string memory p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2)); } function log(string memory p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2)); } function log(string memory p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2)); } function log(bool p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2)); } function log(bool p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2)); } function log(bool p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2)); } function log(bool p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2)); } function log(bool p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2)); } function log(bool p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2)); } function log(bool p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2)); } function log(bool p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2)); } function log(bool p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2)); } function log(bool p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2)); } function log(bool p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2)); } function log(bool p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2)); } function log(bool p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2)); } function log(bool p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2)); } function log(bool p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2)); } function log(bool p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2)); } function log(address p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2)); } function log(address p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2)); } function log(address p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2)); } function log(address p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2)); } function log(address p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2)); } function log(address p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2)); } function log(address p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2)); } function log(address p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2)); } function log(address p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2)); } function log(address p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2)); } function log(address p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2)); } function log(address p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2)); } function log(address p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2)); } function log(address p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2)); } function log(address p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2)); } function log(address p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2)); } function log(uint p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.1; pragma experimental ABIEncoderV2; /******************************************************************************\ * Author: Nick Mudge * * Implementation of Diamond facet. * This is gas optimized by reducing storage reads and storage writes. * This code is as complex as it is to reduce gas costs. /******************************************************************************/ import "../interfaces/IDiamondCut.sol"; library LibDiamond { bytes32 constant DIAMOND_STORAGE_POSITION = keccak256("diamond.standard.diamond.storage"); struct DiamondStorage { // maps function selectors to the facets that execute the functions. // and maps the selectors to their position in the selectorSlots array. // func selector => address facet, selector position mapping(bytes4 => bytes32) facets; // array of slots of function selectors. // each slot holds 8 function selectors. mapping(uint256 => bytes32) selectorSlots; // The number of function selectors in selectorSlots uint16 selectorCount; // owner of the contract // Used to query if a contract implements an interface. // Used to implement ERC-165. mapping(bytes4 => bool) supportedInterfaces; // owner of the contract address contractOwner; } function diamondStorage() internal pure returns (DiamondStorage storage ds) { bytes32 position = DIAMOND_STORAGE_POSITION; assembly { ds.slot := position } } event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); function setContractOwner(address _newOwner) internal { DiamondStorage storage ds = diamondStorage(); address previousOwner = ds.contractOwner; ds.contractOwner = _newOwner; emit OwnershipTransferred(previousOwner, _newOwner); } function contractOwner() internal view returns (address contractOwner_) { contractOwner_ = diamondStorage().contractOwner; } function enforceIsContractOwner() view internal { require(msg.sender == diamondStorage().contractOwner, "LibDiamond: Must be contract owner"); } modifier onlyOwner { require(msg.sender == diamondStorage().contractOwner, "LibDiamond: Must be contract owner"); _; } event DiamondCut(IDiamondCut.FacetCut[] _diamondCut, address _init, bytes _calldata); bytes32 constant CLEAR_ADDRESS_MASK = bytes32(uint256(0xffffffffffffffffffffffff)); bytes32 constant CLEAR_SELECTOR_MASK = bytes32(uint256(0xffffffff << 224)); // Internal function version of diamondCut // This code is almost the same as the external diamondCut, // except it is using 'Facet[] memory _diamondCut' instead of // 'Facet[] calldata _diamondCut'. // The code is duplicated to prevent copying calldata to memory which // causes an error for a two dimensional array. function diamondCut( IDiamondCut.FacetCut[] memory _diamondCut, address _init, bytes memory _calldata ) internal { DiamondStorage storage ds = diamondStorage(); uint256 originalSelectorCount = ds.selectorCount; uint256 selectorCount = originalSelectorCount; bytes32 selectorSlot; // Check if last selector slot is not full if (selectorCount % 8 > 0) { // get last selectorSlot selectorSlot = ds.selectorSlots[selectorCount / 8]; } // loop through diamond cut for (uint256 facetIndex; facetIndex < _diamondCut.length; facetIndex++) { (selectorCount, selectorSlot) = addReplaceRemoveFacetSelectors( selectorCount, selectorSlot, _diamondCut[facetIndex].facetAddress, _diamondCut[facetIndex].action, _diamondCut[facetIndex].functionSelectors ); } if (selectorCount != originalSelectorCount) { ds.selectorCount = uint16(selectorCount); } // If last selector slot is not full if (selectorCount % 8 > 0) { ds.selectorSlots[selectorCount / 8] = selectorSlot; } emit DiamondCut(_diamondCut, _init, _calldata); initializeDiamondCut(_init, _calldata); } function addReplaceRemoveFacetSelectors( uint256 _selectorCount, bytes32 _selectorSlot, address _newFacetAddress, IDiamondCut.FacetCutAction _action, bytes4[] memory _selectors ) internal returns (uint256, bytes32) { DiamondStorage storage ds = diamondStorage(); require(_selectors.length > 0, "LibDiamondCut: No selectors in facet to cut"); if (_action == IDiamondCut.FacetCutAction.Add) { require(_newFacetAddress != address(0), "LibDiamondCut: Add facet can't be address(0)"); enforceHasContractCode(_newFacetAddress, "LibDiamondCut: Add facet has no code"); for (uint256 selectorIndex; selectorIndex < _selectors.length; selectorIndex++) { bytes4 selector = _selectors[selectorIndex]; bytes32 oldFacet = ds.facets[selector]; require(address(bytes20(oldFacet)) == address(0), "LibDiamondCut: Can't add function that already exists"); // add facet for selector ds.facets[selector] = bytes20(_newFacetAddress) | bytes32(_selectorCount); uint256 selectorInSlotPosition = (_selectorCount % 8) * 32; // clear selector position in slot and add selector _selectorSlot = (_selectorSlot & ~(CLEAR_SELECTOR_MASK >> selectorInSlotPosition)) | (bytes32(selector) >> selectorInSlotPosition); // if slot is full then write it to storage if (selectorInSlotPosition == 224) { ds.selectorSlots[_selectorCount / 8] = _selectorSlot; _selectorSlot = 0; } _selectorCount++; } } else if(_action == IDiamondCut.FacetCutAction.Replace) { require(_newFacetAddress != address(0), "LibDiamondCut: Replace facet can't be address(0)"); enforceHasContractCode(_newFacetAddress, "LibDiamondCut: Replace facet has no code"); for (uint256 selectorIndex; selectorIndex < _selectors.length; selectorIndex++) { bytes4 selector = _selectors[selectorIndex]; bytes32 oldFacet = ds.facets[selector]; address oldFacetAddress = address(bytes20(oldFacet)); // only useful if immutable functions exist require(oldFacetAddress != address(this), "LibDiamondCut: Can't replace immutable function"); require(oldFacetAddress != _newFacetAddress, "LibDiamondCut: Can't replace function with same function"); require(oldFacetAddress != address(0), "LibDiamondCut: Can't replace function that doesn't exist"); // replace old facet address ds.facets[selector] = (oldFacet & CLEAR_ADDRESS_MASK) | bytes20(_newFacetAddress); } } else if(_action == IDiamondCut.FacetCutAction.Remove) { require(_newFacetAddress == address(0), "LibDiamondCut: Remove facet address must be address(0)"); uint256 selectorSlotCount = _selectorCount / 8; uint256 selectorInSlotIndex = (_selectorCount % 8) - 1; for (uint256 selectorIndex; selectorIndex < _selectors.length; selectorIndex++) { if (_selectorSlot == 0) { // get last selectorSlot selectorSlotCount--; _selectorSlot = ds.selectorSlots[selectorSlotCount]; selectorInSlotIndex = 7; } bytes4 lastSelector; uint256 oldSelectorsSlotCount; uint256 oldSelectorInSlotPosition; // adding a block here prevents stack too deep error { bytes4 selector = _selectors[selectorIndex]; bytes32 oldFacet = ds.facets[selector]; require(address(bytes20(oldFacet)) != address(0), "LibDiamondCut: Can't remove function that doesn't exist"); // only useful if immutable functions exist require(address(bytes20(oldFacet)) != address(this), "LibDiamondCut: Can't remove immutable function"); // replace selector with last selector in ds.facets // gets the last selector lastSelector = bytes4(_selectorSlot << (selectorInSlotIndex * 32)); if (lastSelector != selector) { // update last selector slot position info ds.facets[lastSelector] = (oldFacet & CLEAR_ADDRESS_MASK) | bytes20(ds.facets[lastSelector]); } delete ds.facets[selector]; uint256 oldSelectorCount = uint16(uint256(oldFacet)); oldSelectorsSlotCount = oldSelectorCount / 8; oldSelectorInSlotPosition = (oldSelectorCount % 8) * 32; } if (oldSelectorsSlotCount != selectorSlotCount) { bytes32 oldSelectorSlot = ds.selectorSlots[oldSelectorsSlotCount]; // clears the selector we are deleting and puts the last selector in its place. oldSelectorSlot = (oldSelectorSlot & ~(CLEAR_SELECTOR_MASK >> oldSelectorInSlotPosition)) | (bytes32(lastSelector) >> oldSelectorInSlotPosition); // update storage with the modified slot ds.selectorSlots[oldSelectorsSlotCount] = oldSelectorSlot; } else { // clears the selector we are deleting and puts the last selector in its place. _selectorSlot = (_selectorSlot & ~(CLEAR_SELECTOR_MASK >> oldSelectorInSlotPosition)) | (bytes32(lastSelector) >> oldSelectorInSlotPosition); } if (selectorInSlotIndex == 0) { delete ds.selectorSlots[selectorSlotCount]; _selectorSlot = 0; } selectorInSlotIndex--; } _selectorCount = selectorSlotCount * 8 + selectorInSlotIndex + 1; } else { revert("LibDiamondCut: Incorrect FacetCutAction"); } return (_selectorCount, _selectorSlot); } function initializeDiamondCut(address _init, bytes memory _calldata) internal { if (_init == address(0)) { require(_calldata.length == 0, "LibDiamondCut: _init is address(0) but_calldata is not empty"); } else { require(_calldata.length > 0, "LibDiamondCut: _calldata is empty but _init is not address(0)"); if (_init != address(this)) { enforceHasContractCode(_init, "LibDiamondCut: _init address has no code"); } (bool success, bytes memory error) = _init.delegatecall(_calldata); if (!success) { if (error.length > 0) { // bubble up the error revert(string(error)); } else { revert("LibDiamondCut: _init function reverted"); } } } } function enforceHasContractCode(address _contract, string memory _errorMessage) internal view { uint256 contractSize; assembly { contractSize := extcodesize(_contract) } require(contractSize > 0, _errorMessage); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.1; pragma experimental ABIEncoderV2; /******************************************************************************\ * Author: Mick de Graaf * * Tracks if the contract is already intialized or not /******************************************************************************/ import "../interfaces/IDiamondCut.sol"; library LibDiamondInitialize { bytes32 constant DIAMOND_INITIALIZE_STORAGE_POSITION = keccak256("diamond.standard.initialize.diamond.storage"); struct InitializedStorage { bool initialized; } function diamondInitializeStorage() internal pure returns (InitializedStorage storage ids) { bytes32 position = DIAMOND_INITIALIZE_STORAGE_POSITION; assembly { ids.slot := position } } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.1; pragma experimental ABIEncoderV2; // A loupe is a small magnifying glass used to look at diamonds. // These functions look at diamonds interface IDiamondLoupe { /// These functions are expected to be called frequently /// by tools. struct Facet { address facetAddress; bytes4[] functionSelectors; } /// @notice Gets all facet addresses and their four byte function selectors. /// @return facets_ Facet function facets() external view returns (Facet[] memory facets_); /// @notice Gets all the function selectors supported by a specific facet. /// @param _facet The facet address. /// @return facetFunctionSelectors_ function facetFunctionSelectors(address _facet) external view returns (bytes4[] memory facetFunctionSelectors_); /// @notice Get all the facet addresses used by a diamond. /// @return facetAddresses_ function facetAddresses() external view returns (address[] memory facetAddresses_); /// @notice Gets the facet that supports the given selector. /// @dev If facet is not found return address(0). /// @param _functionSelector The function selector. /// @return facetAddress_ The facet address. function facetAddress(bytes4 _functionSelector) external view returns (address facetAddress_); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.1; /// @title ERC-173 Contract Ownership Standard /// Note: the ERC-165 identifier for this interface is 0x7f5828d0 /* is ERC165 */ interface IERC173 { /// @dev This emits when ownership of a contract changes. event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /// @notice Get the address of the owner /// @return owner_ The address of the owner. function owner() external view returns (address owner_); /// @notice Set the address of the new owner of the contract /// @dev Set _newOwner to address(0) to renounce any ownership. /// @param _newOwner The address of the new owner of the contract function transferOwnership(address _newOwner) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.1; pragma experimental ABIEncoderV2; interface IERC165 { /// @notice Query if a contract implements an interface /// @param interfaceId The interface identifier, as specified in ERC-165 /// @dev Interface identification is specified in ERC-165. This function /// uses less than 30,000 gas. /// @return `true` if the contract implements `interfaceID` and /// `interfaceID` is not 0xffffffff, `false` otherwise function supportsInterface(bytes4 interfaceId) external view returns (bool); } // 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.7.1; pragma experimental ABIEncoderV2; interface IBasketFacet { event TokenAdded(address indexed _token); event TokenRemoved(address indexed _token); event EntryFeeSet(uint256 fee); event ExitFeeSet(uint256 fee); event AnnualizedFeeSet(uint256 fee); event FeeBeneficiarySet(address indexed beneficiary); event EntryFeeBeneficiaryShareSet(uint256 share); event ExitFeeBeneficiaryShareSet(uint256 share); event PoolJoined(address indexed who, uint256 amount); event PoolExited(address indexed who, uint256 amount); event FeeCharged(uint256 amount); event LockSet(uint256 lockBlock); event CapSet(uint256 cap); /** @notice Sets entry fee paid when minting @param _fee Amount of fee. 1e18 == 100%, capped at 10% */ function setEntryFee(uint256 _fee) external; /** @notice Get the entry fee @return Current entry fee */ function getEntryFee() external view returns(uint256); /** @notice Set the exit fee paid when exiting @param _fee Amount of fee. 1e18 == 100%, capped at 10% */ function setExitFee(uint256 _fee) external; /** @notice Get the exit fee @return Current exit fee */ function getExitFee() external view returns(uint256); /** @notice Set the annualized fee. Often referred to as streaming fee @param _fee Amount of fee. 1e18 == 100%, capped at 10% */ function setAnnualizedFee(uint256 _fee) external; /** @notice Get the annualized fee. @return Current annualized fee. */ function getAnnualizedFee() external view returns(uint256); /** @notice Set the address receiving the fees. */ function setFeeBeneficiary(address _beneficiary) external; /** @notice Get the fee benificiary @return The current fee beneficiary */ function getFeeBeneficiary() external view returns(address); /** @notice Set the fee beneficiaries share of the entry fee @notice _share Share of the fee. 1e18 == 100%. Capped at 100% */ function setEntryFeeBeneficiaryShare(uint256 _share) external; /** @notice Get the entry fee beneficiary share @return Feeshare amount */ function getEntryFeeBeneficiaryShare() external view returns(uint256); /** @notice Set the fee beneficiaries share of the exit fee @notice _share Share of the fee. 1e18 == 100%. Capped at 100% */ function setExitFeeBeneficiaryShare(uint256 _share) external; /** @notice Get the exit fee beneficiary share @return Feeshare amount */ function getExitFeeBeneficiaryShare() external view returns(uint256); /** @notice Calculate the oustanding annualized fee @return Amount of pool tokens to be minted to charge the annualized fee */ function calcOutStandingAnnualizedFee() external view returns(uint256); /** @notice Charges the annualized fee */ function chargeOutstandingAnnualizedFee() external; /** @notice Pulls underlying from caller and mints the pool token @param _amount Amount of pool tokens to mint */ function joinPool(uint256 _amount) external; /** @notice Burns pool tokens from the caller and returns underlying assets */ function exitPool(uint256 _amount) external; /** @notice Get if the pool is locked or not. (not accepting exit and entry) @return Boolean indicating if the pool is locked */ function getLock() external view returns (bool); /** @notice Get the block until which the pool is locked @return The lock block */ function getLockBlock() external view returns (uint256); /** @notice Set the lock block @param _lock Block height of the lock */ function setLock(uint256 _lock) external; /** @notice Get the maximum of pool tokens that can be minted @return Cap */ function getCap() external view returns (uint256); /** @notice Set the maximum of pool tokens that can be minted @param _maxCap Max cap */ function setCap(uint256 _maxCap) external; /** @notice Get the amount of tokens owned by the pool @param _token Addres of the token @return Amount owned by the contract */ function balance(address _token) external view returns (uint256); /** @notice Get the tokens in the pool @return Array of tokens in the pool */ function getTokens() external view returns (address[] memory); /** @notice Add a token to the pool. Should have at least a balance of 10**6 @param _token Address of the token to add */ function addToken(address _token) external; /** @notice Removes a token from the pool @param _token Address of the token to remove */ function removeToken(address _token) external; /** @notice Checks if a token was added to the pool @param _token address of the token @return If token is in the pool or not */ function getTokenInPool(address _token) external view returns (bool); /** @notice Calculate the amounts of underlying needed to mint that pool amount. @param _amount Amount of pool tokens to mint @return tokens Tokens needed @return amounts Amounts of underlying needed */ function calcTokensForAmount(uint256 _amount) external view returns (address[] memory tokens, uint256[] memory amounts); /** @notice Calculate the amounts of underlying to receive when burning that pool amount @param _amount Amount of pool tokens to burn @return tokens Tokens returned @return amounts Amounts of underlying returned */ function calcTokensForAmountExit(uint256 _amount) external view returns (address[] memory tokens, uint256[] memory amounts); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.1; pragma experimental ABIEncoderV2; interface IERC20Facet { /** @notice Get the token name @return The token name */ function name() external view returns (string memory); /** @notice Get the token symbol @return The token symbol */ function symbol() external view returns (string memory); /** @notice Get the amount of decimals @return Amount of decimals */ function decimals() external view returns (uint8); /** @notice Mints tokens. Can only be called by the contract owner or the contract itself @param _receiver Address receiving the tokens @param _amount Amount to mint */ function mint(address _receiver, uint256 _amount) external; /** @notice Burns tokens. Can only be called by the contract owner or the contract itself @param _from Address to burn from @param _amount Amount to burn */ function burn(address _from, uint256 _amount) external; /** @notice Sets up the metadata and initial supply. Can be called by the contract owner @param _initialSupply Initial supply of the token @param _name Name of the token @param _symbol Symbol of the token */ function initialize( uint256 _initialSupply, string memory _name, string memory _symbol ) external; /** @notice Set the token name of the contract. Can only be called by the contract owner or the contract itself @param _name New token name */ function setName(string calldata _name) external; /** @notice Set the token symbol of the contract. Can only be called by the contract owner or the contract itself @param _symbol New token symbol */ function setSymbol(string calldata _symbol) external; /** @notice Increase the amount of tokens another address can spend @param _spender Spender @param _amount Amount to increase by */ function increaseApproval(address _spender, uint256 _amount) external returns (bool); /** @notice Decrease the amount of tokens another address can spend @param _spender Spender @param _amount Amount to decrease by */ function decreaseApproval(address _spender, uint256 _amount) external returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.1; pragma experimental ABIEncoderV2; interface ICallFacet { event CallerAdded(address indexed caller); event CallerRemoved(address indexed caller); event Call(address indexed caller, address indexed target, bytes data, uint256 value); /** @notice Lets whitelisted callers execute a batch of arbitrary calls from the pool. Reverts if one of the calls fails @param _targets Array of addresses of targets to call @param _calldata Array of calldata for each call @param _values Array of amounts of ETH to send with the call */ function call( address[] memory _targets, bytes[] memory _calldata, uint256[] memory _values ) external; /** @notice Lets whitelisted callers execute a batch of arbitrary calls from the pool without sending any Ether. Reverts if one of the calls fail @param _targets Array of addresses of targets to call @param _calldata Array of calldata for each call */ function callNoValue( address[] memory _targets, bytes[] memory _calldata ) external; /** @notice Lets whitelisted callers execute a single arbitrary call from the pool. Reverts if the call fails @param _target Address of the target to call @param _calldata Calldata of the call @param _value Amount of ETH to send with the call */ function singleCall( address _target, bytes calldata _calldata, uint256 _value ) external; /** @notice Add a whitelisted caller. Can only be called by the contract owner @param _caller Caller to add */ function addCaller(address _caller) external; /** @notice Remove a whitelisted caller. Can only be called by the contract owner */ function removeCaller(address _caller) external; /** @notice Checks if an address is a whitelisted caller @param _caller Address to check @return If the address is whitelisted */ function canCall(address _caller) external view returns (bool); /** @notice Get all whitelisted callers @return Array of whitelisted callers */ function getCallers() external view returns (address[] memory); }
/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/ This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is disstributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http:www.gnu.org/licenses/>.
interface IBPool { function isBound(address token) external view returns (bool); function getBalance(address token) external view returns (uint256); function rebind( address token, uint256 balance, uint256 denorm ) external; function setSwapFee(uint256 swapFee) external; function setPublicSwap(bool _public) external; function bind( address token, uint256 balance, uint256 denorm ) external; function unbind(address token) external; function getDenormalizedWeight(address token) external view returns (uint256); function getTotalDenormalizedWeight() external view returns (uint256); function getCurrentTokens() external view returns (address[] memory); function setController(address manager) external; function isPublicSwap() external view returns (bool); function getSwapFee() external view returns (uint256); function gulp(address token) external; function calcPoolOutGivenSingleIn( uint256 tokenBalanceIn, uint256 tokenWeightIn, uint256 poolSupply, uint256 totalWeight, uint256 tokenAmountIn, uint256 swapFee ) external pure returns (uint256 poolAmountOut); function calcSingleInGivenPoolOut( uint256 tokenBalanceIn, uint256 tokenWeightIn, uint256 poolSupply, uint256 totalWeight, uint256 poolAmountOut, uint256 swapFee ) external pure returns (uint256 tokenAmountIn); function calcSingleOutGivenPoolIn( uint256 tokenBalanceOut, uint256 tokenWeightOut, uint256 poolSupply, uint256 totalWeight, uint256 poolAmountIn, uint256 swapFee ) external pure returns (uint256 tokenAmountOut); function calcPoolInGivenSingleOut( uint256 tokenBalanceOut, uint256 tokenWeightOut, uint256 poolSupply, uint256 totalWeight, uint256 tokenAmountOut, uint256 swapFee ) external pure returns (uint256 poolAmountIn); }
14,728,672
[ 1, 6461, 25494, 759, 1220, 5402, 353, 4843, 17888, 30, 1846, 848, 5813, 887, 518, 471, 19, 280, 5612, 518, 3613, 326, 6548, 434, 326, 611, 50, 57, 9544, 7224, 16832, 487, 9487, 635, 326, 15217, 24199, 31289, 16, 3344, 1177, 890, 434, 326, 16832, 16, 578, 261, 270, 3433, 1456, 13, 1281, 5137, 1177, 18, 1220, 5402, 353, 1015, 87, 11050, 316, 326, 27370, 716, 518, 903, 506, 5301, 16, 1496, 13601, 5069, 16743, 678, 985, 54, 1258, 5538, 31, 2887, 5456, 326, 23547, 341, 5399, 970, 93, 434, 490, 654, 1792, 6856, 22879, 578, 478, 1285, 5407, 1260, 12108, 432, 20814, 2871, 19545, 30817, 18, 225, 2164, 326, 611, 50, 57, 9544, 7224, 16832, 364, 1898, 3189, 18, 4554, 1410, 1240, 5079, 279, 1610, 434, 326, 611, 50, 57, 9544, 7224, 16832, 7563, 598, 333, 5402, 18, 225, 971, 486, 16, 2621, 411, 2505, 30, 5591, 18, 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, 5831, 23450, 2864, 288, 203, 225, 445, 353, 3499, 12, 2867, 1147, 13, 3903, 1476, 1135, 261, 6430, 1769, 203, 203, 225, 445, 2882, 6112, 12, 2867, 1147, 13, 3903, 1476, 1135, 261, 11890, 5034, 1769, 203, 203, 225, 445, 283, 4376, 12, 203, 565, 1758, 1147, 16, 203, 565, 2254, 5034, 11013, 16, 203, 565, 2254, 5034, 5545, 535, 203, 225, 262, 3903, 31, 203, 203, 225, 445, 444, 12521, 14667, 12, 11890, 5034, 7720, 14667, 13, 3903, 31, 203, 203, 225, 445, 27467, 12521, 12, 6430, 389, 482, 13, 3903, 31, 203, 203, 225, 445, 1993, 12, 203, 565, 1758, 1147, 16, 203, 565, 2254, 5034, 11013, 16, 203, 565, 2254, 5034, 5545, 535, 203, 225, 262, 3903, 31, 203, 203, 225, 445, 17449, 12, 2867, 1147, 13, 3903, 31, 203, 203, 225, 445, 2343, 275, 1687, 1235, 6544, 12, 2867, 1147, 13, 3903, 1476, 1135, 261, 11890, 5034, 1769, 203, 203, 225, 445, 12831, 8517, 1687, 1235, 6544, 1435, 3903, 1476, 1135, 261, 11890, 5034, 1769, 203, 203, 225, 445, 5175, 5157, 1435, 3903, 1476, 1135, 261, 2867, 8526, 3778, 1769, 203, 203, 225, 445, 444, 2933, 12, 2867, 3301, 13, 3903, 31, 203, 203, 225, 445, 19620, 12521, 1435, 3903, 1476, 1135, 261, 6430, 1769, 203, 203, 225, 445, 1322, 91, 438, 14667, 1435, 3903, 1476, 1135, 261, 11890, 5034, 1769, 203, 203, 225, 445, 18568, 12, 2867, 1147, 13, 3903, 31, 203, 203, 225, 445, 7029, 2864, 1182, 6083, 5281, 382, 12, 203, 565, 2254, 5034, 1147, 13937, 382, 2 ]
./full_match/4/0x6b158de65B8338C065F6b8e0f26DC83484B51972/sources/contracts/tokens/ERC1155BridgeToken.sol
* @title ERC1155BridgeToken @dev template token contract for bridged ERC1155 tokens./ Optional mapping for token URIs Base URI
contract ERC1155BridgeToken is BaseRelayRecipient, ERC1155, IBurnableMintableERC1155Token { string public name; string public symbol; mapping(uint256 => string) private tokenURIs; string private baseURI; address public bridgeContract; bool private hasAlreadyMinted; constructor( string memory _name, string memory _symbol, address _bridgeContract ) ERC1155("") BaseRelayRecipient(address(0x83A54884bE4657706785D7309cf46B58FE5f6e8a)) { name = _name; symbol = _symbol; bridgeContract = _bridgeContract; } function _msgSender() internal override(Context, BaseRelayRecipient) view returns (address payable ret) { return BaseRelayRecipient._msgSender(); } function versionRecipient() external override view returns (string memory) { return "1.0.0"; } modifier onlyBridge() { require(msg.sender == bridgeContract); _; } modifier onlyOwner() { require(msg.sender == bridgeContract || msg.sender == IOwnable(bridgeContract).owner()); _; } function supportsInterface(bytes4 interfaceId) public view override(ERC165, IERC165) returns (bool) { bytes4 INTERFACE_ID_ERC165 = 0x01ffc9a7; bytes4 INTERFACE_ID_ERC1155 = 0xd9b67a26; bytes4 INTERFACE_ID_ERC1155_METADATA_URI = 0x0e89341c; return interfaceId == INTERFACE_ID_ERC165 || interfaceId == INTERFACE_ID_ERC1155 || interfaceId == INTERFACE_ID_ERC1155_METADATA_URI; } function _registerInterface(bytes4) internal override {} function mint( address _to, uint256[] memory _tokenIds, uint256[] memory _values ) external override onlyBridge { if (_tokenIds.length == 1 && _values.length == 1) { _mint(_to, _tokenIds[0], _values[0], new bytes(0)); if (!hasAlreadyMinted) { require(_tokenIds.length > 1 && _tokenIds.length == _values.length); uint256 len = _tokenIds.length - 1; _mint(_to, _tokenIds[len], _values[len], new bytes(0)); assembly { } } _mintBatch(_to, _tokenIds, _values, new bytes(0)); } hasAlreadyMinted = true; } function mint( address _to, uint256[] memory _tokenIds, uint256[] memory _values ) external override onlyBridge { if (_tokenIds.length == 1 && _values.length == 1) { _mint(_to, _tokenIds[0], _values[0], new bytes(0)); if (!hasAlreadyMinted) { require(_tokenIds.length > 1 && _tokenIds.length == _values.length); uint256 len = _tokenIds.length - 1; _mint(_to, _tokenIds[len], _values[len], new bytes(0)); assembly { } } _mintBatch(_to, _tokenIds, _values, new bytes(0)); } hasAlreadyMinted = true; } } else { function mint( address _to, uint256[] memory _tokenIds, uint256[] memory _values ) external override onlyBridge { if (_tokenIds.length == 1 && _values.length == 1) { _mint(_to, _tokenIds[0], _values[0], new bytes(0)); if (!hasAlreadyMinted) { require(_tokenIds.length > 1 && _tokenIds.length == _values.length); uint256 len = _tokenIds.length - 1; _mint(_to, _tokenIds[len], _values[len], new bytes(0)); assembly { } } _mintBatch(_to, _tokenIds, _values, new bytes(0)); } hasAlreadyMinted = true; } function mint( address _to, uint256[] memory _tokenIds, uint256[] memory _values ) external override onlyBridge { if (_tokenIds.length == 1 && _values.length == 1) { _mint(_to, _tokenIds[0], _values[0], new bytes(0)); if (!hasAlreadyMinted) { require(_tokenIds.length > 1 && _tokenIds.length == _values.length); uint256 len = _tokenIds.length - 1; _mint(_to, _tokenIds[len], _values[len], new bytes(0)); assembly { } } _mintBatch(_to, _tokenIds, _values, new bytes(0)); } hasAlreadyMinted = true; } function burn(uint256[] memory _tokenIds, uint256[] memory _values) external override onlyBridge { _burnBatch(msg.sender, _tokenIds, _values); } function setBridgeContract(address _bridgeContract) external onlyOwner { require(_bridgeContract != address(0)); bridgeContract = _bridgeContract; } function setBaseURI(string calldata _baseURI) external onlyOwner { baseURI = _baseURI; } function setTokenURI(uint256 _tokenId, string calldata _tokenURI) external onlyOwner { tokenURIs[_tokenId] = _tokenURI; } function uri(uint256 _tokenId) external view override returns (string memory) { string memory tokenURI = tokenURIs[_tokenId]; string memory base = baseURI; if (bytes(base).length == 0) { return tokenURI; } } function uri(uint256 _tokenId) external view override returns (string memory) { string memory tokenURI = tokenURIs[_tokenId]; string memory base = baseURI; if (bytes(base).length == 0) { return tokenURI; } } return string(abi.encodePacked(base, tokenURI)); function getTokenInterfacesVersion() external pure returns ( uint64 major, uint64 minor, uint64 patch ) { return (1, 1, 0); } }
12,305,741
[ 1, 654, 39, 2499, 2539, 13691, 1345, 225, 1542, 1147, 6835, 364, 324, 1691, 2423, 4232, 39, 2499, 2539, 2430, 18, 19, 4055, 2874, 364, 1147, 24565, 3360, 3699, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 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, 4232, 39, 2499, 2539, 13691, 1345, 353, 3360, 27186, 18241, 16, 4232, 39, 2499, 2539, 16, 23450, 321, 429, 49, 474, 429, 654, 39, 2499, 2539, 1345, 288, 203, 565, 533, 1071, 508, 31, 203, 565, 533, 1071, 3273, 31, 203, 203, 565, 2874, 12, 11890, 5034, 516, 533, 13, 3238, 1147, 1099, 2520, 31, 203, 565, 533, 3238, 1026, 3098, 31, 203, 203, 565, 1758, 1071, 10105, 8924, 31, 203, 203, 565, 1426, 3238, 711, 9430, 49, 474, 329, 31, 203, 203, 565, 3885, 12, 203, 3639, 533, 3778, 389, 529, 16, 203, 3639, 533, 3778, 389, 7175, 16, 203, 3639, 1758, 389, 18337, 8924, 203, 565, 262, 4232, 39, 2499, 2539, 2932, 7923, 3360, 27186, 18241, 12, 2867, 12, 20, 92, 10261, 37, 6564, 28, 5193, 70, 41, 8749, 25, 4700, 7677, 27, 7140, 40, 27, 5082, 29, 8522, 8749, 38, 8204, 8090, 25, 74, 26, 73, 28, 69, 3719, 288, 203, 3639, 508, 273, 389, 529, 31, 203, 3639, 3273, 273, 389, 7175, 31, 203, 3639, 10105, 8924, 273, 389, 18337, 8924, 31, 203, 565, 289, 203, 203, 565, 445, 389, 3576, 12021, 1435, 2713, 3849, 12, 1042, 16, 3360, 27186, 18241, 13, 1476, 1135, 261, 2867, 8843, 429, 325, 13, 288, 203, 3639, 327, 3360, 27186, 18241, 6315, 3576, 12021, 5621, 203, 565, 289, 203, 203, 565, 445, 1177, 18241, 1435, 3903, 3849, 1476, 1135, 261, 1080, 3778, 13, 288, 203, 3639, 327, 315, 21, 18, 20, 18, 20, 14432, 203, 565, 289, 203, 203, 565, 9606, 1338, 13691, 2 ]
pragma solidity ^0.6.4; import "./Item.sol"; import "./Ownable.sol"; //We want to initially deploy the ItemManager contract contract ItemManager is Ownable { //enum of the state the item is in enum SupplyChainState{Created, Paid, Delivered} //Creating the item structure struct S_Item { // from contract "Item" Item _item; string _identifier; uint _itemPrice; //Simplifying enum to _state ItemManager.SupplyChainState _state; } //Mapping stores each item as an object/struct mapping(uint => S_Item) public items; uint itemIndex; event SupplyChainStep(uint _itemIndex, uint _step, address _itemAddress); //This creates the item. Param 1 is name of item, param 2 is its price //Only the owner can create items function createItem(string memory _identifier, uint _itemPrice) public onlyOwner{ //creates new instance of Item Item item = new Item(this, _itemPrice, itemIndex); items[itemIndex]._item = item; //Assigns item's attributes to the mapping items[itemIndex]._identifier = _identifier; items[itemIndex]._itemPrice = _itemPrice; items[itemIndex]._state = SupplyChainState.Created; //returns index of item and step in the enum emit SupplyChainStep(itemIndex, uint(items[itemIndex]._state), address(item)); itemIndex++; } function triggerPayment(uint _itemIndex) public payable { //The address must send a full payment and the item must be in the "Created" state require(items[_itemIndex]._itemPrice == msg.value, "Sorry! We only accept full payments..."); require(items[_itemIndex]._state == SupplyChainState.Created, "Seems like you have already paid for your product!"); items[_itemIndex]._state = SupplyChainState.Paid; emit SupplyChainStep(_itemIndex, uint(items[_itemIndex]._state), address(items[_itemIndex]._item)); } function triggerDelivery(uint _itemIndex) public onlyOwner { //Item must be in the "Paid" state require(items[_itemIndex]._state == SupplyChainState.Paid, "Seems like the product has been delivered or hasn't been created!"); items[_itemIndex]._state = SupplyChainState.Delivered; emit SupplyChainStep(_itemIndex, uint(items[_itemIndex]._state), address(items[_itemIndex]._item)); } }
We want to initially deploy the ItemManager contractenum of the state the item is inCreating the item structure
contract ItemManager is Ownable { enum SupplyChainState{Created, Paid, Delivered} struct S_Item { Item _item; string _identifier; uint _itemPrice; ItemManager.SupplyChainState _state; } uint itemIndex; event SupplyChainStep(uint _itemIndex, uint _step, address _itemAddress); mapping(uint => S_Item) public items; function createItem(string memory _identifier, uint _itemPrice) public onlyOwner{ Item item = new Item(this, _itemPrice, itemIndex); items[itemIndex]._item = item; items[itemIndex]._identifier = _identifier; items[itemIndex]._itemPrice = _itemPrice; items[itemIndex]._state = SupplyChainState.Created; emit SupplyChainStep(itemIndex, uint(items[itemIndex]._state), address(item)); itemIndex++; } function triggerPayment(uint _itemIndex) public payable { require(items[_itemIndex]._itemPrice == msg.value, "Sorry! We only accept full payments..."); require(items[_itemIndex]._state == SupplyChainState.Created, "Seems like you have already paid for your product!"); items[_itemIndex]._state = SupplyChainState.Paid; emit SupplyChainStep(_itemIndex, uint(items[_itemIndex]._state), address(items[_itemIndex]._item)); } function triggerDelivery(uint _itemIndex) public onlyOwner { require(items[_itemIndex]._state == SupplyChainState.Paid, "Seems like the product has been delivered or hasn't been created!"); items[_itemIndex]._state = SupplyChainState.Delivered; emit SupplyChainStep(_itemIndex, uint(items[_itemIndex]._state), address(items[_itemIndex]._item)); } }
974,246
[ 1, 3218, 2545, 358, 22458, 7286, 326, 4342, 1318, 6835, 7924, 434, 326, 919, 326, 761, 353, 316, 11092, 326, 761, 3695, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 16351, 4342, 1318, 353, 14223, 6914, 288, 203, 203, 203, 565, 2792, 3425, 1283, 3893, 1119, 95, 6119, 16, 453, 20736, 16, 6603, 1667, 329, 97, 203, 565, 1958, 348, 67, 1180, 288, 203, 3639, 4342, 389, 1726, 31, 203, 203, 3639, 533, 389, 5644, 31, 203, 3639, 2254, 389, 1726, 5147, 31, 203, 3639, 4342, 1318, 18, 3088, 1283, 3893, 1119, 389, 2019, 31, 203, 565, 289, 203, 203, 203, 565, 2254, 761, 1016, 31, 203, 203, 565, 871, 3425, 1283, 3893, 4160, 12, 11890, 389, 1726, 1016, 16, 2254, 389, 4119, 16, 1758, 389, 1726, 1887, 1769, 203, 203, 565, 2874, 12, 11890, 516, 348, 67, 1180, 13, 1071, 1516, 31, 203, 565, 445, 29274, 12, 1080, 3778, 389, 5644, 16, 2254, 389, 1726, 5147, 13, 1071, 1338, 5541, 95, 203, 3639, 4342, 761, 273, 394, 4342, 12, 2211, 16, 389, 1726, 5147, 16, 761, 1016, 1769, 203, 3639, 1516, 63, 1726, 1016, 65, 6315, 1726, 273, 761, 31, 203, 540, 203, 3639, 1516, 63, 1726, 1016, 65, 6315, 5644, 273, 389, 5644, 31, 203, 3639, 1516, 63, 1726, 1016, 65, 6315, 1726, 5147, 273, 389, 1726, 5147, 31, 203, 3639, 1516, 63, 1726, 1016, 65, 6315, 2019, 273, 3425, 1283, 3893, 1119, 18, 6119, 31, 203, 3639, 3626, 3425, 1283, 3893, 4160, 12, 1726, 1016, 16, 2254, 12, 3319, 63, 1726, 1016, 65, 6315, 2019, 3631, 1758, 12, 1726, 10019, 203, 3639, 761, 1016, 9904, 31, 203, 565, 289, 203, 203, 565, 445, 3080, 6032, 12, 11890, 389, 1726, 1016, 13, 2 ]
./full_match/4/0xA42e1Fa47208874B8620890C293E89F49Cd5843E/sources/contracts/BSTICKS.sol
@notice Claim Breadsticks for a given NFOG ID @param tokenId The tokenId of the NFOG NFT Further Checks, Effects, and Interactions are contained within the _claim() function
function claimById(uint256 tokenId) external { require(_msgSender() == nfogAirdropWallet, "Can only be initiated by NFOG wallet"); require(bsticksPerNFOG <= balanceOf(nfogAirdropWallet), "NFOG Airdrop Wallet doesn't have enough $BSTICK for this claim"); require(tokenId >= 0 && tokenId <= 879); _claim(tokenId, _msgSender()); }
697,567
[ 1, 9762, 605, 896, 334, 20642, 364, 279, 864, 423, 3313, 43, 1599, 225, 1147, 548, 1021, 1147, 548, 434, 326, 423, 3313, 43, 423, 4464, 478, 8753, 13074, 16, 30755, 87, 16, 471, 5294, 4905, 854, 7542, 3470, 326, 389, 14784, 1435, 445, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 7516, 5132, 12, 11890, 5034, 1147, 548, 13, 3903, 288, 203, 3639, 2583, 24899, 3576, 12021, 1435, 422, 290, 617, 75, 37, 6909, 1764, 16936, 16, 315, 2568, 1338, 506, 27183, 635, 423, 3313, 43, 9230, 8863, 203, 3639, 2583, 12, 70, 334, 20642, 2173, 50, 3313, 43, 1648, 11013, 951, 12, 82, 617, 75, 37, 6909, 1764, 16936, 3631, 315, 50, 3313, 43, 432, 6909, 1764, 20126, 3302, 1404, 1240, 7304, 271, 38, 882, 16656, 364, 333, 7516, 8863, 203, 3639, 2583, 12, 2316, 548, 1545, 374, 597, 1147, 548, 1648, 1725, 7235, 1769, 203, 203, 3639, 389, 14784, 12, 2316, 548, 16, 389, 3576, 12021, 10663, 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 ]
pragma solidity 0.5.15; pragma experimental ABIEncoderV2; import {PredicateRegistry} from 'ROOT/matic/PredicateRegistry.sol'; import {BytesLib} from 'ROOT/matic/libraries/BytesLib.sol'; import {RLPEncode} from 'ROOT/matic/libraries/RLPEncode.sol'; import {RLPReader} from 'ROOT/matic/libraries/RLPReader.sol'; import {IWithdrawManager} from 'ROOT/matic/plasma/IWithdrawManager.sol'; import {IShareToken} from 'ROOT/reporting/IShareToken.sol'; import {IMarket} from 'ROOT/reporting/IMarket.sol'; import {Initializable} from 'ROOT/libraries/Initializable.sol'; contract ShareTokenPredicate is Initializable { using RLPReader for bytes; using RLPReader for RLPReader.RLPItem; event ExitFinalized(uint256 indexed exitId, address indexed exitor); bytes32 internal constant SHARE_TOKEN_BALANCE_CHANGED_EVENT_SIG = 0x350ea32dc29530b9557420816d743c436f8397086f98c96292138edd69e01cb3; uint256 internal constant MAX_LOGS = 100; PredicateRegistry public predicateRegistry; IWithdrawManager public withdrawManager; // keccak256('unsafeTransferFrom(address,address,uint256,uint256)').slice(0, 4) bytes4 constant UNSAFE_TRANSFER_FROM_FUNC_SIG = 0xa9059cbb; // @todo write the correct sig // keccak256('unsafeBatchTransferFrom(address,address,uint256[],uint256[])').slice(0, 4) bytes4 constant UNSAFE_BATCH_TRANSFER_FROM_FUNC_SIG = 0xa9059cbb; // @todo write the correct sig function initialize( PredicateRegistry _predicateRegistry, IWithdrawManager _withdrawManager ) public // IErc20Predicate _erc20Predicate { endInitialization(); predicateRegistry = _predicateRegistry; withdrawManager = _withdrawManager; // erc20Predicate = _erc20Predicate; } /** * @notice Proof receipt and index of the log (ShareTokenBalanceChanged) in the receipt to claim balance from Matic * @param data RLP encoded data of the reference tx (proof-of-funds) that encodes the following fields * headerNumber Header block number of which the reference tx was a part of * blockProof Proof that the block header (in the child chain) is a leaf in the submitted merkle root * blockNumber Block number of which the reference tx is a part of * blockTime Reference tx block time * blocktxRoot Transactions root of block * blockReceiptsRoot Receipts root of block * receipt Receipt of the reference transaction * receiptProof Merkle proof of the reference receipt * branchMask Merkle proof branchMask for the receipt * logIndex Log Index to read from the receipt */ function parseData(bytes calldata data) external view returns ( address account, address market, uint256 outcome, uint256 balance, uint256 age ) { RLPReader.RLPItem[] memory referenceTxData = data.toRlpItem().toList(); bytes memory receipt = referenceTxData[6].toBytes(); RLPReader.RLPItem[] memory inputItems = receipt.toRlpItem().toList(); uint256 logIndex = referenceTxData[9].toUint(); require(logIndex < MAX_LOGS, 'Supporting a max of 100 logs'); age = withdrawManager.verifyInclusion( data, 0, /* offset */ false /* verifyTxInclusion */ ); inputItems = inputItems[3].toList()[logIndex].toList(); // select log based on given logIndex bytes memory logData = inputItems[2].toBytes(); inputItems = inputItems[1].toList(); // topics // now, inputItems[i] refers to i-th (0-based) topic in the topics array // event ShareTokenBalanceChanged(address indexed universe, address indexed account, address indexed market, uint256 outcome, uint256 balance); require( bytes32(inputItems[0].toUint()) == SHARE_TOKEN_BALANCE_CHANGED_EVENT_SIG, 'ShareTokenPredicate.parseData: Not ShareTokenBalanceChanged event signature' ); // inputItems[1] is the universe account = address(inputItems[2].toUint()); market = address(inputItems[3].toUint()); outcome = BytesLib.toUint(logData, 0); balance = BytesLib.toUint(logData, 32); } function executeInFlightTransaction( bytes memory txData, address signer, IShareToken exitShareToken ) public returns (int256 nonce) { RLPReader.RLPItem[] memory txList = txData.toRlpItem().toList(); nonce = int256(txList[0].toUint()); txData = RLPReader.toBytes(txList[5]); bytes4 funcSig = BytesLib.toBytes4(BytesLib.slice(txData, 0, 4)); if (funcSig == UNSAFE_TRANSFER_FROM_FUNC_SIG) { (address from, address to, uint256 id, uint256 value) = abi.decode( BytesLib.slice(txData, 4, txData.length - 4), (address, address, uint256, uint256) ); require(signer == from, 'signer != from'); exitShareToken.unsafeTransferFrom( from, to, repackageTokenId(id), value ); } else if (funcSig == UNSAFE_BATCH_TRANSFER_FROM_FUNC_SIG) { ( address from, address to, uint256[] memory id, uint256[] memory value ) = abi.decode( BytesLib.slice(txData, 4, txData.length - 4), (address, address, uint256[], uint256[]) ); require(signer == from, 'signer != from'); exitShareToken.unsafeBatchTransferFrom( from, to, repackageTokenIds(id), value ); } else { revert('Inflight tx type not supported'); } } function isValidDeprecation(bytes memory txData) public pure returns (bool) { bytes4 funcSig = BytesLib.toBytes4(BytesLib.slice(txData, 0, 4)); if ( funcSig == UNSAFE_TRANSFER_FROM_FUNC_SIG || funcSig == UNSAFE_BATCH_TRANSFER_FROM_FUNC_SIG ) { return true; } } function repackageTokenIds(uint256[] memory _tokenIds) internal view returns (uint256[] memory tokenIds) { tokenIds = new uint256[](_tokenIds.length); for (uint256 i = 0; i < _tokenIds.length; i++) { tokenIds[i] = repackageTokenId(_tokenIds[i]); } } function repackageTokenId(uint256 _tokenId) internal view returns ( uint256 /* tokenId */ ) { (address _market, uint256 _outcome) = unpackTokenId(_tokenId); (address _rootMarket, , ) = predicateRegistry.childToRootMarket( _market ); require( _rootMarket != address(0x0), 'repackageTokenId: Market does not exist' ); return getTokenId(IMarket(_rootMarket), _outcome); } function getTokenId(IMarket _market, uint256 _outcome) internal pure returns (uint256 _tokenId) { bytes memory _tokenIdBytes = abi.encodePacked(_market, uint8(_outcome)); assembly { _tokenId := mload(add(_tokenIdBytes, add(0x20, 0))) } } function unpackTokenId(uint256 _tokenId) internal pure returns (address _market, uint256 _outcome) { assembly { _market := shr( 96, and( _tokenId, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF000000000000000000000000 ) ) _outcome := shr( 88, and( _tokenId, 0x0000000000000000000000000000000000000000FF0000000000000000000000 ) ) } } }
* @notice Proof receipt and index of the log (ShareTokenBalanceChanged) in the receipt to claim balance from Matic @param data RLP encoded data of the reference tx (proof-of-funds) that encodes the following fields headerNumber Header block number of which the reference tx was a part of blockProof Proof that the block header (in the child chain) is a leaf in the submitted merkle root blockNumber Block number of which the reference tx is a part of blockTime Reference tx block time blocktxRoot Transactions root of block blockReceiptsRoot Receipts root of block receipt Receipt of the reference transaction receiptProof Merkle proof of the reference receipt branchMask Merkle proof branchMask for the receipt logIndex Log Index to read from the receipt/ now, inputItems[i] refers to i-th (0-based) topic in the topics array event ShareTokenBalanceChanged(address indexed universe, address indexed account, address indexed market, uint256 outcome, uint256 balance); inputItems[1] is the universe
function parseData(bytes calldata data) external view returns ( address account, address market, uint256 outcome, uint256 balance, uint256 age ) { RLPReader.RLPItem[] memory referenceTxData = data.toRlpItem().toList(); bytes memory receipt = referenceTxData[6].toBytes(); RLPReader.RLPItem[] memory inputItems = receipt.toRlpItem().toList(); uint256 logIndex = referenceTxData[9].toUint(); require(logIndex < MAX_LOGS, 'Supporting a max of 100 logs'); age = withdrawManager.verifyInclusion( data, 0, /* offset */ false /* verifyTxInclusion */ ); bytes memory logData = inputItems[2].toBytes(); require( bytes32(inputItems[0].toUint()) == SHARE_TOKEN_BALANCE_CHANGED_EVENT_SIG, 'ShareTokenPredicate.parseData: Not ShareTokenBalanceChanged event signature' ); account = address(inputItems[2].toUint()); market = address(inputItems[3].toUint()); outcome = BytesLib.toUint(logData, 0); balance = BytesLib.toUint(logData, 32); }
12,725,885
[ 1, 20439, 16030, 471, 770, 434, 326, 613, 261, 9535, 1345, 13937, 5033, 13, 316, 326, 16030, 358, 7516, 11013, 628, 490, 2126, 225, 501, 534, 14461, 3749, 501, 434, 326, 2114, 2229, 261, 24207, 17, 792, 17, 74, 19156, 13, 716, 16834, 326, 3751, 1466, 1446, 1854, 4304, 1203, 1300, 434, 1492, 326, 2114, 2229, 1703, 279, 1087, 434, 1203, 20439, 1186, 792, 716, 326, 1203, 1446, 261, 267, 326, 1151, 2687, 13, 353, 279, 7839, 316, 326, 9638, 30235, 1365, 1203, 1854, 3914, 1300, 434, 1492, 326, 2114, 2229, 353, 279, 1087, 434, 1203, 950, 6268, 2229, 1203, 813, 1203, 978, 2375, 27148, 1365, 434, 1203, 1203, 4779, 27827, 2375, 9797, 27827, 1365, 434, 1203, 16030, 29787, 434, 326, 2114, 2492, 16030, 20439, 31827, 14601, 434, 326, 2114, 16030, 3803, 5796, 31827, 14601, 3803, 5796, 364, 326, 16030, 613, 1016, 1827, 3340, 358, 855, 628, 326, 16030, 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, 1109, 751, 12, 3890, 745, 892, 501, 13, 203, 3639, 3903, 203, 3639, 1476, 203, 3639, 1135, 261, 203, 5411, 1758, 2236, 16, 203, 5411, 1758, 13667, 16, 203, 5411, 2254, 5034, 12884, 16, 203, 5411, 2254, 5034, 11013, 16, 203, 5411, 2254, 5034, 9388, 203, 3639, 262, 203, 565, 288, 203, 3639, 534, 14461, 2514, 18, 54, 48, 1102, 874, 8526, 3778, 2114, 4188, 751, 273, 501, 18, 869, 54, 9953, 1180, 7675, 869, 682, 5621, 203, 3639, 1731, 3778, 16030, 273, 2114, 4188, 751, 63, 26, 8009, 869, 2160, 5621, 203, 3639, 534, 14461, 2514, 18, 54, 48, 1102, 874, 8526, 3778, 810, 3126, 273, 16030, 18, 869, 54, 9953, 1180, 7675, 869, 682, 5621, 203, 3639, 2254, 5034, 613, 1016, 273, 2114, 4188, 751, 63, 29, 8009, 869, 5487, 5621, 203, 3639, 2583, 12, 1330, 1016, 411, 4552, 67, 4842, 55, 16, 296, 6289, 310, 279, 943, 434, 2130, 5963, 8284, 203, 3639, 9388, 273, 598, 9446, 1318, 18, 8705, 382, 15335, 12, 203, 5411, 501, 16, 203, 5411, 374, 16, 1748, 1384, 1195, 203, 5411, 629, 1748, 3929, 4188, 382, 15335, 1195, 203, 3639, 11272, 203, 3639, 1731, 3778, 613, 751, 273, 810, 3126, 63, 22, 8009, 869, 2160, 5621, 203, 3639, 2583, 12, 203, 5411, 1731, 1578, 12, 2630, 3126, 63, 20, 8009, 869, 5487, 10756, 422, 203, 7734, 6122, 9332, 67, 8412, 67, 38, 1013, 4722, 67, 24435, 67, 10454, 67, 18513, 16, 203, 5411, 296, 9535, 1345, 8634, 18, 2670, 751, 30, 2288, 25805, 1345, 2 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.6.6; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@chainlink/contracts/src/v0.6/ChainlinkClient.sol"; contract Turtis is ERC721, ChainlinkClient { address public contractOwner; // Owner of this contract // Bytes32 data related to IPFS Hash returned from the API bytes32 private ipfsHashOneBytes32; bytes32 private ipfsHashTwoBytes32; string public ipfsLink = "ipfs://"; // Stores the IPFS link after the API call // Chainlink Oracle, Job ID and fee required for making the API call using Chainlink address private oracle; bytes32 private jobId; uint256 private fee; uint256 private uniqueTokenId = 0; // Unique TokenID string private apiBaseUrl; // Stores the base url of the api string private apiSecondUrl; // API url for the second call address[] private users; // Address array to store all the users // Mapping from Token ID to Price mapping(uint256 => uint256) public turtlesForSale; // Mapping from User address to high score mapping(address => string) public userAddressToHighScore; // Events // Emitted when a new Turtle is generated after reaching a new checkpoint in the game event NewTurtleGenerated(uint256 tokenId); // Emitted when the data received from the API is successful event DataReceivedFromAPI(string ipfsLink); // Emitted when a turtle is bought event TurtleBought(uint256 tokenId); // Emitted when a turtle is put up for sale event TurtleUpForSale(uint256 tokenId); /** * Network: Matic Mumbai Testnet * Oracle: 0xc8D925525CA8759812d0c299B90247917d4d4b7C * Job ID: a7330d0b4b964c05abc66a26307047c0 * LINK address: 0x326C977E6efc84E512bB9C30f76E30c160eD06FB * Fee: 0.01 LINK */ // Contructor is called when an instance of 'TurtleCharacter' contract is deployed constructor() public ERC721("TurtleCharacter", "TRTL") { setChainlinkToken(0x326C977E6efc84E512bB9C30f76E30c160eD06FB); uniqueTokenId = 0; contractOwner = msg.sender; apiBaseUrl = "https://images-blend.herokuapp.com/"; apiSecondUrl = "https://images-blend.herokuapp.com/second/"; oracle = 0xc8D925525CA8759812d0c299B90247917d4d4b7C; // Address of the chainlink oracle jobId = "a7330d0b4b964c05abc66a26307047c0"; // This Job gets data from an API in the form of a bytes32 variable fee = 0.01 * 10**18; // 0.01 LINK (Fee for Chainlink Oracle for returning the required data) } // Modifer that checks to see if msg.sender == contractOwner modifier onlyContractOwner() { require( msg.sender == contractOwner, "The caller is not the contract owner" ); _; } // Function 'getUsers' returns the address array of users function getUsers() public view returns (address[] memory) { return users; } // Function 'setOracleAddress' sets a new oracle address function setOracleAddress(address _oracleAddress) public onlyContractOwner { oracle = _oracleAddress; } // Function 'setJobID' sets a new job ID function setJobID(string memory _jobID) public onlyContractOwner { jobId = stringToBytes32(_jobID); } // Function 'setFeeInLink' sets a new fee for the Chainlink Oracle function setFeeInLink(uint256 _fee) public onlyContractOwner { fee = _fee * 10**18; } // Function 'setApiBaseUrl' sets a new base URL link for the API function setApiBaseUrl(string memory _url) public onlyContractOwner { apiBaseUrl = _url; } // Function 'setApiSecondUrl' sets a new second URL link for the API function setApiSecondUrl(string memory _url) public onlyContractOwner { apiSecondUrl = _url; } // Function 'setHighScore' sets a new highScore for the user function setHighScore(string memory _highScore, address _sender) internal { bytes memory score = bytes(userAddressToHighScore[_sender]); if (score.length == 0) { users.push(_sender); } userAddressToHighScore[_sender] = _highScore; } // Function 'buyTurtle' allows anyone to buy a turtle that is put up for sale function buyTurtle(uint256 _tokenId) public payable { require(turtlesForSale[_tokenId] > 0, "The Turtle should be up for sale"); uint256 turtleCost = turtlesForSale[_tokenId]; turtlesForSale[_tokenId] = 0; address ownerAddress = ownerOf(_tokenId); require(msg.value > turtleCost, "You need to have enough Ether"); _safeTransfer(ownerAddress, msg.sender, _tokenId, bytes("Buy a Turtle")); // ERC721 Token is safely transferred using this function call address payable ownerAddressPayable = payable(ownerAddress); ownerAddressPayable.transfer(turtleCost); if (msg.value > turtleCost) { payable(msg.sender).transfer(msg.value - turtleCost); // Excess Ether is returned back to the buyer } emit TurtleBought(_tokenId); } // Function 'putUpTurtleForSale' allows a turtle owner to put it up for sale function putUpTurtleForSale(uint256 _tokenId, uint256 _price) public { require( _isApprovedOrOwner(_msgSender(), _tokenId), "ERC721: Caller is not owner nor approved" ); turtlesForSale[_tokenId] = _price; emit TurtleUpForSale(_tokenId); } // Function 'requestNewRandomTurtle' mints a new Turtle character function requestNewRandomTurtle(string memory score) public { setHighScore(score, msg.sender); ipfsLink = "ipfs://"; _safeMint(msg.sender, uniqueTokenId++); string memory apiLink = append(apiBaseUrl, "?score=", score); string memory characterId = uint2str(totalSupply()); apiLink = append(apiLink, "&characterId=", characterId); requestIPFSHash(apiLink); } // Function 'requestIPFSHash' requests a new IPFS hash from the API function requestIPFSHash(string memory apiLink) private returns (bytes32 requestId) { Chainlink.Request memory request = buildChainlinkRequest( jobId, address(this), this.fulfill.selector ); request.add("get", apiLink); request.add("path", "IPFS_PATH"); return sendChainlinkRequestTo(oracle, request, fee); } // Function 'fulfill' is called after the response for the API call is received function fulfill(bytes32 _requestId, bytes32 dataFromAPI) public recordChainlinkFulfillment(_requestId) returns (bytes32 requestId) { ipfsHashOneBytes32 = dataFromAPI; Chainlink.Request memory request = buildChainlinkRequest( jobId, address(this), this.fulfillSecondRequest.selector ); request.add("get", apiSecondUrl); request.add("path", "IPFS_PATH"); return sendChainlinkRequestTo(oracle, request, fee); } // Function 'fulfillSecondRequest' is called after the response for the API call is received function fulfillSecondRequest(bytes32 _requestId, bytes32 dataFromAPI) public recordChainlinkFulfillment(_requestId) { ipfsHashTwoBytes32 = dataFromAPI; generateIPFSLink(); emit DataReceivedFromAPI(ipfsLink); setTokenURI(ipfsLink); emit NewTurtleGenerated(uniqueTokenId - 1); } // Function 'bytes32ToString' convers a bytes32 variable to a string variable function bytes32ToString(bytes32 _bytes32) internal pure returns (string memory) { uint8 i = 0; while (i < 32 && _bytes32[i] != 0) { i++; } bytes memory bytesArray = new bytes(i); for (i = 0; i < 32 && _bytes32[i] != 0; i++) { bytesArray[i] = _bytes32[i]; } return string(bytesArray); } // Function 'stringToBytes32' convers a string variable to a bytes32 variable function stringToBytes32(string memory source) internal pure returns (bytes32 result) { bytes memory tempEmptyStringTest = bytes(source); if (tempEmptyStringTest.length == 0) { return 0x0; } assembly { result := mload(add(source, 32)) } } // Function 'generateIPFSLink' generates the IPFS link from the 2 API calls function generateIPFSLink() private { string memory ipfsHashPartOne = bytes32ToString(ipfsHashOneBytes32); string memory ipfsHashPartTwo = bytes32ToString(ipfsHashTwoBytes32); ipfsLink = append(ipfsLink, ipfsHashPartOne, ipfsHashPartTwo); ipfsLink = append(ipfsLink, "/metadata", ".json"); } // Function 'append' appends 3 strings function append( string memory a, string memory b, string memory c ) internal pure returns (string memory) { return string(abi.encodePacked(a, b, c)); } // Function 'uint2str' converts a uint256 variable to a string variable function uint2str(uint256 _i) internal pure returns (string memory _uintAsString) { 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; while (_i != 0) { k = k - 1; uint8 temp = (48 + uint8(_i - (_i / 10) * 10)); bytes1 b1 = bytes1(temp); bstr[k] = b1; _i /= 10; } return string(bstr); } // Function 'setTokenURI' sets the Token URI for the ERC721 standard token function setTokenURI(string memory _tokenURI) private { uint256 lastTokenId = totalSupply() - 1; _setTokenURI(lastTokenId, _tokenURI); } // Function 'updateTokenURI' updates the Token URI for a specific Token function updateTokenURI(uint256 _tokenId, string memory _tokenURI) public onlyContractOwner { _setTokenURI(_tokenId, _tokenURI); } }
API url for the second call
string private apiSecondUrl;
12,617,613
[ 1, 2557, 880, 364, 326, 2205, 745, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 225, 533, 3238, 1536, 8211, 1489, 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 ]
./partial_match/3/0xBB9dAB0ecb218ad758453E3e4d7c06BDF72754DC/sources/Users/erinshaben/Work/box-project/contracts/ArrayContract.sol
assignment to a storage array performs a copy of ``newPairs`` and replaces the complete array ``m_pairsOfFlags``.
function setAllFlagPairs(string[2][] memory newPairs) public { m_pairsOfStrings = newPairs; }
5,272,667
[ 1, 12960, 358, 279, 2502, 526, 11199, 279, 1610, 434, 12176, 2704, 10409, 10335, 471, 12878, 326, 3912, 526, 12176, 81, 67, 11545, 951, 5094, 68, 8338, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 30213, 4678, 10409, 12, 1080, 63, 22, 6362, 65, 3778, 394, 10409, 13, 1071, 288, 203, 3639, 312, 67, 11545, 951, 7957, 273, 394, 10409, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity 0.8.11; import "sol-temple/src/tokens/ERC721.sol"; import "sol-temple/src/utils/Auth.sol"; import "sol-temple/src/utils/Pausable.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol"; /** * @title Ape Runners * @author naomsa <https://twitter.com/naomsa666> */ contract ApeRunners is Auth, Pausable, ERC721("Ape Runners", "AR") { using Strings for uint256; using MerkleProof for bytes32[]; /// @notice Max supply. uint256 public constant MAX_SUPPLY = 5000; /// @notice Max amount per claim (public sale). uint256 public constant MAX_PER_TX = 10; /// @notice Claim price. uint256 public constant PRICE = 0.04 ether; /// @notice 0 = CLOSED, 1 = WHITELIST, 2 = PUBLIC. uint256 public saleState; /// @notice Metadata base URI. string public baseURI; /// @notice Metadata URI extension. string public baseExtension; /// @notice Unrevealed metadata URI. string public unrevealedURI; /// @notice Whitelist merkle root. bytes32 public merkleRoot; /// @notice Whitelist mints per address. mapping(address => uint256) public whitelistMinted; /// @notice OpenSea proxy registry. address public opensea; /// @notice LooksRare marketplace transfer manager. address public looksrare; /// @notice Check if marketplaces pre-approve is enabled. bool public marketplacesApproved = true; constructor( string memory unrevealedURI_, bytes32 merkleRoot_, address opensea_, address looksrare_ ) { unrevealedURI = unrevealedURI_; merkleRoot = merkleRoot_; opensea = opensea_; looksrare = looksrare_; for (uint256 i = 0; i < 50; i++) _safeMint(msg.sender, i); } /// @notice Claim one or more tokens. function claim(uint256 amount_) external payable { uint256 supply = totalSupply(); require(supply + amount_ <= MAX_SUPPLY, "Max supply exceeded"); if (msg.sender != owner()) { require(saleState == 2, "Public sale is not open"); require(amount_ > 0 && amount_ <= MAX_PER_TX, "Invalid claim amount"); require(msg.value == PRICE * amount_, "Invalid ether amount"); } for (uint256 i = 0; i < amount_; i++) _safeMint(msg.sender, supply++); } /// @notice Claim one or more tokens for whitelisted user. function claimWhitelist(uint256 amount_, bytes32[] memory proof_) external payable { uint256 supply = totalSupply(); require(supply + amount_ <= MAX_SUPPLY, "Max supply exceeded"); if (msg.sender != owner()) { require(saleState == 1, "Whitelist sale is not open"); require( amount_ > 0 && amount_ + whitelistMinted[msg.sender] <= MAX_PER_TX, "Invalid claim amount" ); require(msg.value == PRICE * amount_, "Invalid ether amount"); require(isWhitelisted(msg.sender, proof_), "Invalid proof"); } whitelistMinted[msg.sender] += amount_; for (uint256 i = 0; i < amount_; i++) _safeMint(msg.sender, supply++); } /// @notice Retrieve if `user_` is whitelisted based on his `proof_`. function isWhitelisted(address user_, bytes32[] memory proof_) public view returns (bool) { bytes32 leaf = keccak256(abi.encodePacked(user_)); return proof_.verify(merkleRoot, leaf); } /** * @notice See {IERC721-tokenURI}. * @dev In order to make a metadata reveal, there must be an unrevealedURI string, which * gets set on the constructor and, for optimization purposes, when the owner() sets a new * baseURI, the unrevealedURI gets deleted, saving gas and triggering a reveal. */ function tokenURI(uint256 tokenId_) public view override returns (string memory) { if (bytes(unrevealedURI).length > 0) return unrevealedURI; return string(abi.encodePacked(baseURI, tokenId_.toString(), baseExtension)); } /// @notice Set baseURI to `baseURI_`, baseExtension to `baseExtension_` and deletes unrevealedURI, triggering a reveal. function setBaseURI(string memory baseURI_, string memory baseExtension_) external onlyAuthorized { baseURI = baseURI_; baseExtension = baseExtension_; delete unrevealedURI; } /// @notice Set unrevealedURI to `unrevealedURI_`. function setUnrevealedURI(string memory unrevealedURI_) external onlyAuthorized { unrevealedURI = unrevealedURI_; } /// @notice Set unrevealedURI to `unrevealedURI_`. function setSaleState(uint256 saleState_) external onlyAuthorized { saleState = saleState_; } /// @notice Set merkleRoot to `merkleRoot_`. function setMerkleRoot(bytes32 merkleRoot_) external onlyAuthorized { merkleRoot = merkleRoot_; } /// @notice Set opensea to `opensea_`. function setOpensea(address opensea_) external onlyAuthorized { opensea = opensea_; } /// @notice Set looksrare to `looksrare_`. function setLooksrare(address looksrare_) external onlyAuthorized { looksrare = looksrare_; } /// @notice Toggle pre-approve feature state for sender. function toggleMarketplacesApproved() external onlyAuthorized { marketplacesApproved = !marketplacesApproved; } /// @notice Toggle paused state. function togglePaused() external onlyAuthorized { _togglePaused(); } /** * @notice Withdraw `amount_` of ether to msg.sender. * @dev Combined with the Auth util, this function can be called by * anyone with the authorization from the owner, so a team member can * get his shares with a permissioned call and exact data. */ function withdraw(uint256 amount_) external onlyAuthorized { payable(msg.sender).transfer(amount_); } /// @dev Modified for opensea and looksrare pre-approve so users can make truly gasless sales. function isApprovedForAll(address owner, address operator) public view override returns (bool) { if (!marketplacesApproved) return super.isApprovedForAll(owner, operator); return operator == OpenSeaProxyRegistry(opensea).proxies(owner) || operator == looksrare || super.isApprovedForAll(owner, operator); } /// @dev Edited in order to block transfers while paused unless msg.sender is the owner(). function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal override { require( msg.sender == owner() || paused() == false, "Pausable: contract paused" ); super._beforeTokenTransfer(from, to, tokenId); } } contract OpenSeaProxyRegistry { mapping(address => address) public proxies; } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity >=0.8.0 <0.9.0; /** * @title ERC721 * @author naomsa <https://twitter.com/naomsa666> * @notice A complete ERC721 implementation including metadata and enumerable * functions. Completely gas optimized and extensible. */ abstract contract ERC721 { /* _ _ */ /* ( )_ ( )_ */ /* ___ | ,_) _ _ | ,_) __ */ /* /',__)| | /'_` )| | /'__`\ */ /* \__, \| |_ ( (_| || |_ ( ___/ */ /* (____/`\__)`\__,_)`\__)`\____) */ /// @dev This emits when ownership of any NFT changes by any mechanism. event Transfer(address indexed _from, address indexed _to, uint256 indexed _tokenId); /// @dev This emits when the approved address for an NFT is changed or event Approval(address indexed _owner, address indexed _approved, uint256 indexed _tokenId); /// @dev This emits when an operator is enabled or disabled for an owner. event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved); /// @notice See {IERC721Metadata-name}. string public name; /// @notice See {IERC721Metadata-symbol}. string public symbol; /// @notice Array of all owners. address[] private _owners; /// @notice Mapping of all balances. mapping(address => uint256) private _balanceOf; /// @notice Mapping from token ID to approved address. mapping(uint256 => address) private _tokenApprovals; /// @notice Mapping of approvals between owner and operator. mapping(address => mapping(address => bool)) private _isApprovedForAll; /* _ */ /* (_ ) _ */ /* | | _ __ (_) ___ */ /* | | /'_`\ /'_ `\| | /'___) */ /* | | ( (_) )( (_) || |( (___ */ /* (___)`\___/'`\__ |(_)`\____) */ /* ( )_) | */ /* \___/' */ constructor(string memory name_, string memory symbol_) { name = name_; symbol = symbol_; } /// @notice See {IERC721-balanceOf}. function balanceOf(address owner) public view virtual returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balanceOf[owner]; } /// @notice See {IERC721-ownerOf}. function ownerOf(uint256 tokenId) public view virtual returns (address) { require(_exists(tokenId), "ERC721: query for nonexistent token"); address owner = _owners[tokenId]; return owner; } /// @notice See {IERC721Metadata-tokenURI}. function tokenURI(uint256) public view virtual returns (string memory); /// @notice See {IERC721-approve}. function approve(address to, uint256 tokenId) public virtual { address owner = ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( msg.sender == owner || _isApprovedForAll[owner][msg.sender], "ERC721: caller is not owner nor approved for all" ); _approve(to, tokenId); } /// @notice See {IERC721-getApproved}. function getApproved(uint256 tokenId) public view virtual returns (address) { require(_exists(tokenId), "ERC721: query for nonexistent token"); return _tokenApprovals[tokenId]; } /// @notice See {IERC721-setApprovalForAll}. function setApprovalForAll(address operator, bool approved) public virtual { _setApprovalForAll(msg.sender, operator, approved); } /// @notice See {IERC721-isApprovedForAll} function isApprovedForAll(address owner, address operator) public view virtual returns (bool) { return _isApprovedForAll[owner][operator]; } /// @notice See {IERC721-transferFrom}. function transferFrom( address from, address to, uint256 tokenId ) public virtual { require(_isApprovedOrOwner(msg.sender, tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /// @notice See {IERC721-safeTransferFrom}. function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual { safeTransferFrom(from, to, tokenId, ""); } /// @notice See {IERC721-safeTransferFrom}. function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory data_ ) public virtual { require(_isApprovedOrOwner(msg.sender, tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, data_); } /// @notice See {IERC721Enumerable.tokenOfOwnerByIndex}. function tokenOfOwnerByIndex(address owner, uint256 index) public view returns (uint256 tokenId) { require(index < balanceOf(owner), "ERC721Enumerable: Index out of bounds"); uint256 count; for (uint256 i; i < _owners.length; ++i) { if (owner == _owners[i]) { if (count == index) return i; else count++; } } revert("ERC721Enumerable: Index out of bounds"); } /// @notice See {IERC721Enumerable.totalSupply}. function totalSupply() public view virtual returns (uint256) { return _owners.length; } /// @notice See {IERC721Enumerable.tokenByIndex}. function tokenByIndex(uint256 index) public view virtual returns (uint256) { require(index < _owners.length, "ERC721Enumerable: Index out of bounds"); return index; } /// @notice Returns a list of all token Ids owned by `owner`. function tokensOfOwner(address owner) public view returns (uint256[] memory) { uint256 balance = balanceOf(owner); uint256[] memory ids = new uint256[](balance); for (uint256 i = 0; i < balance; i++) { ids[i] = tokenOfOwnerByIndex(owner, i); } return ids; } /* _ _ */ /* _ ( )_ (_ ) */ /* (_) ___ | ,_) __ _ __ ___ _ _ | | */ /* | |/' _ `\| | /'__`\( '__)/' _ `\ /'_` ) | | */ /* | || ( ) || |_ ( ___/| | | ( ) |( (_| | | | */ /* (_)(_) (_)`\__)`\____)(_) (_) (_)`\__,_)(___) */ /** * @notice 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); _checkOnERC721Received(from, to, tokenId, data_); } /** * @notice 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 tokenId < _owners.length && _owners[tokenId] != address(0); } /** * @notice 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: query for nonexistent token"); address owner = _owners[tokenId]; return (spender == owner || getApproved(tokenId) == spender || _isApprovedForAll[owner][spender]); } /** * @notice 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, ""); } /** * @notice Same as {_safeMint}, but 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); _checkOnERC721Received(address(0), to, tokenId, data_); } /** * @notice Mints `tokenId` and transfers it to `to`. * * Requirements: * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _owners.push(to); unchecked { _balanceOf[to]++; } emit Transfer(address(0), to, tokenId); } /** * @notice 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); delete _owners[tokenId]; _balanceOf[owner]--; emit Transfer(owner, address(0), tokenId); } /** * @notice Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(_owners[tokenId] == from, "ERC721: transfer of token that is not own"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _owners[tokenId] = to; unchecked { _balanceOf[from]--; _balanceOf[to]++; } emit Transfer(from, to, tokenId); } /** * @notice Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(_owners[tokenId], to, tokenId); } /** * @notice 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"); _isApprovedForAll[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @notice 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 */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory data ) private { if (to.code.length > 0) { try IERC721Receiver(to).onERC721Received(msg.sender, from, tokenId, data) returns (bytes4 returned) { require(returned == 0x150b7a02, "ERC721: safe transfer to non ERC721Receiver implementation"); } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: safe transfer to non ERC721Receiver implementation"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } } /** * @notice 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. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} /* ___ _ _ _ _ __ _ __ */ /* /',__)( ) ( )( '_`\ /'__`\( '__) */ /* \__, \| (_) || (_) )( ___/| | */ /* (____/`\___/'| ,__/'`\____)(_) */ /* | | */ /* (_) */ /// @notice See {IERC165-supportsInterface}. function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) { return interfaceId == 0x80ac58cd || // ERC721 interfaceId == 0x5b5e139f || // ERC721Metadata interfaceId == 0x780e9d63 || // ERC721Enumerable interfaceId == 0x01ffc9a7; // ERC165 } } interface IERC721Receiver { function onERC721Received( address operator, address from, uint256 tokenId, bytes memory data ) external returns (bytes4); } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity >=0.8.0 <0.9.0; /** * @title Auth * @author naomsa <https://twitter.com/naomsa666> * @notice Authing system where the `owner` can authorize function calls * to other addresses as well as control the contract by his own. */ abstract contract Auth { /* _ _ */ /* ( )_ ( )_ */ /* ___ | ,_) _ _ | ,_) __ */ /* /',__)| | /'_` )| | /'__`\ */ /* \__, \| |_ ( (_| || |_ ( ___/ */ /* (____/`\__)`\__,_)`\__)`\____) */ /// @notice Emited when the ownership is transfered. event OwnershipTransfered(address indexed from, address indexed to); /// @notice Emited a new call with `data` is authorized to `to`. event AuthorizationGranted(address indexed to, bytes data); /// @notice Emited a new call with `data` is forbidden to `to`. event AuthorizationForbidden(address indexed to, bytes data); /// @notice Contract's owner address. address private _owner; /// @notice A mapping to retrieve if a call data was authed and is valid for the address. mapping(address => mapping(bytes => bool)) private _isAuthorized; /** * @notice A modifier that requires the user to be the owner or authorization to call. * After the call, the user loses it's authorization if he's not the owner. */ modifier onlyAuthorized() { require(isAuthorized(msg.sender, msg.data), "Auth: sender is not the owner or authorized to call"); _; if (msg.sender != _owner) _isAuthorized[msg.sender][msg.data] = false; } /// @notice A simple modifier just to check whether the sender is the owner. modifier onlyOwner() { require(msg.sender == _owner, "Auth: sender is not the owner"); _; } /* _ */ /* (_ ) _ */ /* | | _ __ (_) ___ */ /* | | /'_`\ /'_ `\| | /'___) */ /* | | ( (_) )( (_) || |( (___ */ /* (___)`\___/'`\__ |(_)`\____) */ /* ( )_) | */ /* \___/' */ constructor() { _transferOwnership(msg.sender); } /// @notice Returns the current contract owner. function owner() public view returns (address) { return _owner; } /// @notice Retrieves whether `user_` is authorized to call with `data_`. function isAuthorized(address user_, bytes memory data_) public view returns (bool) { return user_ == _owner || _isAuthorized[user_][data_]; } /// @notice Set the owner address to `owner_`. function transferOwnership(address owner_) public onlyOwner { require(_owner != owner_, "Auth: transfering ownership to current owner"); _transferOwnership(owner_); } /// @notice Set the owner address to `owner_`. Does not require anything function _transferOwnership(address owner_) internal { address oldOwner = _owner; _owner = owner_; emit OwnershipTransfered(oldOwner, owner_); } /// @notice Authorize a call with `data_` to the address `to_`. function auth(address to_, bytes memory data_) public onlyOwner { require(to_ != _owner, "Auth: authorizing call to the owner"); require(!_isAuthorized[to_][data_], "Auth: authorized calls cannot be authed"); _isAuthorized[to_][data_] = true; emit AuthorizationGranted(to_, data_); } /// @notice Authorize a call with `data_` to the address `to_`. function forbid(address to_, bytes memory data_) public onlyOwner { require(_isAuthorized[to_][data_], "Auth: unauthorized calls cannot be forbidden"); delete _isAuthorized[to_][data_]; emit AuthorizationForbidden(to_, data_); } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity >=0.8.0 <0.9.0; /** * @title Pausable * @author naomsa <https://twitter.com/naomsa666> * @notice Freeze your contract with a secure paused mechanism. */ abstract contract Pausable { /* _ _ */ /* ( )_ ( )_ */ /* ___ | ,_) _ _ | ,_) __ */ /* /',__)| | /'_` )| | /'__`\ */ /* \__, \| |_ ( (_| || |_ ( ___/ */ /* (____/`\__)`\__,_)`\__)`\____) */ /// @notice Emited when the contract is paused. event Paused(address indexed by); /// @notice Emited when the contract is unpaused. event Unpaused(address indexed by); /// @notice Read-only pause state. bool private _paused; /// @notice A modifier to be used when the contract must be paused. modifier onlyWhenPaused() { require(_paused, "Pausable: contract not paused"); _; } /// @notice A modifier to be used when the contract must be unpaused. modifier onlyWhenUnpaused() { require(!_paused, "Pausable: contract paused"); _; } /* _ */ /* (_ ) _ */ /* | | _ __ (_) ___ */ /* | | /'_`\ /'_ `\| | /'___) */ /* | | ( (_) )( (_) || |( (___ */ /* (___)`\___/'`\__ |(_)`\____) */ /* ( )_) | */ /* \___/' */ /// @notice Retrieve contracts pause state. function paused() public view returns (bool) { return _paused; } /// @notice Inverts pause state. Declared internal so it can be combined with the Auth contract. function _togglePaused() internal { _paused = !_paused; if (_paused) emit Unpaused(msg.sender); else emit Paused(msg.sender); } } // 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/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 MerkleProof { /** * @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 = keccak256(abi.encodePacked(computedHash, proofElement)); } else { // Hash(current element of the proof + current computed hash) computedHash = keccak256(abi.encodePacked(proofElement, computedHash)); } } return computedHash; } }
* @title Pausable @notice Freeze your contract with a secure paused mechanism./
abstract contract Pausable { event Paused(address indexed by); event Unpaused(address indexed by); bool private _paused; pragma solidity >=0.8.0 <0.9.0; modifier onlyWhenPaused() { require(_paused, "Pausable: contract not paused"); _; } modifier onlyWhenUnpaused() { require(!_paused, "Pausable: contract paused"); _; } function paused() public view returns (bool) { return _paused; } function _togglePaused() internal { _paused = !_paused; if (_paused) emit Unpaused(msg.sender); else emit Paused(msg.sender); } }
5,470,704
[ 1, 16507, 16665, 225, 15217, 8489, 3433, 6835, 598, 279, 8177, 17781, 12860, 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 ]
[ 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, 17801, 6835, 21800, 16665, 288, 203, 203, 225, 871, 21800, 3668, 12, 2867, 8808, 635, 1769, 203, 203, 225, 871, 1351, 8774, 3668, 12, 2867, 8808, 635, 1769, 203, 203, 225, 1426, 3238, 389, 8774, 3668, 31, 203, 203, 683, 9454, 18035, 560, 1545, 20, 18, 28, 18, 20, 411, 20, 18, 29, 18, 20, 31, 203, 225, 9606, 1338, 9434, 28590, 1435, 288, 203, 565, 2583, 24899, 8774, 3668, 16, 315, 16507, 16665, 30, 6835, 486, 17781, 8863, 203, 565, 389, 31, 203, 225, 289, 203, 203, 225, 9606, 1338, 9434, 984, 8774, 3668, 1435, 288, 203, 565, 2583, 12, 5, 67, 8774, 3668, 16, 315, 16507, 16665, 30, 6835, 17781, 8863, 203, 565, 389, 31, 203, 225, 289, 203, 203, 203, 225, 445, 17781, 1435, 1071, 1476, 1135, 261, 6430, 13, 288, 203, 565, 327, 389, 8774, 3668, 31, 203, 225, 289, 203, 203, 225, 445, 389, 14401, 28590, 1435, 2713, 288, 203, 565, 389, 8774, 3668, 273, 401, 67, 8774, 3668, 31, 203, 565, 309, 261, 67, 8774, 3668, 13, 3626, 1351, 8774, 3668, 12, 3576, 18, 15330, 1769, 203, 565, 469, 3626, 21800, 3668, 12, 3576, 18, 15330, 1769, 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 ]
pragma solidity ^0.5.2; pragma experimental ABIEncoderV2; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; import "openzeppelin-solidity/contracts/cryptography/ECDSA.sol"; /** * @title Perun Ledger Payment Channels * @author Sebastian Stammler, Marius van der Wijden * @notice Single-deployment ledger payment channels contract. * Allows two parties to block ether in a payment channel and execute * off-chain transactions within this channel. * @dev This is a single-deployment version of payment channels, where each * channel state resides at its own uint id in the channels mapping. * The channel initiator is sometimes referred to as A, the confirmer as B. */ contract LedgerChannels { using SafeMath for uint256; enum State { Null, Opening, Open, ClosingByA, ClosingByB, Closed, Withdrawn } struct Party { address addr; uint balance; } /** * @dev LedgerChannel holds the state of a channel. * The initiator's address is stored at A, the confirmer's at B. * The channel-blocked money of X is stored in X.balance * When opening the channel, the required amount to deposit by the * confirmer is saved at requiredBalanceConfirmer. * We cannot save it at B.balance directly, otherwise there would be * possible a withdraw() attack after timeoutOpen() */ struct LedgerChannel { State state; uint48 timeout; // absolute timeout of pending confirmation for open or close uint48 timeoutDuration; // relative timeout Party A; Party B; uint version; uint requiredBalanceConfirmer; } /// @dev mapping from channel id to its state mapping(uint => LedgerChannel) channels; event Opening(uint indexed id, address indexed initiator, address indexed confirmer, uint balanceA); event OpenTimeout(uint indexed id, address indexed initiator, address indexed confirmer, uint balanceA); event Open(uint indexed id, address indexed initiator, address indexed confirmer, uint balanceA, uint balanceB); event Closing(uint indexed id, address indexed closer, address indexed confirmer, uint finalBalanceA, uint finalBalanceB); event Closed(uint indexed id, address indexed closer, address indexed confirmer, uint finalBalanceA, uint finalBalanceB); event ClosedTimeout(uint indexed id, address indexed closer, address indexed confirmer, uint finalBalanceA, uint finalBalanceB); event ClosedDisputed(uint indexed id, address indexed closer, address indexed confirmer, uint finalBalanceA, uint finalBalanceB); event Withdrawal(uint indexed id, address indexed by, uint balance); /** * @dev All public functions have to use the inState() modifier to prevent * invalid state transitions. Besides open(), they also have to use an * onlyX() modifer to only let allowed parties call. If they depend on a * timeout constraint, the have to use a within/afterTimeout() modifier. */ modifier onlyParty(uint _id) { require(channels[_id].A.addr == msg.sender || channels[_id].B.addr == msg.sender, "Caller is not a party of this channel."); _; } modifier onlyInitiator(uint _id) { require(initiator(_id) == msg.sender, "Caller is not the initiator of this channel."); _; } modifier onlyConfirmer(uint _id) { require(confirmer(_id) == msg.sender, "Caller is not the confirmer of this channel."); _; } modifier inState(uint _id, State _state) { require(channels[_id].state == _state, "Channel in wrong state."); _; } modifier inStateClosing(uint _id) { State state = channels[_id].state; require(state == State.ClosingByA || state == State.ClosingByB, "Channel not in state Closing."); _; } modifier withinTimeout(uint _id) { require(channels[_id].timeout > now, "Confirmation timeout reached."); _; } modifier afterTimeout(uint _id) { require(channels[_id].timeout < now, "Confirmation timeout not reached yet."); _; } /** * @notice opens request to open a payment channel by the sender of the tx. * Sent ether is blocked in the opening channel as A's balance. * The id of this channel will be genId(msg.sender, _counterParty, _idSeed) * @param _idSeed seed that is used to calculate the channel id, which will * be genId(msg.sender, _counterParty, _idSeed) * @param _timeoutDuration duration of confirmations of channel opening * and closing * @param _counterParty The channel's other side, who needs to confirm the channel. * @param _counterBalance The other side's required balance. */ function open(uint _idSeed, uint48 _timeoutDuration, address _counterParty, uint _counterBalance) payable external { uint id = genId(msg.sender, _counterParty, _idSeed); LedgerChannel storage chan = channels[id]; require(chan.state == State.Null, "Channel already exists."); chan.A.addr = msg.sender; chan.A.balance = msg.value; chan.B.addr = _counterParty; chan.requiredBalanceConfirmer = _counterBalance; chan.timeoutDuration = _timeoutDuration; resetTimeout(chan); chan.state = State.Opening; emit Opening(id, msg.sender, _counterParty, msg.value); } function confirmOpen(uint _id) payable external inState(_id, State.Opening) onlyConfirmer(_id) withinTimeout(_id) { LedgerChannel storage chan = channels[_id]; require(msg.value == chan.requiredBalanceConfirmer, "Wrong amount from opening confirmer."); chan.B.balance = msg.value; chan.state = State.Open; emit Open(_id, chan.A.addr, msg.sender, chan.A.balance, msg.value); } function timeoutOpen(uint _id) external inState(_id, State.Opening) onlyInitiator(_id) afterTimeout(_id) { LedgerChannel storage chan = channels[_id]; chan.state = State.Closed; emit OpenTimeout(_id, msg.sender, chan.B.addr, chan.A.balance); withdraw(_id); } function close(uint _id, uint _version, uint _balanceA, uint _balanceB, bytes calldata _sigA, bytes calldata _sigB) external inState(_id, State.Open) onlyParty(_id) { verifySigs(_id, _version, _balanceA, _balanceB, _sigA, _sigB); update(_id, _version, _balanceA, _balanceB); closeCurrentBalance(_id); } /** * @notice Initiates closing of channel _id without updating the initial * balance. This is like close() without the udpate. * Transitions: Open -> ClosingByX * @param _id channel id */ function closeInitialBalance(uint _id) external inState(_id, State.Open) onlyParty(_id) { closeCurrentBalance(_id); } function confirmClose(uint _id) external inStateClosing(_id) onlyConfirmer(_id) withinTimeout(_id) { LedgerChannel storage chan = channels[_id]; chan.state = State.Closed; emit Closed(_id, initiator(_id), msg.sender, chan.A.balance, chan.B.balance); withdraw(_id); } function disputedClose(uint _id, uint _version, uint _balanceA, uint _balanceB, bytes calldata _sigA, bytes calldata _sigB) external inStateClosing(_id) onlyConfirmer(_id) withinTimeout(_id) { verifySigs(_id, _version, _balanceA, _balanceB, _sigA, _sigB); update(_id, _version, _balanceA, _balanceB); LedgerChannel storage chan = channels[_id]; chan.state = State.Closed; emit ClosedDisputed(_id, initiator(_id), msg.sender, chan.A.balance, chan.B.balance); withdraw(_id); } function timeoutClose(uint _id) external inStateClosing(_id) onlyInitiator(_id) afterTimeout(_id) { LedgerChannel storage chan = channels[_id]; chan.state = State.Closed; emit ClosedTimeout(_id, msg.sender, confirmer(_id), chan.A.balance, chan.B.balance); withdraw(_id); } function withdraw(uint _id) public inState(_id, State.Closed) onlyParty(_id) { LedgerChannel storage chan = channels[_id]; Party storage party = (msg.sender == chan.A.addr) ? chan.A : chan.B; uint balance = party.balance; party.balance = 0; if (chan.A.balance == 0 && chan.B.balance == 0) { chan.state = State.Withdrawn; } emit Withdrawal(_id, msg.sender, balance); msg.sender.transfer(balance); // party.addr is not payable } /** * Public getter for LedgerChannels. * Primarily used for testing. */ function getChannel(uint _id) public view returns (LedgerChannel memory) { return channels[_id]; } /** * @notice generates a deterministic channel id for a channel between _A and * _B, using seed _idSeed. * Channels are saved to the channels map at this id, having the effect * that a channel id can never belong to a different pair of channel * parties. */ function genId(address _A, address _B, uint _idSeed) public pure returns (uint) { return uint256(keccak256(abi.encodePacked(_A, _B, _idSeed))); } function exists(uint _id) public view returns (bool) { return (channels[_id].state != State.Null); } function initiator(uint _id) public view returns (address) { LedgerChannel storage chan = channels[_id]; return (chan.state == State.ClosingByB) ? chan.B.addr : chan.A.addr; } function confirmer(uint _id) public view returns (address) { LedgerChannel storage chan = channels[_id]; return (chan.state == State.ClosingByB) ? chan.A.addr : chan.B.addr; } function resetTimeout(LedgerChannel storage chan) internal { chan.timeout = uint48(now) + chan.timeoutDuration; // SafeMath is only implemented for uint256 and would be inefficient here require(chan.timeout > uint48(now), "Bogus timeout duration."); } function verifySigs(uint _id, uint _version, uint _balanceA, uint _balanceB, bytes memory _sigA, bytes memory _sigB) internal view { LedgerChannel storage chan = channels[_id]; bytes32 hash = ethSignedMsgHash(_id, _version, _balanceA, _balanceB); require(ECDSA.recover(hash, _sigA) == chan.A.addr, "Signature verification of channel update failed for A."); require(ECDSA.recover(hash, _sigB) == chan.B.addr, "Signature verification of channel update failed for B."); } function update(uint _id, uint _version, uint _balanceA, uint _balanceB) internal { LedgerChannel storage chan = channels[_id]; require(chan.version < _version, "Update version is not greater than current."); require(_balanceA.add(_balanceB) <= chan.A.balance.add(chan.B.balance), "Update total balance greater than current balance."); chan.version = _version; chan.A.balance = _balanceA; chan.B.balance = _balanceB; } function closeCurrentBalance(uint _id) internal { LedgerChannel storage chan = channels[_id]; resetTimeout(chan); chan.state = (msg.sender == chan.A.addr) ? State.ClosingByA : State.ClosingByB; emit Closing(_id, msg.sender, confirmer(_id), chan.A.balance, chan.B.balance); } /** * @notice returns the channel update message to sign by each party. * Mimic this in your off-chain application. * Note that the channel id already encodes the parties of the channel, so * we don't need to add them to the message digest. */ function ethSignedMsgHash(uint _id, uint _version, uint _balanceA, uint _balanceB) public pure returns (bytes32) { return ECDSA.toEthSignedMessageHash( keccak256(abi.encodePacked( _id, _version, _balanceA, _balanceB))); } function verify(bytes32 _hash, bytes memory _sig, address _signer) internal pure returns (bool) { return (_signer == ECDSA.recover(_hash, _sig)); } }
* @notice generates a deterministic channel id for a channel between _A and _B, using seed _idSeed. Channels are saved to the channels map at this id, having the effect that a channel id can never belong to a different pair of channel parties./
function genId(address _A, address _B, uint _idSeed) public pure returns (uint) { return uint256(keccak256(abi.encodePacked(_A, _B, _idSeed))); }
6,412,496
[ 1, 3441, 815, 279, 25112, 1904, 612, 364, 279, 1904, 3086, 389, 37, 471, 282, 389, 38, 16, 1450, 5009, 389, 350, 12702, 18, 282, 25263, 854, 5198, 358, 326, 5750, 852, 622, 333, 612, 16, 7999, 326, 5426, 282, 716, 279, 1904, 612, 848, 5903, 10957, 358, 279, 3775, 3082, 434, 1904, 282, 1087, 606, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 3157, 548, 12, 2867, 389, 37, 16, 1758, 389, 38, 16, 2254, 389, 350, 12702, 13, 1071, 16618, 1135, 261, 11890, 13, 288, 203, 3639, 327, 2254, 5034, 12, 79, 24410, 581, 5034, 12, 21457, 18, 3015, 4420, 329, 24899, 37, 16, 389, 38, 16, 389, 350, 12702, 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, -100, -100, -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/0x52A043bcebdB2f939BaEF2E8b6F01652290eAB3f/sources/contracts/Depository.sol
Calculate the number of pending bonds
uint256 numBonds = bondCounter;
3,040,662
[ 1, 8695, 326, 1300, 434, 4634, 15692, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2254, 5034, 818, 26090, 273, 8427, 4789, 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 ]
// SPDX-License-Identifier: MIT pragma solidity >=0.6.2; /* * ZaigarFinance */ import '@pancakeswap/pancake-swap-lib/contracts/math/SafeMath.sol'; import '@pancakeswap/pancake-swap-lib/contracts/token/BEP20/IBEP20.sol'; import '@pancakeswap/pancake-swap-lib/contracts/token/BEP20/SafeBEP20.sol'; import '@pancakeswap/pancake-swap-lib/contracts/access/Ownable.sol'; // File @openzeppelin/contracts/utils/[email protected] /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () internal { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } import "./ZafiraToken.sol"; // import "@nomiclabs/buidler/console.sol"; // MasterZai is the master of ZFAI // He can make ZFAI and he is a fair guy. // // Note that it's ownable and the owner wields tremendous power. The ownership // will be transferred to a governance smart contract once ZFAI is sufficiently // distributed and the community can show to govern itself. // // Have fun reading it. Hopefully it's bug-free. God bless. contract MasterZai is Ownable, ReentrancyGuard { using SafeMath for uint256; using SafeBEP20 for IBEP20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of ZFAIs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accZfaiPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accZfaiPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IBEP20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. ZFAIs to distribute per block. uint256 lastRewardBlock; // Last block number that ZFAIs distribution occurs. uint256 accZfaiPerShare; // Accumulated ZFAIs per share, times 1e12. See below. uint16 depositFeeBP; // Deposit fee in basis points uint256 totalLp; // Total Token in Pool } // The Zafira TOKEN! ZafiraToken public zfai; //On Distribution Dev address. address public devaddr; // Deposit Fee address address public feeAddress; //On Distribution Marketing Address address public marktAddress; //On Distribution Staff team Address address public staffAddress; // ZFAI tokens created per block. uint256 public zfaiPerBlock; // Bonus muliplier for early zfai makers. uint256 public BONUS_MULTIPLIER = 1; // 10% for Marketing on distribution uint16 public constant blockMktFee = 1000; // 4% for staff on distribution uint16 public constant blockStaffFee = 400; // 1% for development on distribution uint16 public constant blockDevFee = 100; uint256 currentDevFee = 0; uint256 currentStaffFee = 0; uint256 currentMarketingFee = 0; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping (uint256 => mapping (address => UserInfo)) public userInfo; // Total allocation points. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when ZFAI mining starts. uint256 public startBlock; // Total ZFAI in ZFAI Pools (can be multiple pools) uint256 public totalZfaiInPools = 0; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmissionRateUpdated(address indexed caller, uint256 previousAmount, uint256 newAmount); constructor( ZafiraToken _zfai, address _devaddr, address _feeAddress, address _marktAddress, address _staffAddress, uint256 _zfaiPerBlock, uint256 _startBlock, uint256 _multiplier ) public { zfai = _zfai; devaddr = _devaddr; feeAddress = _feeAddress; marktAddress = _marktAddress; staffAddress = _staffAddress; zfaiPerBlock = _zfaiPerBlock; startBlock = _startBlock; BONUS_MULTIPLIER = _multiplier; totalAllocPoint = 0; } modifier validatePool(uint256 _pid) { require(_pid < poolInfo.length, "validatePool: pool exists?"); _; } function updateMultiplier(uint256 multiplierNumber) public onlyOwner { BONUS_MULTIPLIER = multiplierNumber; } function poolLength() external view returns (uint256) { return poolInfo.length; } // Detects whether the given pool already exists function checkPoolDuplicate(IBEP20 _lpToken) public view { uint256 length = poolInfo.length; for (uint256 _pid = 0; _pid < length; _pid++) { require(poolInfo[_pid].lpToken != _lpToken, "add: existing pool"); } } fallback() external payable { } //actual Zfai left in MasterChef can be used in rewards, must excluding all in zfai pools //this function is for safety check function remainRewards() public view returns (uint256) { return zfai.balanceOf(address(this)).sub(totalZfaiInPools); } //All Zfais that are not in pools or masterchef reward stack function getCirculatingSupply() external view returns(uint256) { uint256 tSupply = zfai.totalSupply(); uint256 zfaiBalance = zfai.balanceOf(address(this)); return tSupply.sub(zfaiBalance); } // Add a new lp to the pool. Can only be called by the owner. // Can add multiple pool with same lp token without messing up rewards, because each pool's balance is tracked using its own totalLp function add(uint256 _allocPoint, IBEP20 _lpToken, uint16 _depositFeeBP, bool _withUpdate) public onlyOwner { require(_depositFeeBP <= 10000, "add: invalid deposit fee basis points"); if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accZfaiPerShare: 0, depositFeeBP: _depositFeeBP, totalLp : 0 })); } // Update the given pool's ZFAI allocation point. Can only be called by the owner. function set(uint256 _pid, uint256 _allocPoint, uint16 _depositFeeBP, bool _withUpdate) public onlyOwner { require(_depositFeeBP <= 10000, "set: invalid deposit fee basis points"); if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; poolInfo[_pid].depositFeeBP = _depositFeeBP; } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { return _to.sub(_from).mul(BONUS_MULTIPLIER); } // View function to see pending ZFAIs on frontend. function pendingZfai(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accZfaiPerShare = pool.accZfaiPerShare; //uint256 lpSupply = pool.lpToken.balanceOf(address(this)); uint256 lpSupply = pool.totalLp; if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 zfaiReward = multiplier.mul(zfaiPerBlock).mul(pool.allocPoint).div(totalAllocPoint); uint256 totalRewardFees = zfaiReward.mul(1500).div(10000); uint256 zfaiRewardUsers = zfaiReward.sub(totalRewardFees); uint256 totalminted = zfai.totalMinted(); if(totalminted >= 159000000000000000000000000){ accZfaiPerShare = accZfaiPerShare; }else{ accZfaiPerShare = accZfaiPerShare.add(zfaiRewardUsers.mul(1e12).div(lpSupply)); } } return user.amount.mul(accZfaiPerShare).div(1e12).sub(user.rewardDebt); } // View function to see all locked ZFAIs on frontend. function lockedZfai() external view returns (uint256) { return totalZfaiInPools; } // Update reward variables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public validatePool(_pid) { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } if (pool.totalLp == 0 || pool.allocPoint == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 zfaiReward = multiplier.mul(zfaiPerBlock).mul(pool.allocPoint).div(totalAllocPoint); uint256 totalRewardFees = zfaiReward.mul(1500).div(10000); //Total - 15% fees uint256 zfaiRewardUsers = zfaiReward.sub(totalRewardFees); uint256 totalminted = zfai.totalMinted(); if(totalminted >= 159000000000000000000000000){ if(currentDevFee > 0 || currentStaffFee > 0 || currentMarketingFee > 0){ safeZfaiTransfer(devaddr,currentDevFee); safeZfaiTransfer(staffAddress,currentStaffFee); safeZfaiTransfer(marktAddress,currentMarketingFee); } pool.accZfaiPerShare = pool.accZfaiPerShare; currentDevFee = 0; currentMarketingFee = 0; currentStaffFee = 0; }else{ zfai.mint(address(this),zfaiReward); if(currentDevFee > 1100000000000000000000){ safeZfaiTransfer(devaddr,currentDevFee); currentDevFee = 0; } else if(currentStaffFee > 1100000000000000000000){ safeZfaiTransfer(staffAddress,currentStaffFee); currentStaffFee = 0; } else if(currentMarketingFee > 2000000000000000000000){ safeZfaiTransfer(marktAddress,currentMarketingFee); currentMarketingFee = 0; } } //1% dev fee currentDevFee = currentDevFee.add(zfaiReward.mul(blockDevFee).div(10000)); //4% staff fee currentStaffFee = currentStaffFee.add(zfaiReward.mul(blockStaffFee).div(10000)); //10% marketing fee currentMarketingFee = currentMarketingFee.add(zfaiReward.div(10)); pool.accZfaiPerShare = pool.accZfaiPerShare.add(zfaiRewardUsers.mul(1e12).div(pool.totalLp)); pool.lastRewardBlock = block.number; } // Deposit LP tokens to MasterZai for ZFAI allocation. function deposit(uint256 _pid, uint256 _amount) public nonReentrant { // require(block.number >= startBlock, "MasterChef:: Can not deposit before farm start"); PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accZfaiPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { uint256 currentRewardBalance = remainRewards(); if(currentRewardBalance > 0) { if(pending > currentRewardBalance) { safeZfaiTransfer(msg.sender, currentRewardBalance); } else { safeZfaiTransfer(msg.sender, pending); } } } } if (_amount > 0) { //Security Check in Tokens with Tax Fees uint256 beforeDeposit = pool.lpToken.balanceOf(address(this)); pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); uint256 afterDeposit = pool.lpToken.balanceOf(address(this)); _amount = afterDeposit.sub(beforeDeposit); if (pool.depositFeeBP > 0) { uint256 depositFee = _amount.mul(pool.depositFeeBP).div(10000); if (address(pool.lpToken) == address(zfai)) { totalZfaiInPools = totalZfaiInPools.add(_amount).sub(depositFee); } pool.lpToken.safeTransfer(feeAddress, depositFee); user.amount = user.amount.add(_amount).sub(depositFee); pool.totalLp = pool.totalLp.add(_amount).sub(depositFee); } else { user.amount = user.amount.add(_amount); pool.totalLp = pool.totalLp.add(_amount); if (address(pool.lpToken) == address(zfai)) { totalZfaiInPools = totalZfaiInPools.add(_amount); } } } user.rewardDebt = user.amount.mul(pool.accZfaiPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // Withdraw LP tokens from MasterZai. function withdraw(uint256 _pid, uint256 _amount) public validatePool(_pid) nonReentrant { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); //this will make sure that user can only withdraw from his pool //cannot withdraw more than pool's balance and from MasterChef's token require(pool.totalLp >= _amount, "Withdraw: Pool total LP not enough"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accZfaiPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { uint256 currentRewardBalance = remainRewards(); //additional checkings if(currentRewardBalance > 0) { if(pending > currentRewardBalance) { safeZfaiTransfer(msg.sender, currentRewardBalance); } else { safeZfaiTransfer(msg.sender, pending); } } } if(_amount > 0) { if (address(pool.lpToken) == address(zfai)) { uint256 zfaiBal = zfai.balanceOf(address(this)); require(_amount <= zfaiBal,'withdraw: not good'); if(_amount >= totalZfaiInPools){ totalZfaiInPools = 0; }else{ require(totalZfaiInPools >= _amount,'amount bigger than pool wut?'); totalZfaiInPools = totalZfaiInPools.sub(_amount); } pool.lpToken.safeTransfer(address(msg.sender), _amount); } else { pool.lpToken.safeTransfer(address(msg.sender), _amount); } } user.amount = user.amount.sub(_amount); pool.totalLp = pool.totalLp.sub(_amount); user.rewardDebt = user.amount.mul(pool.accZfaiPerShare).div(1e12); emit Withdraw(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public nonReentrant { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; uint256 amount = user.amount; require(pool.totalLp >= amount, "EmergencyWithdraw: Pool total LP not enough"); if (address(pool.lpToken) == address(zfai)) { uint256 zfaiBal = zfai.balanceOf(address(this)); require(amount <= zfaiBal,'withdraw: not good'); if(amount >= totalZfaiInPools){ totalZfaiInPools = 0; }else{ require(totalZfaiInPools >= amount,'amount bigger than pool wut?'); totalZfaiInPools = totalZfaiInPools.sub(amount); } pool.lpToken.safeTransfer(address(msg.sender), amount); }else{ pool.lpToken.safeTransfer(address(msg.sender), amount); } user.amount = 0; user.rewardDebt = 0; pool.totalLp = pool.totalLp.sub(amount); emit EmergencyWithdraw(msg.sender, _pid, amount); } function getPoolInfo(uint256 _pid) public view returns(address lpToken, uint256 allocPoint, uint256 lastRewardBlock, uint256 accZfaiPerShare, uint16 depositFeeBP, uint256 totalLp) { return (address(poolInfo[_pid].lpToken), poolInfo[_pid].allocPoint, poolInfo[_pid].lastRewardBlock, poolInfo[_pid].accZfaiPerShare, poolInfo[_pid].depositFeeBP, poolInfo[_pid].totalLp); } // Safe zfai transfer function, just in case if rounding error causes pool to not have enough ZFAIs. function safeZfaiTransfer(address _to, uint256 _amount) internal { if(zfai.balanceOf(address(this)) > totalZfaiInPools){ //zfaiBal = total zfai in MasterChef - total zfai in zfai pools, this will make sure that MasterChef never transfer rewards from deposited zfai pools uint256 zfaiBal = zfai.balanceOf(address(this)).sub(totalZfaiInPools); if (_amount >= zfaiBal) { zfai.transfer(_to, zfaiBal); } else if (_amount > 0) { zfai.transfer(_to, _amount); } } } // Update dev address by the previous dev. function dev(address _devaddr) public { require(msg.sender == devaddr, "dev: wut?"); devaddr = _devaddr; } //update address that receive deposit fee in pools function setFeeAddress(address _feeAddress) public { require(msg.sender == feeAddress, "setFeeAddress: FORBIDDEN"); feeAddress = _feeAddress; } // Pancake has to add hidden dummy pools in order to alter the emission, here we make it simple and transparent to all. function updateEmissionRate(uint256 _zfaiPerBlock) public onlyOwner { massUpdatePools(); emit EmissionRateUpdated(msg.sender, zfaiPerBlock, _zfaiPerBlock); zfaiPerBlock = _zfaiPerBlock; } }
Update the given pool's ZFAI allocation point. Can only be called by the owner.
function set(uint256 _pid, uint256 _allocPoint, uint16 _depositFeeBP, bool _withUpdate) public onlyOwner { require(_depositFeeBP <= 10000, "set: invalid deposit fee basis points"); if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; poolInfo[_pid].depositFeeBP = _depositFeeBP; }
13,010,926
[ 1, 1891, 326, 864, 2845, 1807, 2285, 2046, 45, 13481, 1634, 18, 4480, 1338, 506, 2566, 635, 326, 3410, 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 ]
[ 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, 444, 12, 11890, 5034, 389, 6610, 16, 2254, 5034, 389, 9853, 2148, 16, 2254, 2313, 389, 323, 1724, 14667, 30573, 16, 1426, 389, 1918, 1891, 13, 1071, 1338, 5541, 288, 203, 3639, 2583, 24899, 323, 1724, 14667, 30573, 1648, 12619, 16, 315, 542, 30, 2057, 443, 1724, 14036, 10853, 3143, 8863, 203, 3639, 309, 261, 67, 1918, 1891, 13, 288, 203, 5411, 8039, 1891, 16639, 5621, 203, 3639, 289, 203, 3639, 2078, 8763, 2148, 273, 2078, 8763, 2148, 18, 1717, 12, 6011, 966, 63, 67, 6610, 8009, 9853, 2148, 2934, 1289, 24899, 9853, 2148, 1769, 203, 3639, 2845, 966, 63, 67, 6610, 8009, 9853, 2148, 273, 389, 9853, 2148, 31, 203, 3639, 2845, 966, 63, 67, 6610, 8009, 323, 1724, 14667, 30573, 273, 389, 323, 1724, 14667, 30573, 31, 203, 565, 289, 203, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2021-12-21 */ // Sources flattened with hardhat v2.6.2 https://hardhat.org // File @openzeppelin/contracts/token/ERC20/extensions/[email protected] pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. * * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. */ interface IERC20Permit { /** * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens, * given ``owner``'s signed approval. * * IMPORTANT: The same issues {IERC20-approve} has related to transaction * ordering also apply here. * * Emits an {Approval} event. * * Requirements: * * - `spender` cannot be the zero address. * - `deadline` must be a timestamp in the future. * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner` * over the EIP712-formatted function arguments. * - the signature must use ``owner``'s current nonce (see {nonces}). * * For more information on the signature format, see the * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP * section]. */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; /** * @dev Returns the current nonce for `owner`. This value must be * included whenever a signature is generated for {permit}. * * Every successful call to {permit} increases ``owner``'s nonce by one. This * prevents a signature from being used multiple times. */ function nonces(address owner) external view returns (uint256); /** * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view returns (bytes32); } // File @openzeppelin/contracts/token/ERC20/[email protected] // 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); } // File @openzeppelin/contracts/token/ERC20/extensions/[email protected] pragma solidity ^0.8.0; /** * @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); } // File @openzeppelin/contracts/utils/[email protected] 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/token/ERC20/[email protected] pragma solidity ^0.8.0; /** * @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 {} } // File @openzeppelin/contracts/utils/cryptography/[email protected] 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)); } } // File @openzeppelin/contracts/utils/cryptography/[email protected] pragma solidity ^0.8.0; /** * @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); } } // File @openzeppelin/contracts/utils/[email protected] pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library Counters { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } // File @openzeppelin/contracts/token/ERC20/extensions/[email protected] pragma solidity ^0.8.0; /** * @dev Implementation of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. * * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by * presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. * * _Available since v3.4._ */ abstract contract ERC20Permit is ERC20, IERC20Permit, EIP712 { using Counters for Counters.Counter; mapping(address => Counters.Counter) private _nonces; // solhint-disable-next-line var-name-mixedcase bytes32 private immutable _PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); /** * @dev Initializes the {EIP712} domain separator using the `name` parameter, and setting `version` to `"1"`. * * It's a good idea to use the same `name` that is defined as the ERC20 token name. */ constructor(string memory name) EIP712(name, "1") {} /** * @dev See {IERC20Permit-permit}. */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public virtual override { require(block.timestamp <= deadline, "ERC20Permit: expired deadline"); bytes32 structHash = keccak256(abi.encode(_PERMIT_TYPEHASH, owner, spender, value, _useNonce(owner), deadline)); bytes32 hash = _hashTypedDataV4(structHash); address signer = ECDSA.recover(hash, v, r, s); require(signer == owner, "ERC20Permit: invalid signature"); _approve(owner, spender, value); } /** * @dev See {IERC20Permit-nonces}. */ function nonces(address owner) public view virtual override returns (uint256) { return _nonces[owner].current(); } /** * @dev See {IERC20Permit-DOMAIN_SEPARATOR}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view override returns (bytes32) { return _domainSeparatorV4(); } /** * @dev "Consume a nonce": return the current value and increment. * * _Available since v4.1._ */ function _useNonce(address owner) internal virtual returns (uint256 current) { Counters.Counter storage nonce = _nonces[owner]; current = nonce.current(); nonce.increment(); } } // File @openzeppelin/contracts/utils/math/[email protected] pragma solidity ^0.8.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow. return (a & b) + (a ^ b) / 2; } /** * @dev Returns the ceiling of the division of two numbers. * * This differs from standard division with `/` in that it rounds up instead * of rounding down. */ function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b - 1) / b can overflow on addition, so we distribute. return a / b + (a % b == 0 ? 0 : 1); } } // File @openzeppelin/contracts/utils/math/[email protected] pragma solidity ^0.8.0; /** * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow * checks. * * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can * easily result in undesired exploitation or bugs, since developers usually * assume that overflows raise errors. `SafeCast` restores this intuition by * reverting the transaction when such an operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. * * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing * all math on `uint256` and `int256` and then downcasting. */ library SafeCast { /** * @dev Returns the downcasted uint224 from uint256, reverting on * overflow (when the input is greater than largest uint224). * * Counterpart to Solidity's `uint224` operator. * * Requirements: * * - input must fit into 224 bits */ function toUint224(uint256 value) internal pure returns (uint224) { require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits"); return uint224(value); } /** * @dev Returns the downcasted uint128 from uint256, reverting on * overflow (when the input is greater than largest uint128). * * Counterpart to Solidity's `uint128` operator. * * Requirements: * * - input must fit into 128 bits */ function toUint128(uint256 value) internal pure returns (uint128) { require(value <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits"); return uint128(value); } /** * @dev Returns the downcasted uint96 from uint256, reverting on * overflow (when the input is greater than largest uint96). * * Counterpart to Solidity's `uint96` operator. * * Requirements: * * - input must fit into 96 bits */ function toUint96(uint256 value) internal pure returns (uint96) { require(value <= type(uint96).max, "SafeCast: value doesn't fit in 96 bits"); return uint96(value); } /** * @dev Returns the downcasted uint64 from uint256, reverting on * overflow (when the input is greater than largest uint64). * * Counterpart to Solidity's `uint64` operator. * * Requirements: * * - input must fit into 64 bits */ function toUint64(uint256 value) internal pure returns (uint64) { require(value <= type(uint64).max, "SafeCast: value doesn't fit in 64 bits"); return uint64(value); } /** * @dev Returns the downcasted uint32 from uint256, reverting on * overflow (when the input is greater than largest uint32). * * Counterpart to Solidity's `uint32` operator. * * Requirements: * * - input must fit into 32 bits */ function toUint32(uint256 value) internal pure returns (uint32) { require(value <= type(uint32).max, "SafeCast: value doesn't fit in 32 bits"); return uint32(value); } /** * @dev Returns the downcasted uint16 from uint256, reverting on * overflow (when the input is greater than largest uint16). * * Counterpart to Solidity's `uint16` operator. * * Requirements: * * - input must fit into 16 bits */ function toUint16(uint256 value) internal pure returns (uint16) { require(value <= type(uint16).max, "SafeCast: value doesn't fit in 16 bits"); return uint16(value); } /** * @dev Returns the downcasted uint8 from uint256, reverting on * overflow (when the input is greater than largest uint8). * * Counterpart to Solidity's `uint8` operator. * * Requirements: * * - input must fit into 8 bits. */ function toUint8(uint256 value) internal pure returns (uint8) { require(value <= type(uint8).max, "SafeCast: value doesn't fit in 8 bits"); return uint8(value); } /** * @dev Converts a signed int256 into an unsigned uint256. * * Requirements: * * - input must be greater than or equal to 0. */ function toUint256(int256 value) internal pure returns (uint256) { require(value >= 0, "SafeCast: value must be positive"); return uint256(value); } /** * @dev Returns the downcasted int128 from int256, reverting on * overflow (when the input is less than smallest int128 or * greater than largest int128). * * Counterpart to Solidity's `int128` operator. * * Requirements: * * - input must fit into 128 bits * * _Available since v3.1._ */ function toInt128(int256 value) internal pure returns (int128) { require(value >= type(int128).min && value <= type(int128).max, "SafeCast: value doesn't fit in 128 bits"); return int128(value); } /** * @dev Returns the downcasted int64 from int256, reverting on * overflow (when the input is less than smallest int64 or * greater than largest int64). * * Counterpart to Solidity's `int64` operator. * * Requirements: * * - input must fit into 64 bits * * _Available since v3.1._ */ function toInt64(int256 value) internal pure returns (int64) { require(value >= type(int64).min && value <= type(int64).max, "SafeCast: value doesn't fit in 64 bits"); return int64(value); } /** * @dev Returns the downcasted int32 from int256, reverting on * overflow (when the input is less than smallest int32 or * greater than largest int32). * * Counterpart to Solidity's `int32` operator. * * Requirements: * * - input must fit into 32 bits * * _Available since v3.1._ */ function toInt32(int256 value) internal pure returns (int32) { require(value >= type(int32).min && value <= type(int32).max, "SafeCast: value doesn't fit in 32 bits"); return int32(value); } /** * @dev Returns the downcasted int16 from int256, reverting on * overflow (when the input is less than smallest int16 or * greater than largest int16). * * Counterpart to Solidity's `int16` operator. * * Requirements: * * - input must fit into 16 bits * * _Available since v3.1._ */ function toInt16(int256 value) internal pure returns (int16) { require(value >= type(int16).min && value <= type(int16).max, "SafeCast: value doesn't fit in 16 bits"); return int16(value); } /** * @dev Returns the downcasted int8 from int256, reverting on * overflow (when the input is less than smallest int8 or * greater than largest int8). * * Counterpart to Solidity's `int8` operator. * * Requirements: * * - input must fit into 8 bits. * * _Available since v3.1._ */ function toInt8(int256 value) internal pure returns (int8) { require(value >= type(int8).min && value <= type(int8).max, "SafeCast: value doesn't fit in 8 bits"); return int8(value); } /** * @dev Converts an unsigned uint256 into a signed int256. * * Requirements: * * - input must be less than or equal to maxInt256. */ function toInt256(uint256 value) internal pure returns (int256) { // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive require(value <= uint256(type(int256).max), "SafeCast: value doesn't fit in an int256"); return int256(value); } } // File @openzeppelin/contracts/token/ERC20/extensions/[email protected] pragma solidity ^0.8.0; /** * @dev Extension of ERC20 to support Compound-like voting and delegation. This version is more generic than Compound's, * and supports token supply up to 2^224^ - 1, while COMP is limited to 2^96^ - 1. * * NOTE: If exact COMP compatibility is required, use the {ERC20VotesComp} variant of this module. * * This extension keeps a history (checkpoints) of each account's vote power. Vote power can be delegated either * by calling the {delegate} function directly, or by providing a signature to be used with {delegateBySig}. Voting * power can be queried through the public accessors {getVotes} and {getPastVotes}. * * By default, token balance does not account for voting power. This makes transfers cheaper. The downside is that it * requires users to delegate to themselves in order to activate checkpoints and have their voting power tracked. * Enabling self-delegation can easily be done by overriding the {delegates} function. Keep in mind however that this * will significantly increase the base gas cost of transfers. * * _Available since v4.2._ */ abstract contract ERC20Votes is ERC20Permit { struct Checkpoint { uint32 fromBlock; uint224 votes; } bytes32 private constant _DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); mapping(address => address) private _delegates; mapping(address => Checkpoint[]) private _checkpoints; Checkpoint[] private _totalSupplyCheckpoints; /** * @dev Emitted when an account changes their delegate. */ event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /** * @dev Emitted when a token transfer or delegate change results in changes to an account's voting power. */ event DelegateVotesChanged(address indexed delegate, uint256 previousBalance, uint256 newBalance); /** * @dev Get the `pos`-th checkpoint for `account`. */ function checkpoints(address account, uint32 pos) public view virtual returns (Checkpoint memory) { return _checkpoints[account][pos]; } /** * @dev Get number of checkpoints for `account`. */ function numCheckpoints(address account) public view virtual returns (uint32) { return SafeCast.toUint32(_checkpoints[account].length); } /** * @dev Get the address `account` is currently delegating to. */ function delegates(address account) public view virtual returns (address) { return _delegates[account]; } /** * @dev Gets the current votes balance for `account` */ function getVotes(address account) public view returns (uint256) { uint256 pos = _checkpoints[account].length; return pos == 0 ? 0 : _checkpoints[account][pos - 1].votes; } /** * @dev Retrieve the number of votes for `account` at the end of `blockNumber`. * * Requirements: * * - `blockNumber` must have been already mined */ function getPastVotes(address account, uint256 blockNumber) public view returns (uint256) { require(blockNumber < block.number, "ERC20Votes: block not yet mined"); return _checkpointsLookup(_checkpoints[account], blockNumber); } /** * @dev Retrieve the `totalSupply` at the end of `blockNumber`. Note, this value is the sum of all balances. * It is but NOT the sum of all the delegated votes! * * Requirements: * * - `blockNumber` must have been already mined */ function getPastTotalSupply(uint256 blockNumber) public view returns (uint256) { require(blockNumber < block.number, "ERC20Votes: block not yet mined"); return _checkpointsLookup(_totalSupplyCheckpoints, blockNumber); } /** * @dev Lookup a value in a list of (sorted) checkpoints. */ function _checkpointsLookup(Checkpoint[] storage ckpts, uint256 blockNumber) private view returns (uint256) { // We run a binary search to look for the earliest checkpoint taken after `blockNumber`. // // During the loop, the index of the wanted checkpoint remains in the range [low-1, high). // With each iteration, either `low` or `high` is moved towards the middle of the range to maintain the invariant. // - If the middle checkpoint is after `blockNumber`, we look in [low, mid) // - If the middle checkpoint is before or equal to `blockNumber`, we look in [mid+1, high) // Once we reach a single value (when low == high), we've found the right checkpoint at the index high-1, if not // out of bounds (in which case we're looking too far in the past and the result is 0). // Note that if the latest checkpoint available is exactly for `blockNumber`, we end up with an index that is // past the end of the array, so we technically don't find a checkpoint after `blockNumber`, but it works out // the same. uint256 high = ckpts.length; uint256 low = 0; while (low < high) { uint256 mid = Math.average(low, high); if (ckpts[mid].fromBlock > blockNumber) { high = mid; } else { low = mid + 1; } } return high == 0 ? 0 : ckpts[high - 1].votes; } /** * @dev Delegate votes from the sender to `delegatee`. */ function delegate(address delegatee) public virtual { return _delegate(_msgSender(), delegatee); } /** * @dev Delegates votes from signer to `delegatee` */ function delegateBySig( address delegatee, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s ) public virtual { require(block.timestamp <= expiry, "ERC20Votes: signature expired"); address signer = ECDSA.recover( _hashTypedDataV4(keccak256(abi.encode(_DELEGATION_TYPEHASH, delegatee, nonce, expiry))), v, r, s ); require(nonce == _useNonce(signer), "ERC20Votes: invalid nonce"); return _delegate(signer, delegatee); } /** * @dev Maximum token supply. Defaults to `type(uint224).max` (2^224^ - 1). */ function _maxSupply() internal view virtual returns (uint224) { return type(uint224).max; } /** * @dev Snapshots the totalSupply after it has been increased. */ function _mint(address account, uint256 amount) internal virtual override { super._mint(account, amount); require(totalSupply() <= _maxSupply(), "ERC20Votes: total supply risks overflowing votes"); _writeCheckpoint(_totalSupplyCheckpoints, _add, amount); } /** * @dev Snapshots the totalSupply after it has been decreased. */ function _burn(address account, uint256 amount) internal virtual override { super._burn(account, amount); _writeCheckpoint(_totalSupplyCheckpoints, _subtract, amount); } /** * @dev Move voting power when tokens are transferred. * * Emits a {DelegateVotesChanged} event. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual override { super._afterTokenTransfer(from, to, amount); _moveVotingPower(delegates(from), delegates(to), amount); } /** * @dev Change delegation for `delegator` to `delegatee`. * * Emits events {DelegateChanged} and {DelegateVotesChanged}. */ function _delegate(address delegator, address delegatee) internal virtual { address currentDelegate = delegates(delegator); uint256 delegatorBalance = balanceOf(delegator); _delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveVotingPower(currentDelegate, delegatee, delegatorBalance); } function _moveVotingPower( address src, address dst, uint256 amount ) private { if (src != dst && amount > 0) { if (src != address(0)) { (uint256 oldWeight, uint256 newWeight) = _writeCheckpoint(_checkpoints[src], _subtract, amount); emit DelegateVotesChanged(src, oldWeight, newWeight); } if (dst != address(0)) { (uint256 oldWeight, uint256 newWeight) = _writeCheckpoint(_checkpoints[dst], _add, amount); emit DelegateVotesChanged(dst, oldWeight, newWeight); } } } function _writeCheckpoint( Checkpoint[] storage ckpts, function(uint256, uint256) view returns (uint256) op, uint256 delta ) private returns (uint256 oldWeight, uint256 newWeight) { uint256 pos = ckpts.length; oldWeight = pos == 0 ? 0 : ckpts[pos - 1].votes; newWeight = op(oldWeight, delta); if (pos > 0 && ckpts[pos - 1].fromBlock == block.number) { ckpts[pos - 1].votes = SafeCast.toUint224(newWeight); } else { ckpts.push(Checkpoint({fromBlock: SafeCast.toUint32(block.number), votes: SafeCast.toUint224(newWeight)})); } } function _add(uint256 a, uint256 b) private pure returns (uint256) { return a + b; } function _subtract(uint256 a, uint256 b) private pure returns (uint256) { return a - b; } } // 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 contracts/libraries/Utils.sol pragma solidity ^0.8.0; library Utils { using Utils for Unlock; using Utils for Vest; struct Vest { uint256 shortAmnt; uint256 longAmnt; uint256 lastUpdate; } struct Unlock { uint256 unlockAmnt; uint256 unlockTime; } // note: we should be able to unlock all tokens (including vested tokens) function unlock( Unlock storage self, uint256 amount, uint256 lockTime ) internal { self.unlockAmnt = amount; self.unlockTime = block.timestamp + lockTime; } function useUnlocked(Unlock storage self, uint256 amount) internal { require(self.unlockTime <= block.timestamp, "sRelU: tokens are not unlocked yet"); require(self.unlockAmnt >= amount, "sRelU: tokens should be unlocked before transfer"); self.unlockAmnt -= amount; // update locked amount; } function resetLock(Unlock storage self) internal { self.unlockAmnt = 0; self.unlockTime = 0; } function transferUnvestedTokens(Vest storage self, Vest storage vestTo) internal { require(self.shortAmnt | self.longAmnt != 0, "sRelU: nothing to transfer"); require( vestTo.shortAmnt | vestTo.longAmnt == 0, "sRelU: cannot transfer to account with unvested tokens" ); vestTo.shortAmnt = self.shortAmnt; vestTo.longAmnt = self.longAmnt; vestTo.lastUpdate = self.lastUpdate; // reset initial vest self.shortAmnt = 0; self.longAmnt = 0; self.lastUpdate = 0; } function setUnvestedAmount( Vest storage self, uint256 shortAmnt, uint256 longAmnt ) public { require(self.shortAmnt + self.longAmnt == 0, "sRelU: account has unvested tokens"); if (shortAmnt > 0) self.shortAmnt = shortAmnt; if (longAmnt > 0) self.longAmnt = longAmnt; self.lastUpdate = 0; } function unvested(Vest storage self) internal view returns (uint256) { return self.shortAmnt + self.longAmnt; } // this method updates long and short unvested amounts and returns vested amount function updateUnvestedAmount( Vest storage self, uint256 vestShort, uint256 vestLong, uint256 vestBegin ) public returns (uint256 amount) { if (block.timestamp <= vestBegin) return 0; uint256 shortAmnt = self.shortAmnt; uint256 longAmnt = self.longAmnt; uint256 last = self.lastUpdate < vestBegin ? vestBegin : self.lastUpdate; if (shortAmnt > 0 && last < vestShort) { uint256 sAmnt = block.timestamp < vestShort ? (shortAmnt * (block.timestamp - last)) / (vestShort - last) : shortAmnt; self.shortAmnt = shortAmnt - sAmnt; amount += sAmnt; } if (longAmnt > 0 && last < vestLong) { uint256 lAmnt = block.timestamp < vestLong ? (longAmnt * (block.timestamp - last)) / (vestLong - last) : longAmnt; self.longAmnt = longAmnt - lAmnt; amount += lAmnt; } self.lastUpdate = block.timestamp; return amount; } } // File contracts/interfaces/IsRel.sol pragma solidity ^0.8.0; // Relevant Governance Token interface IsRel { event lockUpdated(address indexed account, Utils.Unlock unlockData); // staking events event vestUpdated(address indexed account, address sender, Utils.Vest vestData); // vesting events // governance events event lockPeriodUpdated(uint256 newLockPeriod); event vestAdminUpdated(address newVestAdmin); // staking function unlock(uint256 amount) external; function resetLock() external; function stakeRel(uint256 amount) external; function withdrawRel(uint256 amount) external; // vesting function setUnvestedAmount( address account, uint256 amountShort, uint256 amountLong ) external; function initVesting( uint256 _shortAmount, uint256 _longAmount, bytes memory _sig ) external; function claimVestedRel() external; function transferUnvestedTokens(address to) external; // governance function updateLockPeriod(uint256 newLockPeriod) external; function setVestAdmin(address newAdmin) external; // view function nonceOf(address account) external view returns (uint256); function unstaked(address account) external view returns (uint256); function staked(address account) external view returns (uint256); function unlockTime(address account) external view returns (uint256); function unvested(address account) external view returns (uint256); function vestData(address account) external view returns (Utils.Vest memory); } // File contracts/sRel.sol pragma solidity ^0.8.0; contract sRel is IsRel, ERC20Votes, Ownable { using Utils for Utils.Vest; using Utils for Utils.Unlock; IERC20 public immutable r3l; // RELEVANT TOKEN address public vestAdmin; // role is responsible for sending tokens to vesting contract uint256 public lockPeriod = 4 days; // how long it takes for staked tokens to become unlocked uint256 public immutable vestBegin; // start of all vesting periods uint256 public immutable vestShort; // short vesting end date uint256 public immutable vestLong; // long vesting end date uint256 public totalUnvested; mapping(address => uint256) private vestNonce; mapping(address => Utils.Unlock) private unlocks; mapping(address => Utils.Vest) private vest; // keccak256("InitVesting(address account,uint256 shortAmnt,uint256 longAmnt,uint256 nonce)") bytes32 public constant CLAIM_HASH = 0xaa930e3affe03e95a7e73cc03af79eab35ac3f46fe4ae69839f76986ecaa957d; constructor( IERC20 _r3l, address _vestAdmin, uint256 _vestBegin, uint256 _vestShort, uint256 _vestLong ) ERC20("Staked REL", "sREL") ERC20Permit("Staked REL") { require( _vestBegin <= _vestShort && _vestShort <= _vestLong, "sRel: incorrect vesting timestamps" ); r3l = _r3l; vestBegin = _vestBegin; vestShort = _vestShort; vestLong = _vestLong; vestAdmin = _vestAdmin; } // only unlocked & unvested tokens can be transferred function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual override(ERC20) { super._beforeTokenTransfer(from, to, amount); // minting and transfers from contract are not subject to unlocks if (from == address(0) || from == address(this)) return; uint256 vestedBalance = balanceOf(from) - vest[from].unvested(); require(amount <= vestedBalance, "sRel: you cannot transfer unvested tokens"); Utils.Unlock storage lock = unlocks[from]; lock.useUnlocked(amount); // only unlocked tokens can be transferred emit lockUpdated(from, lock); } // ---- STAKING METHODS ---- // unlock sRel - after lockPeriod tokens can be transferred or withdrawn function unlock(uint256 amount) external override(IsRel) { Utils.Unlock storage lock = unlocks[msg.sender]; lock.unlock(amount, lockPeriod); emit lockUpdated(msg.sender, lock); } // re-lock tokens function resetLock() external override(IsRel) { Utils.Unlock storage lock = unlocks[msg.sender]; lock.resetLock(); emit lockUpdated(msg.sender, lock); } // deposit REL in exchange for sREL function stakeRel(uint256 amount) external override(IsRel) { require(r3l.transferFrom(msg.sender, address(this), amount), "sRel: transfer failed"); _mint(msg.sender, amount); } // withdraws all unlocked tokens function withdrawRel(uint256 amount) external override(IsRel) { _burn(msg.sender, amount); require(r3l.transfer(msg.sender, amount), "sRel: transfer failed"); } // ---- VESTING METHODS ---- // onwer can set amount of unvested tokens manually // NOTE: REL must be sent to this contract before this method is called function setUnvestedAmount( address account, uint256 shortAmnt, uint256 longAmnt ) external override(IsRel) onlyOwner { _setUnvestedAmount(account, shortAmnt, longAmnt); } // Claim curation reward tokens (to be called by user from an app) function initVesting( uint256 _shortAmount, uint256 _longAmount, bytes memory _sig ) external override(IsRel) { uint256 nonce = vestNonce[msg.sender]; bytes32 structHash = keccak256( abi.encode(CLAIM_HASH, msg.sender, _shortAmount, _longAmount, nonce) ); // _domainSeparatorV4 is from EIP712 which is a base contract of ERC20Votes bytes32 digest = ECDSA.toTypedDataHash(_domainSeparatorV4(), structHash); address signer = ECDSA.recover(digest, _sig); // check that the message was signed by a vest admin require(signer == vestAdmin, "sRel: Claim not authorized"); vestNonce[msg.sender] = nonce + 1; _setUnvestedAmount(msg.sender, _shortAmount, _longAmount); } // helper function that initializes unvested amounts // NOTE: REL must be sent to this contract *before* this method is called function _setUnvestedAmount( address account, uint256 shortAmnt, uint256 longAmnt ) internal { Utils.Vest storage vesting = vest[account]; vesting.setUnvestedAmount(shortAmnt, longAmnt); uint256 totalUnvestedAmnt = shortAmnt + longAmnt; require( totalSupply() + totalUnvestedAmnt <= r3l.balanceOf(address(this)), "sRel: Not enought REL in contract" ); _mint(account, totalUnvestedAmnt); totalUnvested += totalUnvestedAmnt; emit vestUpdated(account, msg.sender, vesting); } // unvest and unlock tokens function claimVestedRel() external override(IsRel) { Utils.Vest storage vesting = vest[msg.sender]; uint256 amount = vesting.updateUnvestedAmount(vestShort, vestLong, vestBegin); require(amount > 0, "sRel: no unvested tokens to claim"); totalUnvested -= amount; unlocks[msg.sender].unlock(amount, lockPeriod); emit vestUpdated(msg.sender, msg.sender, vesting); } // transfer all unvested tokens to a new address function transferUnvestedTokens(address to) external override(IsRel) { Utils.Vest storage senderVest = vest[msg.sender]; Utils.Vest storage toVest = vest[to]; uint256 amount = senderVest.unvested(); senderVest.transferUnvestedTokens(toVest); transfer(to, amount); emit vestUpdated(msg.sender, msg.sender, senderVest); emit vestUpdated(to, msg.sender, toVest); } // ---- GOVERNANCE ---- function updateLockPeriod(uint256 newLockPeriod) external override(IsRel) onlyOwner { require(lockPeriod != newLockPeriod, "sRel: nothing to update"); lockPeriod = newLockPeriod; emit lockPeriodUpdated(lockPeriod); } function setVestAdmin(address newAdmin) external override(IsRel) { require(msg.sender == owner() || msg.sender == vestAdmin, "sRel: not authorized"); require(vestAdmin != newAdmin, "sRel: nothing to update"); vestAdmin = newAdmin; emit vestAdminUpdated(vestAdmin); } // ---- VIEW -------- function nonceOf(address account) external view override(IsRel) returns (uint256) { return vestNonce[account]; } function staked(address account) external view override(IsRel) returns (uint256) { return balanceOf(account) - unlocks[account].unlockAmnt; } function unstaked(address account) external view override(IsRel) returns (uint256) { return unlocks[account].unlockAmnt; } function unlockTime(address account) external view override(IsRel) returns (uint256) { return unlocks[account].unlockTime; } function unvested(address account) external view override(IsRel) returns (uint256) { return vest[account].unvested(); } function vestData(address account) external view override(IsRel) returns (Utils.Vest memory) { return vest[account]; } }
long vesting end date
uint256 public immutable vestLong;
8,030,312
[ 1, 5748, 331, 10100, 679, 1509, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 225, 2254, 5034, 1071, 11732, 331, 395, 3708, 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 ]
/** *Submitted for verification at Etherscan.io on 2021-04-28 */ // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; // Part: IBalancerPool interface IBalancerPool { function getFinalTokens() external view returns (address[] memory); function getNormalizedWeight(address token) external view returns (uint); function getSwapFee() external view returns (uint); function getNumTokens() external view returns (uint); function getBalance(address token) external view returns (uint); function totalSupply() external view returns (uint); function joinPool(uint poolAmountOut, uint[] calldata maxAmountsIn) external; function swapExactAmountOut( address tokenIn, uint maxAmountIn, address tokenOut, uint tokenAmountOut, uint maxPrice ) external returns (uint tokenAmountIn, uint spotPriceAfter); function joinswapExternAmountIn( address tokenIn, uint tokenAmountIn, uint minPoolAmountOut ) external returns (uint poolAmountOut); function exitPool(uint poolAmoutnIn, uint[] calldata minAmountsOut) external; function exitswapExternAmountOut( address tokenOut, uint tokenAmountOut, uint maxPoolAmountIn ) external returns (uint poolAmountIn); } // Part: IBank interface IBank { /// The governor adds a new bank gets added to the system. event AddBank(address token, address cToken); /// The governor sets the address of the oracle smart contract. event SetOracle(address oracle); /// The governor sets the basis point fee of the bank. event SetFeeBps(uint feeBps); /// The governor withdraw tokens from the reserve of a bank. event WithdrawReserve(address user, address token, uint amount); /// Someone borrows tokens from a bank via a spell caller. event Borrow(uint positionId, address caller, address token, uint amount, uint share); /// Someone repays tokens to a bank via a spell caller. event Repay(uint positionId, address caller, address token, uint amount, uint share); /// Someone puts tokens as collateral via a spell caller. event PutCollateral(uint positionId, address caller, address token, uint id, uint amount); /// Someone takes tokens from collateral via a spell caller. event TakeCollateral(uint positionId, address caller, address token, uint id, uint amount); /// Someone calls liquidatation on a position, paying debt and taking collateral tokens. event Liquidate( uint positionId, address liquidator, address debtToken, uint amount, uint share, uint bounty ); /// @dev Return the current position while under execution. function POSITION_ID() external view returns (uint); /// @dev Return the current target while under execution. function SPELL() external view returns (address); /// @dev Return the current executor (the owner of the current position). function EXECUTOR() external view returns (address); /// @dev Return bank information for the given token. function getBankInfo(address token) external view returns ( bool isListed, address cToken, uint reserve, uint totalDebt, uint totalShare ); /// @dev Return position information for the given position id. function getPositionInfo(uint positionId) external view returns ( address owner, address collToken, uint collId, uint collateralSize ); /// @dev Return the borrow balance for given positon and token without trigger interest accrual. function borrowBalanceStored(uint positionId, address token) external view returns (uint); /// @dev Trigger interest accrual and return the current borrow balance. function borrowBalanceCurrent(uint positionId, address token) external returns (uint); /// @dev Borrow tokens from the bank. function borrow(address token, uint amount) external; /// @dev Repays tokens to the bank. function repay(address token, uint amountCall) external; /// @dev Transmit user assets to the spell. function transmit(address token, uint amount) external; /// @dev Put more collateral for users. function putCollateral( address collToken, uint collId, uint amountCall ) external; /// @dev Take some collateral back. function takeCollateral( address collToken, uint collId, uint amount ) external; /// @dev Liquidate a position. function liquidate( uint positionId, address debtToken, uint amountCall ) external; function getBorrowETHValue(uint positionId) external view returns (uint); function accrue(address token) external; function nextPositionId() external view returns (uint); /// @dev Return current position information. function getCurrentPositionInfo() external view returns ( address owner, address collToken, uint collId, uint collateralSize ); function support(address token) external view returns (bool); } // Part: IERC20Wrapper interface IERC20Wrapper { /// @dev Return the underlying ERC-20 for the given ERC-1155 token id. function getUnderlyingToken(uint id) external view returns (address); /// @dev Return the conversion rate from ERC-1155 to ERC-20, multiplied by 2**112. function getUnderlyingRate(uint id) external view returns (uint); } // Part: IWETH interface IWETH { function balanceOf(address user) external returns (uint); function approve(address to, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function deposit() external payable; function withdraw(uint) external; } // 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) { // 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); } } } } // Part: OpenZeppelin/[email protected]/IERC165 /** * @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); } // 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]/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, 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; } } // Part: HomoraMath library HomoraMath { using SafeMath for uint; function divCeil(uint lhs, uint rhs) internal pure returns (uint) { return lhs.add(rhs).sub(1) / rhs; } function fmul(uint lhs, uint rhs) internal pure returns (uint) { return lhs.mul(rhs) / (2**112); } function fdiv(uint lhs, uint rhs) internal pure returns (uint) { return lhs.mul(2**112) / rhs; } // implementation from https://github.com/Uniswap/uniswap-lib/commit/99f3f28770640ba1bb1ff460ac7c5292fb8291a0 // original implementation: https://github.com/abdk-consulting/abdk-libraries-solidity/blob/master/ABDKMath64x64.sol#L687 function sqrt(uint x) internal pure returns (uint) { if (x == 0) return 0; uint xx = x; uint 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 uint r1 = x / r; return (r < r1 ? r : r1); } } // Part: OpenZeppelin/[email protected]/ERC165 /** * @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; } } // Part: OpenZeppelin/[email protected]/IERC1155 /** * @dev Required interface of an ERC1155 compliant contract, as defined in the * https://eips.ethereum.org/EIPS/eip-1155[EIP]. * * _Available since v3.1._ */ interface IERC1155 is IERC165 { /** * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`. */ event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); /** * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all * transfers. */ event TransferBatch(address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values); /** * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to * `approved`. */ event ApprovalForAll(address indexed account, address indexed operator, bool approved); /** * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI. * * If an {URI} event was emitted for `id`, the standard * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value * returned by {IERC1155MetadataURI-uri}. */ event URI(string value, uint256 indexed id); /** * @dev Returns the amount of tokens of token type `id` owned by `account`. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, * * Emits an {ApprovalForAll} event. * * Requirements: * * - `operator` cannot be the caller. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns true if `operator` is approved to transfer ``account``'s tokens. * * See {setApprovalForAll}. */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes calldata data) external; /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function safeBatchTransferFrom(address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data) external; } // Part: OpenZeppelin/[email protected]/IERC1155Receiver /** * _Available since v3.1._ */ interface IERC1155Receiver is IERC165 { /** @dev Handles the receipt of a single ERC1155 token type. This function is called at the end of a `safeTransferFrom` after the balance has been updated. To accept the transfer, this must return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` (i.e. 0xf23a6e61, or its own function selector). @param operator The address which initiated the transfer (i.e. msg.sender) @param from The address which previously owned the token @param id The ID of the token being transferred @param value The amount of tokens being transferred @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed */ function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external returns(bytes4); /** @dev Handles the receipt of a multiple ERC1155 token types. This function is called at the end of a `safeBatchTransferFrom` after the balances have been updated. To accept the transfer(s), this must return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` (i.e. 0xbc197c81, or its own function selector). @param operator The address which initiated the batch transfer (i.e. msg.sender) @param from The address which previously owned the token @param ids An array containing ids of each token being transferred (order and length must match values array) @param values An array containing amounts of each token being transferred (order and length must match ids array) @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed */ function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external returns(bytes4); } // Part: OpenZeppelin/[email protected]/Initializable /** * @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) { return !Address.isContract(address(this)); } } // 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: Governable contract Governable is Initializable { event SetGovernor(address governor); event SetPendingGovernor(address pendingGovernor); event AcceptGovernor(address governor); address public governor; // The current governor. address public pendingGovernor; // The address pending to become the governor once accepted. bytes32[64] _gap; // reserve space for upgrade modifier onlyGov() { require(msg.sender == governor, 'not the governor'); _; } /// @dev Initialize using msg.sender as the first governor. function __Governable__init() internal initializer { governor = msg.sender; pendingGovernor = address(0); emit SetGovernor(msg.sender); } /// @dev Set the pending governor, which will be the governor once accepted. /// @param _pendingGovernor The address to become the pending governor. function setPendingGovernor(address _pendingGovernor) external onlyGov { pendingGovernor = _pendingGovernor; emit SetPendingGovernor(_pendingGovernor); } /// @dev Accept to become the new governor. Must be called by the pending governor. function acceptGovernor() external { require(msg.sender == pendingGovernor, 'not the pending governor'); pendingGovernor = address(0); governor = msg.sender; emit AcceptGovernor(msg.sender); } } // Part: IWERC20 interface IWERC20 is IERC1155, IERC20Wrapper { /// @dev Return the underlying ERC20 balance for the user. function balanceOfERC20(address token, address user) external view returns (uint); /// @dev Mint ERC1155 token for the given ERC20 token. function mint(address token, uint amount) external; /// @dev Burn ERC1155 token to redeem ERC20 token back. function burn(address token, uint amount) external; } // Part: IWStakingRewards interface IWStakingRewards is IERC1155, IERC20Wrapper { /// @dev Mint ERC1155 token for the given ERC20 token. function mint(uint amount) external returns (uint id); /// @dev Burn ERC1155 token to redeem ERC20 token back. function burn(uint id, uint amount) external returns (uint); function reward() external returns (address); } // Part: OpenZeppelin/[email protected]/ERC1155Receiver /** * @dev _Available since v3.1._ */ abstract contract ERC1155Receiver is ERC165, IERC1155Receiver { constructor() internal { _registerInterface( ERC1155Receiver(address(0)).onERC1155Received.selector ^ ERC1155Receiver(address(0)).onERC1155BatchReceived.selector ); } } // Part: ERC1155NaiveReceiver contract ERC1155NaiveReceiver is ERC1155Receiver { bytes32[64] __gap; // reserve space for upgrade function onERC1155Received( address, /* operator */ address, /* from */ uint, /* id */ uint, /* value */ bytes calldata /* data */ ) external override returns (bytes4) { return this.onERC1155Received.selector; } function onERC1155BatchReceived( address, /* operator */ address, /* from */ uint[] calldata, /* ids */ uint[] calldata, /* values */ bytes calldata /* data */ ) external override returns (bytes4) { return this.onERC1155BatchReceived.selector; } } // Part: BasicSpell abstract contract BasicSpell is ERC1155NaiveReceiver { using SafeERC20 for IERC20; IBank public immutable bank; IWERC20 public immutable werc20; address public immutable weth; mapping(address => mapping(address => bool)) public approved; // Mapping from token to (mapping from spender to approve status) constructor( IBank _bank, address _werc20, address _weth ) public { bank = _bank; werc20 = IWERC20(_werc20); weth = _weth; ensureApprove(_weth, address(_bank)); IWERC20(_werc20).setApprovalForAll(address(_bank), true); } /// @dev Ensure that the spell has approved the given spender to spend all of its tokens. /// @param token The token to approve. /// @param spender The spender to allow spending. /// NOTE: This is safe because spell is never built to hold fund custody. function ensureApprove(address token, address spender) internal { if (!approved[token][spender]) { IERC20(token).safeApprove(spender, uint(-1)); approved[token][spender] = true; } } /// @dev Internal call to convert msg.value ETH to WETH inside the contract. function doTransmitETH() internal { if (msg.value > 0) { IWETH(weth).deposit{value: msg.value}(); } } /// @dev Internal call to transmit tokens from the bank if amount is positive. /// @param token The token to perform the transmit action. /// @param amount The amount to transmit. /// @notice Do not use `amount` input argument to handle the received amount. function doTransmit(address token, uint amount) internal { if (amount > 0) { bank.transmit(token, amount); } } /// @dev Internal call to refund tokens to the current bank executor. /// @param token The token to perform the refund action. function doRefund(address token) internal { uint balance = IERC20(token).balanceOf(address(this)); if (balance > 0) { IERC20(token).safeTransfer(bank.EXECUTOR(), balance); } } /// @dev Internal call to refund all WETH to the current executor as native ETH. function doRefundETH() internal { uint balance = IWETH(weth).balanceOf(address(this)); if (balance > 0) { IWETH(weth).withdraw(balance); (bool success, ) = bank.EXECUTOR().call{value: balance}(new bytes(0)); require(success, 'refund ETH failed'); } } /// @dev Internal call to borrow tokens from the bank on behalf of the current executor. /// @param token The token to borrow from the bank. /// @param amount The amount to borrow. /// @notice Do not use `amount` input argument to handle the received amount. function doBorrow(address token, uint amount) internal { if (amount > 0) { bank.borrow(token, amount); } } /// @dev Internal call to repay tokens to the bank on behalf of the current executor. /// @param token The token to repay to the bank. /// @param amount The amount to repay. function doRepay(address token, uint amount) internal { if (amount > 0) { ensureApprove(token, address(bank)); bank.repay(token, amount); } } /// @dev Internal call to put collateral tokens in the bank. /// @param token The token to put in the bank. /// @param amount The amount to put in the bank. function doPutCollateral(address token, uint amount) internal { if (amount > 0) { ensureApprove(token, address(werc20)); werc20.mint(token, amount); bank.putCollateral(address(werc20), uint(token), amount); } } /// @dev Internal call to take collateral tokens from the bank. /// @param token The token to take back. /// @param amount The amount to take back. function doTakeCollateral(address token, uint amount) internal { if (amount > 0) { if (amount == uint(-1)) { (, , , amount) = bank.getCurrentPositionInfo(); } bank.takeCollateral(address(werc20), uint(token), amount); werc20.burn(token, amount); } } /// @dev Fallback function. Can only receive ETH from WETH contract. receive() external payable { require(msg.sender == weth, 'ETH must come from WETH'); } } // Part: WhitelistSpell contract WhitelistSpell is BasicSpell, Governable { mapping(address => bool) public whitelistedLpTokens; // mapping from lp token to whitelist status constructor( IBank _bank, address _werc20, address _weth ) public BasicSpell(_bank, _werc20, _weth) { __Governable__init(); } /// @dev Set whitelist LP token statuses for spell /// @param lpTokens LP tokens to set whitelist statuses /// @param statuses Whitelist statuses function setWhitelistLPTokens(address[] calldata lpTokens, bool[] calldata statuses) external onlyGov { require(lpTokens.length == statuses.length, 'lpTokens & statuses length mismatched'); for (uint idx = 0; idx < lpTokens.length; idx++) { if (statuses[idx]) { require(bank.support(lpTokens[idx]), 'oracle not support lp token'); } whitelistedLpTokens[lpTokens[idx]] = statuses[idx]; } } } // File: BalancerSpellV1.sol contract BalancerSpellV1 is WhitelistSpell { using SafeMath for uint; using HomoraMath for uint; mapping(address => address[2]) public pairs; // Mapping from lp token to underlying token (only pairs) constructor( IBank _bank, address _werc20, address _weth ) public WhitelistSpell(_bank, _werc20, _weth) {} /// @dev Return the underlying pairs for the lp token. /// @param lp LP token function getAndApprovePair(address lp) public returns (address, address) { address[2] memory ulTokens = pairs[lp]; if (ulTokens[0] == address(0) || ulTokens[1] == address(0)) { address[] memory tokens = IBalancerPool(lp).getFinalTokens(); require(tokens.length == 2, 'underlying tokens not 2'); ulTokens[0] = tokens[0]; ulTokens[1] = tokens[1]; pairs[lp] = ulTokens; ensureApprove(ulTokens[0], lp); ensureApprove(ulTokens[1], lp); } return (ulTokens[0], ulTokens[1]); } struct Amounts { uint amtAUser; // Supplied tokenA amount uint amtBUser; // Supplied tokenB amount uint amtLPUser; // Supplied LP token amount uint amtABorrow; // Borrow tokenA amount uint amtBBorrow; // Borrow tokenB amount uint amtLPBorrow; // Borrow LP token amount uint amtLPDesired; // Desired LP token amount (slippage control) } /// @dev Add liquidity to Balancer pool /// @param lp LP token for the pool /// @param amt Amounts of tokens to supply, borrow, and get. /// @return added lp amount function addLiquidityInternal(address lp, Amounts calldata amt) internal returns (uint) { require(whitelistedLpTokens[lp], 'lp token not whitelisted'); (address tokenA, address tokenB) = getAndApprovePair(lp); // 1. Get user input amounts doTransmitETH(); doTransmit(tokenA, amt.amtAUser); doTransmit(tokenB, amt.amtBUser); doTransmit(lp, amt.amtLPUser); // 2. Borrow specified amounts doBorrow(tokenA, amt.amtABorrow); doBorrow(tokenB, amt.amtBBorrow); doBorrow(lp, amt.amtLPBorrow); // 3.1 Add Liquidity using equal value two side to minimize swap fee uint[] memory maxAmountsIn = new uint[](2); maxAmountsIn[0] = IERC20(tokenA).balanceOf(address(this)); maxAmountsIn[1] = IERC20(tokenB).balanceOf(address(this)); uint totalLPSupply = IBalancerPool(lp).totalSupply(); uint poolAmountFromA = maxAmountsIn[0].mul(1e18).div(IBalancerPool(lp).getBalance(tokenA)).mul(totalLPSupply).div( 1e18 ); // compute in reverse order of how Balancer's `joinPool` computes tokenAmountIn uint poolAmountFromB = maxAmountsIn[1].mul(1e18).div(IBalancerPool(lp).getBalance(tokenB)).mul(totalLPSupply).div( 1e18 ); // compute in reverse order of how Balancer's `joinPool` computes tokenAmountIn uint poolAmountOut = poolAmountFromA > poolAmountFromB ? poolAmountFromB : poolAmountFromA; if (poolAmountOut > 0) IBalancerPool(lp).joinPool(poolAmountOut, maxAmountsIn); // 3.2 Add Liquidity leftover for each token uint ABal = IERC20(tokenA).balanceOf(address(this)); uint BBal = IERC20(tokenB).balanceOf(address(this)); if (ABal > 0) IBalancerPool(lp).joinswapExternAmountIn(tokenA, ABal, 0); if (BBal > 0) IBalancerPool(lp).joinswapExternAmountIn(tokenB, BBal, 0); // 4. Slippage control uint lpBalance = IERC20(lp).balanceOf(address(this)); require(lpBalance >= amt.amtLPDesired, 'lp desired not met'); return lpBalance; } /// @dev Add liquidity to Balancer pool (with 2 underlying tokens), without staking rewards (use WERC20 wrapper) /// @param lp LP token for the pool /// @param amt Amounts of tokens to supply, borrow, and get. function addLiquidityWERC20(address lp, Amounts calldata amt) external payable { // 1-4. add liquidity uint lpBalance = addLiquidityInternal(lp, amt); // 5. Put collateral doPutCollateral(lp, lpBalance); // 6. Refund leftovers to users (address tokenA, address tokenB) = getAndApprovePair(lp); doRefundETH(); doRefund(tokenA); doRefund(tokenB); } /// @dev Add liquidity to Balancer pool (with 2 underlying tokens), with staking rewards (use WStakingRewards) /// @param lp LP token for the pool /// @param amt Amounts of tokens to supply, borrow, and desire. /// @param wstaking Wrapped staking rewards contract address function addLiquidityWStakingRewards( address lp, Amounts calldata amt, address wstaking ) external payable { // 1-4. add liquidity addLiquidityInternal(lp, amt); // 5. Take out collateral (, address collToken, uint collId, uint collSize) = bank.getCurrentPositionInfo(); if (collSize > 0) { require(IWStakingRewards(collToken).getUnderlyingToken(collId) == lp, 'incorrect underlying'); require(collToken == wstaking, 'collateral token & wstaking mismatched'); bank.takeCollateral(wstaking, collId, collSize); IWStakingRewards(wstaking).burn(collId, collSize); } // 6. Put collateral ensureApprove(lp, wstaking); uint amount = IERC20(lp).balanceOf(address(this)); uint id = IWStakingRewards(wstaking).mint(amount); if (!IWStakingRewards(wstaking).isApprovedForAll(address(this), address(bank))) { IWStakingRewards(wstaking).setApprovalForAll(address(bank), true); } bank.putCollateral(address(wstaking), id, amount); // 7. Refund leftovers to users (address tokenA, address tokenB) = getAndApprovePair(lp); doRefundETH(); doRefund(tokenA); doRefund(tokenB); // 8. Refund reward doRefund(IWStakingRewards(wstaking).reward()); } struct RepayAmounts { uint amtLPTake; // Take out LP token amount (from Homora) uint amtLPWithdraw; // Withdraw LP token amount (back to caller) uint amtARepay; // Repay tokenA amount uint amtBRepay; // Repay tokenB amount uint amtLPRepay; // Repay LP token amount uint amtAMin; // Desired tokenA amount (slippage control) uint amtBMin; // Desired tokenB amount (slippage control) } /// @dev Remove liquidity from Balancer pool (with 2 underlying tokens) /// @param lp LP token for the pool /// @param amt Amounts of tokens to take out, withdraw, repay and get. function removeLiquidityInternal(address lp, RepayAmounts calldata amt) internal { require(whitelistedLpTokens[lp], 'lp token not whitelisted'); (address tokenA, address tokenB) = getAndApprovePair(lp); uint amtARepay = amt.amtARepay; uint amtBRepay = amt.amtBRepay; uint amtLPRepay = amt.amtLPRepay; // 2. Compute repay amount if MAX_INT is supplied (max debt) { uint positionId = bank.POSITION_ID(); if (amtARepay == uint(-1)) { amtARepay = bank.borrowBalanceCurrent(positionId, tokenA); } if (amtBRepay == uint(-1)) { amtBRepay = bank.borrowBalanceCurrent(positionId, tokenB); } if (amtLPRepay == uint(-1)) { amtLPRepay = bank.borrowBalanceCurrent(positionId, lp); } } // 3.1 Remove liquidity 2 sides uint amtLPToRemove = IERC20(lp).balanceOf(address(this)).sub(amt.amtLPWithdraw); if (amtLPToRemove > 0) { uint[] memory minAmountsOut = new uint[](2); IBalancerPool(lp).exitPool(amtLPToRemove, minAmountsOut); } // 3.2 Minimize trading uint amtADesired = amtARepay.add(amt.amtAMin); uint amtBDesired = amtBRepay.add(amt.amtBMin); uint amtA = IERC20(tokenA).balanceOf(address(this)); uint amtB = IERC20(tokenB).balanceOf(address(this)); if (amtA < amtADesired && amtB > amtBDesired) { IBalancerPool(lp).swapExactAmountOut( tokenB, amtB.sub(amtBDesired), tokenA, amtADesired.sub(amtA), uint(-1) ); } else if (amtA > amtADesired && amtB < amtBDesired) { IBalancerPool(lp).swapExactAmountOut( tokenA, amtA.sub(amtADesired), tokenB, amtBDesired.sub(amtB), uint(-1) ); } // 4. Repay doRepay(tokenA, amtARepay); doRepay(tokenB, amtBRepay); doRepay(lp, amtLPRepay); // 5. Slippage control require(IERC20(tokenA).balanceOf(address(this)) >= amt.amtAMin); require(IERC20(tokenB).balanceOf(address(this)) >= amt.amtBMin); require(IERC20(lp).balanceOf(address(this)) >= amt.amtLPWithdraw); // 6. Refund leftover doRefundETH(); doRefund(tokenA); doRefund(tokenB); doRefund(lp); } /// @dev Remove liquidity from Balancer pool (with 2 underlying tokens), without staking rewards (use WERC20 wrapper) /// @param lp LP token for the pool /// @param amt Amounts of tokens to take out, withdraw, repay, and get. function removeLiquidityWERC20(address lp, RepayAmounts calldata amt) external { // 1. Take out collateral doTakeCollateral(lp, amt.amtLPTake); // 2-6. remove liquidity removeLiquidityInternal(lp, amt); } /// @dev Remove liquidity from Balancer pool (with 2 underlying tokens), with staking rewards /// @param lp LP token for the pool /// @param amt Amounts of tokens to take out, withdraw, repay, and get.v function removeLiquidityWStakingRewards( address lp, RepayAmounts calldata amt, address wstaking ) external { (, address collToken, uint collId, ) = bank.getCurrentPositionInfo(); // 1. Take out collateral require(IWStakingRewards(collToken).getUnderlyingToken(collId) == lp, 'incorrect underlying'); require(collToken == wstaking, 'collateral token & wstaking mismatched'); bank.takeCollateral(wstaking, collId, amt.amtLPTake); IWStakingRewards(wstaking).burn(collId, amt.amtLPTake); // 2-6. remove liquidity removeLiquidityInternal(lp, amt); // 7. Refund reward doRefund(IWStakingRewards(wstaking).reward()); } /// @dev Harvest staking reward tokens to in-exec position's owner /// @param wstaking Wrapped staking rewards function harvestWStakingRewards(address wstaking) external { (, address collToken, uint collId, ) = bank.getCurrentPositionInfo(); address lp = IWStakingRewards(wstaking).getUnderlyingToken(collId); require(whitelistedLpTokens[lp], 'lp token not whitelisted'); require(collToken == wstaking, 'collateral token & wstaking mismatched'); // 1. Take out collateral bank.takeCollateral(wstaking, collId, uint(-1)); IWStakingRewards(wstaking).burn(collId, uint(-1)); // 2. put collateral uint amount = IERC20(lp).balanceOf(address(this)); ensureApprove(lp, wstaking); uint id = IWStakingRewards(wstaking).mint(amount); bank.putCollateral(wstaking, id, amount); // 3. Refund reward doRefund(IWStakingRewards(wstaking).reward()); } }
@dev Internal call to borrow tokens from the bank on behalf of the current executor. @param token The token to borrow from the bank. @param amount The amount to borrow. @notice Do not use `amount` input argument to handle the received amount.
function doBorrow(address token, uint amount) internal { if (amount > 0) { bank.borrow(token, amount); } }
2,414,075
[ 1, 3061, 745, 358, 29759, 2430, 628, 326, 11218, 603, 12433, 6186, 434, 326, 783, 6601, 18, 225, 1147, 1021, 1147, 358, 29759, 628, 326, 11218, 18, 225, 3844, 1021, 3844, 358, 29759, 18, 225, 2256, 486, 999, 1375, 8949, 68, 810, 1237, 358, 1640, 326, 5079, 3844, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 225, 445, 741, 38, 15318, 12, 2867, 1147, 16, 2254, 3844, 13, 2713, 288, 203, 565, 309, 261, 8949, 405, 374, 13, 288, 203, 1377, 11218, 18, 70, 15318, 12, 2316, 16, 3844, 1769, 203, 565, 289, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/3/0x640E550F1Ed4b25f7902a79eA211D56b9223d0EE/sources/fMain.sol
Withdraw LP tokens from TLTMain.
function withdraw(uint256 _aid, uint256 _pid, uint256 _amount) payable public { PoolInfo storage pool = poolInfo[_aid][_pid]; UserInfo storage user = userInfo[_aid][_pid][msg.sender]; require((pool.bLock == false) || (pool.bLock && (block.number >= (startBlock.add(lockPeriods)))), "withdraw: pool lock"); require(user.amount >= _amount, "withdraw: not good"); if (_amount > 0){ require((pool.bWithdrawFee == false) || (pool.bWithdrawFee == true && msg.value == pool.withdrawFee), "withdraw: not enough"); } updatePool(_aid, _pid); uint256 _value = 0; if(_amount > 0) { if (user.value != 0){ _value = _amount.mul(user.value).div(user.amount); } user.amount = user.amount.sub(_amount); user.value = user.value.sub(_value); pool.lpToken.safeTransfer(address(msg.sender), _amount); if (_value != 0){ otherToken.safeTransfer(address(msg.sender), _value); } } emit Withdraw(msg.sender, _aid, _pid, _amount, _value); }
5,084,758
[ 1, 1190, 9446, 511, 52, 2430, 628, 399, 12050, 6376, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 598, 9446, 12, 11890, 5034, 389, 20736, 16, 2254, 5034, 389, 6610, 16, 2254, 5034, 389, 8949, 13, 8843, 429, 1071, 288, 203, 3639, 8828, 966, 2502, 2845, 273, 2845, 966, 63, 67, 20736, 6362, 67, 6610, 15533, 203, 3639, 25003, 2502, 729, 273, 16753, 63, 67, 20736, 6362, 67, 6610, 6362, 3576, 18, 15330, 15533, 203, 3639, 2583, 12443, 6011, 18, 70, 2531, 422, 629, 13, 747, 261, 6011, 18, 70, 2531, 597, 261, 2629, 18, 2696, 1545, 261, 1937, 1768, 18, 1289, 12, 739, 30807, 20349, 3631, 315, 1918, 9446, 30, 2845, 2176, 8863, 203, 3639, 2583, 12, 1355, 18, 8949, 1545, 389, 8949, 16, 315, 1918, 9446, 30, 486, 7494, 8863, 203, 540, 203, 3639, 309, 261, 67, 8949, 405, 374, 15329, 203, 5411, 2583, 12443, 6011, 18, 70, 1190, 9446, 14667, 422, 629, 13, 747, 261, 6011, 18, 70, 1190, 9446, 14667, 422, 638, 597, 1234, 18, 1132, 422, 2845, 18, 1918, 9446, 14667, 3631, 315, 1918, 9446, 30, 486, 7304, 8863, 203, 3639, 289, 203, 203, 3639, 1089, 2864, 24899, 20736, 16, 389, 6610, 1769, 203, 203, 3639, 2254, 5034, 389, 1132, 273, 374, 31, 203, 3639, 309, 24899, 8949, 405, 374, 13, 288, 203, 5411, 309, 261, 1355, 18, 1132, 480, 374, 15329, 203, 7734, 389, 1132, 273, 389, 8949, 18, 16411, 12, 1355, 18, 1132, 2934, 2892, 12, 1355, 18, 8949, 1769, 203, 5411, 289, 203, 2398, 203, 5411, 729, 18, 8949, 273, 729, 18, 8949, 18, 1717, 24899, 8949, 1769, 203, 5411, 729, 18, 2 ]