file_name
stringlengths
71
779k
comments
stringlengths
20
182k
code_string
stringlengths
20
36.9M
__index_level_0__
int64
0
17.2M
input_ids
sequence
attention_mask
sequence
labels
sequence
./partial_match/1/0xFB15127f6464fcBB82b05Dc4b772283236C65167/sources/LexSecurityToken.sol
* prev. withdrawableDividendOf @notice View the amount of funds that an address can withdraw. @param _owner The address of a token holder. @return The amount funds that `_owner` can withdraw./
function withdrawableFundsOf(address _owner) public view returns(uint256) { return accumulativeFundsOf(_owner).sub(withdrawnFunds[_owner]); }
3,647,131
[ 1, 10001, 18, 598, 9446, 429, 7244, 26746, 951, 225, 4441, 326, 3844, 434, 284, 19156, 716, 392, 1758, 848, 598, 9446, 18, 225, 389, 8443, 1021, 1758, 434, 279, 1147, 10438, 18, 327, 1021, 3844, 284, 19156, 716, 1375, 67, 8443, 68, 848, 598, 9446, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 202, 915, 598, 9446, 429, 42, 19156, 951, 12, 2867, 389, 8443, 13, 1071, 1476, 1135, 12, 11890, 5034, 13, 288, 203, 202, 202, 2463, 8822, 1535, 42, 19156, 951, 24899, 8443, 2934, 1717, 12, 1918, 9446, 82, 42, 19156, 63, 67, 8443, 19226, 203, 202, 97, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.5.16; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/ownership/Ownable.sol"; import "./interfaces/IIdleTokenV3.sol"; import "./others/BasicMetaTransaction.sol"; import "./GST2Consumer.sol"; contract IdleProxyPersonalSign is Ownable, GST2Consumer, BasicMetaTransaction { using SafeERC20 for IERC20; using SafeMath for uint256; constructor() public { IIdleTokenV3 daiBest = IIdleTokenV3(address(0x78751B12Da02728F467A44eAc40F5cbc16Bd7934)); IERC20 dai = IERC20(daiBest.token()); IIdleTokenV3 daiRisk = IIdleTokenV3(address(0x1846bdfDB6A0f5c473dEc610144513bd071999fB)); IIdleTokenV3 usdcBest = IIdleTokenV3(address(0x12B98C621E8754Ae70d0fDbBC73D6208bC3e3cA6)); IERC20 usdc = IERC20(usdcBest.token()); IIdleTokenV3 usdcRisk = IIdleTokenV3(address(0xcDdB1Bceb7a1979C6caa0229820707429dd3Ec6C)); IIdleTokenV3 usdtBest = IIdleTokenV3(address(0x63D27B3DA94A9E871222CB0A32232674B02D2f2D)); IERC20 usdt = IERC20(usdtBest.token()); IIdleTokenV3 usdtRisk = IIdleTokenV3(address(0x42740698959761BAF1B06baa51EfBD88CB1D862B)); dai.safeApprove(address(daiBest), uint256(-1)); dai.safeApprove(address(daiRisk), uint256(-1)); usdc.safeApprove(address(usdcBest), uint256(-1)); usdc.safeApprove(address(usdcRisk), uint256(-1)); usdt.safeApprove(address(usdtBest), uint256(-1)); usdt.safeApprove(address(usdtRisk), uint256(-1)); } function approveNewIdleToken(address _idleToken) external onlyOwner { IERC20 underlying = IERC20(IIdleTokenV3(_idleToken).token()); underlying.safeApprove(_idleToken, uint256(-1)); } // One should approve this contract first to spend `_underlying` tokens // _amount : in oldIdleTokens // _idleTokenAddr : idle address function mintIdleTokensProxy(uint256 _amount, address _idleTokenAddr) external gasDiscountFrom(address(this)) returns (uint256 idleTokens) { IIdleTokenV3 idleToken = IIdleTokenV3(_idleTokenAddr); IERC20 underlying = IERC20(idleToken.token()); underlying.safeTransferFrom(msgSender(), address(this), _amount); idleToken.mintIdleToken(underlying.balanceOf(address(this)), new uint256[](0)); idleTokens = IERC20(_idleTokenAddr).balanceOf(address(this)); IERC20(_idleTokenAddr).safeTransfer(msgSender(), idleTokens); } // One should approve this contract first to spend idleTokens // _amount of idleTokens to redeem // _idleTokenAddr : idle address function redeemIdleTokensProxy(uint256 _amount, address _idleTokenAddr) external gasDiscountFrom(address(this)) returns (uint256 tokens) { IIdleTokenV3 idleToken = IIdleTokenV3(_idleTokenAddr); IERC20 underlying = IERC20(idleToken.token()); IERC20(address(idleToken)).safeTransferFrom(msgSender(), address(this), _amount); idleToken.redeemIdleToken(_amount, true, new uint256[](0)); tokens = underlying.balanceOf(address(this)); underlying.safeTransfer(msgSender(), tokens); } // onlyOwner, at the end of the tx not token should be present in this contract, // if anything got stuck we can unlock it though this methd function emergencyWithdrawToken(address _token, address _to) external onlyOwner { IERC20(_token).safeTransfer(_to, IERC20(_token).balanceOf(address(this))); } }
One should approve this contract first to spend idleTokens _amount of idleTokens to redeem _idleTokenAddr : idle address
function redeemIdleTokensProxy(uint256 _amount, address _idleTokenAddr) external gasDiscountFrom(address(this)) returns (uint256 tokens) { IIdleTokenV3 idleToken = IIdleTokenV3(_idleTokenAddr); IERC20 underlying = IERC20(idleToken.token()); IERC20(address(idleToken)).safeTransferFrom(msgSender(), address(this), _amount); idleToken.redeemIdleToken(_amount, true, new uint256[](0)); tokens = underlying.balanceOf(address(this)); underlying.safeTransfer(msgSender(), tokens); }
1,768,374
[ 1, 3335, 1410, 6617, 537, 333, 6835, 1122, 358, 17571, 12088, 5157, 389, 8949, 434, 12088, 5157, 358, 283, 24903, 389, 20390, 1345, 3178, 294, 12088, 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 ]
[ 1, 1, 1, 1, 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, 225, 445, 283, 24903, 13834, 5157, 3886, 12, 11890, 5034, 389, 8949, 16, 1758, 389, 20390, 1345, 3178, 13, 203, 565, 3903, 16189, 9866, 1265, 12, 2867, 12, 2211, 3719, 1135, 261, 11890, 5034, 2430, 13, 288, 203, 565, 467, 13834, 1345, 58, 23, 12088, 1345, 273, 467, 13834, 1345, 58, 23, 24899, 20390, 1345, 3178, 1769, 203, 565, 467, 654, 39, 3462, 6808, 273, 467, 654, 39, 3462, 12, 20390, 1345, 18, 2316, 10663, 203, 203, 565, 467, 654, 39, 3462, 12, 2867, 12, 20390, 1345, 13, 2934, 4626, 5912, 1265, 12, 3576, 12021, 9334, 1758, 12, 2211, 3631, 389, 8949, 1769, 203, 565, 12088, 1345, 18, 266, 24903, 13834, 1345, 24899, 8949, 16, 638, 16, 394, 2254, 5034, 8526, 12, 20, 10019, 203, 203, 565, 2430, 273, 6808, 18, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 565, 6808, 18, 4626, 5912, 12, 3576, 12021, 9334, 2430, 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 ]
pragma solidity 0.4.24; import "../Derivative.sol"; import "../interfaces/FundInterface.sol"; import "../interfaces/implementations/OlympusExchangeInterface.sol"; import "../interfaces/WithdrawInterface.sol"; import "../interfaces/MarketplaceInterface.sol"; import "../interfaces/ChargeableInterface.sol"; import "../interfaces/RiskControlInterface.sol"; import "../interfaces/ReimbursableInterface.sol"; import "../interfaces/WhitelistInterface.sol"; import "../interfaces/StepInterface.sol"; import "../libs/ERC20NoReturn.sol"; import "../interfaces/FeeChargerInterface.sol"; import "../interfaces/LockerInterface.sol"; import "../interfaces/TokenBrokenInterface.sol"; import "../interfaces/MappeableDerivative.sol"; contract OlympusFund is FundInterface, Derivative, MappeableDerivative { using SafeMath for uint256; // Does not fit in derivative, index out of gas bytes32 public constant TOKENBROKEN = "TokenBroken"; uint public constant TOKEN_DENOMINATOR = 10**18; // Apply % to a denominator, 18 is the minimum highetst precision required enum Status { AVAILABLE, WITHDRAWING, SELLINGTOKENS } Status public productStatus = Status.AVAILABLE; uint private freezeTokenPercentage; // Freeze variable for ETH tokens ERC20Extended[] private tokenBrokensERC20Freeze; uint public constant INITIAL_VALUE = 10**18; // 1 ETH uint public constant INITIAL_FEE = 10**17; mapping(address => uint) public investors; mapping(address => uint) public amounts; mapping(address => bool) public activeTokens; mapping(address=> bool) public isBrokenToken; // Starts from 1 address[] public tokensToRelease; // List of tokens brokens with balance to release uint public accumulatedFee = 0; // Mappeable mapping (address => uint) public activeInvestorIndex; // Starts from 1 (0 is not existing) address[] public activeInvestors; // Start in 0 bool public unhandledWithdraws; constructor( string _name, string _symbol, string _description, bytes32 _category, uint _decimals ) public { require(0<=_decimals&&_decimals<=18); name = _name; symbol = _symbol; category = _category; description = _description; version = "x"; decimals = _decimals; status = DerivativeStatus.New; fundType = DerivativeType.Fund; } // ----------------------------- CONFIG ----------------------------- // One time call function initialize(address _componentList, uint _initialFundFee, uint _withdrawFrequency ) external onlyOwner payable { require(_componentList != 0x0); require(status == DerivativeStatus.New); require(msg.value >= INITIAL_FEE); // Require some balance for internal opeations as reimbursable // Set PausedCycle pausedCycle = 365 days; super._initialize(_componentList); excludedComponents[TOKENBROKEN] = true; bytes32[10] memory names = [MARKET, EXCHANGE, RISK, WHITELIST, FEE, REIMBURSABLE, WITHDRAW, LOCKER, STEP, TOKENBROKEN]; for (uint i = 0; i < names.length; i++) { updateComponent(names[i]); } MarketplaceInterface(getComponentByName(MARKET)).registerProduct(); ChargeableInterface(getComponentByName(FEE)).setFeePercentage(_initialFundFee); LockerInterface(getComponentByName(LOCKER)).setTimeInterval(WITHDRAW, _withdrawFrequency); uint[] memory _maxSteps = new uint[](2); bytes32[] memory _categories = new bytes32[](2); _maxSteps[0] = 10; _maxSteps[1] = 5; _categories[0] = WITHDRAW; _categories[1] = GETETH; StepInterface(getComponentByName(STEP)).setMultipleMaxCalls(_categories, _maxSteps); status = DerivativeStatus.Active; accumulatedFee = accumulatedFee.add(msg.value); } function getTokens() external view returns(address[], uint[]) { uint[] memory _amounts = new uint[](tokens.length); for (uint i = 0; i < tokens.length; i++) { _amounts[i] = amounts[tokens[i]]; } return (tokens, _amounts); } // ----------------------------- FUND INTERFACE ----------------------------- function buyTokens(bytes32 _exchangeId, ERC20Extended[] _tokens, uint[] _amounts, uint[] _minimumRates) public onlyOwnerOrWhitelisted(WhitelistKeys.Admin) returns(bool) { require(productStatus == Status.AVAILABLE); // Check we have the ethAmount required uint totalEthRequired = 0; for (uint i = 0; i < _tokens.length; i++) { // Setting amount to 0 if (isBrokenToken[_tokens[i]]) { _amounts[i] = 0; continue; } require(erc20Decimals(_tokens[i]) <=18); // Cant buy tokens with more than 18 require( !hasRisk(address(this), getComponentByName(EXCHANGE), ETH, _amounts[i], _minimumRates[i]) ); totalEthRequired = totalEthRequired.add(_amounts[i]); } require(getETHBalance() >= totalEthRequired); if (!getExchangeInterface() .buyTokens.value(totalEthRequired)(_tokens, _amounts, _minimumRates, address(this), _exchangeId)) { checkBrokenTokens(_tokens); updateTokens(_tokens); return false; } updateTokens(_tokens); return true; } function sellTokens(bytes32 _exchangeId, ERC20Extended[] _tokens, uint[] _amounts, uint[] _rates) public onlyOwnerOrWhitelisted(WhitelistKeys.Admin) returns (bool) { require(productStatus == Status.AVAILABLE); OlympusExchangeInterface exchange = getExchangeInterface(); for (uint i = 0; i < _tokens.length; i++) { // Setting amount to 0 skips the sell if (isBrokenToken[_tokens[i]]) { _amounts[i] = 0; continue; } require(!hasRisk(address(this), exchange, address(_tokens[i]), _amounts[i], _rates[i])); approveExchange(_tokens[i], _amounts[i]); } if(!exchange.sellTokens(_tokens, _amounts, _rates, address(this), _exchangeId)){ checkBrokenTokens(_tokens); updateTokens(_tokens); return false; } updateTokens(_tokens); return true; } // ----------------------------- DERIVATIVE ----------------------------- function invest() public payable whitelisted(WhitelistKeys.Investment) withoutRisk(msg.sender, address(this), ETH, msg.value, 1) whenNotPaused returns(bool) { require(status == DerivativeStatus.Active); require(msg.value >= 10**15); // Current value is already added in the balance, reduce it uint _sharePrice = INITIAL_VALUE; // Map investor (do it at starting) addInvestor(msg.sender); if (totalSupply_ > 0) { _sharePrice = getPrice().sub((msg.value.mul(10**decimals)).div(totalSupply_)); } ChargeableInterface feeManager = ChargeableInterface(getComponentByName(FEE)); uint fee = feeManager.calculateFee(msg.sender, msg.value); uint _investorShare = msg.value.sub(fee).mul(10**decimals).div(_sharePrice); accumulatedFee = accumulatedFee.add(fee); balances[msg.sender] = balances[msg.sender].add(_investorShare); totalSupply_ = totalSupply_.add(_investorShare); emit Transfer(0x0, msg.sender, _investorShare); // ERC20 Required event return true; } function close() OnlyOwnerOrPausedTimeout public returns(bool success) { require(status != DerivativeStatus.New); status = DerivativeStatus.Closed; return true; } function sellAllTokensOnClosedFund() onlyOwnerOrWhitelisted(WhitelistKeys.Maintenance) public returns (bool) { require(status == DerivativeStatus.Closed && unhandledWithdraws == false); require(productStatus == Status.AVAILABLE || productStatus == Status.SELLINGTOKENS); startGasCalculation(); productStatus = Status.SELLINGTOKENS; bool result = getETHFromTokens(TOKEN_DENOMINATOR); if(result) { productStatus = Status.AVAILABLE; } reimburse(); return result; } function getPrice() public view returns(uint) { if (totalSupply_ == 0) { return INITIAL_VALUE; } // Total Value in ETH among its tokens + ETH new added value return ( getAssetsValue().add(getETHBalance()).mul(10**decimals).div(totalSupply_), ); } function getETHBalance() public view returns(uint) { return address(this).balance.sub(accumulatedFee); } function getAssetsValue() public view returns (uint) { OlympusExchangeInterface exchangeProvider = getExchangeInterface(); uint _totalTokensValue = 0; // Iterator uint _expectedRate; uint _balance; uint _decimals; ERC20Extended token; for (uint i = 0; i < tokens.length; i++) { if(isBrokenToken[tokens[i]]) {continue;} token = ERC20Extended(tokens[i]); _decimals = erc20Decimals(tokens[i]); _balance = token.balanceOf(address(this)); if (_balance == 0) {continue;} (_expectedRate, ) = exchangeProvider.getPrice(token, ETH, 10**_decimals, 0x0); if (_expectedRate == 0) {continue;} _totalTokensValue = _totalTokensValue.add(_balance.mul(_expectedRate).div(10**_decimals)); } return _totalTokensValue; } // ----------------------------- FEES ----------------------------- // Owner can send ETH to the Index, to perform some task, this eth belongs to him // solhint-disable-next-line function addOwnerBalance() external payable { accumulatedFee = accumulatedFee.add(msg.value); } // solhint-disable-next-line function withdrawFee(uint _amount) external onlyOwner whenNotPaused returns(bool) { require(_amount > 0); require(( status == DerivativeStatus.Closed && getAssetsValue() == 0 && getWithdrawAmount() == 0 ) ? // everything is done, take all. (_amount <= accumulatedFee) : (_amount.add(INITIAL_FEE) <= accumulatedFee) // else, the initial fee stays. ); accumulatedFee = accumulatedFee.sub(_amount); // Exchange to MOT OlympusExchangeInterface exchange = getExchangeInterface(); ERC20Extended MOT = ERC20Extended(FeeChargerInterface(address(exchange)).MOT()); uint _rate; (, _rate ) = exchange.getPrice(ETH, MOT, _amount, 0x0); // This is MOT, so we should require this to be true. require(exchange.buyToken.value(_amount)(MOT, _amount, _rate, owner, 0x0)); return true; } // solhint-disable-next-line function setManagementFee(uint _fee) external onlyOwner { ChargeableInterface(getComponentByName(FEE)).setFeePercentage(_fee); } // ----------------------------- WITHDRAW ----------------------------- // solhint-disable-next-line function requestWithdraw(uint amount) external whenNotPaused withoutRisk(msg.sender, address(this), address(this), amount, getPrice()) { WithdrawInterface withdrawProvider = WithdrawInterface(getComponentByName(WITHDRAW)); withdrawProvider.request(msg.sender, amount); if(status == DerivativeStatus.Closed && getAssetsValue() == 0 && getWithdrawAmount() == amount){ withdrawFreeze(); handleWithdraw(withdrawProvider, msg.sender); withdrawFinalize(); return; } unhandledWithdraws = true; } function guaranteeLiquidity(uint tokenBalance) internal returns(bool success){ uint _price = getPrice(); // Case first call if(getStatusStep(GETETH) == 0) { // Case price is broken while withdrawing if(_price == 0) { freezeTokenPercentage = (10 ** decimals); // Tokens got broken? return getETHFromTokens(freezeTokenPercentage); } // Case is not required to sell Assets (we will not detect token brokens) uint _totalETHToReturn = tokenBalance.mul(_price).div(10**decimals); if (_totalETHToReturn <= getETHBalance()) { return true; } // Case is required to sell some assets // tokenPercentToSell must be freeze as class variable freezeTokenPercentage = _totalETHToReturn.sub(getETHBalance()).mul(TOKEN_DENOMINATOR).div(getAssetsValue()); return getETHFromTokens(freezeTokenPercentage); } // Case second call return getETHFromTokens(freezeTokenPercentage); } // solhint-disable-next-line function withdraw() external onlyOwnerOrWhitelisted(WhitelistKeys.Maintenance) whenNotPaused returns(bool) { startGasCalculation(); require(productStatus == Status.AVAILABLE || productStatus == Status.WITHDRAWING); productStatus = Status.WITHDRAWING; WithdrawInterface withdrawProvider = WithdrawInterface(getComponentByName(WITHDRAW)); // Check if there is request address[] memory _requests = withdrawProvider.getUserRequests(); uint _withdrawStatus = getStatusStep(WITHDRAW); if (_withdrawStatus == 0 && getStatusStep(GETETH) == 0) { LockerInterface(getComponentByName(LOCKER)).checkLockerByTime(WITHDRAW); if (_requests.length == 0) { productStatus = Status.AVAILABLE; reimburse(); return true; } } if (_withdrawStatus == 0) { if(!guaranteeLiquidity(getWithdrawAmount())) { reimburse(); return false; } withdrawFreeze(); } uint _transfers = initializeOrContinueStep(WITHDRAW); uint i; for (i = _transfers; i < _requests.length && goNextStep(WITHDRAW); i++) { if(!handleWithdraw(withdrawProvider, _requests[i])){ continue; } } if (i == _requests.length) { withdrawFinalize(); finalizeStep(WITHDRAW); unhandledWithdraws = false; productStatus = Status.AVAILABLE; } reimburse(); return i == _requests.length; // True if completed } function handleWithdraw(WithdrawInterface _withdrawProvider, address _investor) private returns (bool) { uint _eth; uint _tokenAmount; releaseTokensBroken(_investor); // Investors (_eth, _tokenAmount) = _withdrawProvider.withdraw(_investor); if (_tokenAmount == 0) { return false; } balances[_investor] = balances[_investor].sub(_tokenAmount); totalSupply_ = totalSupply_.sub(_tokenAmount); emit Transfer(_investor, 0x0, _tokenAmount); // ERC20 Required event // Can be 0 in case all tokens are broken if (_eth > 0){ _transfer(_investor, _eth); } // Unmap investor (do it at the end) removeInvestor(_investor); return true; } function releaseTokensBroken(address _investor) internal returns(bool) { if(tokensToRelease.length == 0) {return true;} TokenBrokenInterface tokenBrokenProvider = TokenBrokenInterface(getComponentByName(TOKENBROKEN)); uint[] memory _tokenBalances = tokenBrokenProvider.tokenBalancesOf(tokensToRelease, _investor); uint i; uint _requestPending; for(i = 0; i < tokensToRelease.length; i++) { tokenBrokensERC20Freeze.push(ERC20Extended(tokensToRelease[i])); // Cast if(_tokenBalances[i] == 0) {continue;} _requestPending = tokenBrokenProvider.withdraw(tokensToRelease[i], _investor); tokenTransfer(tokensToRelease[i], _investor, _tokenBalances[i]); // Remove token broken completed if(_requestPending == 0) { tokensToRelease[i] = tokensToRelease[tokensToRelease.length-1]; _tokenBalances[i] = _tokenBalances[tokensToRelease.length-1]; // Also change the mapping delete(tokensToRelease[tokensToRelease.length-1]); i--; tokensToRelease.length--; } } updateTokens(tokenBrokensERC20Freeze); // Update internal balances delete tokenBrokensERC20Freeze; // Reset return true; } // solhint-disable-next-line function tokensWithAmount() public view returns( ERC20Extended[] memory) { // First check the length uint length = 0; for (uint i = 0; i < tokens.length; i++) { // Has balance and is NOT broken if (isBrokenToken[tokens[i]] == false && amounts[tokens[i]] > 0 ) {length++;} } ERC20Extended[] memory _tokensWithAmount = new ERC20Extended[](length); // Then create they array uint index = 0; for (uint j = 0; j < tokens.length; j++) { if (isBrokenToken[tokens[j]] == false && amounts[tokens[j]] > 0) { _tokensWithAmount[index] = ERC20Extended(tokens[j]); index++; } } return _tokensWithAmount; } // solhint-disable-next-line function getETHFromTokens(uint _tokenPercentage) internal returns(bool success) { OlympusExchangeInterface exchange = getExchangeInterface(); ERC20Extended[] memory _tokensToSell = tokensWithAmount(); if(_tokensToSell.length == 0) {return true;} uint currentStep = initializeOrContinueStep(GETETH); uint i; // Current step to tokens.length uint arrayLength = getNextArrayLength(GETETH, currentStep); ERC20Extended[] memory _tokensThisStep = new ERC20Extended[](arrayLength); uint[] memory _amounts = new uint[](arrayLength); uint[] memory _sellRates = new uint[](arrayLength); for(i = currentStep;i < _tokensToSell.length && goNextStep(GETETH); i++) { uint sellIndex = i.sub(currentStep); _tokensThisStep[sellIndex] = _tokensToSell[i]; _amounts[sellIndex] = _tokenPercentage.mul(amounts[_tokensToSell[i]]).div(TOKEN_DENOMINATOR); (, _sellRates[sellIndex] ) = exchange.getPrice(_tokensToSell[i], ETH, _amounts[sellIndex], 0x0); require(!hasRisk(address(this), exchange, address(_tokensThisStep[sellIndex]), _amounts[sellIndex], 0)); approveExchange(address(_tokensThisStep[sellIndex]), _amounts[sellIndex]); } if(!exchange.sellTokens(_tokensThisStep, _amounts, _sellRates, address(this), 0x0)){ checkBrokenTokens(_tokensThisStep); } if(i == _tokensToSell.length) { updateTokens(_tokensToSell); // Must update tokens at the end to keep _tokensToSell freeze finalizeStep(GETETH); return true; } return false; } function initializeOrContinueStep(bytes32 category) internal returns(uint) { return StepInterface(getComponentByName(STEP)).initializeOrContinue(category); } function getStatusStep(bytes32 category) internal view returns(uint) { return StepInterface(getComponentByName(STEP)).getStatus(category); } function finalizeStep(bytes32 category) internal returns(bool) { return StepInterface(getComponentByName(STEP)).finalize(category); } function goNextStep(bytes32 category) internal returns(bool) { return StepInterface(getComponentByName(STEP)).goNextStep(category); } function getNextArrayLength(bytes32 stepCategory, uint currentStep) internal view returns(uint) { uint arrayLength = StepInterface(getComponentByName(STEP)).getMaxCalls(stepCategory); if(arrayLength.add(currentStep) >= tokens.length ) { arrayLength = tokens.length.sub(currentStep); } return arrayLength; } // ----------------------------- WHITELIST ----------------------------- // solhint-disable-next-line function enableWhitelist(WhitelistKeys _key, bool enable) external onlyOwner returns(bool) { WhitelistInterface(getComponentByName(WHITELIST)).setStatus(uint(_key), enable); return true; } // solhint-disable-next-line function setAllowed(address[] accounts, WhitelistKeys _key, bool allowed) public onlyOwner returns(bool) { WhitelistInterface(getComponentByName(WHITELIST)).setAllowed(accounts, uint(_key), allowed); return true; } function checkBrokenTokens(ERC20Extended[] _tokens) internal { TokenBrokenInterface tokenBrokenProvider = TokenBrokenInterface(getComponentByName(TOKENBROKEN)); uint[] memory _failedTimes = new uint[](_tokens.length); _failedTimes = getExchangeInterface().getFailedTradesArray(_tokens); for(uint t = 0;t < _tokens.length; t++) { // Is successfull or already broken if((_failedTimes[t]) <= 0 || isBrokenToken[_tokens[t]]) { continue; } isBrokenToken[_tokens[t]] = true; // When a token becomes broken, it cant recover // I broken, check if has balance to distribute if(amounts[_tokens[t]] > 0) { tokensToRelease.push(_tokens[t]); tokenBrokenProvider.calculateBalanceByInvestor(_tokens[t]); } } } // solhint-disable-next-line function reimburse() private { uint reimbursedAmount = ReimbursableInterface(getComponentByName(REIMBURSABLE)).reimburse(); accumulatedFee = accumulatedFee.sub(reimbursedAmount); _transfer(msg.sender, reimbursedAmount); } function updateTokens(ERC20Extended[] _updatedTokens) private returns(bool success) { ERC20 _tokenAddress; for (uint i = 0; i < _updatedTokens.length; i++) { if(_updatedTokens[i] == address(0)){continue;} _tokenAddress = _updatedTokens[i]; amounts[_tokenAddress] = _tokenAddress.balanceOf(this); if (amounts[_tokenAddress] > 0 && !activeTokens[_tokenAddress]) { tokens.push(_tokenAddress); activeTokens[_tokenAddress] = true; continue; } } return true; } function startGasCalculation() internal { ReimbursableInterface(getComponentByName(REIMBURSABLE)).startGasCalculation(); } // ----------------------------- MAPPEABLE ---------------------------- function addInvestor(address investor) internal { if (activeInvestorIndex[investor] == 0) { activeInvestorIndex[investor] = activeInvestors.push(investor); } } function removeInvestor(address investor) internal { if (balances[investor] > 0) {return;} activeInvestors[activeInvestorIndex[investor]-1] = activeInvestors[activeInvestors.length - 1]; activeInvestorIndex[activeInvestors[activeInvestors.length - 1]] = activeInvestorIndex[investor]; activeInvestors.length -= 1; activeInvestorIndex[investor] = 0; } function getActiveInvestors() external view returns(address[]) { return activeInvestors; } function approveExchange(address _token, uint amount) internal { OlympusExchangeInterface exchange = getExchangeInterface(); ERC20NoReturn(_token).approve(exchange, 0); ERC20NoReturn(_token).approve(exchange, amount); } function tokenTransfer(address _tokenAddress, address _to, uint _amount) private { ERC20NoReturn(_tokenAddress).transfer(_to, _amount); } function _transfer(address _from, uint _amount) private { _from.transfer(_amount); } function getExchangeInterface() private view returns (OlympusExchangeInterface){ return OlympusExchangeInterface(getComponentByName(EXCHANGE)); } function getWithdrawAmount() internal view returns(uint) { return WithdrawInterface(getComponentByName(WITHDRAW)).getTotalWithdrawAmount(); } function withdrawFreeze() internal { WithdrawInterface(getComponentByName(WITHDRAW)).freeze(); } function withdrawFinalize() internal { WithdrawInterface(getComponentByName(WITHDRAW)).finalize(); } function erc20Decimals(address erc20) internal view returns(uint) { return ERC20Extended(erc20).decimals(); } // // THIS IS FOR TESTING ONLY, DO MEMEMBER TO REMOVE IT WHEN GOING ON PRODUCTION!!!!! // function panic() external onlyOwner { // _transfer(owner, address(this).balance); // for (uint i = 0; i < tokens.length; i++) { // tokenTransfer(tokens[i], owner, amounts[tokens[i]]); // } // } }
----------------------------- CONFIG ----------------------------- One time call Set PausedCycle
function initialize(address _componentList, uint _initialFundFee, uint _withdrawFrequency ) external onlyOwner payable { require(_componentList != 0x0); require(status == DerivativeStatus.New); pausedCycle = 365 days; super._initialize(_componentList); excludedComponents[TOKENBROKEN] = true; bytes32[10] memory names = [MARKET, EXCHANGE, RISK, WHITELIST, FEE, REIMBURSABLE, WITHDRAW, LOCKER, STEP, TOKENBROKEN]; for (uint i = 0; i < names.length; i++) { updateComponent(names[i]); } MarketplaceInterface(getComponentByName(MARKET)).registerProduct(); ChargeableInterface(getComponentByName(FEE)).setFeePercentage(_initialFundFee); LockerInterface(getComponentByName(LOCKER)).setTimeInterval(WITHDRAW, _withdrawFrequency); uint[] memory _maxSteps = new uint[](2); bytes32[] memory _categories = new bytes32[](2); _maxSteps[0] = 10; _maxSteps[1] = 5; _categories[0] = WITHDRAW; _categories[1] = GETETH; StepInterface(getComponentByName(STEP)).setMultipleMaxCalls(_categories, _maxSteps); status = DerivativeStatus.Active; accumulatedFee = accumulatedFee.add(msg.value); }
13,009,674
[ 1, 1271, 16982, 9128, 12146, 7620, 6942, 813, 745, 1000, 21800, 3668, 13279, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 4046, 12, 2867, 389, 4652, 682, 16, 2254, 389, 6769, 42, 1074, 14667, 16, 2254, 389, 1918, 9446, 13865, 262, 3903, 1338, 5541, 8843, 429, 288, 203, 3639, 2583, 24899, 4652, 682, 480, 374, 92, 20, 1769, 203, 3639, 2583, 12, 2327, 422, 14969, 427, 1535, 1482, 18, 1908, 1769, 203, 203, 3639, 17781, 13279, 273, 21382, 4681, 31, 203, 203, 3639, 2240, 6315, 11160, 24899, 4652, 682, 1769, 203, 3639, 8845, 7171, 63, 8412, 38, 1457, 47, 1157, 65, 273, 638, 31, 203, 203, 3639, 1731, 1578, 63, 2163, 65, 3778, 1257, 273, 306, 12693, 1584, 16, 5675, 14473, 16, 534, 5127, 47, 16, 24353, 7085, 16, 478, 9383, 16, 2438, 3445, 38, 1099, 55, 2782, 16, 13601, 40, 10821, 16, 14631, 654, 16, 25538, 16, 14275, 38, 1457, 47, 1157, 15533, 203, 203, 3639, 364, 261, 11890, 277, 273, 374, 31, 277, 411, 1257, 18, 2469, 31, 277, 27245, 288, 203, 5411, 1089, 1841, 12, 1973, 63, 77, 19226, 203, 3639, 289, 203, 203, 3639, 6622, 24577, 1358, 12, 588, 1841, 5911, 12, 12693, 1584, 13, 2934, 4861, 4133, 5621, 203, 3639, 3703, 908, 28628, 12, 588, 1841, 5911, 12, 8090, 41, 13, 2934, 542, 14667, 16397, 24899, 6769, 42, 1074, 14667, 1769, 203, 3639, 3488, 264, 1358, 12, 588, 1841, 5911, 12, 6589, 654, 13, 2934, 542, 950, 4006, 12, 9147, 40, 10821, 16, 389, 1918, 9446, 13865, 1769, 203, 3639, 2254, 8526, 3778, 389, 1896, 11811, 273, 394, 2254, 8526, 12, 22, 1769, 203, 3639, 1731, 1578, 8526, 2 ]
./full_match/1/0x1111306F3d849B133f533D6E9F7341d40De0cB4b/sources/src/RPVault.sol
@notice vaultState = array of vault states per epoch
mapping(uint256 => VaultState) public vaultStates;
8,293,554
[ 1, 26983, 1119, 273, 526, 434, 9229, 5493, 1534, 7632, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2874, 12, 11890, 5034, 516, 17329, 1119, 13, 1071, 9229, 7629, 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 ]
pragma solidity ^0.4.24; import "./PreSaleSTO.sol"; import "../ModuleFactory.sol"; import "../../libraries/Util.sol"; /** * @title Factory for deploying PreSaleSTO module */ contract PreSaleSTOFactory is ModuleFactory { /** * @notice Constructor * @param _polyAddress Address of the polytoken */ constructor (address _polyAddress, uint256 _setupCost, uint256 _usageCost, uint256 _subscriptionCost) public ModuleFactory(_polyAddress, _setupCost, _usageCost, _subscriptionCost) { version = "1.0.0"; name = "PreSaleSTO"; title = "PreSale STO"; description = "Allows Issuer to configure pre-sale token allocations"; compatibleSTVersionRange["lowerBound"] = VersionUtils.pack(uint8(0), uint8(0), uint8(0)); compatibleSTVersionRange["upperBound"] = VersionUtils.pack(uint8(0), uint8(0), uint8(0)); } /** * @notice Used to launch the Module with the help of factory * @param _data Data used for the intialization of the module factory variables * @return address Contract address of the Module */ function deploy(bytes _data) external returns(address) { if (setupCost > 0) { require(polyToken.transferFrom(msg.sender, owner, setupCost), "Sufficent Allowance is not provided"); } //Check valid bytes - can only call module init function PreSaleSTO preSaleSTO = new PreSaleSTO(msg.sender, address(polyToken)); //Checks that _data is valid (not calling anything it shouldn't) require(Util.getSig(_data) == preSaleSTO.getInitFunction(), "Invalid data"); /*solium-disable-next-line security/no-low-level-calls*/ require(address(preSaleSTO).call(_data), "Unsuccessfull call"); /*solium-disable-next-line security/no-block-members*/ emit GenerateModuleFromFactory(address(preSaleSTO), getName(), address(this), msg.sender, setupCost, now); return address(preSaleSTO); } /** * @notice Type of the Module factory */ function getTypes() external view returns(uint8[]) { uint8[] memory res = new uint8[](1); res[0] = 3; return res; } /** * @notice Returns the instructions associated with the module */ function getInstructions() external view returns(string) { return "Configure and track pre-sale token allocations"; } /** * @notice Get the tags related to the module factory */ function getTags() external view returns(bytes32[]) { bytes32[] memory availableTags = new bytes32[](1); availableTags[0] = "Presale"; return availableTags; } }
solium-disable-next-line security/no-low-level-calls*/
require(address(preSaleSTO).call(_data), "Unsuccessfull call");
1,000,719
[ 1, 18281, 5077, 17, 8394, 17, 4285, 17, 1369, 4373, 19, 2135, 17, 821, 17, 2815, 17, 12550, 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, 3639, 2583, 12, 2867, 12, 1484, 30746, 31487, 2934, 1991, 24899, 892, 3631, 315, 984, 4768, 2854, 745, 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, -100, -100, -100 ]
./partial_match/1/0x8531b6118C70924BFcE5643D0e4306631418648c/sources/DSCCoin.sol
uint8 temp = self.initPercent;
function check(Rule storage self, uint256 totalFrozenValue) internal view returns (uint256) { if (totalFrozenValue == uint256(0)) { return 0; } if (self.timeT == uint256(0) || self.timeT > block.timestamp) { return totalFrozenValue.sub(totalFrozenValue.mul(self.initPercent).div(100)); } for (uint256 i = 0; i < self.periods.length.sub(1); i = i.add(1)) { if (block.timestamp >= self.timeT.add(self.periods[i]) && block.timestamp < self.timeT.add(self.periods[i.add(1)])) { return totalFrozenValue.sub(totalFrozenValue.mul(self.percents[i]).div(100)); } } if (block.timestamp >= self.timeT.add(self.periods[self.periods.length.sub(1)])) { return totalFrozenValue.sub(totalFrozenValue.mul(self.percents[self.periods.length.sub(1)]).div(100)); } return 0; }
4,391,461
[ 1, 11890, 28, 1906, 273, 365, 18, 2738, 8410, 31, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 866, 12, 2175, 2502, 365, 16, 2254, 5034, 2078, 42, 9808, 620, 13, 2713, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 309, 261, 4963, 42, 9808, 620, 422, 2254, 5034, 12, 20, 3719, 288, 203, 5411, 327, 374, 31, 203, 3639, 289, 203, 3639, 309, 261, 2890, 18, 957, 56, 422, 2254, 5034, 12, 20, 13, 747, 365, 18, 957, 56, 405, 1203, 18, 5508, 13, 288, 203, 5411, 327, 2078, 42, 9808, 620, 18, 1717, 12, 4963, 42, 9808, 620, 18, 16411, 12, 2890, 18, 2738, 8410, 2934, 2892, 12, 6625, 10019, 203, 3639, 289, 203, 3639, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 365, 18, 20659, 18, 2469, 18, 1717, 12, 21, 1769, 277, 273, 277, 18, 1289, 12, 21, 3719, 288, 203, 5411, 309, 261, 2629, 18, 5508, 1545, 365, 18, 957, 56, 18, 1289, 12, 2890, 18, 20659, 63, 77, 5717, 597, 1203, 18, 5508, 411, 365, 18, 957, 56, 18, 1289, 12, 2890, 18, 20659, 63, 77, 18, 1289, 12, 21, 13, 22643, 288, 203, 7734, 327, 2078, 42, 9808, 620, 18, 1717, 12, 4963, 42, 9808, 620, 18, 16411, 12, 2890, 18, 8849, 87, 63, 77, 65, 2934, 2892, 12, 6625, 10019, 203, 5411, 289, 203, 3639, 289, 203, 3639, 309, 261, 2629, 18, 5508, 1545, 365, 18, 957, 56, 18, 1289, 12, 2890, 18, 20659, 63, 2890, 18, 20659, 18, 2469, 18, 1717, 12, 21, 13, 22643, 288, 203, 5411, 327, 2078, 42, 9808, 620, 18, 1717, 12, 4963, 42, 2 ]
./partial_match/1/0x11b2164DDf1C3c0a420cEaD050d422B26530d11C/sources/contracts/facets/AccessControl/AccessControlLib.sol
@notice query admin role for given role @param role role to query @return admin role/
function getRoleAdmin( bytes32 role ) internal view returns (bytes32) { return AccessControlStorage.layout().roles[role].adminRole; }
9,188,880
[ 1, 2271, 3981, 2478, 364, 864, 2478, 225, 2478, 2478, 358, 843, 327, 3981, 2478, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 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, 15673, 4446, 12, 203, 3639, 1731, 1578, 2478, 203, 565, 262, 2713, 1476, 1135, 261, 3890, 1578, 13, 288, 203, 3639, 327, 24349, 3245, 18, 6741, 7675, 7774, 63, 4615, 8009, 3666, 2996, 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 ]
pragma solidity 0.4.24; import "../../upgradeability/EternalStorage.sol"; import "../../libraries/Bytes.sol"; contract MessageProcessor is EternalStorage { /** * @dev Returns a status of the message that came from the other side. * @param _messageId id of the message from the other side that triggered a call. * @return true if call executed successfully. */ function messageCallStatus(bytes32 _messageId) external view returns (bool) { return boolStorage[keccak256(abi.encodePacked("messageCallStatus", _messageId))]; } /** * @dev Sets a status of the message that came from the other side. * @param _messageId id of the message from the other side that triggered a call. * @param _status execution status, true if executed successfully. */ function setMessageCallStatus(bytes32 _messageId, bool _status) internal { boolStorage[keccak256(abi.encodePacked("messageCallStatus", _messageId))] = _status; } /** * @dev Returns a data hash of the failed message that came from the other side. * NOTE: dataHash was used previously to identify outgoing message before AMB message id was introduced. * It is kept for backwards compatibility with old mediators contracts. * @param _messageId id of the message from the other side that triggered a call. * @return keccak256 hash of message data. */ function failedMessageDataHash(bytes32 _messageId) external view returns (bytes32) { return bytes32(uintStorage[keccak256(abi.encodePacked("failedMessageDataHash", _messageId))]); } /** * @dev Sets a data hash of the failed message that came from the other side. * NOTE: dataHash was used previously to identify outgoing message before AMB message id was introduced. * It is kept for backwards compatibility with old mediators contracts. * @param _messageId id of the message from the other side that triggered a call. * @param data of the processed message. */ function setFailedMessageDataHash(bytes32 _messageId, bytes data) internal { uintStorage[keccak256(abi.encodePacked("failedMessageDataHash", _messageId))] = uint256(keccak256(data)); } /** * @dev Returns a receiver address of the failed message that came from the other side. * @param _messageId id of the message from the other side that triggered a call. * @return receiver address. */ function failedMessageReceiver(bytes32 _messageId) external view returns (address) { return addressStorage[keccak256(abi.encodePacked("failedMessageReceiver", _messageId))]; } /** * @dev Sets a sender address of the failed message that came from the other side. * @param _messageId id of the message from the other side that triggered a call. * @param _receiver address of the receiver. */ function setFailedMessageReceiver(bytes32 _messageId, address _receiver) internal { addressStorage[keccak256(abi.encodePacked("failedMessageReceiver", _messageId))] = _receiver; } /** * @dev Returns a sender address of the failed message that came from the other side. * @param _messageId id of the message from the other side that triggered a call. * @return sender address on the other side. */ function failedMessageSender(bytes32 _messageId) external view returns (address) { return addressStorage[keccak256(abi.encodePacked("failedMessageSender", _messageId))]; } /** * @dev Sets a sender address of the failed message that came from the other side. * @param _messageId id of the message from the other side that triggered a call. * @param _sender address of the sender on the other side. */ function setFailedMessageSender(bytes32 _messageId, address _sender) internal { addressStorage[keccak256(abi.encodePacked("failedMessageSender", _messageId))] = _sender; } /** * @dev Returns an address of the sender on the other side for the currently processed message. * Can be used by executors for getting other side caller address. * @return address of the sender on the other side. */ function messageSender() external view returns (address sender) { assembly { // Even though this is not the same as addressStorage[keccak256(abi.encodePacked("messageSender"))], // since solidity mapping introduces another level of addressing, such slot change is safe // for temporary variables which are cleared at the end of the call execution. sender := sload(0x7b58b2a669d8e0992eae9eaef641092c0f686fd31070e7236865557fa1571b5b) // keccak256(abi.encodePacked("messageSender")) } } /** * @dev Sets an address of the sender on the other side for the currently processed message. * @param _sender address of the sender on the other side. */ function setMessageSender(address _sender) internal { assembly { // Even though this is not the same as addressStorage[keccak256(abi.encodePacked("messageSender"))], // since solidity mapping introduces another level of addressing, such slot change is safe // for temporary variables which are cleared at the end of the call execution. sstore(0x7b58b2a669d8e0992eae9eaef641092c0f686fd31070e7236865557fa1571b5b, _sender) // keccak256(abi.encodePacked("messageSender")) } } /** * @dev Returns an id of the currently processed message. * @return id of the message that originated on the other side. */ function messageId() public view returns (bytes32 id) { assembly { // Even though this is not the same as uintStorage[keccak256(abi.encodePacked("messageId"))], // since solidity mapping introduces another level of addressing, such slot change is safe // for temporary variables which are cleared at the end of the call execution. id := sload(0xe34bb2103dc34f2c144cc216c132d6ffb55dac57575c22e089161bbe65083304) // keccak256(abi.encodePacked("messageId")) } } /** * @dev Returns an id of the currently processed message. * NOTE: transactionHash was used previously to identify incoming message before AMB message id was introduced. * It is kept for backwards compatibility with old mediators contracts, although it doesn't return txHash anymore. * @return id of the message that originated on the other side. */ function transactionHash() external view returns (bytes32) { return messageId(); } /** * @dev Sets a message id of the currently processed message. * @param _messageId id of the message that originated on the other side. */ function setMessageId(bytes32 _messageId) internal { assembly { // Even though this is not the same as uintStorage[keccak256(abi.encodePacked("messageId"))], // since solidity mapping introduces another level of addressing, such slot change is safe // for temporary variables which are cleared at the end of the call execution. sstore(0xe34bb2103dc34f2c144cc216c132d6ffb55dac57575c22e089161bbe65083304, _messageId) // keccak256(abi.encodePacked("messageId")) } } /** * @dev Returns an originating chain id of the currently processed message. * @return source chain id of the message that originated on the other side. */ function messageSourceChainId() external view returns (uint256 id) { assembly { // Even though this is not the same as uintStorage[keccak256(abi.encodePacked("messageSourceChainId"))], // since solidity mapping introduces another level of addressing, such slot change is safe // for temporary variables which are cleared at the end of the call execution. id := sload(0x7f0fcd9e49860f055dd0c1682d635d309ecb5e3011654c716d9eb59a7ddec7d2) // keccak256(abi.encodePacked("messageSourceChainId")) } } /** * @dev Sets an originating chain id of the currently processed message. * @param _sourceChainId source chain id of the message that originated on the other side. */ function setMessageSourceChainId(uint256 _sourceChainId) internal { assembly { // Even though this is not the same as uintStorage[keccak256(abi.encodePacked("messageSourceChainId"))], // since solidity mapping introduces another level of addressing, such slot change is safe // for temporary variables which are cleared at the end of the call execution. sstore(0x7f0fcd9e49860f055dd0c1682d635d309ecb5e3011654c716d9eb59a7ddec7d2, _sourceChainId) // keccak256(abi.encodePacked("messageSourceChainId")) } } /** * @dev Processes received message. Makes a call to the message executor, * sets dataHash, receive, sender variables for failed messages. * @param _sender sender address on the other side. * @param _executor address of an executor. * @param _messageId id of the processed message. * @param _gasLimit gas limit for a call to executor. * @param _sourceChainId source chain id is of the received message. * @param _data calldata for a call to executor. */ function processMessage( address _sender, address _executor, bytes32 _messageId, uint256 _gasLimit, uint8, /* dataType */ uint256 _sourceChainId, bytes memory _data ) internal { bool status = _passMessage(_sender, _executor, _data, _gasLimit, _messageId, _sourceChainId); setMessageCallStatus(_messageId, status); if (!status) { setFailedMessageDataHash(_messageId, _data); setFailedMessageReceiver(_messageId, _executor); setFailedMessageSender(_messageId, _sender); } emitEventOnMessageProcessed(_sender, _executor, _messageId, status); } /** * @dev Makes a call to the message executor. * @param _sender sender address on the other side. * @param _contract address of an executor contract. * @param _data calldata for a call to executor. * @param _gas gas limit for a call to executor. 2^32 - 1, if caller will pass all available gas for the execution. * @param _messageId id of the processed message. * @param _sourceChainId source chain id is of the received message. */ function _passMessage( address _sender, address _contract, bytes _data, uint256 _gas, bytes32 _messageId, uint256 _sourceChainId ) internal returns (bool) { setMessageSender(_sender); setMessageId(_messageId); setMessageSourceChainId(_sourceChainId); // After EIP-150, max gas cost allowed to be passed to the internal call is equal to the 63/64 of total gas left. // In reality, min(gasLimit, 63/64 * gasleft()) will be used as the call gas limit. // Imagine a situation, when message requires 10000000 gas to be executed successfully. // Also suppose, that at this point, gasleft() is equal to 10158000, so the callee will receive ~ 10158000 * 63 / 64 = 9999300 gas. // That amount of gas is not enough, so the call will fail. At the same time, // even if the callee failed the bridge contract still has ~ 158000 gas to // finish its execution and it will be enough. The internal call fails but // only because the oracle provides incorrect gas limit for the transaction // This check is needed here in order to force contract to pass exactly the requested amount of gas. // Avoiding it may lead to the unwanted message failure in some extreme cases. require(_gas == 0xffffffff || (gasleft() * 63) / 64 > _gas); bool status = _contract.call.gas(_gas)(_data); _validateExecutionStatus(status); setMessageSender(address(0)); setMessageId(bytes32(0)); setMessageSourceChainId(0); return status; } /** * @dev Validates message execution status. In simplest case, does nothing. * @param _status message execution status. */ function _validateExecutionStatus(bool _status) internal { (_status); } /* solcov ignore next */ function emitEventOnMessageProcessed(address sender, address executor, bytes32 messageId, bool status) internal; }
* @dev Sets a status of the message that came from the other side. @param _messageId id of the message from the other side that triggered a call. @param _status execution status, true if executed successfully./
function setMessageCallStatus(bytes32 _messageId, bool _status) internal { boolStorage[keccak256(abi.encodePacked("messageCallStatus", _messageId))] = _status; }
980,223
[ 1, 2785, 279, 1267, 434, 326, 883, 716, 22497, 628, 326, 1308, 4889, 18, 225, 389, 2150, 548, 612, 434, 326, 883, 628, 326, 1308, 4889, 716, 10861, 279, 745, 18, 225, 389, 2327, 4588, 1267, 16, 638, 309, 7120, 4985, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 15227, 1477, 1482, 12, 3890, 1578, 389, 2150, 548, 16, 1426, 389, 2327, 13, 2713, 288, 203, 3639, 1426, 3245, 63, 79, 24410, 581, 5034, 12, 21457, 18, 3015, 4420, 329, 2932, 2150, 1477, 1482, 3113, 389, 2150, 548, 3719, 65, 273, 389, 2327, 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 ]
./full_match/1/0x2B6d357b0585Be3DBc448366A23486437ba2015C/sources/lib/solady/src/utils/FixedPointMathLib.sol
@dev Returns a non-zero number if `b` is true, else 0. If `b` is from plain Solidity, the non-zero number will be 1.
function rawBoolToUint(bool b) internal pure returns (uint256 z) { assembly { z := b } }
4,914,269
[ 1, 1356, 279, 1661, 17, 7124, 1300, 309, 1375, 70, 68, 353, 638, 16, 469, 374, 18, 971, 1375, 70, 68, 353, 628, 7351, 348, 7953, 560, 16, 326, 1661, 17, 7124, 1300, 903, 506, 404, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 1831, 7464, 774, 5487, 12, 6430, 324, 13, 2713, 16618, 1135, 261, 11890, 5034, 998, 13, 288, 203, 3639, 19931, 288, 203, 5411, 998, 519, 324, 203, 3639, 289, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/4/0xC509703234E675623C5eA75258e4E19ec51Cb58E/sources/contracts/BaseBallersNft.sol
uint256 public costForDev = 0 ether; address[] public DevAdrdresses = ["0xAb8483F64d9C6d1EcF9b849Ae677dD3315835cb2","0x5c6B0f7Bf3E7ce046039Bd8FABdfD3f9F5021678","0x4B20993Bc481177ec7E8f571ceCaE8A9e22C02db" ];
contract BaseBallersNft is ERC721Enumerable, Ownable { using Strings for uint256; string public baseURI; string public baseExtension = ".json"; string public notRevealedUri; uint256 public cost = 0.04 ether; uint256 public maxSupply = 7000; uint256 public maxMintAmount = 15; uint256 public maxMintAmountPerWhitelistAddressV = 1 ; bool public paused = true; bool public revealed = false; bool public preSaleOnOff = true; address[] public whitelistedAdrdresses; constructor( string memory _name, string memory _symbol, string memory _initBaseURI, string memory _initNotRevealedUri pragma solidity >=0.7.0 <0.9.0; ) ERC721(_name, _symbol) { setBaseURI(_initBaseURI); setNotRevealedURI(_initNotRevealedUri); } function _baseURI() internal view virtual override returns (string memory) { return baseURI; } function mint(uint256 _mintAmount) public payable { require(!paused); uint256 supply = totalSupply(); require(_mintAmount > 0); require(supply + _mintAmount <= maxSupply); if (msg.sender != owner()) { if(preSaleOnOff == true) { require(_mintAmount <= maxMintAmountPerWhitelistAddressV); require(isWhiteListed(msg.sender),"Not whitelistedAdrdress"); uint256 ownerTokenCount = balanceOf(msg.sender); require(ownerTokenCount< maxMintAmountPerWhitelistAddressV ,"already minted" ); } else { require(_mintAmount <= maxMintAmount); } require(msg.value >= cost * _mintAmount); } { require(msg.value >= costForDev * _mintAmount); } for (uint256 i = 1; i <= _mintAmount; i++) { _safeMint(msg.sender, supply + i); } } function mint(uint256 _mintAmount) public payable { require(!paused); uint256 supply = totalSupply(); require(_mintAmount > 0); require(supply + _mintAmount <= maxSupply); if (msg.sender != owner()) { if(preSaleOnOff == true) { require(_mintAmount <= maxMintAmountPerWhitelistAddressV); require(isWhiteListed(msg.sender),"Not whitelistedAdrdress"); uint256 ownerTokenCount = balanceOf(msg.sender); require(ownerTokenCount< maxMintAmountPerWhitelistAddressV ,"already minted" ); } else { require(_mintAmount <= maxMintAmount); } require(msg.value >= cost * _mintAmount); } { require(msg.value >= costForDev * _mintAmount); } for (uint256 i = 1; i <= _mintAmount; i++) { _safeMint(msg.sender, supply + i); } } function mint(uint256 _mintAmount) public payable { require(!paused); uint256 supply = totalSupply(); require(_mintAmount > 0); require(supply + _mintAmount <= maxSupply); if (msg.sender != owner()) { if(preSaleOnOff == true) { require(_mintAmount <= maxMintAmountPerWhitelistAddressV); require(isWhiteListed(msg.sender),"Not whitelistedAdrdress"); uint256 ownerTokenCount = balanceOf(msg.sender); require(ownerTokenCount< maxMintAmountPerWhitelistAddressV ,"already minted" ); } else { require(_mintAmount <= maxMintAmount); } require(msg.value >= cost * _mintAmount); } { require(msg.value >= costForDev * _mintAmount); } for (uint256 i = 1; i <= _mintAmount; i++) { _safeMint(msg.sender, supply + i); } } function mint(uint256 _mintAmount) public payable { require(!paused); uint256 supply = totalSupply(); require(_mintAmount > 0); require(supply + _mintAmount <= maxSupply); if (msg.sender != owner()) { if(preSaleOnOff == true) { require(_mintAmount <= maxMintAmountPerWhitelistAddressV); require(isWhiteListed(msg.sender),"Not whitelistedAdrdress"); uint256 ownerTokenCount = balanceOf(msg.sender); require(ownerTokenCount< maxMintAmountPerWhitelistAddressV ,"already minted" ); } else { require(_mintAmount <= maxMintAmount); } require(msg.value >= cost * _mintAmount); } { require(msg.value >= costForDev * _mintAmount); } for (uint256 i = 1; i <= _mintAmount; i++) { _safeMint(msg.sender, supply + i); } } if (msg.sender == isDev()) function mint(uint256 _mintAmount) public payable { require(!paused); uint256 supply = totalSupply(); require(_mintAmount > 0); require(supply + _mintAmount <= maxSupply); if (msg.sender != owner()) { if(preSaleOnOff == true) { require(_mintAmount <= maxMintAmountPerWhitelistAddressV); require(isWhiteListed(msg.sender),"Not whitelistedAdrdress"); uint256 ownerTokenCount = balanceOf(msg.sender); require(ownerTokenCount< maxMintAmountPerWhitelistAddressV ,"already minted" ); } else { require(_mintAmount <= maxMintAmount); } require(msg.value >= cost * _mintAmount); } { require(msg.value >= costForDev * _mintAmount); } for (uint256 i = 1; i <= _mintAmount; i++) { _safeMint(msg.sender, supply + i); } } function mint(uint256 _mintAmount) public payable { require(!paused); uint256 supply = totalSupply(); require(_mintAmount > 0); require(supply + _mintAmount <= maxSupply); if (msg.sender != owner()) { if(preSaleOnOff == true) { require(_mintAmount <= maxMintAmountPerWhitelistAddressV); require(isWhiteListed(msg.sender),"Not whitelistedAdrdress"); uint256 ownerTokenCount = balanceOf(msg.sender); require(ownerTokenCount< maxMintAmountPerWhitelistAddressV ,"already minted" ); } else { require(_mintAmount <= maxMintAmount); } require(msg.value >= cost * _mintAmount); } { require(msg.value >= costForDev * _mintAmount); } for (uint256 i = 1; i <= _mintAmount; i++) { _safeMint(msg.sender, supply + i); } } function isDev(address _dev) { if(msg.sender==) }*/ function walletOfOwner(address _owner) public view returns (uint256[] memory) { uint256 ownerTokenCount = balanceOf(_owner); uint256[] memory tokenIds = new uint256[](ownerTokenCount); for (uint256 i; i < ownerTokenCount; i++) { tokenIds[i] = tokenOfOwnerByIndex(_owner, i); } return tokenIds; } function walletOfOwner(address _owner) public view returns (uint256[] memory) { uint256 ownerTokenCount = balanceOf(_owner); uint256[] memory tokenIds = new uint256[](ownerTokenCount); for (uint256 i; i < ownerTokenCount; i++) { tokenIds[i] = tokenOfOwnerByIndex(_owner, i); } return tokenIds; } function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); if(revealed == false) { return notRevealedUri; } string memory currentBaseURI = _baseURI(); return bytes(currentBaseURI).length > 0 ? string(abi.encodePacked(currentBaseURI, tokenId.toString(), baseExtension)) : ""; } function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); if(revealed == false) { return notRevealedUri; } string memory currentBaseURI = _baseURI(); return bytes(currentBaseURI).length > 0 ? string(abi.encodePacked(currentBaseURI, tokenId.toString(), baseExtension)) : ""; } function reveal() public onlyOwner { revealed = true; } function setCost(uint256 _newCost) public onlyOwner { cost = _newCost; } function setmaxMintAmount(uint256 _newmaxMintAmount) public onlyOwner { maxMintAmount = _newmaxMintAmount; } function setNotRevealedURI(string memory _notRevealedURI) public onlyOwner { notRevealedUri = _notRevealedURI; } function setBaseURI(string memory _newBaseURI) public onlyOwner { baseURI = _newBaseURI; } function setBaseExtension(string memory _newBaseExtension) public onlyOwner { baseExtension = _newBaseExtension; } function pause(bool _state) public onlyOwner { paused = _state; } function whitelistUsers(address[] calldata _users) public onlyOwner { delete whitelistedAdrdresses; whitelistedAdrdresses = _users; } function isWhiteListed(address _user)public view returns(bool) { for(uint256 i=0;i<whitelistedAdrdresses.length;i++) { if(whitelistedAdrdresses[i]== _user) { return true; } } return false; } function isWhiteListed(address _user)public view returns(bool) { for(uint256 i=0;i<whitelistedAdrdresses.length;i++) { if(whitelistedAdrdresses[i]== _user) { return true; } } return false; } function isWhiteListed(address _user)public view returns(bool) { for(uint256 i=0;i<whitelistedAdrdresses.length;i++) { if(whitelistedAdrdresses[i]== _user) { return true; } } return false; } function maxMintAmountPerWhitelistAddress(uint256 _limit) public onlyOwner { maxMintAmountPerWhitelistAddressV = _limit; } function preSaleOffOn(bool _state) public onlyOwner { preSaleOnOff = _state; } function burn(uint256 tokenId ) public onlyOwner { _burn(tokenId); } function Weeklyburn( uint256[] calldata tokenId ) public onlyOwner { for(uint256 i = 0 ; i<tokenId.length;i++) { _burn(tokenId[i]); } } function Weeklyburn( uint256[] calldata tokenId ) public onlyOwner { for(uint256 i = 0 ; i<tokenId.length;i++) { _burn(tokenId[i]); } } function withdraw() public payable onlyOwner { require(success); } (bool success, ) = payable(msg.sender).call{value: address(this).balance}(""); }
12,400,443
[ 1, 11890, 5034, 1071, 6991, 1290, 8870, 273, 374, 225, 2437, 31, 1758, 8526, 1071, 9562, 1871, 13623, 15807, 273, 8247, 20, 92, 5895, 5193, 10261, 42, 1105, 72, 29, 39, 26, 72, 21, 23057, 42, 29, 70, 5193, 29, 37, 73, 26, 4700, 72, 40, 3707, 25984, 4763, 7358, 22, 15937, 20, 92, 25, 71, 26, 38, 20, 74, 27, 38, 74, 23, 41, 27, 311, 3028, 26, 4630, 29, 38, 72, 28, 2046, 38, 2180, 40, 23, 74, 29, 42, 25, 3103, 2313, 8285, 15937, 20, 92, 24, 38, 3462, 2733, 23, 38, 71, 8875, 2499, 4700, 557, 27, 41, 28, 74, 10321, 21, 311, 23508, 41, 28, 37, 29, 73, 3787, 39, 3103, 1966, 6, 308, 31, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 16351, 3360, 38, 454, 414, 50, 1222, 353, 4232, 39, 27, 5340, 3572, 25121, 16, 14223, 6914, 288, 203, 225, 1450, 8139, 364, 2254, 5034, 31, 203, 203, 225, 533, 1071, 1026, 3098, 31, 203, 225, 533, 1071, 1026, 3625, 273, 3552, 1977, 14432, 203, 225, 533, 1071, 486, 426, 537, 18931, 3006, 31, 203, 225, 2254, 5034, 1071, 6991, 273, 374, 18, 3028, 225, 2437, 31, 203, 21281, 225, 2254, 5034, 1071, 943, 3088, 1283, 273, 2371, 3784, 31, 203, 225, 2254, 5034, 1071, 943, 49, 474, 6275, 273, 4711, 31, 203, 225, 2254, 5034, 1071, 943, 49, 474, 6275, 2173, 18927, 1887, 58, 273, 404, 274, 203, 225, 1426, 1071, 17781, 273, 638, 31, 203, 225, 1426, 1071, 283, 537, 18931, 273, 629, 31, 203, 225, 1426, 1071, 675, 30746, 1398, 7210, 273, 638, 31, 203, 225, 1758, 8526, 1071, 26944, 1871, 13623, 15807, 31, 203, 21281, 203, 225, 3885, 12, 203, 565, 533, 3778, 389, 529, 16, 203, 565, 533, 3778, 389, 7175, 16, 203, 565, 533, 3778, 389, 2738, 2171, 3098, 16, 203, 565, 533, 3778, 389, 2738, 1248, 426, 537, 18931, 3006, 203, 683, 9454, 18035, 560, 1545, 20, 18, 27, 18, 20, 411, 20, 18, 29, 18, 20, 31, 203, 225, 262, 4232, 39, 27, 5340, 24899, 529, 16, 389, 7175, 13, 288, 203, 565, 26435, 3098, 24899, 2738, 2171, 3098, 1769, 203, 565, 444, 1248, 426, 537, 18931, 3098, 24899, 2738, 1248, 426, 537, 18931, 3006, 1769, 203, 225, 289, 203, 203, 225, 445, 389, 1969, 3098, 2 ]
pragma solidity 0.5.11; // Rollup solidity implementation import "@openzeppelin/contracts/math/SafeMath.sol"; import "./Hasher.sol"; import "./Whitelist.sol"; import "./MerkleTree.sol"; import {WithdrawVerifier as WithdrawVerifier} from "./WithdrawVerifier.sol"; import {TxVerifier as TxVerifier} from "./TxVerifier.sol"; contract RollUp { using SafeMath for uint256; // Contract owner address owner; // Hasher function Hasher hasher; // Merkle Tree that represents all users's // deposits MerkleTree balanceTree; // ZK Proofs WithdrawVerifier withdrawVerifier; TxVerifier txVerifier; // Deposit event event Deposit( uint256 balanceTreeIndex, uint256 publicKeyX, uint256 publicKeyY, uint256 balance, uint256 nonce ); // Withdraw event Withdraw( uint256 balanceTreeIndex, uint256 publicKeyX, uint256 publicKeyY, uint256 balance, uint256 nonce ); event RollUpProcessed(uint256 newBalanceTreeRoot); // Registered users struct User { uint256 balanceTreeLeafIndex; uint256 publicKeyX; uint256 publicKeyY; uint256 balance; uint256 nonce; } mapping(uint256 => User) balanceTreeUsers; mapping(uint256 => bool) isPublicKeysRegistered; mapping(uint256 => bool) usedNullifiers; // index => hash(public key) mapping(uint256 => uint256) balanceTreeKeys; uint256 accuredFees; constructor( address hasherAddress, address balanceTreeAddress, address withdrawVerifierAddress, address txVerifierAddress ) public { owner = msg.sender; hasher = Hasher(hasherAddress); balanceTree = MerkleTree(balanceTreeAddress); withdrawVerifier = WithdrawVerifier(withdrawVerifierAddress); txVerifier = TxVerifier(txVerifierAddress); accuredFees = 0; } function rollUp( uint256[2] memory a, uint256[2][2] memory b, uint256[2] memory c, uint256[73] memory input ) public { // TODO: Check if current merkle tree is // equal to supplied merkle tree uint256 balanceTreeRoot = input[1]; // uint256 newBalanceTreeRoot = input[1]; if (balanceTree.getRoot() != balanceTreeRoot) { revert("Proof not valid for current tree"); } if (!txVerifier.verifyProof(a, b, c, input)) { revert("Invalid roll up proofs"); } // Transaction one uint256 from; uint256 to; uint256 amount; uint256 fee; uint256 nonce; uint256 curOffset; uint256 senderLeaf; uint256 recipientLeaf; uint256 senderPublicKeyHash; uint256 recipientPublicKeyHash; uint256 txDataOffset = 3; uint256 txDataLength = 8; uint256 batchSize = 2; for (uint256 i = 0; i < batchSize; i++) { curOffset = txDataOffset + (txDataLength * i); from = input[curOffset]; to = input[curOffset + 1]; amount = input[curOffset + 2]; fee = input[curOffset + 3]; nonce = input[curOffset + 4]; // Update user data senderPublicKeyHash = balanceTreeKeys[from]; recipientPublicKeyHash = balanceTreeKeys[to]; User storage sender = balanceTreeUsers[senderPublicKeyHash]; sender.balance -= amount; sender.balance -= fee; sender.nonce = nonce; User storage recipient = balanceTreeUsers[recipientPublicKeyHash]; recipient.balance += amount; accuredFees += fee; // Update merkle tree leaf senderLeaf = hasher.hashBalanceTreeLeaf( sender.publicKeyX, sender.publicKeyY, sender.balance, sender.nonce ); recipientLeaf = hasher.hashBalanceTreeLeaf( recipient.publicKeyX, recipient.publicKeyY, recipient.balance, recipient.nonce ); balanceTree.update(sender.balanceTreeLeafIndex, senderLeaf); balanceTree.update(recipient.balanceTreeLeafIndex, recipientLeaf); } emit RollUpProcessed(balanceTree.getRoot()); } // Checks if public key is registered function isPublicKeyRegistered(uint256 publicKeyX, uint256 publicKeyY) public view returns (bool) { uint256 publicKeyHash = hasher.hashPair(publicKeyX, publicKeyY); return isPublicKeysRegistered[publicKeyHash]; } function getUserKey(uint256 index) public view returns (uint256) { return balanceTreeKeys[index]; } function getUserData(uint256 publicKeyHash) public view returns (uint256, uint256, uint256, uint256, uint256) { User memory user = balanceTreeUsers[publicKeyHash]; return ( user.balanceTreeLeafIndex, user.publicKeyX, user.publicKeyY, user.balance, user.nonce ); } function withdrawAll( uint256[2] memory a, uint256[2][2] memory b, uint256[2] memory c, uint256[3] memory input ) public { // Inputs are the public signal uint256 publicKeyX = input[0]; uint256 publicKeyY = input[1]; uint256 publicKeyHash = hasher.hashPair(publicKeyX, publicKeyY); User memory user = balanceTreeUsers[publicKeyHash]; if (user.balance <= 0) { revert("Cannot withdraw with 0 balance"); } withdraw(user.balance, a, b, c, input); } function withdraw( uint256 amount, uint256[2] memory a, uint256[2][2] memory b, uint256[2] memory c, uint256[3] memory input ) public { // Inputs are the public signal uint256 publicKeyX = input[0]; uint256 publicKeyY = input[1]; uint256 nullifier = input[2]; if (usedNullifiers[nullifier]) { revert("Nullifier has been used"); } // Check if proof is valid bool validProof = withdrawVerifier.verifyProof(a, b, c, input); if (!validProof) { revert("Unauthorized to withdraw funds"); } // CHeck user balance uint256 publicKeyHash = hasher.hashPair(publicKeyX, publicKeyY); User storage user = balanceTreeUsers[publicKeyHash]; if (amount > user.balance) { revert("Withdraw amount is more than remaining balance"); } // Register nullifier as used usedNullifiers[nullifier] = true; user.balance -= amount; msg.sender.transfer(amount); emit Withdraw( user.balanceTreeLeafIndex, publicKeyX, publicKeyY, user.balance, user.nonce ); } function deposit(uint256 publicKeyX, uint256 publicKeyY) public payable { uint256 publicKeyHash = hasher.hashPair(publicKeyX, publicKeyY); User storage user = balanceTreeUsers[publicKeyHash]; user.balance += msg.value; // Insert user into balance tree uint256 leaf = hasher.hashBalanceTreeLeaf( publicKeyX, publicKeyY, user.balance, user.nonce ); // If its a new user, mark them as registered, // and insert them into the merkleTree if (!isPublicKeysRegistered[publicKeyHash]) { isPublicKeysRegistered[publicKeyHash] = true; // Saves user's public key user.publicKeyX = publicKeyX; user.publicKeyY = publicKeyY; // Saves user's index in balance tree user.balanceTreeLeafIndex = balanceTree.getInsertedLeavesNo(); balanceTree.insert(leaf); // Saves user's index in balanceTreeKeys balanceTreeKeys[user.balanceTreeLeafIndex] = publicKeyHash; } else { // Updates balance and data in balance tree balanceTree.update(user.balanceTreeLeafIndex, leaf); } emit Deposit( user.balanceTreeLeafIndex, publicKeyX, publicKeyY, user.balance, user.nonce ); } function getAccuredFees() public view returns (uint256) { return accuredFees; } function withdrawAccuredFees() public { if (msg.sender != owner) { revert("Only owner can call this function"); } msg.sender.transfer(accuredFees); accuredFees = 0; } }
index => hash(public key)
mapping(uint256 => uint256) balanceTreeKeys;
2,566,730
[ 1, 1615, 516, 1651, 12, 482, 498, 13, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 2874, 12, 11890, 5034, 516, 2254, 5034, 13, 11013, 2471, 2396, 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 ]
./partial_match/1/0x7b05cE308915299B0a31D5E5f020b4DE66779BCa/sources/contracts/BSGGStaking.sol
@notice Pause new Staking @return bool
function pause() external onlyOwner returns (bool) { _pause(); emit Paused(true); return true; }
9,150,371
[ 1, 19205, 394, 934, 6159, 327, 1426, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 11722, 1435, 3903, 1338, 5541, 1135, 261, 6430, 13, 288, 203, 3639, 389, 19476, 5621, 203, 3639, 3626, 21800, 3668, 12, 3767, 1769, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/8453/0x2d3D67271C48D5E952113799828bcBC02cd70a82/sources/RouterV2.sol
helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library TransferHelper { function safeApprove( address token, address to, uint256 value pragma solidity >=0.6.0; ) internal { (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value)); require( success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper::safeApprove: approve failed' ); } function safeTransfer( address token, address to, uint256 value ) internal { (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value)); require( success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper::safeTransfer: transfer failed' ); } function safeTransferFrom( address token, address from, address to, uint256 value ) internal { (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value)); require( success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper::transferFrom: transferFrom failed' ); } function safeTransferETH(address to, uint256 value) internal { require(success, 'TransferHelper::safeTransferETH: ETH transfer failed'); } (bool success, ) = to.call{value: value}(new bytes(0)); }
16,730,160
[ 1, 4759, 2590, 364, 16592, 310, 598, 4232, 39, 3462, 2430, 471, 5431, 512, 2455, 716, 741, 486, 11071, 715, 327, 638, 19, 5743, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 12083, 12279, 2276, 288, 203, 565, 445, 4183, 12053, 537, 12, 203, 3639, 1758, 1147, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 460, 203, 203, 203, 683, 9454, 18035, 560, 1545, 20, 18, 26, 18, 20, 31, 203, 565, 262, 2713, 288, 203, 3639, 261, 6430, 2216, 16, 1731, 3778, 501, 13, 273, 1147, 18, 1991, 12, 21457, 18, 3015, 1190, 4320, 12, 20, 92, 5908, 25, 24852, 27, 70, 23, 16, 358, 16, 460, 10019, 203, 3639, 2583, 12, 203, 5411, 2216, 597, 261, 892, 18, 2469, 422, 374, 747, 24126, 18, 3922, 12, 892, 16, 261, 6430, 3719, 3631, 203, 5411, 296, 5912, 2276, 2866, 4626, 12053, 537, 30, 6617, 537, 2535, 11, 203, 3639, 11272, 203, 565, 289, 203, 203, 565, 445, 4183, 5912, 12, 203, 3639, 1758, 1147, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 460, 203, 565, 262, 2713, 288, 203, 3639, 261, 6430, 2216, 16, 1731, 3778, 501, 13, 273, 1147, 18, 1991, 12, 21457, 18, 3015, 1190, 4320, 12, 20, 6995, 9349, 6162, 7358, 70, 16, 358, 16, 460, 10019, 203, 3639, 2583, 12, 203, 5411, 2216, 597, 261, 892, 18, 2469, 422, 374, 747, 24126, 18, 3922, 12, 892, 16, 261, 6430, 3719, 3631, 203, 5411, 296, 5912, 2276, 2866, 4626, 5912, 30, 7412, 2535, 11, 203, 3639, 11272, 203, 565, 289, 203, 203, 565, 445, 4183, 5912, 1265, 12, 203, 3639, 1758, 1147, 16, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 460, 2 ]
// SPDX-License-Identifier: MIT import "@chainlink/contracts/src/v0.8/VRFConsumerBase.sol"; pragma solidity >=0.8.0; interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval( address indexed owner, address indexed spender, uint256 value ); } interface 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); } contract VRFRequestIDBase { /** * @notice returns the seed which is actually input to the VRF coordinator * * @dev To prevent repetition of VRF output due to repetition of the * @dev user-supplied seed, that seed is combined in a hash with the * @dev user-specific nonce, and the address of the consuming contract. The * @dev risk of repetition is mostly mitigated by inclusion of a blockhash in * @dev the final seed, but the nonce does protect against repetition in * @dev requests which are included in a single block. * * @param _userSeed VRF seed input provided by user * @param _requester Address of the requesting contract * @param _nonce User-specific nonce at the time of the request */ function makeVRFInputSeed( bytes32 _keyHash, uint256 _userSeed, address _requester, uint256 _nonce ) internal pure returns (uint256) { return uint256(keccak256(abi.encode(_keyHash, _userSeed, _requester, _nonce))); } /** * @notice Returns the id for this request * @param _keyHash The serviceAgreement ID to be used for this request * @param _vRFInputSeed The seed to be passed directly to the VRF * @return The id for this request * * @dev Note that _vRFInputSeed is not the seed passed by the consuming * @dev contract, but the one generated by makeVRFInputSeed */ function makeRequestId(bytes32 _keyHash, uint256 _vRFInputSeed) internal pure returns (bytes32) { return keccak256(abi.encodePacked(_keyHash, _vRFInputSeed)); } } /** **************************************************************************** * @notice Interface for contracts using VRF randomness * ***************************************************************************** * @dev PURPOSE * * @dev Reggie the Random Oracle (not his real job) wants to provide randomness * @dev to Vera the verifier in such a way that Vera can be sure he's not * @dev making his output up to suit himself. Reggie provides Vera a public key * @dev to which he knows the secret key. Each time Vera provides a seed to * @dev Reggie, he gives back a value which is computed completely * @dev deterministically from the seed and the secret key. * * @dev Reggie provides a proof by which Vera can verify that the output was * @dev correctly computed once Reggie tells it to her, but without that proof, * @dev the output is indistinguishable to her from a uniform random sample * @dev from the output space. * * @dev The purpose of this contract is to make it easy for unrelated contracts * @dev to talk to Vera the verifier about the work Reggie is doing, to provide * @dev simple access to a verifiable source of randomness. * ***************************************************************************** * @dev USAGE * * @dev Calling contracts must inherit from VRFConsumerBase, and can * @dev initialize VRFConsumerBase's attributes in their constructor as * @dev shown: * * @dev contract VRFConsumer { * @dev constuctor(<other arguments>, address _vrfCoordinator, address _link) * @dev VRFConsumerBase(_vrfCoordinator, _link) public { * @dev <initialization with other arguments goes here> * @dev } * @dev } * * @dev The oracle will have given you an ID for the VRF keypair they have * @dev committed to (let's call it keyHash), and have told you the minimum LINK * @dev price for VRF service. Make sure your contract has sufficient LINK, and * @dev call requestRandomness(keyHash, fee, seed), where seed is the input you * @dev want to generate randomness from. * * @dev Once the VRFCoordinator has received and validated the oracle's response * @dev to your request, it will call your contract's fulfillRandomness method. * * @dev The randomness argument to fulfillRandomness is the actual random value * @dev generated from your seed. * * @dev The requestId argument is generated from the keyHash and the seed by * @dev makeRequestId(keyHash, seed). If your contract could have concurrent * @dev requests open, you can use the requestId to track which seed is * @dev associated with which randomness. See VRFRequestIDBase.sol for more * @dev details. (See "SECURITY CONSIDERATIONS" for principles to keep in mind, * @dev if your contract could have multiple requests in flight simultaneously.) * * @dev Colliding `requestId`s are cryptographically impossible as long as seeds * @dev differ. (Which is critical to making unpredictable randomness! See the * @dev next section.) * * ***************************************************************************** * @dev SECURITY CONSIDERATIONS * * @dev A method with the ability to call your fulfillRandomness method directly * @dev could spoof a VRF response with any random value, so it's critical that * @dev it cannot be directly called by anything other than this base contract * @dev (specifically, by the VRFConsumerBase.rawFulfillRandomness method). * * @dev For your users to trust that your contract's random behavior is free * @dev from malicious interference, it's best if you can write it so that all * @dev behaviors implied by a VRF response are executed *during* your * @dev fulfillRandomness method. If your contract must store the response (or * @dev anything derived from it) and use it later, you must ensure that any * @dev user-significant behavior which depends on that stored value cannot be * @dev manipulated by a subsequent VRF request. * * @dev Similarly, both miners and the VRF oracle itself have some influence * @dev over the order in which VRF responses appear on the blockchain, so if * @dev your contract could have multiple VRF requests in flight simultaneously, * @dev you must ensure that the order in which the VRF responses arrive cannot * @dev be used to manipulate your contract's user-significant behavior. * * @dev Since the ultimate input to the VRF is mixed with the block hash of the * @dev block in which the request is made, user-provided seeds have no impact * @dev on its economic security properties. They are only included for API * @dev compatability with previous versions of this contract. * * @dev Since the block hash of the block which contains the requestRandomness * @dev call is mixed into the input to the VRF *last*, a sufficiently powerful * @dev miner could, in principle, fork the blockchain to evict the block * @dev containing the request, forcing the request to be included in a * @dev different block with a different hash, and therefore a different input * @dev to the VRF. However, such an attack would incur a substantial economic * @dev cost. This cost scales with the number of blocks the VRF oracle waits * @dev until it calls responds to a request. */ abstract contract VRFConsumerBase is VRFRequestIDBase { /** * @notice fulfillRandomness handles the VRF response. Your contract must * @notice implement it. See "SECURITY CONSIDERATIONS" above for important * @notice principles to keep in mind when implementing your fulfillRandomness * @notice method. * * @dev VRFConsumerBase expects its subcontracts to have a method with this * @dev signature, and will call it once it has verified the proof * @dev associated with the randomness. (It is triggered via a call to * @dev rawFulfillRandomness, below.) * * @param requestId The Id initially returned by requestRandomness * @param randomness the VRF output */ function fulfillRandomness(bytes32 requestId, uint256 randomness) internal virtual; /** * @dev In order to keep backwards compatibility we have kept the user * seed field around. We remove the use of it because given that the blockhash * enters later, it overrides whatever randomness the used seed provides. * Given that it adds no security, and can easily lead to misunderstandings, * we have removed it from usage and can now provide a simpler API. */ uint256 private constant USER_SEED_PLACEHOLDER = 0; /** * @notice requestRandomness initiates a request for VRF output given _seed * * @dev The fulfillRandomness method receives the output, once it's provided * @dev by the Oracle, and verified by the vrfCoordinator. * * @dev The _keyHash must already be registered with the VRFCoordinator, and * @dev the _fee must exceed the fee specified during registration of the * @dev _keyHash. * * @dev The _seed parameter is vestigial, and is kept only for API * @dev compatibility with older versions. It can't *hurt* to mix in some of * @dev your own randomness, here, but it's not necessary because the VRF * @dev oracle will mix the hash of the block containing your request into the * @dev VRF seed it ultimately uses. * * @param _keyHash ID of public key against which randomness is generated * @param _fee The amount of LINK to send with the request * * @return requestId unique ID for this request * * @dev The returned requestId can be used to distinguish responses to * @dev concurrent requests. It is passed as the first argument to * @dev fulfillRandomness. */ function requestRandomness(bytes32 _keyHash, uint256 _fee) internal returns (bytes32 requestId) { LINK.transferAndCall(vrfCoordinator, _fee, abi.encode(_keyHash, USER_SEED_PLACEHOLDER)); // This is the seed passed to VRFCoordinator. The oracle will mix this with // the hash of the block containing this request to obtain the seed/input // which is finally passed to the VRF cryptographic machinery. uint256 vRFSeed = makeVRFInputSeed(_keyHash, USER_SEED_PLACEHOLDER, address(this), nonces[_keyHash]); // nonces[_keyHash] must stay in sync with // VRFCoordinator.nonces[_keyHash][this], which was incremented by the above // successful LINK.transferAndCall (in VRFCoordinator.randomnessRequest). // This provides protection against the user repeating their input seed, // which would result in a predictable/duplicate output, if multiple such // requests appeared in the same block. nonces[_keyHash] = nonces[_keyHash] + 1; return makeRequestId(_keyHash, vRFSeed); } LinkTokenInterface internal immutable LINK; address private immutable vrfCoordinator; // Nonces for each VRF key from which randomness has been requested. // // Must stay in sync with VRFCoordinator[_keyHash][this] mapping(bytes32 => uint256) /* keyHash */ /* nonce */ private nonces; /** * @param _vrfCoordinator address of VRFCoordinator contract * @param _link address of LINK token contract * * @dev https://docs.chain.link/docs/link-token-contracts */ constructor(address _vrfCoordinator, address _link) { vrfCoordinator = _vrfCoordinator; LINK = LinkTokenInterface(_link); } // rawFulfillRandomness is called by VRFCoordinator when it receives a valid VRF // proof. rawFulfillRandomness then calls fulfillRandomness, after validating // the origin of the call function rawFulfillRandomness(bytes32 requestId, uint256 randomness) external { require(msg.sender == vrfCoordinator, "Only VRFCoordinator can fulfill"); fulfillRandomness(requestId, randomness); } } // TODO: add emits to the contract contract VarietySavingsDAO is VRFConsumerBase { // --------------- General Round Info ---------------- uint32 public roundNumber; // -------------------- User Info -------------------- address[] private usersWhoVoted; mapping(address => bool) private hasUserVoted; // TODO: add start date, end date mapping(address => bool) addressVotingEligibity; // ------------------- Token Info -------------------- address[] public availableTokens = [ 0x4997910AC59004383561Ac7D6d8a65721Fa2A663, 0xd5936853145A0212AA86BeDc434F8365f84069D5, 0x98C50fa9f048E8F452d32B8dE8E96c0b14642B9F ]; mapping(address => uint32) private tokenVoteTotal; // TODO: keep symbol/name of tokens somewhere mapping(address => bool) tokenAvailableForVoting; address public lastRoundWinningToken; uint8 TRANSFER_TOKEN_AMOUNT = 10; // ----------------- Contract Info ------------------- address public owner; address public mainSavingsContract; // -------------------- VRF Info --------------------- bytes32 internal keyHash; uint256 internal fee; // ~~~ randomness uint8 public chanceOfWinning = 10; uint256 public randomResult; uint256 MAX_INT = 2**256 - 1; uint256 public cutoffInt; // -------------------- Constructor --------------------- /** * Constructor inherits VRFConsumerBase * * Network: Polygon (Matic) Mumbai Testnet * Chainlink VRF Coordinator address: 0x8C7382F9D8f56b33781fE506E897a4F1e2d17255 * LINK token address: 0x326C977E6efc84E512bB9C30f76E30c160eD06FB * Key Hash: 0x6e75b569a01ef56d18cab6a8e71e6600d6ce853834d4a5748b720d06f878b3a4 */ constructor() VRFConsumerBase( 0x8C7382F9D8f56b33781fE506E897a4F1e2d17255, // VRF Coordinator 0x326C977E6efc84E512bB9C30f76E30c160eD06FB // LINK Token ) { owner = msg.sender; /// Added owner to set VarietySavings contract address uint8 numberOfAvailableTokens = uint8(availableTokens.length); // to begin with, add some choice tokens to votable pool for (uint8 i = 0; i < numberOfAvailableTokens; i++) { tokenAvailableForVoting[availableTokens[i]] = true; } keyHash = 0x6e75b569a01ef56d18cab6a8e71e6600d6ce853834d4a5748b720d06f878b3a4; fee = 0.0001 * 10**18; // 0.0001 LINK (Varies by network) owner = msg.sender; cutoffInt = (MAX_INT / 100) * chanceOfWinning; } // -------------------- Randomness Functions --------------------- /** * Requests randomness */ function getRandomNumber() public returns (bytes32 requestId) { require( LINK.balanceOf(address(this)) >= fee, "Not enough LINK - fill contract with faucet" ); return requestRandomness(keyHash, fee); } /** * Callback function used by VRF Coordinator */ function fulfillRandomness(bytes32 requestId, uint256 randomness) internal override { randomResult = randomness; } /** * Turns single random number into array of random numbers */ function expand(uint256 randomValue, uint256 n) public pure returns (uint256[] memory expandedValues) { expandedValues = new uint256[](n); for (uint256 i = 0; i < n; i++) { expandedValues[i] = uint256(keccak256(abi.encode(randomValue, i))); } return expandedValues; } function changeChanceOfWinning(uint8 _newChance) public { chanceOfWinning = _newChance; cutoffInt = (MAX_INT / 100) * _newChance; } // -------------------- Set State Functions --------------------- function setMainSavingsContract(address contractAddress) public onlyOwner(msg.sender) { mainSavingsContract = contractAddress; } // TODO: Only callable by savings contract // -> function setWalletVotingEligibility(address user, bool eligibility) external onlyMain(msg.sender) { function setWalletVotingEligibility(address user, bool eligibility) public { addressVotingEligibity[user] = eligibility; } // -------------------- Modifiers --------------------- modifier onlyMain(address caller) { require(caller == mainSavingsContract, "Unauthorized"); _; } modifier onlyOwner(address caller) { require(caller == owner, "Unauthorized"); _; } modifier walletEligibleToVote() { require( addressVotingEligibity[msg.sender], "You are not eligible to vote" ); _; } modifier walletNotVotedYet() { require(!hasUserVoted[msg.sender], "You can only vote once"); _; } // -------------------- Contract State Visibility --------------------- function isTokenAvailableForVoting(address _token) public view returns (bool) { return tokenAvailableForVoting[_token]; } function tokenVotes(address _token) public view returns (uint32) { return tokenVoteTotal[_token]; } function getUserVotedStatus(address _user) public view returns (bool) { return hasUserVoted[_user]; } function isUserEligibleToVote(address _user) public view returns (bool) { return addressVotingEligibity[_user]; } // -------------------- Voting Functions --------------------- function voteForTokens(address[] memory _chosenTokens) public walletEligibleToVote walletNotVotedYet { uint8 numberOfVotedTokens = uint8(_chosenTokens.length); for (uint8 i = 0; i < numberOfVotedTokens; i++) { address currentToken = _chosenTokens[i]; // only vote for allowed tokens if (tokenAvailableForVoting[currentToken]) { tokenVoteTotal[currentToken] += 1; } } // register that the user has voted hasUserVoted[msg.sender] = true; } // -------------------- End Round Functions --------------------- // ~~~ Delete Round Data function deleteUsersVotingRoundInfo(address _user) private { hasUserVoted[_user] = false; } function deleteTokenVotesForRound() private { uint8 numberOfTokens = uint8(availableTokens.length); for (uint8 i = 0; i < numberOfTokens; i++) { tokenVoteTotal[availableTokens[i]] = 0; } } // ~~~ win selections // TODO: change this to private function selectWinningToken() public { uint8 numberOfTokens = uint8(availableTokens.length); address _tempToken = availableTokens[0]; uint32 _tempTokenVote = tokenVoteTotal[_tempToken]; // TODO: deal with ties for (uint8 i = 1; i < numberOfTokens; i++) { if (tokenVoteTotal[availableTokens[i]] > _tempTokenVote) { _tempToken = availableTokens[i]; _tempTokenVote = tokenVoteTotal[_tempToken]; } } lastRoundWinningToken = _tempToken; require(tokenVoteTotal[lastRoundWinningToken] != 0, "No votes registered"); } // TODO: use safe transfer // TODO: use swap to make token transfers of equal value function distributeTokens(address _user, uint256 _winningChance) private { if (_winningChance < cutoffInt) { IERC20 token = IERC20(lastRoundWinningToken); token.transfer(_user, TRANSFER_TOKEN_AMOUNT); } } // ~~~ control end round execution // TODO: add constraints to who can trigger this function function newVotingRound() public { uint64 numberPriorRoundVoters = uint64(usersWhoVoted.length); // get chances of winning from vrf getRandomNumber(); uint256[] memory userWinningChances = new uint256[]( numberPriorRoundVoters ); userWinningChances = expand(randomResult, numberPriorRoundVoters); for (uint64 i = 0; i < numberPriorRoundVoters; i++) { address user = usersWhoVoted[i]; uint256 userWinningChance = userWinningChances[i]; // distribute rewards according to vrf distributeTokens(user, userWinningChance); // TODO: delete only if token distribution is successful deleteUsersVotingRoundInfo(user); } // TODO: delete only if token distribution is successful deleteTokenVotesForRound(); delete usersWhoVoted; roundNumber += 1; } // -------------------- Auxiliary Functions --------------------- // Implement a withdraw function to avoid locking your LINK in the contract // TODO: add security function withdrawLink() external { LINK.transfer(owner, LINK.balanceOf(address(this))); uint8 numberOfTokens = uint8(availableTokens.length); // send all ERC20 tokens back for (uint8 i = 1; i < numberOfTokens; i++) { IERC20 token = IERC20(availableTokens[i]); token.transfer(owner, token.balanceOf(address(this))); } } // -------------------- Remaining TODOs --------------------- // TODO: change options from one round to the next as per user wants // -> give users the ability to vote for new tokens on the next round // -> change tokens on the next round if necessary // TODO: this contract should custody variety tokens? // TODO: tidy and refactor contract }
-------------------- Randomness Functions ---------------------* Requests randomness/
function getRandomNumber() public returns (bytes32 requestId) { require( LINK.balanceOf(address(this)) >= fee, "Not enough LINK - fill contract with faucet" ); return requestRandomness(keyHash, fee); }
1,752,494
[ 1, 1271, 553, 8072, 4496, 15486, 12146, 553, 7090, 2744, 4496, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 20581, 1854, 1435, 1071, 1135, 261, 3890, 1578, 14459, 13, 288, 203, 3639, 2583, 12, 203, 5411, 22926, 18, 12296, 951, 12, 2867, 12, 2211, 3719, 1545, 14036, 16, 203, 5411, 315, 1248, 7304, 22926, 300, 3636, 6835, 598, 11087, 5286, 278, 6, 203, 3639, 11272, 203, 3639, 327, 590, 8529, 4496, 12, 856, 2310, 16, 14036, 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 ]
pragma solidity >=0.5; pragma experimental ABIEncoderV2; /** * @title DexStatus * @dev Status for Dex */ contract DexStatus { string constant ONLY_RELAYER = "ONLY_RELAYER"; string constant ONLY_AIRDROP = "ONLY_AIRDROP"; string constant ONLY_INACTIVITY = "ONLY_INACTIVITY"; string constant ONLY_WITHDRAWALAPPROVED = "ONLY_WITHDRAWALAPPROVED"; string constant INVALID_NONCE = "INVALID_NONCE"; string constant INVALID_PERIOD = "INVALID_PERIOD"; string constant INVALID_AMOUNT = "INVALID_AMOUNT"; string constant INVALID_TIME = "INVALID_TIME"; string constant INVALID_GASTOKEN = "INVALID_GASTOKEN"; string constant TRANSFER_FAILED = "TRANSFER_FAILED"; string constant ECRECOVER_FAILED = "ECRECOVER_FAILED"; string constant INSUFFICIENT_FOUND = "INSUFFICIENT"; string constant TRADE_EXISTS = "TRADED"; string constant WITHDRAW_EXISTS = "WITHDRAWN"; string constant MAX_VALUE_LIMIT = "MAX_LIMIT"; string constant AMOUNT_EXCEEDED = "AMOUNT_EXCEEDED"; } /** * @title IGasStorage * @dev GasStorage interface to burn and mint gastoken */ interface IGasStorage { function mint(uint256 value) external; function burn(uint256 value) external; function balanceOf() external view returns (uint256 balance); } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = tx.origin; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @dev ERC20 interface */ interface ERC20 { function balanceOf(address _owner) external view returns (uint256 balance); function transfer(address _to, uint256 _value) external returns (bool success) ; function transferFrom(address _from, address _to, uint256 _value) external returns (bool success); function approve(address _spender, uint256 _value) external returns (bool success); function allowance(address _owner, address _spender) view external returns (uint256 remaining); } /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring '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 numbers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0); // Solidity only automatically asserts when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } /** * @title Dex * @dev Smart contract for https://www.dex.io */ contract Dex is Ownable,DexStatus { using SafeMath for uint256; struct Order { address token; address baseToken; address user; uint256 tokenAmount; uint256 baseTokenAmount; uint nonce; uint expireTime; uint maxGasFee; uint timestamp; address gasToken; bool sell; uint8 V; bytes32 R; bytes32 S; uint signType; } struct TradeInfo { uint256 tradeTokenAmount; uint256 tradeTakerFee; uint256 tradeMakerFee; uint256 tradeGasFee; uint tradeNonce; address tradeGasToken; } mapping (address => mapping (address => uint256)) public _balances; mapping (address => uint) public _invalidOrderNonce; mapping (bytes32 => uint256) public _orderFills; mapping (address => bool) public _relayers; mapping (bytes32 => bool) public _traded; mapping (bytes32 => bool) public _withdrawn; mapping (bytes32 => uint256) public _orderGasFee; mapping (address => uint) public _withdrawalApplication; address public _feeAccount; address public _airdropContract; address public _gasStorage; uint256 public _withdrawalApplicationPeriod = 10 days; uint256 public _takerFeeRate = 0.002 ether; uint256 public _makerFeeRate = 0.001 ether; string private constant EIP712DOMAIN_TYPE = "EIP712Domain(string name)"; bytes32 private constant EIP712DOMAIN_TYPEHASH = keccak256(abi.encodePacked(EIP712DOMAIN_TYPE)); bytes32 private constant DOMAIN_SEPARATOR = keccak256(abi.encode(EIP712DOMAIN_TYPEHASH,keccak256(bytes("Dex.io")))); string private constant ORDER_TYPE = "Order(address token,address baseToken,uint256 tokenAmount,uint256 baseTokenAmount,uint256 nonce,bool sell,uint256 expireTime,uint256 maxGasFee,address gasToken,uint timestamp)"; bytes32 private constant ORDER_TYPEHASH = keccak256(abi.encodePacked(ORDER_TYPE)); string private constant WITHDRAW_TYPE = "Withdraw(address token,uint256 tokenAmount,address to,uint256 nonce,address feeToken,uint256 feeWithdrawal,uint timestamp)"; bytes32 private constant WITHDRAW_TYPEHASH = keccak256(abi.encodePacked(WITHDRAW_TYPE)); event Trade(bytes32 takerHash,bytes32 makerHash,uint256 tradeAmount,uint256 tradeBaseTokenAmount,uint256 tradeNonce,uint256 takerCostFee, uint makerCostFee,bool sellerIsMaker,uint256 gasFee); event Balance(uint256 takerBaseTokenBalance,uint256 takerTokenBalance,uint256 makerBaseTokenBalance,uint256 makerTokenBalance); event Deposit(address indexed token, address indexed user, uint256 amount, uint256 balance); event Withdraw(address indexed token,address indexed from,address indexed to, uint256 amount, uint256 balance); event Transfer(address indexed token,address indexed from,address indexed to, uint256 amount, uint256 fromBalance,uint256 toBalance); event Airdrop(address indexed to, address indexed token,uint256 amount); event WithdrawalApplication(address user,uint timestamp); modifier onlyRelayer { if (msg.sender != owner && !_relayers[msg.sender]) revert(ONLY_RELAYER); _; } modifier onlyAirdropContract { if (msg.sender != _airdropContract) revert(ONLY_AIRDROP); _; } /** * @dev approved in 10 days */ modifier onlyWithdrawalApplicationApproved { require ( _withdrawalApplication[msg.sender] != uint(0) && block.timestamp - _withdrawalApplicationPeriod > _withdrawalApplication[msg.sender], ONLY_WITHDRAWALAPPROVED); _; } /** * @param feeAccount account to receive the fee */ constructor(address feeAccount) public { _feeAccount = feeAccount; } /** * @dev do no send eth to dex contract directly. */ function() external { revert(); } /** * @dev set a relayer */ function setRelayer(address relayer, bool isRelayer) public onlyOwner { _relayers[relayer] = isRelayer; } /** * @dev check a relayer */ function isRelayer(address relayer) public view returns(bool) { return _relayers[relayer]; } /** * @dev set account that receive the fee */ function setFeeAccount(address feeAccount) public onlyOwner { _feeAccount = feeAccount; } /** * @dev set set maker and taker fee rate * @param makerFeeRate maker fee rate can't be more than 0.5% * @param takerFeeRate taker fee rate can't be more than 0.5% */ function setFee(uint256 makerFeeRate,uint256 takerFeeRate) public onlyOwner { require(makerFeeRate <= 0.005 ether && takerFeeRate <= 0.005 ether,MAX_VALUE_LIMIT); _makerFeeRate = makerFeeRate; _takerFeeRate = takerFeeRate; } /** * @dev set gasStorage contract to save gas */ function setGasStorage(address gasStorage) public onlyOwner { _gasStorage = gasStorage; } /** * @dev set airdrop contract to implement airdrop function */ function setAirdrop(address airdrop) public onlyOwner{ _airdropContract = airdrop; } /** * @dev set withdraw application period * @param period the period can't be more than 10 days */ function setWithdrawalApplicationPeriod(uint period) public onlyOwner { if(period > 10 days ){ return; } _withdrawalApplicationPeriod = period; } /** * @dev invalid the orders before nonce */ function invalidateOrdersBefore(address user, uint256 nonce) public onlyRelayer { if (nonce < _invalidOrderNonce[user]) { revert(INVALID_NONCE); } _invalidOrderNonce[user] = nonce; } /** * @dev deposit token */ function depositToken(address token, uint256 amount) public { require(ERC20(token).transferFrom(msg.sender, address(this), amount),TRANSFER_FAILED); _deposit(msg.sender,token,amount); } /** * @dev deposit token from msg.sender to someone */ function depositTokenTo(address to,address token, uint256 amount) public { require(ERC20(token).transferFrom(msg.sender, address(this), amount),TRANSFER_FAILED); _deposit(to,token,amount); } /** * @dev deposit eth */ function deposit() public payable { _deposit(msg.sender,address(0),msg.value); } /** * @dev deposit eth from msg.sender to someone */ function depositTo(address to) public payable { _deposit(to,address(0),msg.value); } /** * @dev _deposit */ function _deposit(address user,address token,uint256 amount) internal { _balances[token][user] = _balances[token][user].add(amount); emit Deposit(token, user, amount, _balances[token][user]); } /** * @dev submit a withdrawal application, user can not place any orders after submit a withdrawal application */ function submitWithdrawApplication() public { _withdrawalApplication[msg.sender] = block.timestamp; emit WithdrawalApplication(msg.sender,block.timestamp); } /** * @dev cancel withdraw application */ function cancelWithdrawApplication() public { _withdrawalApplication[msg.sender] = 0; emit WithdrawalApplication(msg.sender,0); } /** * @dev check user withdraw application status */ function isWithdrawApplication(address user) view public returns(bool) { if(_withdrawalApplication[user] == uint(0)) { return false; } return true; } /** * @dev withdraw token */ function _withdraw(address from,address payable to,address token,uint256 amount) internal { if ( _balances[token][from] < amount) { revert(INSUFFICIENT_FOUND); } _balances[token][from] = _balances[token][from].sub(amount); if(token == address(0)) { to.transfer(amount); }else{ require(ERC20(token).transfer(to, amount),TRANSFER_FAILED); } emit Withdraw(token, from, to, amount, _balances[token][from]); } /** * @dev user withdraw token */ function withdraw(address token) public onlyWithdrawalApplicationApproved { uint256 amount = _balances[token][msg.sender]; if(amount != 0){ _withdraw(msg.sender,msg.sender,token,amount); } } /** * @dev user withdraw many tokens */ function withdrawAll(address[] memory tokens) public onlyWithdrawalApplicationApproved { for(uint256 i = 0; i< tokens.length ;i++){ uint256 amount = _balances[tokens[i]][msg.sender]; if(amount == 0){ continue; } _withdraw(msg.sender,msg.sender,tokens[i],amount); } } /** * @dev user send withdraw request with relayer's authorized signature */ function authorizedWithdraw(address payable to,address token,uint256 amount, uint256 nonce,uint expiredTime,address relayer,uint8 v, bytes32 r,bytes32 s) public { require(_withdrawalApplication[msg.sender] == uint(0)); require(expiredTime >= block.timestamp,INVALID_TIME); require(_relayers[relayer] == true,ONLY_RELAYER); bytes32 hash = keccak256(abi.encodePacked(msg.sender,to, token, amount, nonce, expiredTime)); if (_withdrawn[hash]) { revert(WITHDRAW_EXISTS); } _withdrawn[hash] = true; if (ecrecover(keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)), v, r, s) != relayer) { revert(ECRECOVER_FAILED); } _withdraw(msg.sender,to,token,amount); } /** * @dev withdraw the token from Dex Wallet to Etheruem Wallet,signType [0 = signTypeDataV3, 1 = eth_sign] */ function adminWithdraw(address from,address payable to,address token,uint256 amount,uint256 nonce,uint8 v,bytes32[2] memory rs, address feeToken,uint256 feeWithdrawal,uint timestamp,uint signType) public onlyRelayer { bytes32 hash = ecrecoverWithdraw(from,to,token,amount,nonce,v,rs,feeToken,feeWithdrawal,timestamp,signType); if (_withdrawn[hash]) { revert(WITHDRAW_EXISTS); } _withdrawn[hash] = true; _transfer(from,to,token,amount,feeToken,feeWithdrawal,false); } /** * @dev transfer the token between Dex Wallet,signType [0 = signTypeDataV3, 1 = eth_sign] */ function adminTransfer(address from,address payable to,address token,uint256 amount,uint256 nonce,uint8 v,bytes32[2] memory rs, address feeToken,uint256 feeWithdrawal,uint timestamp,uint signType) public onlyRelayer { bytes32 hash = ecrecoverWithdraw(from,to,token,amount,nonce,v,rs,feeToken,feeWithdrawal,timestamp,signType); if (_withdrawn[hash]) { revert(WITHDRAW_EXISTS); } _withdrawn[hash] = true; _transfer(from,to,token,amount,feeToken,feeWithdrawal,true); } /** * @dev transfer the token * @param from token sender * @param to token receiver * @param token The address of token to transfer * @param amount The amount to transfer * @param feeToken The address of token to pay the fee * @param feeWithdrawal The amount of feeToken to pay the fee * @param isInternal True is transfer token from a Dex Wallet to a Dex Wallet, False is transfer a token from Dex wallet to a Etheruem Wallet */ function _transfer(address from,address payable to,address token,uint256 amount, address feeToken,uint256 feeWithdrawal, bool isInternal) internal { if (feeWithdrawal > 0) { require(_balances[feeToken][from] >= feeWithdrawal, INSUFFICIENT_FOUND ); _balances[feeToken][from] = _balances[feeToken][from].sub(feeWithdrawal); _balances[feeToken][_feeAccount] = _balances[feeToken][_feeAccount].add(feeWithdrawal); } if ( _balances[token][from] < amount) { revert(INSUFFICIENT_FOUND); } _balances[token][from] = _balances[token][from].sub(amount); if(isInternal) { _balances[token][to] = _balances[token][to].add(amount); emit Transfer(token, from, to, amount, _balances[token][from], _balances[token][to]); }else{ if(token == address(0)) { to.transfer(amount); }else{ require(ERC20(token).transfer(to, amount),TRANSFER_FAILED); } emit Withdraw(token, from, to, amount, _balances[token][from]); } } /** * @dev mirgate function will withdraw all user token balances to wallet */ function adminWithdrawAll(address payable user,address[] memory tokens) public onlyOwner { for(uint256 i = 0; i< tokens.length ;i++){ address token = tokens[i]; uint256 amount = _balances[token][user]; if(amount == 0){ continue; } _withdraw(user,user,token,amount); } } /** * @dev get the balance of the account */ function balanceOf(address token, address user) public view returns (uint256) { return _balances[token][user]; } /** * @dev trade order only call by relayer, ti.signType: 0 = signTypeDataV3, 1 = eth_sign */ function tradeOrder(Order memory taker,Order memory maker, TradeInfo memory ti) public onlyRelayer { uint256 gasInitial = gasleft(); bytes32 takerHash = ecrecoverOrder(taker,taker.signType); bytes32 makerHash = ecrecoverOrder(maker,maker.signType); bytes32 tradeHash = keccak256(abi.encodePacked(takerHash ,makerHash)); require(_traded[tradeHash] == false,TRADE_EXISTS); _traded[tradeHash] = true; _tradeOrder(taker,maker,ti,takerHash,makerHash); uint256 gasUsed = gasInitial - gasleft(); _burnGas(gasUsed); } /** * @dev trade order internal */ function _tradeOrder(Order memory taker,Order memory maker, TradeInfo memory ti, bytes32 takerHash,bytes32 makerHash) internal { require(taker.baseToken == maker.baseToken && taker.token == maker.token); require(ti.tradeTokenAmount > 0 , INVALID_AMOUNT ); require((block.timestamp <= taker.expireTime) && (block.timestamp <= maker.expireTime) , INVALID_TIME ); require( (_invalidOrderNonce[taker.user] < taker.nonce) &&(_invalidOrderNonce[maker.user] < maker.nonce),INVALID_NONCE) ; require( (taker.tokenAmount.sub(_orderFills[takerHash]) >= ti.tradeTokenAmount) && (maker.tokenAmount.sub(_orderFills[makerHash]) >= ti.tradeTokenAmount), AMOUNT_EXCEEDED); require(taker.gasToken == ti.tradeGasToken, INVALID_GASTOKEN); uint256 tradeBaseTokenAmount = ti.tradeTokenAmount.mul(maker.baseTokenAmount).div(maker.tokenAmount); (uint256 takerFee,uint256 makerFee) = calcMaxFee(ti,tradeBaseTokenAmount,maker.sell); uint gasFee = ti.tradeGasFee; if(gasFee != 0) { if( taker.maxGasFee < _orderGasFee[takerHash].add(gasFee)) { gasFee = taker.maxGasFee.sub(_orderGasFee[takerHash]); } if(gasFee != 0) { _orderGasFee[takerHash] = _orderGasFee[takerHash].add(gasFee); _balances[taker.gasToken][taker.user] = _balances[taker.gasToken][taker.user].sub(gasFee); } } if( maker.sell) { //maker is seller _updateOrderBalance(taker.user,maker.user,taker.baseToken,taker.token, tradeBaseTokenAmount,ti.tradeTokenAmount,takerFee,makerFee); }else { //maker is buyer _updateOrderBalance(maker.user,taker.user,taker.baseToken,taker.token, tradeBaseTokenAmount,ti.tradeTokenAmount,makerFee,takerFee); } //fill order _orderFills[takerHash] = _orderFills[takerHash].add(ti.tradeTokenAmount); _orderFills[makerHash] = _orderFills[makerHash].add(ti.tradeTokenAmount); emit Trade(takerHash,makerHash,ti.tradeTokenAmount,tradeBaseTokenAmount,ti.tradeNonce,takerFee,makerFee, maker.sell ,gasFee); emit Balance(_balances[taker.baseToken][taker.user],_balances[taker.token][taker.user],_balances[maker.baseToken][maker.user],_balances[maker.token][maker.user]); } /** * @dev update the balance after each order traded */ function _updateOrderBalance(address buyer,address seller,address base,address token,uint256 baseAmount,uint256 amount,uint256 buyFee,uint256 sellFee) internal { _balances[base][seller] = _balances[base][seller].add(baseAmount.sub(sellFee)); _balances[base][buyer] = _balances[base][buyer].sub(baseAmount); _balances[token][buyer] = _balances[token][buyer].add(amount.sub(buyFee)); _balances[token][seller] = _balances[token][seller].sub(amount); _balances[base][_feeAccount] = _balances[base][_feeAccount].add(sellFee); _balances[token][_feeAccount] = _balances[token][_feeAccount].add(buyFee); } /** * @dev calc max fee for maker and taker * @return return a taker and maker fee limit by _takerFeeRate and _makerFeeRate */ function calcMaxFee(TradeInfo memory ti,uint256 tradeBaseTokenAmount,bool sellerIsMaker) view public returns (uint256 takerFee,uint256 makerFee) { uint maxTakerFee; uint maxMakerFee; takerFee = ti.tradeTakerFee; makerFee = ti.tradeMakerFee; if(sellerIsMaker) { // taker is buyer maxTakerFee = (ti.tradeTokenAmount * _takerFeeRate) / 1 ether; maxMakerFee = (tradeBaseTokenAmount * _makerFeeRate) / 1 ether; }else{ // maker is buyer maxTakerFee = (tradeBaseTokenAmount * _takerFeeRate) / 1 ether; maxMakerFee = (ti.tradeTokenAmount * _makerFeeRate) / 1 ether; } if(ti.tradeTakerFee > maxTakerFee) { takerFee = maxTakerFee; } if(ti.tradeMakerFee > maxMakerFee) { makerFee = maxMakerFee; } } /** * @dev get fee Rate */ function getFeeRate() view public returns(uint256 makerFeeRate,uint256 takerFeeRate) { return (_makerFeeRate,_takerFeeRate); } /** * @dev get order filled amount * @param orderHash the order hash * @return return the filled amount for a order */ function getOrderFills(bytes32 orderHash) view public returns(uint256 filledAmount) { return _orderFills[orderHash]; } ///@dev check orders traded function isTraded(bytes32 buyOrderHash,bytes32 sellOrderHash) view public returns(bool traded) { return _traded[keccak256(abi.encodePacked(buyOrderHash, sellOrderHash))]; } /** * @dev Airdrop the token directly to Dex user's walle,only airdrop contract can call this function. * @param to the recipient * @param token the ERC20 token to send * @param amount the token amount to send */ function airdrop(address to,address token,uint256 amount) public onlyAirdropContract { //Not EOA require(tx.origin != msg.sender); require(_balances[token][msg.sender] >= amount ,INSUFFICIENT_FOUND); _balances[token][msg.sender] = _balances[token][msg.sender].sub(amount); _balances[token][to] = _balances[token][to].add(amount); emit Airdrop(to,token,amount); } /** * @dev ecreover the order sign * @return return a order hash */ function ecrecoverOrder(Order memory order,uint signType) public pure returns (bytes32 orderHash) { if(signType == 0 ) { orderHash = keccak256(abi.encode( ORDER_TYPEHASH, order.token,order.baseToken,order.tokenAmount,order.baseTokenAmount,order.nonce,order.sell,order.expireTime,order.maxGasFee,order.gasToken,order.timestamp)); if (ecrecover(keccak256(abi.encodePacked("\x19\x01",DOMAIN_SEPARATOR,orderHash)),order.V,order.R, order.S) != order.user) { revert(ECRECOVER_FAILED); } }else { orderHash = keccak256(abi.encodePacked(order.token,order.baseToken,order.tokenAmount,order.baseTokenAmount,order.nonce,order.sell,order.expireTime,order.maxGasFee,order.gasToken,order.timestamp)); if(ecrecover(keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32",orderHash)),order.V,order.R, order.S) != order.user) { revert(ECRECOVER_FAILED); } } } /** * @dev ecrecover the withdraw sign * @return return a withdraw hash */ function ecrecoverWithdraw(address from,address payable to,address token,uint256 amount,uint256 nonce,uint8 v,bytes32[2] memory rs, address feeToken,uint256 feeWithdrawal,uint timestamp,uint signType) public pure returns (bytes32 orderHash) { if(signType == 1 ) { orderHash = keccak256(abi.encodePacked(token, amount, to, nonce,feeToken,feeWithdrawal,timestamp)); if (ecrecover(keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", orderHash)), v, rs[0], rs[1]) != from) { revert(ECRECOVER_FAILED); } } else { orderHash = keccak256(abi.encode(WITHDRAW_TYPEHASH,token, amount, to, nonce,feeToken,feeWithdrawal,timestamp)); if (ecrecover(keccak256(abi.encodePacked("\x19\x01",DOMAIN_SEPARATOR,orderHash)), v, rs[0], rs[1]) != from) { revert(ECRECOVER_FAILED); } } } /** * @dev burn the stored gastoken * @param gasUsed The gas uesed to calc the gastoken to burn */ function _burnGas(uint gasUsed) internal { if(_gasStorage == address(0x0)){ return; } IGasStorage(_gasStorage).burn(gasUsed); } }
* @dev set account that receive the fee/
function setFeeAccount(address feeAccount) public onlyOwner { _feeAccount = feeAccount; }
1,805,284
[ 1, 542, 2236, 716, 6798, 326, 14036, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 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, 444, 14667, 3032, 12, 2867, 14036, 3032, 13, 1071, 1338, 5541, 288, 203, 3639, 389, 21386, 3032, 273, 14036, 3032, 31, 203, 565, 289, 203, 7010, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x936dF79234533F9A7765841653E2e191441A9Ee2/sources/contracts/HoneyBBToken.sol
start from 1 to avoid swap on first tx
uint256 public transferTxCount = 1;
4,482,003
[ 1, 1937, 628, 404, 358, 4543, 7720, 603, 1122, 2229, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 5034, 1071, 7412, 4188, 1380, 273, 404, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.24; /* * -PlayerBook - v0.3.14 * ┌┬┐┌─┐┌─┐┌┬┐ ╦╦ ╦╔═╗╔╦╗ ┌─┐┬─┐┌─┐┌─┐┌─┐┌┐┌┌┬┐┌─┐ * │ ├┤ ├─┤│││ ║║ ║╚═╗ ║ ├─┘├┬┘├┤ └─┐├┤ │││ │ └─┐ * ┴ └─┘┴ ┴┴ ┴ ╚╝╚═╝╚═╝ ╩ ┴ ┴└─└─┘└─┘└─┘┘└┘ ┴ └─┘ * _____ _____ * (, / /) /) /) (, / /) /) * ┌─┐ / _ (/_ // // / _ // _ __ _(/ * ├─┤ ___/___(/_/(__(_/_(/_(/_ ___/__/_)_(/_(_(_/ (_(_(_ * ┴ ┴ / / .-/ _____ (__ / * (__ / (_/ (, / /)™ * / __ __ __ __ _ __ __ _ _/_ _ _(/ * ┌─┐┬─┐┌─┐┌┬┐┬ ┬┌─┐┌┬┐ /__/ (_(__(_)/ (_/_)_(_)/ (_(_(_(__(/_(_(_ * ├─┘├┬┘│ │ │││ ││ │ (__ / .-/ © Jekyll Island Inc. 2018 * ┴ ┴└─└─┘─┴┘└─┘└─┘ ┴ (_/ * ______ _ ______ _ *====(_____ \=| |===============================(____ \===============| |=============* * _____) )| | _____ _ _ _____ ____ ____) ) ___ ___ | | _ * | ____/ | | (____ || | | || ___ | / ___) | __ ( / _ \ / _ \ | |_/ ) * | | | | / ___ || |_| || ____|| | | |__) )| |_| || |_| || _ ( *====|_|=======\_)\_____|=\__ ||_____)|_|======|______/==\___/==\___/=|_|=\_)=========* * (____/ * ╔═╗┌─┐┌┐┌┌┬┐┬─┐┌─┐┌─┐┌┬┐ ╔═╗┌─┐┌┬┐┌─┐ ┌──────────┐ * ║ │ ││││ │ ├┬┘├─┤│ │ ║ │ │ ││├┤ │ Inventor │ * ╚═╝└─┘┘└┘ ┴ ┴└─┴ ┴└─┘ ┴ ╚═╝└─┘─┴┘└─┘ └──────────┘ */ import "./library/SafeMath.sol"; import "./library/NameFilter.sol"; import "./library/MSFun.sol"; import "./interface/TeamJustInterface.sol"; import "./interface/PlayerBookReceiverInterface.sol"; import "./interface/PlayerBookInterface.sol"; import "./TeamJust.sol"; contract PlayerBook is PlayerBookInterface { using NameFilter for string; using SafeMath for uint256; address private Jekyll_Island_Inc; address public teamJust; // = new TeamJustInterface(); MSFun.Data private msData; function multiSigDev(bytes32 _whatFunction) private returns (bool) { return ( MSFun.multiSig( msData, TeamJustInterface(teamJust).requiredDevSignatures(), _whatFunction ) ); } function deleteProposal(bytes32 _whatFunction) private { MSFun.deleteProposal(msData, _whatFunction); } function deleteAnyProposal(bytes32 _whatFunction) public onlyDevs() { MSFun.deleteProposal(msData, _whatFunction); } function checkData(bytes32 _whatFunction) public view onlyDevs() returns (bytes32, uint256) { return ( MSFun.checkMsgData(msData, _whatFunction), MSFun.checkCount(msData, _whatFunction) ); } function checkSignersByAddress( bytes32 _whatFunction, uint256 _signerA, uint256 _signerB, uint256 _signerC ) public view onlyDevs() returns ( address, address, address ) { return ( MSFun.checkSigner(msData, _whatFunction, _signerA), MSFun.checkSigner(msData, _whatFunction, _signerB), MSFun.checkSigner(msData, _whatFunction, _signerC) ); } function checkSignersByName( bytes32 _whatFunction, uint256 _signerA, uint256 _signerB, uint256 _signerC ) public view onlyDevs() returns ( bytes32, bytes32, bytes32 ) { return ( TeamJustInterface(teamJust).adminName( MSFun.checkSigner(msData, _whatFunction, _signerA) ), TeamJustInterface(teamJust).adminName( MSFun.checkSigner(msData, _whatFunction, _signerB) ), TeamJustInterface(teamJust).adminName( MSFun.checkSigner(msData, _whatFunction, _signerC) ) ); } //============================================================================== // _| _ _|_ _ _ _ _|_ _ . // (_|(_| | (_| _\(/_ | |_||_) . //=============================|================================================ uint256 public registrationFee_ = 10 finney; // price to register a name mapping(uint256 => address) public games_; // mapping of our game interfaces for sending your account info to games mapping(address => bytes32) public gameNames_; // lookup a games name mapping(address => uint256) public gameIDs_; // lokup a games ID uint256 public gID_; // total number of games uint256 public pID_; // total number of players mapping(address => uint256) public pIDxAddr_; // (addr => pID) returns player id by address mapping(bytes32 => uint256) public pIDxName_; // (name => pID) returns player id by name mapping(uint256 => Player) public plyr_; // (pID => data) player data mapping(uint256 => mapping(bytes32 => bool)) public plyrNames_; // (pID => name => bool) list of names a player owns. (used so you can change your display name amoungst any name you own) mapping(uint256 => mapping(uint256 => bytes32)) public plyrNameList_; // (pID => nameNum => name) list of names a player owns struct Player { address addr; bytes32 name; uint256 laff; uint256 names; } address public owner; function setTeam(address _teamJust) external { require(msg.sender == owner, "only dev!"); require(address(teamJust) == address(0), "already set!"); teamJust = _teamJust; } //============================================================================== // _ _ _ __|_ _ __|_ _ _ . // (_(_)| |_\ | | |_|(_ | (_)| . (initial data setup upon contract deploy) //============================================================================== constructor() public { owner = msg.sender; // premine the dev names (sorry not sorry) // No keys are purchased with this method, it's simply locking our addresses, // PID's and names for referral codes. plyr_[1].addr = msg.sender; plyr_[1].name = "wq"; plyr_[1].names = 1; pIDxAddr_[msg.sender] = 1; pIDxName_["wq"] = 1; plyrNames_[1]["wq"] = true; plyrNameList_[1][1] = "wq"; pID_ = 1; Jekyll_Island_Inc = msg.sender; } //============================================================================== // _ _ _ _|. |`. _ _ _ . // | | |(_)(_||~|~|(/_| _\ . (these are safety checks) //============================================================================== /** * @dev prevents contracts from interacting with fomo3d */ modifier isHuman() { address _addr = msg.sender; uint256 _codeLength; assembly { _codeLength := extcodesize(_addr) } require(_codeLength == 0, "sorry humans only"); _; } modifier onlyDevs() { require( TeamJustInterface(teamJust).isDev(msg.sender) == true, "msg sender is not a dev" ); _; } modifier isRegisteredGame() { require(gameIDs_[msg.sender] != 0); _; } //============================================================================== // _ _ _ _|_ _ . // (/_\/(/_| | | _\ . //============================================================================== // fired whenever a player registers a name event onNewName( uint256 indexed playerID, address indexed playerAddress, bytes32 indexed playerName, bool isNewPlayer, uint256 affiliateID, address affiliateAddress, bytes32 affiliateName, uint256 amountPaid, uint256 timeStamp ); //============================================================================== // _ _ _|__|_ _ _ _ . // (_|(/_ | | (/_| _\ . (for UI & viewing things on etherscan) //=====_|======================================================================= function checkIfNameValid(string _nameStr) public view returns (bool) { bytes32 _name = _nameStr.nameFilter(); if (pIDxName_[_name] == 0) return (true); else return (false); } //============================================================================== // _ |_ |. _ |` _ __|_. _ _ _ . // |_)|_||_)||(_ ~|~|_|| |(_ | |(_)| |_\ . (use these to interact with contract) //====|========================================================================= /** * @dev registers a name. UI will always display the last name you registered. * but you will still own all previously registered names to use as affiliate * links. * - must pay a registration fee. * - name must be unique * - names will be converted to lowercase * - name cannot start or end with a space * - cannot have more than 1 space in a row * - cannot be only numbers * - cannot start with 0x * - name must be at least 1 char * - max length of 32 characters long * - allowed characters: a-z, 0-9, and space * -functionhash- 0x921dec21 (using ID for affiliate) * -functionhash- 0x3ddd4698 (using address for affiliate) * -functionhash- 0x685ffd83 (using name for affiliate) * @param _nameString players desired name * @param _affCode affiliate ID, address, or name of who refered you * @param _all set to true if you want this to push your info to all games * (this might cost a lot of gas) */ function registerNameXID( string _nameString, uint256 _affCode, bool _all ) public payable isHuman() { // make sure name fees paid require( msg.value >= registrationFee_, "umm..... you have to pay the name fee" ); // filter name + condition checks bytes32 _name = NameFilter.nameFilter(_nameString); // set up address address _addr = msg.sender; // set up our tx event data and determine if player is new or not bool _isNewPlayer = determinePID(_addr); // fetch player id uint256 _pID = pIDxAddr_[_addr]; // manage affiliate residuals // if no affiliate code was given, no new affiliate code was given, or the // player tried to use their own pID as an affiliate code, lolz if (_affCode != 0 && _affCode != plyr_[_pID].laff && _affCode != _pID) { // update last affiliate plyr_[_pID].laff = _affCode; } else if (_affCode == _pID) { _affCode = 0; } // register name registerNameCore(_pID, _addr, _affCode, _name, _isNewPlayer, _all); } function registerNameXaddr( string _nameString, address _affCode, bool _all ) public payable isHuman() { // make sure name fees paid require( msg.value >= registrationFee_, "umm..... you have to pay the name fee" ); // filter name + condition checks bytes32 _name = NameFilter.nameFilter(_nameString); // set up address address _addr = msg.sender; // set up our tx event data and determine if player is new or not bool _isNewPlayer = determinePID(_addr); // fetch player id uint256 _pID = pIDxAddr_[_addr]; // manage affiliate residuals // if no affiliate code was given or player tried to use their own, lolz uint256 _affID; if (_affCode != address(0) && _affCode != _addr) { // get affiliate ID from aff Code _affID = pIDxAddr_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // register name registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all); } function registerNameXname( string _nameString, bytes32 _affCode, bool _all ) public payable isHuman() { // make sure name fees paid require( msg.value >= registrationFee_, "umm..... you have to pay the name fee" ); // filter name + condition checks bytes32 _name = NameFilter.nameFilter(_nameString); // set up address address _addr = msg.sender; // set up our tx event data and determine if player is new or not bool _isNewPlayer = determinePID(_addr); // fetch player id uint256 _pID = pIDxAddr_[_addr]; // manage affiliate residuals // if no affiliate code was given or player tried to use their own, lolz uint256 _affID; if (_affCode != "" && _affCode != _name) { // get affiliate ID from aff Code _affID = pIDxName_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // register name registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all); } /** * @dev players, if you registered a profile, before a game was released, or * set the all bool to false when you registered, use this function to push * your profile to a single game. also, if you've updated your name, you * can use this to push your name to games of your choosing. * -functionhash- 0x81c5b206 * @param _gameID game id */ function addMeToGame(uint256 _gameID) public isHuman() { require(_gameID <= gID_, "silly player, that game doesn't exist yet"); address _addr = msg.sender; uint256 _pID = pIDxAddr_[_addr]; require(_pID != 0, "hey there buddy, you dont even have an account"); uint256 _totalNames = plyr_[_pID].names; // add players profile and most recent name PlayerBookReceiverInterface(games_[_gameID]).receivePlayerInfo( _pID, _addr, plyr_[_pID].name, plyr_[_pID].laff ); // add list of all names if (_totalNames > 1) for (uint256 ii = 1; ii <= _totalNames; ii++) PlayerBookReceiverInterface(games_[_gameID]) .receivePlayerNameList(_pID, plyrNameList_[_pID][ii]); } /** * @dev players, use this to push your player profile to all registered games. * -functionhash- 0x0c6940ea */ function addMeToAllGames() public isHuman() { address _addr = msg.sender; uint256 _pID = pIDxAddr_[_addr]; require(_pID != 0, "hey there buddy, you dont even have an account"); uint256 _laff = plyr_[_pID].laff; uint256 _totalNames = plyr_[_pID].names; bytes32 _name = plyr_[_pID].name; for (uint256 i = 1; i <= gID_; i++) { PlayerBookReceiverInterface(games_[i]).receivePlayerInfo( _pID, _addr, _name, _laff ); if (_totalNames > 1) for (uint256 ii = 1; ii <= _totalNames; ii++) PlayerBookReceiverInterface(games_[i]) .receivePlayerNameList(_pID, plyrNameList_[_pID][ii]); } } /** * @dev players use this to change back to one of your old names. tip, you'll * still need to push that info to existing games. * -functionhash- 0xb9291296 * @param _nameString the name you want to use */ function useMyOldName(string _nameString) public isHuman() { // filter name, and get pID bytes32 _name = _nameString.nameFilter(); uint256 _pID = pIDxAddr_[msg.sender]; // make sure they own the name require( plyrNames_[_pID][_name] == true, "umm... thats not a name you own" ); // update their current name plyr_[_pID].name = _name; } //============================================================================== // _ _ _ _ | _ _ . _ . // (_(_)| (/_ |(_)(_||(_ . //=====================_|======================================================= function registerNameCore( uint256 _pID, address _addr, uint256 _affID, bytes32 _name, bool _isNewPlayer, bool _all ) private { // if names already has been used, require that current msg sender owns the name if (pIDxName_[_name] != 0) require( plyrNames_[_pID][_name] == true, "sorry that names already taken" ); // add name to player profile, registry, and name book plyr_[_pID].name = _name; pIDxName_[_name] = _pID; if (plyrNames_[_pID][_name] == false) { plyrNames_[_pID][_name] = true; plyr_[_pID].names++; plyrNameList_[_pID][plyr_[_pID].names] = _name; } // registration fee goes directly to community rewards Jekyll_Island_Inc.transfer(address(this).balance); // push player info to games if (_all == true) for (uint256 i = 1; i <= gID_; i++) PlayerBookReceiverInterface(games_[i]).receivePlayerInfo( _pID, _addr, _name, _affID ); // fire event emit onNewName( _pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, msg.value, now ); } //============================================================================== // _|_ _ _ | _ . // | (_)(_)|_\ . //============================================================================== function determinePID(address _addr) private returns (bool) { if (pIDxAddr_[_addr] == 0) { pID_++; pIDxAddr_[_addr] = pID_; plyr_[pID_].addr = _addr; // set the new player bool to true return (true); } else { return (false); } } //============================================================================== // _ _|_ _ _ _ _ | _ _ || _ . // (/_>< | (/_| | |(_|| (_(_|||_\ . //============================================================================== function getPlayerID(address _addr) external isRegisteredGame() returns (uint256) { determinePID(_addr); return (pIDxAddr_[_addr]); } function getPlayerName(uint256 _pID) external view returns (bytes32) { return (plyr_[_pID].name); } function getPlayerLAff(uint256 _pID) external view returns (uint256) { return (plyr_[_pID].laff); } function getPlayerAddr(uint256 _pID) external view returns (address) { return (plyr_[_pID].addr); } function getNameFee() external view returns (uint256) { return (registrationFee_); } function registerNameXIDFromDapp( address _addr, bytes32 _name, uint256 _affCode, bool _all ) external payable isRegisteredGame() returns (bool, uint256) { // make sure name fees paid require( msg.value >= registrationFee_, "umm..... you have to pay the name fee" ); // set up our tx event data and determine if player is new or not bool _isNewPlayer = determinePID(_addr); // fetch player id uint256 _pID = pIDxAddr_[_addr]; // manage affiliate residuals // if no affiliate code was given, no new affiliate code was given, or the // player tried to use their own pID as an affiliate code, lolz uint256 _affID = _affCode; if (_affID != 0 && _affID != plyr_[_pID].laff && _affID != _pID) { // update last affiliate plyr_[_pID].laff = _affID; } else if (_affID == _pID) { _affID = 0; } // register name registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all); return (_isNewPlayer, _affID); } function registerNameXaddrFromDapp( address _addr, bytes32 _name, address _affCode, bool _all ) external payable isRegisteredGame() returns (bool, uint256) { // make sure name fees paid require( msg.value >= registrationFee_, "umm..... you have to pay the name fee" ); // set up our tx event data and determine if player is new or not bool _isNewPlayer = determinePID(_addr); // fetch player id uint256 _pID = pIDxAddr_[_addr]; // manage affiliate residuals // if no affiliate code was given or player tried to use their own, lolz uint256 _affID; if (_affCode != address(0) && _affCode != _addr) { // get affiliate ID from aff Code _affID = pIDxAddr_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // register name registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all); return (_isNewPlayer, _affID); } function registerNameXnameFromDapp( address _addr, bytes32 _name, bytes32 _affCode, bool _all ) external payable isRegisteredGame() returns (bool, uint256) { // make sure name fees paid require( msg.value >= registrationFee_, "umm..... you have to pay the name fee" ); // set up our tx event data and determine if player is new or not bool _isNewPlayer = determinePID(_addr); // fetch player id uint256 _pID = pIDxAddr_[_addr]; // manage affiliate residuals // if no affiliate code was given or player tried to use their own, lolz uint256 _affID; if (_affCode != "" && _affCode != _name) { // get affiliate ID from aff Code _affID = pIDxName_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // register name registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all); return (_isNewPlayer, _affID); } //============================================================================== // _ _ _|_ _ . // _\(/_ | |_||_) . //=============|================================================================ function addGame(address _gameAddress, bytes32 _gameNameStr) external onlyDevs() { require( gameIDs_[_gameAddress] == 0, "derp, that games already been registered" ); if (multiSigDev("addGame") == true) { deleteProposal("addGame"); gID_++; bytes32 _name = _gameNameStr; gameIDs_[_gameAddress] = gID_; gameNames_[_gameAddress] = _name; games_[gID_] = _gameAddress; // PlayerBookReceiverInterface(games_[gID_]).receivePlayerInfo(1, plyr_[1].addr, plyr_[1].name, 0); } } function setRegistrationFee(uint256 _fee) public onlyDevs() { if (multiSigDev("setRegistrationFee") == true) { deleteProposal("setRegistrationFee"); registrationFee_ = _fee; } } function isDev(address _who) external view returns (bool) { return TeamJustInterface(teamJust).isDev(_who); } }
============================================================================== _ _ _|_ _ . _\(/_ | |_||_) .=============|================================================================ PlayerBookReceiverInterface(games_[gID_]).receivePlayerInfo(1, plyr_[1].addr, plyr_[1].name, 0);
function addGame(address _gameAddress, bytes32 _gameNameStr) external onlyDevs() { require( gameIDs_[_gameAddress] == 0, "derp, that games already been registered" ); if (multiSigDev("addGame") == true) { deleteProposal("addGame"); gID_++; bytes32 _name = _gameNameStr; gameIDs_[_gameAddress] = gID_; gameNames_[_gameAddress] = _name; games_[gID_] = _gameAddress; } }
997,511
[ 1, 9917, 26678, 282, 389, 389, 389, 96, 67, 565, 389, 282, 263, 225, 389, 30351, 18510, 571, 571, 67, 20081, 67, 13, 225, 263, 14468, 33, 96, 9917, 5411, 19185, 9084, 12952, 1358, 12, 75, 753, 67, 63, 75, 734, 67, 65, 2934, 18149, 12148, 966, 12, 21, 16, 293, 715, 86, 67, 63, 21, 8009, 4793, 16, 293, 715, 86, 67, 63, 21, 8009, 529, 16, 374, 1769, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 527, 12496, 12, 2867, 389, 13957, 1887, 16, 1731, 1578, 389, 13957, 461, 1585, 13, 203, 3639, 3903, 203, 3639, 1338, 758, 6904, 1435, 203, 565, 288, 203, 3639, 2583, 12, 203, 5411, 7920, 5103, 67, 63, 67, 13957, 1887, 65, 422, 374, 16, 203, 5411, 315, 765, 84, 16, 716, 28422, 1818, 2118, 4104, 6, 203, 3639, 11272, 203, 203, 3639, 309, 261, 7027, 8267, 8870, 2932, 1289, 12496, 7923, 422, 638, 13, 288, 203, 5411, 1430, 14592, 2932, 1289, 12496, 8863, 203, 5411, 314, 734, 67, 9904, 31, 203, 5411, 1731, 1578, 389, 529, 273, 389, 13957, 461, 1585, 31, 203, 5411, 7920, 5103, 67, 63, 67, 13957, 1887, 65, 273, 314, 734, 67, 31, 203, 5411, 7920, 1557, 67, 63, 67, 13957, 1887, 65, 273, 389, 529, 31, 203, 5411, 28422, 67, 63, 75, 734, 67, 65, 273, 389, 13957, 1887, 31, 203, 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 ]
./full_match/1/0xd5324D3e0Fe24FaB2f05fd70b342aA209119E568/sources/contracts/PermissionedExecutors.sol
@dev To transfer out any ERC20s received
function transfer( IERC20 _token, address _recipient, uint256 _amount ) external onlyOwner { _token.transfer(_recipient, _amount); }
16,475,760
[ 1, 774, 7412, 596, 1281, 4232, 39, 3462, 87, 5079, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 7412, 12, 203, 3639, 467, 654, 39, 3462, 389, 2316, 16, 203, 3639, 1758, 389, 20367, 16, 203, 3639, 2254, 5034, 389, 8949, 203, 565, 262, 3903, 1338, 5541, 288, 203, 3639, 389, 2316, 18, 13866, 24899, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0x73D6df4395CD54DF2E07fD3880c1B47Aeb2Aed97/sources/StrategyCurveRenBTC.sol
* @dev Earning strategy that accepts renCRV, earns CRV and converts CRV back to renCRV as yield./
contract StrategyCurveRenBTC is IStrategy { using SafeERC20 for IERC20; using SafeMath for uint256; event Harvested(address indexed token, uint256 amount); address public vault; } constructor(address _vault) public { require(_vault != address(0x0), "vault not set"); vault = _vault; } function deposit() public override { uint256 _want = IERC20(want).balanceOf(address(this)); if (_want > 0) { IERC20(want).safeApprove(pool, 0); IERC20(want).safeApprove(pool, _want); ICurveGauge(pool).deposit(_want); } } function deposit() public override { uint256 _want = IERC20(want).balanceOf(address(this)); if (_want > 0) { IERC20(want).safeApprove(pool, 0); IERC20(want).safeApprove(pool, _want); ICurveGauge(pool).deposit(_want); } } function withdraw(uint256 _amount) public override { require(msg.sender == vault, "not vault"); uint256 _balance = IERC20(want).balanceOf(address(this)); if (_balance < _amount) { _amount = _withdrawSome(_amount.sub(_balance)); _amount = _amount.add(_balance); } IERC20(want).safeTransfer(vault, _amount); } function withdraw(uint256 _amount) public override { require(msg.sender == vault, "not vault"); uint256 _balance = IERC20(want).balanceOf(address(this)); if (_balance < _amount) { _amount = _withdrawSome(_amount.sub(_balance)); _amount = _amount.add(_balance); } IERC20(want).safeTransfer(vault, _amount); } function withdrawAll() public override returns (uint256 balance) { require(msg.sender == vault, "not vault"); ICurveGauge(pool).withdraw(ICurveGauge(pool).balanceOf(address(this))); balance = IERC20(want).balanceOf(address(this)); IERC20(want).safeTransfer(vault, balance); } function harvest() public override { require(msg.sender == vault, "not vault"); ICurveMinter(mintr).mint(pool); uint256 _crv = IERC20(crv).balanceOf(address(this)); if (_crv > 0) { IERC20(crv).safeApprove(uni, 0); IERC20(crv).safeApprove(uni, _crv); address[] memory path = new address[](3); path[0] = crv; path[1] = weth; path[2] = wbtc; IUniswapRouter(uni).swapExactTokensForTokens(_crv, uint256(0), path, address(this), now.add(1800)); } if (_wbtc > 0) { IERC20(wbtc).safeApprove(curve, 0); IERC20(wbtc).safeApprove(curve, _wbtc); ICurveFi(curve).add_liquidity([0, _wbtc], 0); } uint256 _want = IERC20(want).balanceOf(address(this)); if (_want > 0) { deposit(); } emit Harvested(want, _want); } function harvest() public override { require(msg.sender == vault, "not vault"); ICurveMinter(mintr).mint(pool); uint256 _crv = IERC20(crv).balanceOf(address(this)); if (_crv > 0) { IERC20(crv).safeApprove(uni, 0); IERC20(crv).safeApprove(uni, _crv); address[] memory path = new address[](3); path[0] = crv; path[1] = weth; path[2] = wbtc; IUniswapRouter(uni).swapExactTokensForTokens(_crv, uint256(0), path, address(this), now.add(1800)); } if (_wbtc > 0) { IERC20(wbtc).safeApprove(curve, 0); IERC20(wbtc).safeApprove(curve, _wbtc); ICurveFi(curve).add_liquidity([0, _wbtc], 0); } uint256 _want = IERC20(want).balanceOf(address(this)); if (_want > 0) { deposit(); } emit Harvested(want, _want); } uint256 _wbtc = IERC20(wbtc).balanceOf(address(this)); function harvest() public override { require(msg.sender == vault, "not vault"); ICurveMinter(mintr).mint(pool); uint256 _crv = IERC20(crv).balanceOf(address(this)); if (_crv > 0) { IERC20(crv).safeApprove(uni, 0); IERC20(crv).safeApprove(uni, _crv); address[] memory path = new address[](3); path[0] = crv; path[1] = weth; path[2] = wbtc; IUniswapRouter(uni).swapExactTokensForTokens(_crv, uint256(0), path, address(this), now.add(1800)); } if (_wbtc > 0) { IERC20(wbtc).safeApprove(curve, 0); IERC20(wbtc).safeApprove(curve, _wbtc); ICurveFi(curve).add_liquidity([0, _wbtc], 0); } uint256 _want = IERC20(want).balanceOf(address(this)); if (_want > 0) { deposit(); } emit Harvested(want, _want); } function harvest() public override { require(msg.sender == vault, "not vault"); ICurveMinter(mintr).mint(pool); uint256 _crv = IERC20(crv).balanceOf(address(this)); if (_crv > 0) { IERC20(crv).safeApprove(uni, 0); IERC20(crv).safeApprove(uni, _crv); address[] memory path = new address[](3); path[0] = crv; path[1] = weth; path[2] = wbtc; IUniswapRouter(uni).swapExactTokensForTokens(_crv, uint256(0), path, address(this), now.add(1800)); } if (_wbtc > 0) { IERC20(wbtc).safeApprove(curve, 0); IERC20(wbtc).safeApprove(curve, _wbtc); ICurveFi(curve).add_liquidity([0, _wbtc], 0); } uint256 _want = IERC20(want).balanceOf(address(this)); if (_want > 0) { deposit(); } emit Harvested(want, _want); } function _withdrawSome(uint256 _amount) internal returns (uint256) { ICurveGauge(pool).withdraw(_amount); return _amount; } function balanceOfWant() public view returns (uint256) { return IERC20(want).balanceOf(address(this)); } function balanceOfPool() public view returns (uint256) { return ICurveGauge(pool).balanceOf(address(this)); } function balanceOf() public view override returns (uint256) { return balanceOfWant().add(balanceOfPool()); } }
4,206,260
[ 1, 41, 9542, 6252, 716, 8104, 1654, 5093, 58, 16, 425, 1303, 87, 6732, 58, 471, 7759, 6732, 58, 1473, 358, 1654, 5093, 58, 487, 2824, 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 ]
[ 1, 1, 1, 1, 1, 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, 16351, 19736, 9423, 16290, 38, 15988, 353, 467, 4525, 288, 203, 565, 1450, 14060, 654, 39, 3462, 364, 467, 654, 39, 3462, 31, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 203, 565, 871, 670, 297, 90, 3149, 12, 2867, 8808, 1147, 16, 2254, 5034, 3844, 1769, 203, 203, 203, 565, 1758, 1071, 9229, 31, 203, 203, 97, 203, 565, 3885, 12, 2867, 389, 26983, 13, 1071, 288, 203, 3639, 2583, 24899, 26983, 480, 1758, 12, 20, 92, 20, 3631, 315, 26983, 486, 444, 8863, 203, 3639, 9229, 273, 389, 26983, 31, 203, 565, 289, 203, 203, 565, 445, 443, 1724, 1435, 1071, 3849, 288, 203, 3639, 2254, 5034, 389, 17369, 273, 467, 654, 39, 3462, 12, 17369, 2934, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 3639, 309, 261, 67, 17369, 405, 374, 13, 288, 203, 5411, 467, 654, 39, 3462, 12, 17369, 2934, 4626, 12053, 537, 12, 6011, 16, 374, 1769, 203, 5411, 467, 654, 39, 3462, 12, 17369, 2934, 4626, 12053, 537, 12, 6011, 16, 389, 17369, 1769, 203, 5411, 467, 9423, 18941, 12, 6011, 2934, 323, 1724, 24899, 17369, 1769, 203, 3639, 289, 203, 565, 289, 203, 203, 565, 445, 443, 1724, 1435, 1071, 3849, 288, 203, 3639, 2254, 5034, 389, 17369, 273, 467, 654, 39, 3462, 12, 17369, 2934, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 3639, 309, 261, 67, 17369, 405, 374, 13, 288, 203, 5411, 467, 654, 39, 3462, 12, 17369, 2934, 4626, 12053, 537, 12, 6011, 16, 374, 1769, 203, 5411, 467, 654, 2 ]
./full_match/1/0x2a281305a50627a22eC3e7d82aE656AdFee6D964/sources/BarnOwlz.sol
IPFS URL WILL BE ADDED WHEN OWLS ARE ALL SOLD OUT
string public OWL_PROVENANCE = "";
16,437,921
[ 1, 2579, 4931, 1976, 678, 15125, 9722, 11738, 7660, 29707, 18233, 3045, 432, 862, 8061, 348, 11846, 8210, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 533, 1071, 25266, 67, 3373, 58, 1157, 4722, 273, 1408, 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 ]
pragma solidity ^0.4.22; // 0xdBe3A455Ae330645D931817B7440b1C4f6DcF549, uses 21480 of gas contract LowGasConsumingPayableFallback { function() public payable { for (uint i = 0; i < 10; i++) {} } }
0xdBe3A455Ae330645D931817B7440b1C4f6DcF549, uses 21480 of gas
contract LowGasConsumingPayableFallback { function() public payable { } for (uint i = 0; i < 10; i++) {} }
6,410,038
[ 1, 20, 7669, 1919, 23, 37, 24, 2539, 37, 73, 3707, 20, 1105, 25, 40, 11180, 2643, 4033, 38, 5608, 7132, 70, 21, 39, 24, 74, 26, 40, 71, 42, 6564, 29, 16, 4692, 30149, 3672, 434, 16189, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 23629, 27998, 11911, 310, 9148, 429, 12355, 288, 203, 203, 565, 445, 1435, 1071, 8843, 429, 288, 7010, 203, 203, 565, 289, 203, 3639, 364, 261, 11890, 277, 273, 374, 31, 277, 411, 1728, 31, 277, 27245, 2618, 203, 97, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** * @title Campaign * @section DESCRIPTION * Campaign contract created for every new campaign, by invoking the createCampaign(args..) * in CampaignFactory. Caller of createCamapign will be the manager of the Campign instance. */ pragma solidity ^0.4.24; import "./SafeMath.sol"; import "./Ownable.sol"; import "./ReentrancyGuard.sol"; import "./Pausable.sol"; import "./CampaignFactory.sol"; contract Campaign is Ownable, ReentrancyGuard, Pausable { using SafeMath for uint256; struct Request { string description; uint value; address recipient; bool complete; uint backerCount; mapping(address => bool) backers; } Request[] public requests; address public manager; string public nameOfCampaign; string public details; uint public minimumContribution; uint public deadline; uint public goal; uint public backersCount; uint public ratersCount; uint public ratingSum; uint public rating; bool public refundFlag; uint public amountRaised; uint public requestedAmount; uint public amountRemaining; address public factoryAddress; // Limiting contributions to 10 ETH uint constant MAX_LIMIT_FOR_CONTRIB = 10000000000000000000; CampaignFactory factory; mapping(address => uint256) public backers; mapping(address => uint256) private ratingFrombackers; event Contribute(address contributor, uint amount); event Withdrawal(address contributor, uint amount); event RequestFinalized(address recipient, uint value); /** * @dev Modifier to check if the backer has contributed */ modifier validBacker() { require(backers[msg.sender] > 0); _; } /** * @dev Modifier to check if deadline has passed and the campaign has reached its goal */ modifier postDeadline() { require(block.timestamp > deadline && amountRaised >= goal); _; } /** * @dev Constructor to create a Campaign */ constructor(string _name, uint _minimumContribution, address creator, uint _deadline, uint _goal, string _details) public { require(block.timestamp < _deadline); nameOfCampaign = _name; manager = creator; minimumContribution = _minimumContribution; deadline = _deadline; goal = _goal; details = _details; refundFlag = false; factoryAddress = msg.sender; factory = CampaignFactory(factoryAddress); factory.addToList(creator, 1, deadline); // Otherwise the owner of the Campaign instance will always be the CampaignFactory transferOwnership(creator); } /** * @dev Payable function recieve funds from backers */ function contribute() public payable whenNotPaused nonReentrant { require(msg.value >= minimumContribution && block.timestamp <= deadline); uint checkAmount = amountRaised.add(msg.value); if(checkAmount > MAX_LIMIT_FOR_CONTRIB) { revert(); } if(backers[msg.sender] == 0) { backersCount = backersCount.add(1); } backers[msg.sender] = backers[msg.sender].add(msg.value); amountRaised = amountRaised.add(msg.value); amountRemaining = amountRemaining.add(msg.value); factory.addToList(msg.sender, 2, deadline); emit Contribute(msg.sender, msg.value); } /** * @dev Function to withdraw funds from the campaign */ function withdraw() external validBacker nonReentrant { require(block.timestamp <= deadline || amountRaised < goal || refundFlag); uint amountWithdrawn = backers[msg.sender]; backers[msg.sender] = 0; if(refundFlag) { amountWithdrawn = amountWithdrawn.mul(amountRemaining).div(amountRaised); } else { amountRaised = amountRaised.sub(amountWithdrawn); amountRemaining = amountRemaining.sub(amountWithdrawn); backersCount = backersCount.sub(1); factory.deleteFromList(msg.sender); } msg.sender.transfer(amountWithdrawn); emit Withdrawal(msg.sender, amountWithdrawn); } /** * @dev Create a request to utilize the funds raised * @param description Description of the Request * @param value Value in wei for the particular request * @param recipient Recipient address of the request */ function createRequest(string description, uint value, address recipient) public onlyOwner postDeadline whenNotPaused{ require(!refundFlag); requestedAmount = requestedAmount.add(value); if(requestedAmount > amountRemaining) { revert(); } Request memory newRequest = Request({ description: description, value: value, recipient: recipient, complete: false, backerCount: 0 }); requests.push(newRequest); } /** * @dev Backers of the campaign can approve the request * @param index Index of the request for approval */ function approveRequest(uint index) public validBacker { Request storage request = requests[index]; require(!request.backers[msg.sender]); request.backers[msg.sender] = true; request.backerCount = request.backerCount.add(1); } /** * @dev Finalizing the request for funds if more than 50% of the backers approve * @param index Index of the request for approval */ function finalizeRequest(uint index) public onlyOwner { require(!refundFlag); Request storage request = requests[index]; require(request.backerCount > (backersCount.div(2))); require(!request.complete); request.recipient.transfer(request.value); amountRemaining = amountRemaining.sub(request.value); requestedAmount = requestedAmount.sub(request.value); request.complete = true; emit RequestFinalized(request.recipient, request.value); } /** * @dev Owner can activate the refund flag */ function refundBackerFunds() public onlyOwner postDeadline { refundFlag = true; } /** * @dev Retrieve summary of the Campaign * @return Multiple parameters of the Campaign */ function getSummary() public view returns(string, address, uint, uint, uint, string, uint, uint, uint, uint, uint) { return(nameOfCampaign, manager, minimumContribution, deadline, goal, details, amountRaised, address(this).balance, requests.length, rating, backersCount); } /** * @dev Retrieve status of the Campaign * @return bool If contract is paused or not * @return bool If refundFlag has been activated or not */ function getCampaignStatus() public view returns(bool, bool) { return(paused, refundFlag); } /** * @dev Retrieve the number of Requests in the Campaign * @return uint The number of requests */ function getRequestsCount() public view returns (uint) { return requests.length; } /** * @dev Store rating from a valid backer of the campaign * @param _rating Rating ranges from 1 - 5 */ function giveRating(uint _rating) public validBacker postDeadline { require(ratingFrombackers[msg.sender] == 0); ratingFrombackers[msg.sender] = _rating; ratersCount = ratersCount.add(1); ratingSum = ratingSum.add(_rating); rating = ratingSum.div(ratersCount); } /** * @dev payable fallback */ function () public payable { if (!msg.sender.send(msg.value)) { revert(); } } }
* @dev Payable function recieve funds from backers/
function contribute() public payable whenNotPaused nonReentrant { require(msg.value >= minimumContribution && block.timestamp <= deadline); uint checkAmount = amountRaised.add(msg.value); if(checkAmount > MAX_LIMIT_FOR_CONTRIB) { revert(); } if(backers[msg.sender] == 0) { backersCount = backersCount.add(1); } backers[msg.sender] = backers[msg.sender].add(msg.value); amountRaised = amountRaised.add(msg.value); amountRemaining = amountRemaining.add(msg.value); factory.addToList(msg.sender, 2, deadline); emit Contribute(msg.sender, msg.value); }
12,737,753
[ 1, 9148, 429, 445, 1950, 21271, 284, 19156, 628, 1473, 414, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 356, 887, 1435, 1071, 8843, 429, 1347, 1248, 28590, 1661, 426, 8230, 970, 288, 203, 3639, 2583, 12, 3576, 18, 1132, 1545, 5224, 442, 4027, 597, 1203, 18, 5508, 1648, 14096, 1769, 203, 3639, 2254, 866, 6275, 273, 3844, 12649, 5918, 18, 1289, 12, 3576, 18, 1132, 1769, 203, 203, 3639, 309, 12, 1893, 6275, 405, 4552, 67, 8283, 67, 7473, 67, 6067, 2259, 38, 13, 288, 203, 5411, 15226, 5621, 203, 3639, 289, 203, 203, 3639, 309, 12, 823, 414, 63, 3576, 18, 15330, 65, 422, 374, 13, 288, 203, 5411, 1473, 414, 1380, 273, 1473, 414, 1380, 18, 1289, 12, 21, 1769, 2398, 203, 3639, 289, 203, 203, 3639, 1473, 414, 63, 3576, 18, 15330, 65, 273, 1473, 414, 63, 3576, 18, 15330, 8009, 1289, 12, 3576, 18, 1132, 1769, 203, 3639, 3844, 12649, 5918, 273, 3844, 12649, 5918, 18, 1289, 12, 3576, 18, 1132, 1769, 203, 3639, 3844, 11429, 273, 3844, 11429, 18, 1289, 12, 3576, 18, 1132, 1769, 203, 3639, 3272, 18, 1289, 25772, 12, 3576, 18, 15330, 16, 576, 16, 14096, 1769, 203, 3639, 3626, 735, 887, 12, 3576, 18, 15330, 16, 1234, 18, 1132, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.17; /** * The GiftRegistry contract is designed to store funds put up by a "giver" to * a "recipient" whose Ethereum address is not known or who may not have an * Ethereum account yet. * * To accomplish this, we validate the recipient's claim against a 'signer' * address. This is defined in the contract as type 'address', and is indeed a * valid Ethereum address, but for our purposes it is simply a public/private * keypair used for signing and validating a claim request. * * The idea is that giver creates an Ethereum account and publishes that to the * gift registry along with the gifted funds. He then gives the recipient * the private key. The recipient can then use the private key to validate himself * as the recipient, pointing the funds to any Ethereum address of his choosing. */ contract GiftRegistry { struct GiftEntry { address signer; uint balance; } mapping (address => GiftEntry) m_giftEntries; /** * Register a gift. * * The things we care about in this call are: * * 1) The amount of ETH being sent. This will be stored by the contract and * eligible to be claimed by the recipient. * 2) The 'signer' address. This is an Ethereum address, but is not used to * store or send any ETH. Rather, it is used to verify the recipient. */ function registerGift(address signer) public payable { m_giftEntries[signer] = GiftEntry(signer, msg.value); } /** * Claim a registered gift. * * The claim process involves verifying a couple different things: * * 1) We independently derive a message containing the desired payout address * (payee) as well as the desired payout amount, and compare its hash to * the hash provided. [TODO: explain how this message is assembled] * 2) We verify that the signature is a product of the hash (e.g. that it has * not been tampered with) * 3) We verify that the original 'signer' address is the signer of this * message. Keep in mind that the 'signer' is not used to store or transfer * any ETH, but rather to verify the recipient of the gift funds. */ function claimGift(address signer, bytes signature, address payee, uint amount) public { GiftEntry storage giftEntry= m_giftEntries[signer]; require(giftEntry.balance > 0); // will check both balance > 0 and "existence" of entry require(giftEntry.balance >= amount); // Note: sha3 a.k.a. keccak256 uses "tightly packing", client side must do the same to produce signature // Also, client side prepends a static message before signing, need to do the same here. // see: https://github.com/ethereum/go-ethereum/issues/3731 bytes memory prefix = "\x19Ethereum Signed Message:\n32"; bytes32 messageHash = keccak256(prefix, payee, amount); bool valid = verifySignature(messageHash, signature, signer); require(valid); giftEntry.balance -= amount; payee.transfer(amount); // on failure, will revert state } /** * Verify that 'signature' is a valid result of 'signer' signing 'message'. */ function verifySignature(bytes32 messageHash, bytes signature, address signer) public pure returns (bool valid) { // TODO: implement // // Signing in a Solidity contract is confined to ecrecover, which uses // products of ECC (Eliptical Curve Cryptography), which is documented here: // https://web3js.readthedocs.io/en/1.0/web3-eth-personal.html#ecrecover // // and explained here: // https://medium.com/hello-sugoi/ethereum-signing-and-validating-13a2d7cb0ee3 // // It is assumed that the r, s, and v values are embedded in the signature. // // However, there are suggestions to simplify/abstract this. See: // https://github.com/ethereum/EIPs/issues/79 // https://gist.github.com/axic/5b33912c6f61ae6fd96d6c4a47afde6d return true; } }
on failure, will revert state
payee.transfer(amount);
884,931
[ 1, 265, 5166, 16, 903, 15226, 919, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 8843, 1340, 18, 13866, 12, 8949, 1769, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x6Fa7312aBAA3aF6B0D73c7d9CBfb1cafA327a1D8/sources/ERC721ART.sol
transfer to winner
token223.transfer(_from, nftList[nftIndex].main_prize);
10,999,402
[ 1, 13866, 358, 5657, 1224, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 5411, 1147, 3787, 23, 18, 13866, 24899, 2080, 16, 290, 1222, 682, 63, 82, 1222, 1016, 8009, 5254, 67, 683, 554, 1769, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2020-10-03 */ pragma solidity 0.6.0; library SafeMath { /** * @dev Multiplies two unsigned integers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { //require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two unsigned integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } contract Ownable { address public _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor () public { _owner = msg.sender; emit OwnershipTransferred(address(0), msg.sender); } function owner() public view returns (address) { return _owner; } modifier onlyOwner() { require(_owner == msg.sender, "Ownable: caller is not the owner"); _; } function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } contract YFBEAM is Ownable { using SafeMath for uint256; string public constant name = "YFBEAM"; string public constant symbol = "YFBM"; uint256 public constant decimals = 18; // the supply will not exceed 1,000,000 YFBM uint256 private constant _maximumSupply = 1000000 * 10 ** decimals; uint256 private constant _maximumPresaleBurnAmount = 80000 * 10 ** decimals; uint256 public _presaleBurnTotal = 0; uint256 public _totalSupply; // events event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); // mappings mapping(address => uint256) public _balanceOf; mapping(address => mapping(address => uint256)) public allowance; constructor() public override { // transfer the entire supply to contract creator _owner = msg.sender; _totalSupply = _maximumSupply; _balanceOf[msg.sender] = _maximumSupply; emit Transfer(address(0x0), msg.sender, _maximumSupply); } function totalSupply () public view returns (uint256) { return _totalSupply; } function balanceOf (address who) public view returns (uint256) { return _balanceOf[who]; } // checks that the address is valid function _transfer(address _from, address _to, uint256 _value) internal { _balanceOf[_from] = _balanceOf[_from].sub(_value); _balanceOf[_to] = _balanceOf[_to].add(_value); emit Transfer(_from, _to, _value); } // transfer tokens function transfer(address _to, uint256 _value) public returns (bool success) { require(_balanceOf[msg.sender] >= _value); _transfer(msg.sender, _to, _value); return true; } // performs presale burn function burn (uint256 _burnAmount, bool _presaleBurn) public onlyOwner returns (bool success) { if (_presaleBurn) { require(_presaleBurnTotal.add(_burnAmount) <= _maximumPresaleBurnAmount); _presaleBurnTotal = _presaleBurnTotal.add(_burnAmount); _transfer(_owner, address(0), _burnAmount); _totalSupply = _totalSupply.sub(_burnAmount); //injected INTEGER OVERFLOW OR UNDERFLOW } else { _transfer(_owner, address(0), _burnAmount); _totalSupply = _totalSupply.sub(_burnAmount); //injected INTEGER OVERFLOW OR UNDERFLOW } return true; } // approve spend function approve(address _spender, uint256 _value) public returns (bool success) { require(_spender != address(0)); allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } // transfer from function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= _balanceOf[_from]); require(_value <= allowance[_from][msg.sender]); allowance[_from][msg.sender] = allowance[_from][msg.sender].sub(_value); _transfer(_from, _to, _value); return true; } }
injected INTEGER OVERFLOW OR UNDERFLOW
_totalSupply = _totalSupply.sub(_burnAmount);
7,273,202
[ 1, 267, 6059, 16481, 22577, 17430, 4869, 587, 18556, 17430, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 389, 4963, 3088, 1283, 273, 389, 4963, 3088, 1283, 18, 1717, 24899, 70, 321, 6275, 1769, 202, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/42220/0xE7E1573c32859Dc022001f3ee5a3bcdCEb921C9d/sources/contracts/PoolBalances.sol
* @dev Stores the Asset Managers (by Pool and token), and implements the top level Asset Manager and Pool interfaces, such as registering and deregistering tokens, joining and exiting Pools, and informational functions like `getPool` and `getPoolTokens`, delegating to specialization-specific functions as needed. `managePoolBalance` handles all Asset Manager interactions./
abstract contract PoolBalances is Fees, ReentrancyGuard, PoolTokens, UserBalance { using Math for uint256; using SafeERC20 for IERC20; using BalanceAllocation for bytes32; using BalanceAllocation for bytes32[]; function joinPool( bytes32 poolId, address sender, address recipient, JoinPoolRequest memory request ) external payable override whenNotPaused { _joinOrExit(PoolBalanceChangeKind.JOIN, poolId, sender, payable(recipient), _toPoolBalanceChange(request)); } function exitPool( bytes32 poolId, address sender, address payable recipient, ExitPoolRequest memory request ) external override { _joinOrExit(PoolBalanceChangeKind.EXIT, poolId, sender, recipient, _toPoolBalanceChange(request)); } struct PoolBalanceChange { IAsset[] assets; uint256[] limits; bytes userData; bool useInternalBalance; } function _toPoolBalanceChange(JoinPoolRequest memory request) private pure returns (PoolBalanceChange memory change) { assembly { change := request } } function _toPoolBalanceChange(JoinPoolRequest memory request) private pure returns (PoolBalanceChange memory change) { assembly { change := request } } function _toPoolBalanceChange(ExitPoolRequest memory request) private pure returns (PoolBalanceChange memory change) { assembly { change := request } } function _toPoolBalanceChange(ExitPoolRequest memory request) private pure returns (PoolBalanceChange memory change) { assembly { change := request } } function _joinOrExit( PoolBalanceChangeKind kind, bytes32 poolId, address sender, address payable recipient, PoolBalanceChange memory change ) private nonReentrant withRegisteredPool(poolId) authenticateFor(sender) { InputHelpers.ensureInputLengthMatch(change.assets.length, change.limits.length); IERC20[] memory tokens = _translateToIERC20(change.assets); bytes32[] memory balances = _validateTokensAndGetBalances(poolId, tokens); ( bytes32[] memory finalBalances, uint256[] memory amountsInOrOut, uint256[] memory paidProtocolSwapFeeAmounts ) = _callPoolBalanceChange(kind, poolId, sender, recipient, change, balances); PoolSpecialization specialization = _getPoolSpecialization(poolId); if (specialization == PoolSpecialization.TWO_TOKEN) { _setTwoTokenPoolCashBalances(poolId, tokens[0], finalBalances[0], tokens[1], finalBalances[1]); _setMinimalSwapInfoPoolBalances(poolId, tokens, finalBalances); _setGeneralPoolBalances(poolId, finalBalances); } emit PoolBalanceChanged( poolId, sender, tokens, paidProtocolSwapFeeAmounts ); } function _joinOrExit( PoolBalanceChangeKind kind, bytes32 poolId, address sender, address payable recipient, PoolBalanceChange memory change ) private nonReentrant withRegisteredPool(poolId) authenticateFor(sender) { InputHelpers.ensureInputLengthMatch(change.assets.length, change.limits.length); IERC20[] memory tokens = _translateToIERC20(change.assets); bytes32[] memory balances = _validateTokensAndGetBalances(poolId, tokens); ( bytes32[] memory finalBalances, uint256[] memory amountsInOrOut, uint256[] memory paidProtocolSwapFeeAmounts ) = _callPoolBalanceChange(kind, poolId, sender, recipient, change, balances); PoolSpecialization specialization = _getPoolSpecialization(poolId); if (specialization == PoolSpecialization.TWO_TOKEN) { _setTwoTokenPoolCashBalances(poolId, tokens[0], finalBalances[0], tokens[1], finalBalances[1]); _setMinimalSwapInfoPoolBalances(poolId, tokens, finalBalances); _setGeneralPoolBalances(poolId, finalBalances); } emit PoolBalanceChanged( poolId, sender, tokens, paidProtocolSwapFeeAmounts ); } } else if (specialization == PoolSpecialization.MINIMAL_SWAP_INFO) { } else { _unsafeCastToInt256(amountsInOrOut, positive), function _callPoolBalanceChange( PoolBalanceChangeKind kind, bytes32 poolId, address sender, address payable recipient, PoolBalanceChange memory change, bytes32[] memory balances ) private returns ( bytes32[] memory finalBalances, uint256[] memory amountsInOrOut, uint256[] memory dueProtocolFeeAmounts ) { (uint256[] memory totalBalances, uint256 lastChangeBlock) = balances.totalsAndLastChangeBlock(); IBasePool pool = IBasePool(_getPoolAddress(poolId)); (amountsInOrOut, dueProtocolFeeAmounts) = kind == PoolBalanceChangeKind.JOIN ? pool.onJoinPool( poolId, sender, recipient, totalBalances, lastChangeBlock, _getProtocolSwapFeePercentage(), change.userData ) : pool.onExitPool( poolId, sender, recipient, totalBalances, lastChangeBlock, _getProtocolSwapFeePercentage(), change.userData ); InputHelpers.ensureInputLengthMatch(balances.length, amountsInOrOut.length, dueProtocolFeeAmounts.length); finalBalances = kind == PoolBalanceChangeKind.JOIN ? _processJoinPoolTransfers(sender, change, balances, amountsInOrOut, dueProtocolFeeAmounts) : _processExitPoolTransfers(recipient, change, balances, amountsInOrOut, dueProtocolFeeAmounts); } function _processJoinPoolTransfers( address sender, PoolBalanceChange memory change, bytes32[] memory balances, uint256[] memory amountsIn, uint256[] memory dueProtocolFeeAmounts ) private returns (bytes32[] memory finalBalances) { uint256 wrappedEth = 0; finalBalances = new bytes32[](balances.length); for (uint256 i = 0; i < change.assets.length; ++i) { uint256 amountIn = amountsIn[i]; _require(amountIn <= change.limits[i], Errors.JOIN_ABOVE_MAX); IAsset asset = change.assets[i]; _receiveAsset(asset, amountIn, sender, change.useInternalBalance); if (_isETH(asset)) { wrappedEth = wrappedEth.add(amountIn); } uint256 feeAmount = dueProtocolFeeAmounts[i]; _payFeeAmount(_translateToIERC20(asset), feeAmount); : balances[i].decreaseCash(feeAmount - amountIn); } } function _processJoinPoolTransfers( address sender, PoolBalanceChange memory change, bytes32[] memory balances, uint256[] memory amountsIn, uint256[] memory dueProtocolFeeAmounts ) private returns (bytes32[] memory finalBalances) { uint256 wrappedEth = 0; finalBalances = new bytes32[](balances.length); for (uint256 i = 0; i < change.assets.length; ++i) { uint256 amountIn = amountsIn[i]; _require(amountIn <= change.limits[i], Errors.JOIN_ABOVE_MAX); IAsset asset = change.assets[i]; _receiveAsset(asset, amountIn, sender, change.useInternalBalance); if (_isETH(asset)) { wrappedEth = wrappedEth.add(amountIn); } uint256 feeAmount = dueProtocolFeeAmounts[i]; _payFeeAmount(_translateToIERC20(asset), feeAmount); : balances[i].decreaseCash(feeAmount - amountIn); } } function _processJoinPoolTransfers( address sender, PoolBalanceChange memory change, bytes32[] memory balances, uint256[] memory amountsIn, uint256[] memory dueProtocolFeeAmounts ) private returns (bytes32[] memory finalBalances) { uint256 wrappedEth = 0; finalBalances = new bytes32[](balances.length); for (uint256 i = 0; i < change.assets.length; ++i) { uint256 amountIn = amountsIn[i]; _require(amountIn <= change.limits[i], Errors.JOIN_ABOVE_MAX); IAsset asset = change.assets[i]; _receiveAsset(asset, amountIn, sender, change.useInternalBalance); if (_isETH(asset)) { wrappedEth = wrappedEth.add(amountIn); } uint256 feeAmount = dueProtocolFeeAmounts[i]; _payFeeAmount(_translateToIERC20(asset), feeAmount); : balances[i].decreaseCash(feeAmount - amountIn); } } ? balances[i].increaseCash(amountIn - feeAmount) _handleRemainingEth(wrappedEth); function _processExitPoolTransfers( address payable recipient, PoolBalanceChange memory change, bytes32[] memory balances, uint256[] memory amountsOut, uint256[] memory dueProtocolFeeAmounts ) private returns (bytes32[] memory finalBalances) { finalBalances = new bytes32[](balances.length); for (uint256 i = 0; i < change.assets.length; ++i) { uint256 amountOut = amountsOut[i]; _require(amountOut >= change.limits[i], Errors.EXIT_BELOW_MIN); IAsset asset = change.assets[i]; _sendAsset(asset, amountOut, recipient, change.useInternalBalance); uint256 feeAmount = dueProtocolFeeAmounts[i]; _payFeeAmount(_translateToIERC20(asset), feeAmount); finalBalances[i] = balances[i].decreaseCash(amountOut.add(feeAmount)); } } function _processExitPoolTransfers( address payable recipient, PoolBalanceChange memory change, bytes32[] memory balances, uint256[] memory amountsOut, uint256[] memory dueProtocolFeeAmounts ) private returns (bytes32[] memory finalBalances) { finalBalances = new bytes32[](balances.length); for (uint256 i = 0; i < change.assets.length; ++i) { uint256 amountOut = amountsOut[i]; _require(amountOut >= change.limits[i], Errors.EXIT_BELOW_MIN); IAsset asset = change.assets[i]; _sendAsset(asset, amountOut, recipient, change.useInternalBalance); uint256 feeAmount = dueProtocolFeeAmounts[i]; _payFeeAmount(_translateToIERC20(asset), feeAmount); finalBalances[i] = balances[i].decreaseCash(amountOut.add(feeAmount)); } } function _validateTokensAndGetBalances(bytes32 poolId, IERC20[] memory expectedTokens) private view returns (bytes32[] memory) { (IERC20[] memory actualTokens, bytes32[] memory balances) = _getPoolTokens(poolId); InputHelpers.ensureInputLengthMatch(actualTokens.length, expectedTokens.length); _require(actualTokens.length > 0, Errors.POOL_NO_TOKENS); for (uint256 i = 0; i < actualTokens.length; ++i) { _require(actualTokens[i] == expectedTokens[i], Errors.TOKENS_MISMATCH); } return balances; } function _validateTokensAndGetBalances(bytes32 poolId, IERC20[] memory expectedTokens) private view returns (bytes32[] memory) { (IERC20[] memory actualTokens, bytes32[] memory balances) = _getPoolTokens(poolId); InputHelpers.ensureInputLengthMatch(actualTokens.length, expectedTokens.length); _require(actualTokens.length > 0, Errors.POOL_NO_TOKENS); for (uint256 i = 0; i < actualTokens.length; ++i) { _require(actualTokens[i] == expectedTokens[i], Errors.TOKENS_MISMATCH); } return balances; } function _unsafeCastToInt256(uint256[] memory values, bool positive) private pure returns (int256[] memory signedValues) { signedValues = new int256[](values.length); for (uint256 i = 0; i < values.length; i++) { signedValues[i] = positive ? int256(values[i]) : -int256(values[i]); } } function _unsafeCastToInt256(uint256[] memory values, bool positive) private pure returns (int256[] memory signedValues) { signedValues = new int256[](values.length); for (uint256 i = 0; i < values.length; i++) { signedValues[i] = positive ? int256(values[i]) : -int256(values[i]); } } }
16,340,271
[ 1, 13125, 326, 10494, 490, 11113, 261, 1637, 8828, 471, 1147, 3631, 471, 4792, 326, 1760, 1801, 10494, 8558, 471, 8828, 7349, 16, 4123, 487, 22845, 471, 24310, 310, 2430, 16, 21239, 471, 15702, 453, 8192, 16, 471, 1779, 287, 4186, 3007, 1375, 588, 2864, 68, 471, 1375, 588, 2864, 5157, 9191, 11158, 1776, 358, 4582, 1588, 17, 12524, 4186, 487, 3577, 18, 1375, 12633, 2864, 13937, 68, 7372, 777, 10494, 8558, 23877, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 17801, 6835, 8828, 38, 26488, 353, 5782, 281, 16, 868, 8230, 12514, 16709, 16, 8828, 5157, 16, 2177, 13937, 288, 203, 565, 1450, 2361, 364, 2254, 5034, 31, 203, 565, 1450, 14060, 654, 39, 3462, 364, 467, 654, 39, 3462, 31, 203, 565, 1450, 30918, 17353, 364, 1731, 1578, 31, 203, 565, 1450, 30918, 17353, 364, 1731, 1578, 8526, 31, 203, 203, 565, 445, 1233, 2864, 12, 203, 3639, 1731, 1578, 2845, 548, 16, 203, 3639, 1758, 5793, 16, 203, 3639, 1758, 8027, 16, 203, 3639, 4214, 2864, 691, 3778, 590, 203, 203, 203, 203, 565, 262, 3903, 8843, 429, 3849, 1347, 1248, 28590, 288, 203, 203, 3639, 389, 5701, 1162, 6767, 12, 2864, 13937, 3043, 5677, 18, 18800, 16, 2845, 548, 16, 5793, 16, 8843, 429, 12, 20367, 3631, 389, 869, 2864, 13937, 3043, 12, 2293, 10019, 203, 565, 289, 203, 203, 565, 445, 2427, 2864, 12, 203, 3639, 1731, 1578, 2845, 548, 16, 203, 3639, 1758, 5793, 16, 203, 3639, 1758, 8843, 429, 8027, 16, 203, 3639, 9500, 2864, 691, 3778, 590, 203, 565, 262, 3903, 3849, 288, 203, 3639, 389, 5701, 1162, 6767, 12, 2864, 13937, 3043, 5677, 18, 28682, 16, 2845, 548, 16, 5793, 16, 8027, 16, 389, 869, 2864, 13937, 3043, 12, 2293, 10019, 203, 565, 289, 203, 203, 565, 1958, 8828, 13937, 3043, 288, 203, 3639, 467, 6672, 8526, 7176, 31, 203, 3639, 2254, 5034, 8526, 8181, 31, 203, 3639, 1731, 13530, 31, 203, 3639, 1426, 999, 3061, 13937, 31, 203, 565, 289, 203, 203, 565, 445, 389, 2 ]
pragma solidity ^0.4.25; import "../contracts/SafeMath.sol"; contract FlightSuretyData { using SafeMath for uint256; /********************************************************************************************/ /* DATA VARIABLES */ /********************************************************************************************/ address private contractOwner; bool private operational = true; uint256 private authorizedAirlineCount = 0; uint256 private changeOperatingStatusVotes = 0; uint256 private insuranceBalance = 0; uint256 private MAX_NO_OF_AIRLINES = 4; uint256 private MAX_FUND_LIMIT = 10 ether; struct Airline { string name; address account; bool isRegistered; bool isAuthorized; bool operationalVote; } struct Insuree{ address account; uint256 insuranceAmount; uint256 payoutBalance; } mapping(address => Airline) airlines; mapping(address => Insuree)private insurees; /********************************************************************************************/ /* EVENT DEFINITIONS */ /********************************************************************************************/ event RegisteredAirline(address airline); event AuthorizedAirline(address airline); event BoughtInsurence(address caller, bytes32 key, uint256 amount); event CreditInsuree(address airline, address insuree, uint256 amount); event PayInsuree(address airline, address insuree, uint256 amount); /** * @dev Constructor * The deploying account becomes contractOwner */ constructor() public { contractOwner = msg.sender; airlines[contractOwner] = Airline({ name : "Contract Owner Airline", account : contractOwner, isRegistered : true, isAuthorized : true, operationalVote : true }); authorizedAirlineCount = authorizedAirlineCount.add(1); emit RegisteredAirline(contractOwner); } /********************************************************************************************/ /* 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 requireIsAuthorized() { require(airlines[msg.sender].isAuthorized, "Airline needs to be authorized"); _; } 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 { address caller = msg.sender; if (authorizedAirlineCount < MAX_NO_OF_AIRLINES) { operational = mode; } else { //use multi-party consensus amount authorized airlines to reach 50% aggreement changeOperatingStatusVotes = changeOperatingStatusVotes.add(1); airlines[caller].operationalVote = mode; if (changeOperatingStatusVotes >= (authorizedAirlineCount.div(2))) { operational = mode; changeOperatingStatusVotes = authorizedAirlineCount - changeOperatingStatusVotes; } } } /********************************************************************************************/ /* SMART CONTRACT FUNCTIONS */ /********************************************************************************************/ /** * @dev Add an airline to the registration queue * Can only be called from FlightSuretyApp contract * */ function registerAirline(string name, address airline) external requireIsOperational { require(!airlines[airline].isRegistered,"This airline is already registered."); if(authorizedAirlineCount <= MAX_NO_OF_AIRLINES){ airlines[airline] = Airline({ name: name, account: airline, isRegistered: true, isAuthorized: false, operationalVote: true }); authorizedAirlineCount = authorizedAirlineCount.add(1); } emit RegisteredAirline(airline); } /** * @dev Check if an airline is registered or not. * */ function isAirline(address airline) public returns (bool) { return airlines[airline].isRegistered; } /** * @dev Buy insurance for a flight * */ function buy(address airline, address insuree, string flight, uint256 timeStamp, uint256 amount) external payable requireIsOperational { require(insurees[insuree].account == insuree,"need to provide insuree account address"); require(msg.sender == insuree, "insuree calls this function"); require(amount == msg.value,"amount must equal value sent"); bytes32 key = getFlightKey(airline, flight, timeStamp); airline.transfer(amount); insurees[insuree].insuranceAmount += amount; insuranceBalance += amount; emit BoughtInsurence(msg.sender, key, amount); } /** * @dev Credits payouts to insurees */ function creditInsurees(address airline, address insuree, uint256 creditAmount) requireIsOperational external { require(insurees[insuree].insuranceAmount >= creditAmount); insurees[insuree].payoutBalance = creditAmount; emit CreditInsuree(airline,insuree,creditAmount); } /** * @dev Transfers eligible payout funds to insuree * */ function pay(address airline, address insuree, uint256 payoutAmount) external requireIsOperational { require(msg.sender == airline); insurees[insuree].account.transfer(payoutAmount); emit PayInsuree(airline, insuree, payoutAmount); } /** * @dev Initial funding for the insurance. Unless there are too many delayed flights * resulting in insurance payouts, the contract should be self-sustaining * */ function fund(address airline) public payable requireIsOperational { require(msg.value >= MAX_FUND_LIMIT, "Insufficient funds"); require(airlines[airline].isRegistered, "Sending account must be registered before it can be funded"); uint256 totalAmount = totalAmount.add(msg.value); airline.transfer(msg.value); //their code has the totalAmount being transferred to the contract account. Why? if (!airlines[airline].isAuthorized) { airlines[airline].isAuthorized = true; authorizedAirlineCount = authorizedAirlineCount.add(1); emit AuthorizedAirline(airline); } } function getFlightKey(address airline, string memory flight, uint256 timestamp) pure internal returns (bytes32) { return keccak256(abi.encodePacked(airline, flight, timestamp)); } /** * @dev Fallback function for funding smart contract. * */ function() external payable { fund(msg.sender); } }
* @dev Transfers eligible payout funds to insuree/
function pay(address airline, address insuree, uint256 payoutAmount) external requireIsOperational { require(msg.sender == airline); insurees[insuree].account.transfer(payoutAmount); emit PayInsuree(airline, insuree, payoutAmount); }
13,048,874
[ 1, 1429, 18881, 21351, 293, 2012, 284, 19156, 358, 316, 2055, 73, 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, 8843, 12, 2867, 23350, 1369, 16, 1758, 316, 2055, 73, 16, 2254, 5034, 293, 2012, 6275, 13, 3903, 203, 565, 2583, 2520, 2988, 287, 203, 565, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 23350, 1369, 1769, 203, 3639, 316, 2055, 281, 63, 267, 2055, 73, 8009, 4631, 18, 13866, 12, 84, 2012, 6275, 1769, 203, 3639, 3626, 13838, 382, 2055, 73, 12, 1826, 1369, 16, 316, 2055, 73, 16, 293, 2012, 6275, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/3/0x6cc9b43f81C40E3BB3Fe544472F2653EE539E75C/sources/MyLotto.sol
* @dev get total eth by user address and saleId/
function getTotalSaleAmountByAddAndSaleID(uint256 _saleId, address _userAddress) external view returns(uint256){ return totalSaleAmountByAddAndSaleID[_saleId][_userAddress]; }
5,278,822
[ 1, 588, 2078, 13750, 635, 729, 1758, 471, 272, 5349, 548, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 12831, 30746, 6275, 858, 986, 1876, 30746, 734, 12, 11890, 5034, 389, 87, 5349, 548, 16, 1758, 389, 1355, 1887, 13, 3903, 1476, 1135, 12, 11890, 5034, 15329, 203, 3639, 327, 2078, 30746, 6275, 858, 986, 1876, 30746, 734, 63, 67, 87, 5349, 548, 6362, 67, 1355, 1887, 15533, 203, 565, 289, 203, 7010, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT // File: @openzeppelin/contracts/access/IAccessControl.sol pragma solidity ^0.8.0; interface IAccessControl { event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); function hasRole(bytes32 role, address account) external view returns (bool); function getRoleAdmin(bytes32 role) external view returns (bytes32); function grantRole(bytes32 role, address account) external; function revokeRole(bytes32 role, address account) external; function renounceRole(bytes32 role, address account) external; } // File: @openzeppelin/contracts/utils/Context.sol 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/utils/Strings.sol library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; function toString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File: @openzeppelin/contracts/utils/introspection/IERC165.sol interface IERC165 { function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/utils/introspection/ERC165.sol abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: @openzeppelin/contracts/access/AccessControl.sol abstract contract AccessControl is Context, IAccessControl, ERC165 { struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId); } function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } function _checkRole(bytes32 role, address account) internal view { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", Strings.toHexString(uint160(account), 20), " is missing role ", Strings.toHexString(uint256(role), 32) ) ) ); } } function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } function _grantRole(bytes32 role, address account) private { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } } // File: @openzeppelin/contracts/access/Ownable.sol abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor() { _setOwner(_msgSender()); } function owner() public view virtual returns (address) { return _owner; } modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File: @openzeppelin/contracts/security/Pausable.sol abstract contract Pausable is Context { event Paused(address account); event Unpaused(address account); bool private _paused; constructor() { _paused = false; } function paused() public view virtual returns (bool) { return _paused; } modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // File: @openzeppelin/contracts/security/ReentrancyGuard.sol abstract contract ReentrancyGuard { uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } 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; _; _status = _NOT_ENTERED; } } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol interface IERC20Metadata is IERC20 { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); } // File: contracts/libraries/ERC20.sol contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } function name() public view virtual override returns (string memory) { return _name; } function symbol() public view virtual override returns (string memory) { return _symbol; } function decimals() public view virtual override returns (uint8) { return 18; } function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); _approve(sender, _msgSender(), currentAllowance - amount); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); _approve(_msgSender(), spender, currentAllowance - subtractedValue); return true; } function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); _balances[sender] = senderBalance - amount; _balances[recipient] += amount; emit Transfer(sender, recipient, amount); _afterTokenTransfer(sender, recipient, amount); } function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); _balances[account] = accountBalance - amount; _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // File: contracts/SoulPower.sol contract SoulPower is ERC20('SoulPower', 'SOUL'), AccessControl { address public supreme; // supreme divine bytes32 public anunnaki; // admin role bytes32 public thoth; // minter role bytes32 public constant DOMAIN_TYPEHASH = // EIP-712 typehash for the contract's domain keccak256('EIP712Domain(string name,uint chainId,address verifyingContract)'); bytes32 public constant DELEGATION_TYPEHASH = // EIP-712 typehash for the delegation struct used by the contract keccak256('Delegation(address delegatee,uint nonce,uint expiry)'); // mappings for user accounts (address) mapping(address => mapping(uint => Checkpoint)) public checkpoints; // vote checkpoints mapping(address => uint) public numCheckpoints; // checkpoint count mapping(address => uint) public nonces; // signing / validating states mapping(address => address) internal _delegates; // each accounts' delegate struct Checkpoint { // checkpoint for marking number of votes from a given timestamp uint fromTime; uint votes; } event NewSupreme(address supreme); event Rethroned(bytes32 role, address oldAccount, address newAccount); event DelegateChanged( // emitted when an account changes its delegate address indexed delegator, address indexed fromDelegate, address indexed toDelegate ); event DelegateVotesChanged( // emitted when a delegate account's vote balance changes address indexed delegate, uint previousBalance, uint newBalance ); // restricted to the house of the role passed as an object to obey modifier obey(bytes32 role) { _checkRole(role, _msgSender()); _; } // channels the authority vested in anunnaki and thoth to the supreme constructor() { supreme = msg.sender; // WARNING: set to multi-sig when deploying anunnaki = keccak256('anunnaki'); // alpha supreme thoth = keccak256('thoth'); // god of wisdom and magic _divinationRitual(DEFAULT_ADMIN_ROLE, DEFAULT_ADMIN_ROLE, supreme); // supreme as root admin _divinationRitual(anunnaki, anunnaki, supreme); // anunnaki as admin of anunnaki _divinationRitual(thoth, anunnaki, supreme); // anunnaki as admin of thoth mint(supreme, 50_000_000 * 1e18); // mints initial supply of 50M } // solidifies roles (internal) function _divinationRitual(bytes32 _role, bytes32 _adminRole, address _account) internal { _setupRole(_role, _account); _setRoleAdmin(_role, _adminRole); } // grants `role` to `newAccount` && renounces `role` from `oldAccount` (public role) function rethroneRitual(bytes32 role, address oldAccount, address newAccount) public obey(role) { require(oldAccount != newAccount, 'must be a new address'); grantRole(role, newAccount); // grants new account renounceRole(role, oldAccount); // removes old account of role emit Rethroned(role, oldAccount, newAccount); } // updates supreme address (public anunnaki) function newSupreme(address _supreme) public obey(anunnaki) { require(supreme != _supreme, 'make a change, be the change'); // prevents self-destruct rethroneRitual(DEFAULT_ADMIN_ROLE, supreme, _supreme); // empowers new supreme supreme = _supreme; emit NewSupreme(supreme); } // checks whether sender has divine role (public view) function hasDivineRole(bytes32 role) public view returns (bool) { return hasRole(role, msg.sender); } // mints soul power as the house of thoth so wills (public thoth) function mint(address _to, uint _amount) public obey(thoth) { _mint(_to, _amount); _moveDelegates(address(0), _delegates[_to], _amount); } // destroys `amount` tokens from the caller (public) function burn(uint amount) public { _burn(_msgSender(), amount); _moveDelegates(_delegates[_msgSender()], address(0), amount); } // destroys `amount` tokens from the `account` (public) function burnFrom(address account, uint amount) public { uint currentAllowance = allowance(account, _msgSender()); require(currentAllowance >= amount, 'burn amount exceeds allowance'); _approve(account, _msgSender(), currentAllowance - amount); _burn(account, amount); _moveDelegates(_delegates[account], address(0), amount); } // returns the address delegated by a given delegator (external view) function delegates(address delegator) external view returns (address) { return _delegates[delegator]; } // delegates to the `delegatee` (external) function delegate(address delegatee) external { return _delegate(msg.sender, delegatee); } // delegates votes from signatory to `delegatee` (external) function delegateBySig( address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s ) external { bytes32 domainSeparator = keccak256( abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this)) ); bytes32 structHash = keccak256( abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry) ); bytes32 digest = keccak256( abi.encodePacked('\x19\x01', domainSeparator, structHash) ); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), 'delegateBySig: invalid signature'); require(nonce == nonces[signatory]++, 'delegateBySig: invalid nonce'); require(block.timestamp <= expiry, 'delegateBySig: signature expired'); return _delegate(signatory, delegatee); } // returns current votes balance for `account` (external view) function getCurrentVotes(address account) external view returns (uint) { uint nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } // returns an account's prior vote count as of a given timestamp (external view) function getPriorVotes(address account, uint blockTimestamp) external view returns (uint) { require(blockTimestamp < block.timestamp, 'getPriorVotes: not yet determined'); uint nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // checks most recent balance if (checkpoints[account][nCheckpoints - 1].fromTime <= blockTimestamp) { return checkpoints[account][nCheckpoints - 1].votes; } // checks implicit zero balance if (checkpoints[account][0].fromTime > blockTimestamp) { return 0; } uint lower = 0; uint upper = nCheckpoints - 1; while (upper > lower) { uint center = upper - (upper - lower) / 2; // avoids overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromTime == blockTimestamp) { return cp.votes; } else if (cp.fromTime < blockTimestamp) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function safe256(uint n, string memory errorMessage) internal pure returns (uint) { require(n < type(uint).max, errorMessage); return uint(n); } function getChainId() internal view returns (uint) { uint chainId; assembly { chainId := chainid() } return chainId; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = _delegates[delegator]; uint delegatorBalance = balanceOf(delegator); // balance of underlying SOUL (not scaled) _delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _moveDelegates(address srcRep, address dstRep, uint amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { // decreases old representative uint srcRepNum = numCheckpoints[srcRep]; uint srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint srcRepNew = srcRepOld - amount; _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { // increases new representative uint dstRepNum = numCheckpoints[dstRep]; uint dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint dstRepNew = dstRepOld + amount; _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint nCheckpoints, uint oldVotes, uint newVotes ) internal { uint blockTimestamp = safe256(block.timestamp, 'block timestamp exceeds 256 bits'); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromTime == blockTimestamp) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockTimestamp, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } } // File: contracts/libraries/Operable.sol abstract contract Operable is Context, Ownable { address[] public operators; mapping(address => bool) public operator; event OperatorUpdated(address indexed operator, bool indexed access); constructor () { address msgSender = _msgSender(); operator[msgSender] = true; operators.push(msgSender); emit OperatorUpdated(msgSender, true); } modifier onlyOperator() { address msgSender = _msgSender(); require(operator[msgSender], "Operator: caller is not an operator"); _; } function removeOperator(address removingOperator) public virtual onlyOperator { require(operator[removingOperator], 'Operable: address is not an operator'); operator[removingOperator] = false; for (uint8 i; i < operators.length; i++) { if (operators[i] == removingOperator) { operators[i] = operators[i+1]; operators.pop(); emit OperatorUpdated(removingOperator, false); return; } } } function addOperator(address newOperator) public virtual onlyOperator { require(newOperator != address(0), "Operable: new operator is the zero address"); require(!operator[newOperator], 'Operable: address is already an operator'); operator[newOperator] = true; operators.push(newOperator); emit OperatorUpdated(newOperator, true); } } // File: contracts/SeanceCircle.sol // SeanceCircle with Governance. contract SeanceCircle is ERC20('SeanceCircle', 'SEANCE'), Ownable, Operable { SoulPower public soul; bool isInitialized; function mint(address _to, uint256 _amount) public onlyOperator { require(isInitialized, 'the circle has not yet begun'); _mint(_to, _amount); _moveDelegates(address(0), _delegates[_to], _amount); } function burn(address _from ,uint256 _amount) public onlyOperator { _burn(_from, _amount); _moveDelegates(_delegates[_from], address(0), _amount); } function initialize(SoulPower _soul) external onlyOwner { require(!isInitialized, 'the circle has already begun'); soul = _soul; isInitialized = true; } // safe soul transfer function, just in case if rounding error causes pool to not have enough SOUL. function safeSoulTransfer(address _to, uint256 _amount) public onlyOperator { uint256 soulBal = soul.balanceOf(address(this)); if (_amount > soulBal) { soul.transfer(_to, soulBal); } else { soul.transfer(_to, _amount); } } // record of each accounts delegate mapping (address => address) internal _delegates; // checkpoint for marking number of votes from a given block timestamp struct Checkpoint { uint256 fromTime; uint256 votes; } // record of votes checkpoints for each account, by index mapping (address => mapping (uint256 => Checkpoint)) public checkpoints; // number of checkpoints for each account mapping (address => uint256) public numCheckpoints; // EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); // EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); // record of states for signing / validating signatures mapping (address => uint) public nonces; // emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); // emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); // returns the address delegated by a given delegator (external view) function delegates(address delegator) external view returns (address) { return _delegates[delegator]; } // delegates to the `delegatee` (external) function delegate(address delegatee) external { return _delegate(msg.sender, delegatee); } // delegates votes from signatory to `delegatee` (external) function delegateBySig( address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s ) external { bytes32 domainSeparator = keccak256( abi.encode( DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this) ) ); bytes32 structHash = keccak256( abi.encode( DELEGATION_TYPEHASH, delegatee, nonce, expiry ) ); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", domainSeparator, structHash ) ); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "SOUL::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "SOUL::delegateBySig: invalid nonce"); require(block.timestamp <= expiry, "SOUL::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } // returns current votes balance for `account` (external view) function getCurrentVotes(address account) external view returns (uint) { uint nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } // returns an account's prior vote count as of a given timestamp (external view) function getPriorVotes(address account, uint blockTimestamp) external view returns (uint256) { require(blockTimestamp < block.timestamp, "SOUL::getPriorVotes: not yet determined"); uint256 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // checks most recent balance if (checkpoints[account][nCheckpoints - 1].fromTime <= blockTimestamp) { return checkpoints[account][nCheckpoints - 1].votes; } // checks implicit zero balance if (checkpoints[account][0].fromTime > blockTimestamp) { return 0; } uint256 lower = 0; uint256 upper = nCheckpoints - 1; while (upper > lower) { uint256 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromTime == blockTimestamp) { return cp.votes; } else if (cp.fromTime < blockTimestamp) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = _delegates[delegator]; uint256 delegatorBalance = balanceOf(delegator); // balance of underlying SOUL (not scaled); _delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { // decrease old representative uint256 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld - amount; _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { // increase new representative uint256 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld + amount; _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint256 nCheckpoints, uint256 oldVotes, uint256 newVotes ) internal { uint256 blockTimestamp = safe256(block.timestamp, "SOUL::_writeCheckpoint: block timestamp exceeds 256 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromTime == blockTimestamp) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockTimestamp, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe256(uint n, string memory errorMessage) internal pure returns (uint256) { require(n < type(uint256).max, errorMessage); return uint256(n); } function getChainId() internal view returns (uint) { uint256 chainId; assembly { chainId := chainid() } return chainId; } function newSoul(SoulPower _soul) external onlyOperator { require(soul != _soul, 'must be a new address'); soul = _soul; } } // File: contracts/interfaces/IMigrator.sol interface IMigrator { function migrate(IERC20 token) external returns (IERC20); } // File: contracts/SoulSummoner.sol // the summoner of souls | ownership transferred to a governance smart contract // upon sufficient distribution + the community's desire to self-govern. contract SoulSummoner is AccessControl, Pausable, ReentrancyGuard { // user info struct Users { uint amount; // total tokens user has provided. uint rewardDebt; // reward debt (see below). uint rewardDebtAtTime; // the last time user stake. uint lastWithdrawTime; // the last time a user withdrew at. uint firstDepositTime; // the last time a user deposited at. uint timeDelta; // time passed since withdrawals. uint lastDepositTime; // most recent deposit time. // pending reward = (user.amount * pool.accSoulPerShare) - user.rewardDebt // the following occurs when a user +/- tokens to a pool: // 1. pool: `accSoulPerShare` and `lastRewardTime` update. // 2. user: receives pending reward. // 3. user: `amount` updates(+/-). // 4. user: `rewardDebt` updates (+/-). } // pool info struct Pools { IERC20 lpToken; // lp token ierc20 contract. uint allocPoint; // allocation points assigned to this pool | SOULs to distribute per second. uint lastRewardTime; // most recent UNIX timestamp during which SOULs distribution occurred in the pool. uint accSoulPerShare; // accumulated SOULs per share, times 1e12. } // soul power: our native utility token address private soulAddress; SoulPower public soul; // seance circle: our governance token address private seanceAddress; SeanceCircle public seance; address public team; // receives 1/8 soul supply address public dao; // recieves 1/8 soul supply address public supreme; // has supreme role // migrator contract | has lotsa power IMigrator public migrator; // blockchain variables accounting for share of overall emissions uint public totalWeight; uint public weight; // soul x day x this.chain uint public dailySoul; // = weight * 250K * 1e18; // soul x second x this.chain uint public soulPerSecond; // = dailySoul / 86400; // bonus muliplier for early soul summoners uint public bonusMultiplier = 1; // timestamp when soul rewards began (initialized) uint public startTime; // ttl allocation points | must be the sum of all allocation points uint public totalAllocPoint; // summoner initialized state. bool public isInitialized; // decay rate on withdrawal fee of 1%. uint public immutable dailyDecay = enWei(1); // start rate for the withdrawal fee. uint public startRate; Pools[] public poolInfo; // pool info mapping (uint => mapping (address => Users)) public userInfo; // staker data // divinated roles bytes32 public isis; // soul summoning goddess of magic bytes32 public maat; // goddess of cosmic order event RoleDivinated(bytes32 role, bytes32 supreme); // restricted to the council of the role passed as an object to obey (role) modifier obey(bytes32 role) { _checkRole(role, _msgSender()); _; } // prevents: early reward distribution modifier isSummoned { require(isInitialized, 'rewards have not yet begun'); _; } event Deposit(address indexed user, uint indexed pid, uint amount); event Withdraw(address indexed user, uint indexed pid, uint amount, uint timeStamp); event Initialized(address team, address dao, address soul, address seance, uint totalAllocPoint, uint weight); event PoolAdded(uint pid, uint allocPoint, IERC20 lpToken, uint totalAllocPoint); event PoolSet(uint pid, uint allocPoint); event WeightUpdated(uint weight, uint totalWeight); event RewardsUpdated(uint dailySoul, uint soulPerSecond); event StartRateUpdated(uint startRate); event AccountsUpdated(address dao, address team, address admin); event TokensUpdated(address soul, address seance); event DepositRevised(uint _pid, address _user, uint _time); // validates: pool exists modifier validatePoolByPid(uint pid) { require(pid < poolInfo.length, 'pool does not exist'); _; } // channels the power of the isis and ma'at to the deployer (deployer) constructor() { supreme = msg.sender; // 0x81Dd37687c74Df8F957a370A9A4435D873F5e5A9; // multi-sig safe team = msg.sender; // 0x36d0164e87B58427c4153c089aeDDa8Ec0B80B9D; // team wallet dao = msg.sender; // 0x1C63C726926197BD3CB75d86bCFB1DaeBcD87250; // dao treasury (multi-sig) isis = keccak256("isis"); // goddess of magic who creates pools maat = keccak256("maat"); // goddess of cosmic order who allocates emissions _divinationCeremony(DEFAULT_ADMIN_ROLE, DEFAULT_ADMIN_ROLE, supreme); _divinationCeremony(isis, isis, supreme); // isis role created -- supreme divined admin _divinationCeremony(maat, isis, dao); // maat role created -- isis divined admin } function _divinationCeremony(bytes32 _role, bytes32 _adminRole, address _account) internal returns (bool) { _setupRole(_role, _account); _setRoleAdmin(_role, _adminRole); return true; } // validate: pool uniqueness to eliminate duplication risk (internal view) function checkPoolDuplicate(IERC20 _token) internal view { uint length = poolInfo.length; for (uint pid = 0; pid < length; ++pid) { require(poolInfo[pid].lpToken != _token, 'duplicated pool'); } } // activates: rewards (owner) function initialize() external obey(isis) { require(!isInitialized, 'already initialized'); soulAddress = 0xCF174A6793FA36A73e8fF18A71bd81C985ef5aB5; seanceAddress = 0xD54Cf31D5653F4a062f5DA4C83170A5867d04442; // [required]: update global constants startTime = block.timestamp; totalWeight = 1000; weight = 1000; startRate = enWei(14); uint allocPoint = 1000; soul = SoulPower(soulAddress); seance = SeanceCircle(seanceAddress); // updates: dailySoul and soulPerSecond updateRewards(weight, totalWeight); // adds: staking pool poolInfo.push(Pools({ lpToken: soul, allocPoint: allocPoint, lastRewardTime: startTime, accSoulPerShare: 0 })); isInitialized = true; // triggers: initialize state totalAllocPoint += allocPoint; // kickstarts: total allocation emit Initialized(team, dao, soulAddress, seanceAddress, totalAllocPoint, weight); } // returns: amount of pools function poolLength() external view returns (uint) { return poolInfo.length; } // add: new pool (isis) function addPool(uint _allocPoint, IERC20 _lpToken, bool _withUpdate) public isSummoned obey(isis) { // isis: the soul summoning goddess whose power transcends them all checkPoolDuplicate(_lpToken); _addPool(_allocPoint, _lpToken, _withUpdate); } // add: new pool (internal) function _addPool(uint _allocPoint, IERC20 _lpToken, bool _withUpdate) internal { if (_withUpdate) { massUpdatePools(); } totalAllocPoint += _allocPoint; poolInfo.push( Pools({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardTime: block.timestamp > startTime ? block.timestamp : startTime, accSoulPerShare: 0 })); updateStakingPool(); uint pid = poolInfo.length; emit PoolAdded(pid, _allocPoint, _lpToken, totalAllocPoint); } // set: allocation points (maat) function set(uint pid, uint allocPoint, bool withUpdate) external isSummoned validatePoolByPid(pid) obey(maat) { if (withUpdate) { massUpdatePools(); } // updates all pools uint prevAllocPoint = poolInfo[pid].allocPoint; poolInfo[pid].allocPoint = allocPoint; if (prevAllocPoint != allocPoint) { totalAllocPoint = totalAllocPoint - prevAllocPoint + allocPoint; updateStakingPool(); // updates only selected pool } emit PoolSet(pid, allocPoint); } // set: migrator contract (isis) function setMigrator(IMigrator _migrator) external isSummoned obey(isis) { migrator = _migrator; } // view: user delta function userDelta(uint256 _pid, address _user) public view returns (uint256 delta) { Users memory user = userInfo[_pid][_user]; return user.lastWithdrawTime > 0 ? block.timestamp - user.lastWithdrawTime : block.timestamp - user.firstDepositTime; } // migrate: lp tokens to another contract (migrator) function migrate(uint pid) external isSummoned validatePoolByPid(pid) { require(address(migrator) != address(0), 'no migrator set'); Pools storage pool = poolInfo[pid]; IERC20 lpToken = pool.lpToken; uint bal = lpToken.balanceOf(address(this)); lpToken.approve(address(migrator), bal); IERC20 _lpToken = migrator.migrate(lpToken); require(bal == _lpToken.balanceOf(address(this)), "migrate: insufficient balance"); pool.lpToken = _lpToken; } // view: bonus multiplier (public view) function getMultiplier(uint from, uint to) public view returns (uint) { return (to - from) * bonusMultiplier; // todo: minus parens } // returns: decay rate for a pid (public view) function getFeeRate(uint pid, uint timeDelta) public view returns (uint feeRate) { uint daysPassed = timeDelta < 1 days ? 0 : timeDelta / 1 days; uint rateDecayed = enWei(daysPassed); uint _rate = rateDecayed >= startRate ? 0 : startRate - rateDecayed; // returns 0 for SAS return pid == 0 ? 0 : _rate; } // returns: feeAmount and with withdrawableAmount for a given pid and amount function getWithdrawable(uint pid, uint timeDelta, uint amount) public view returns (uint _feeAmount, uint _withdrawable) { uint feeRate = fromWei(getFeeRate(pid, timeDelta)); uint feeAmount = (amount * feeRate) / 100; uint withdrawable = amount - feeAmount; return (feeAmount, withdrawable); } // view: pending soul rewards (external) function pendingSoul(uint pid, address _user) external view returns (uint pendingAmount) { Pools storage pool = poolInfo[pid]; Users storage user = userInfo[pid][_user]; uint accSoulPerShare = pool.accSoulPerShare; uint lpSupply = pool.lpToken.balanceOf(address(this)); if (block.timestamp > pool.lastRewardTime && lpSupply != 0) { uint multiplier = getMultiplier(pool.lastRewardTime, block.timestamp); uint soulReward = multiplier * soulPerSecond * pool.allocPoint / totalAllocPoint; accSoulPerShare = accSoulPerShare + soulReward * 1e12 / lpSupply; } return user.amount * accSoulPerShare / 1e12 - user.rewardDebt; } // update: rewards for all pools (public) function massUpdatePools() public { uint length = poolInfo.length; for (uint pid = 0; pid < length; ++pid) { updatePool(pid); } } // update: rewards for a given pool id (public) function updatePool(uint pid) public validatePoolByPid(pid) { Pools storage pool = poolInfo[pid]; if (block.timestamp <= pool.lastRewardTime) { return; } uint lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardTime = block.timestamp; return; } // first staker in pool uint multiplier = getMultiplier(pool.lastRewardTime, block.timestamp); uint soulReward = multiplier * soulPerSecond * pool.allocPoint / totalAllocPoint; uint divi = soulReward * 1e12 / 8e12; // 12.5% rewards uint divis = divi * 2; // total divis uint shares = soulReward - divis; // net shares soul.mint(team, divi); soul.mint(dao, divi); soul.mint(address(seance), shares); pool.accSoulPerShare = pool.accSoulPerShare + (soulReward * 1e12 / lpSupply); pool.lastRewardTime = block.timestamp; } // deposit: lp tokens (lp owner) function deposit(uint pid, uint amount) external nonReentrant validatePoolByPid(pid) whenNotPaused { require (pid != 0, 'deposit SOUL by staking'); Pools storage pool = poolInfo[pid]; Users storage user = userInfo[pid][msg.sender]; updatePool(pid); if (user.amount > 0) { // already deposited assets uint pending = (user.amount * pool.accSoulPerShare) / 1e12 - user.rewardDebt; if(pending > 0) { // sends pending rewards, if applicable safeSoulTransfer(msg.sender, pending); } } if (amount > 0) { // if adding more pool.lpToken.transferFrom(address(msg.sender), address(this), amount); user.amount += amount; } user.rewardDebt = user.amount * pool.accSoulPerShare / 1e12; // marks timestamp for first deposit user.firstDepositTime = user.firstDepositTime > 0 ? user.firstDepositTime : block.timestamp; emit Deposit(msg.sender, pid, amount); } // withdraw: lp tokens (external farmers) function withdraw(uint pid, uint amount) external nonReentrant validatePoolByPid(pid) { require (pid != 0, 'withdraw SOUL by unstaking'); Pools storage pool = poolInfo[pid]; Users storage user = userInfo[pid][msg.sender]; require(user.amount >= amount, 'withdraw not good'); updatePool(pid); uint pending = user.amount * pool.accSoulPerShare / 1e12 - user.rewardDebt; if(pending > 0) { safeSoulTransfer(msg.sender, pending); } if(amount > 0) { if(user.lastDepositTime > 0){ user.timeDelta = block.timestamp - user.lastDepositTime; } else { user.timeDelta = block.timestamp - user.firstDepositTime; } user.amount = user.amount - amount; } uint timeDelta = userInfo[pid][msg.sender].timeDelta; (, uint withdrawable) = getWithdrawable(pid, timeDelta, amount); // removes feeAmount from amount uint feeAmount = amount - withdrawable; pool.lpToken.transfer(address(dao), feeAmount); pool.lpToken.transfer(address(msg.sender), withdrawable); user.rewardDebt = user.amount * pool.accSoulPerShare / 1e12; user.lastWithdrawTime = block.timestamp; emit Withdraw(msg.sender, pid, amount, block.timestamp); } // stake: soul into summoner (external) function enterStaking(uint amount) external nonReentrant whenNotPaused { Pools storage pool = poolInfo[0]; Users storage user = userInfo[0][msg.sender]; updatePool(0); if (user.amount > 0) { uint pending = user.amount * pool.accSoulPerShare / 1e12 - user.rewardDebt; if(pending > 0) { safeSoulTransfer(msg.sender, pending); } } if(amount > 0) { pool.lpToken.transferFrom(address(msg.sender), address(this), amount); user.amount = user.amount + amount; } // marks timestamp for first deposit user.firstDepositTime = user.firstDepositTime > 0 ? user.firstDepositTime : block.timestamp; user.rewardDebt = user.amount * pool.accSoulPerShare / 1e12; seance.mint(msg.sender, amount); emit Deposit(msg.sender, 0, amount); } // unstake: your soul (external staker) function leaveStaking(uint amount) external nonReentrant { Pools storage pool = poolInfo[0]; Users storage user = userInfo[0][msg.sender]; require(user.amount >= amount, "withdraw: not good"); updatePool(0); uint pending = user.amount * pool.accSoulPerShare / 1e12 - user.rewardDebt; if(pending > 0) { safeSoulTransfer(msg.sender, pending); } if(amount > 0) { user.amount = user.amount - amount; pool.lpToken.transfer(address(msg.sender), amount); } user.rewardDebt = user.amount * pool.accSoulPerShare / 1e12; user.lastWithdrawTime = block.timestamp; seance.burn(msg.sender, amount); emit Withdraw(msg.sender, 0, amount, block.timestamp); } // transfer: seance (internal) function safeSoulTransfer(address account, uint amount) internal { seance.safeSoulTransfer(account, amount); } // ** UPDATE FUNCTIONS ** // // update: weight (maat) function updateWeights(uint _weight, uint _totalWeight) external obey(maat) { require(weight != _weight || totalWeight != _totalWeight, 'must be at least one new value'); require(_totalWeight >= _weight, 'weight cannot exceed totalWeight'); weight = _weight; totalWeight = _totalWeight; updateRewards(weight, totalWeight); emit WeightUpdated(weight, totalWeight); } // update: staking pool (internal) function updateStakingPool() internal { uint length = poolInfo.length; uint points; for (uint pid = 1; pid < length; ++pid) { points = points + poolInfo[pid].allocPoint; } if (points != 0) { points = points / 3; totalAllocPoint = totalAllocPoint - poolInfo[0].allocPoint + points; poolInfo[0].allocPoint = points; } } // update: multiplier (maat) function updateMultiplier(uint _bonusMultiplier) external obey(maat) { bonusMultiplier = _bonusMultiplier; } // update: rewards (internal) function updateRewards(uint _weight, uint _totalWeight) internal { uint share = enWei(_weight) / _totalWeight; // share of ttl emissions for chain (chain % ttl emissions) dailySoul = share * (250_000); // dailySoul (for this.chain) = share (%) x 250K (soul emissions constant) soulPerSecond = dailySoul / 1 days; // updates: daily rewards expressed in seconds (1 days = 86,400 secs) emit RewardsUpdated(dailySoul, soulPerSecond); } // update: startRate (maat) function updateStartRate(uint _startRate) public obey(maat) { require(startRate != enWei(_startRate)); startRate = enWei(_startRate); emit StartRateUpdated(startRate); } // update accounts: dao, team, and supreme addresses (isis) function updateAccounts(address _dao, address _team, address _supreme) external obey(isis) { require(dao != _dao || team != _team || supreme != _supreme, 'must be a new account'); dao = _dao; team = _team; supreme = _supreme; emit AccountsUpdated(dao, team, supreme); } // update tokens: soul and seance addresses (isis) function updateTokens(address _soul, address _seance) external obey(isis) { require(soul != IERC20(_soul) || seance != IERC20(_seance), 'must be a new token address'); soul = SoulPower(_soul); seance = SeanceCircle(_seance); emit TokensUpdated(_soul, _seance); } // manual override to reassign the first deposit time for a given (pid, account) function reviseDeposit(uint _pid, address _user, uint256 _time) public obey(maat) { Users storage user = userInfo[_pid][_user]; user.firstDepositTime = _time; emit DepositRevised(_pid, _user, _time); } // ** HELPER FUNCTIONS ** // // helper functions to convert to wei and 1/100th function enWei(uint amount) public pure returns (uint) { return amount * 1e18; } function fromWei(uint amount) public pure returns (uint) { return amount / 1e18; } }
restricted to the house of the role passed as an object to obey
modifier obey(bytes32 role) { _checkRole(role, _msgSender()); _; }
956,994
[ 1, 29306, 358, 326, 23867, 434, 326, 2478, 2275, 487, 392, 733, 358, 3768, 402, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 9606, 3768, 402, 12, 3890, 1578, 2478, 13, 288, 203, 3639, 389, 1893, 2996, 12, 4615, 16, 389, 3576, 12021, 10663, 203, 3639, 389, 31, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/* ==================================================================== */ /* Copyright (c) 2018 The TokenTycoon Project. All rights reserved. /* /* https://tokentycoon.io /* /* authors [email protected] /* [email protected] /* ==================================================================== */ pragma solidity ^0.4.23; contract AccessAdmin { bool public isPaused = false; address public addrAdmin; event AdminTransferred(address indexed preAdmin, address indexed newAdmin); constructor() public { addrAdmin = msg.sender; } modifier onlyAdmin() { require(msg.sender == addrAdmin); _; } modifier whenNotPaused() { require(!isPaused); _; } modifier whenPaused { require(isPaused); _; } function setAdmin(address _newAdmin) external onlyAdmin { require(_newAdmin != address(0)); emit AdminTransferred(addrAdmin, _newAdmin); addrAdmin = _newAdmin; } function doPause() external onlyAdmin whenNotPaused { isPaused = true; } function doUnpause() external onlyAdmin whenPaused { isPaused = false; } } contract AccessService is AccessAdmin { address public addrService; address public addrFinance; modifier onlyService() { require(msg.sender == addrService); _; } modifier onlyFinance() { require(msg.sender == addrFinance); _; } function setService(address _newService) external { require(msg.sender == addrService || msg.sender == addrAdmin); require(_newService != address(0)); addrService = _newService; } function setFinance(address _newFinance) external { require(msg.sender == addrFinance || msg.sender == addrAdmin); require(_newFinance != address(0)); addrFinance = _newFinance; } function withdraw(address _target, uint256 _amount) external { require(msg.sender == addrFinance || msg.sender == addrAdmin); require(_amount > 0); address receiver = _target == address(0) ? addrFinance : _target; uint256 balance = address(this).balance; if (_amount < balance) { receiver.transfer(_amount); } else { receiver.transfer(address(this).balance); } } } interface WarTokenInterface { function getFashion(uint256 _tokenId) external view returns(uint16[12]); function ownerOf(uint256 _tokenId) external view returns (address); function safeTransferByContract(uint256 _tokenId, address _to) external; } interface WonderTokenInterface { function transferFrom(address _from, address _to, uint256 _tokenId) external; function safeGiveByContract(uint256 _tokenId, address _to) external; function getProtoIdByTokenId(uint256 _tokenId) external view returns(uint256); } interface ManagerTokenInterface { function transferFrom(address _from, address _to, uint256 _tokenId) external; function safeGiveByContract(uint256 _tokenId, address _to) external; function getProtoIdByTokenId(uint256 _tokenId) external view returns(uint256); } interface TalentCardInterface { function safeSendCard(uint256 _amount, address _to) external; } interface ERC20BaseInterface { function balanceOf(address _from) external view returns(uint256); function transfer(address _to, uint256 _value) external; function transferFrom(address _from, address _to, uint256 _value) external returns (bool); function approve(address _spender, uint256 _value) external; } contract TTCInterface is ERC20BaseInterface { function approveAndCall(address _spender, uint256 _value, bytes _extraData) external returns (bool); } contract TTPresale is AccessService { TTCInterface ttcToken; WarTokenInterface warToken; ManagerTokenInterface ttmToken; WonderTokenInterface ttwToken; event ManagerSold( address indexed buyer, address indexed buyTo, uint256 mgrId, uint256 nextTokenId ); event WonderSold( address indexed buyer, address indexed buyTo, uint256 wonderId, uint256 nextTokenId ); constructor() public { addrAdmin = msg.sender; addrFinance = msg.sender; addrService = msg.sender; ttcToken = TTCInterface(0xfB673F08FC82807b4D0E139e794e3b328d63551f); warToken = WarTokenInterface(0xDA9c03dFd4D137F926c3cF6953cb951832Eb08b2); } function() external payable { } uint64 public nextDiscountTTMTokenId1 = 1; // ManagerId: 1, tokenId: 1~50 uint64 public nextDiscountTTMTokenId6 = 361; // ManagerId: 6, tokenId: 361~390 uint64 public nextCommonTTMTokenId2 = 51; // ManagerId: 2, tokenId: 51~130 uint64 public nextCommonTTMTokenId3 = 131; // ManagerId: 3, tokenId: 131~210 uint64 public nextCommonTTMTokenId7 = 391; // ManagerId: 7, tokenId: 391~450 uint64 public nextCommonTTMTokenId8 = 451; // ManagerId: 8, tokenId: 451~510 uint64 public nextDiscountTTWTokenId1 = 1; // WonderId: 1, tokenId: 1~30 uint64 public nextCommonTTWTokenId2 = 31; // WonderId: 2, tokenId: 31-90 function setNextDiscountTTMTokenId1(uint64 _val) external onlyAdmin { require(nextDiscountTTMTokenId1 >= 1 && nextDiscountTTMTokenId1 <= 51); nextDiscountTTMTokenId1 = _val; } function setNextDiscountTTMTokenId6(uint64 _val) external onlyAdmin { require(nextDiscountTTMTokenId6 >= 361 && nextDiscountTTMTokenId6 <= 391); nextDiscountTTMTokenId6 = _val; } function setNextCommonTTMTokenId2(uint64 _val) external onlyAdmin { require(nextCommonTTMTokenId2 >= 51 && nextCommonTTMTokenId2 <= 131); nextCommonTTMTokenId2 = _val; } function setNextCommonTTMTokenId3(uint64 _val) external onlyAdmin { require(nextCommonTTMTokenId3 >= 131 && nextCommonTTMTokenId3 <= 211); nextCommonTTMTokenId3 = _val; } function setNextCommonTTMTokenId7(uint64 _val) external onlyAdmin { require(nextCommonTTMTokenId7 >= 391 && nextCommonTTMTokenId7 <= 451); nextCommonTTMTokenId7 = _val; } function setNextCommonTTMTokenId8(uint64 _val) external onlyAdmin { require(nextCommonTTMTokenId8 >= 451 && nextCommonTTMTokenId8 <= 511); nextCommonTTMTokenId8 = _val; } function setNextDiscountTTWTokenId1(uint64 _val) external onlyAdmin { require(nextDiscountTTWTokenId1 >= 1 && nextDiscountTTWTokenId1 <= 31); nextDiscountTTWTokenId1 = _val; } function setNextCommonTTWTokenId2(uint64 _val) external onlyAdmin { require(nextCommonTTWTokenId2 >= 31 && nextCommonTTWTokenId2 <= 91); nextCommonTTWTokenId2 = _val; } uint64 public endDiscountTime = 0; function setDiscountTime(uint64 _endTime) external onlyAdmin { require(_endTime > block.timestamp); endDiscountTime = _endTime; } function setWARTokenAddress(address _addr) external onlyAdmin { require(_addr != address(0)); warToken = WarTokenInterface(_addr); } function setTTMTokenAddress(address _addr) external onlyAdmin { require(_addr != address(0)); ttmToken = ManagerTokenInterface(_addr); } function setTTWTokenAddress(address _addr) external onlyAdmin { require(_addr != address(0)); ttwToken = WonderTokenInterface(_addr); } function setTTCTokenAddress(address _addr) external onlyAdmin { require(_addr != address(0)); ttcToken = TTCInterface(_addr); } function _getExtraParam(bytes _extraData) private pure returns(address addr, uint64 f, uint256 protoId) { assembly { addr := mload(add(_extraData, 20)) } f = uint64(_extraData[20]); protoId = uint256(_extraData[21]) * 256 + uint256(_extraData[22]); } function receiveApproval(address _sender, uint256 _value, address _token, bytes _extraData) external whenNotPaused { require(msg.sender == address(ttcToken)); require(_extraData.length == 23); (address toAddr, uint64 f, uint256 protoId) = _getExtraParam(_extraData); require(ttcToken.transferFrom(_sender, address(this), _value)); if (f == 0) { _buyDiscountTTM(_value, protoId, toAddr, _sender); } else if (f == 1) { _buyDiscountTTW(_value, protoId, toAddr, _sender); } else if (f == 2) { _buyCommonTTM(_value, protoId, toAddr, _sender); } else if (f == 3) { _buyCommonTTW(_value, protoId, toAddr, _sender); } else { require(false, "Invalid func id"); } } function exchangeByPet(uint256 _warTokenId, uint256 _mgrId, address _gameWalletAddr) external whenNotPaused { require(warToken.ownerOf(_warTokenId) == msg.sender); uint16[12] memory warData = warToken.getFashion(_warTokenId); uint16 protoId = warData[0]; if (_mgrId == 2) { require(protoId == 10001 || protoId == 10003); require(nextCommonTTMTokenId2 <= 130); warToken.safeTransferByContract(_warTokenId, address(this)); nextCommonTTMTokenId2 += 1; ttmToken.safeGiveByContract(nextCommonTTMTokenId2 - 1, _gameWalletAddr); emit ManagerSold(msg.sender, _gameWalletAddr, 2, nextCommonTTMTokenId2); } else if (_mgrId == 3) { require(protoId == 10001 || protoId == 10003); require(nextCommonTTMTokenId3 <= 210); warToken.safeTransferByContract(_warTokenId, address(this)); nextCommonTTMTokenId3 += 1; ttmToken.safeGiveByContract(nextCommonTTMTokenId3 - 1, _gameWalletAddr); emit ManagerSold(msg.sender, _gameWalletAddr, 3, nextCommonTTMTokenId3); } else if (_mgrId == 7) { require(protoId == 10002 || protoId == 10004 || protoId == 10005); require(nextCommonTTMTokenId7 <= 450); warToken.safeTransferByContract(_warTokenId, address(this)); nextCommonTTMTokenId7 += 1; ttmToken.safeGiveByContract(nextCommonTTMTokenId7 - 1, _gameWalletAddr); emit ManagerSold(msg.sender, _gameWalletAddr, 7, nextCommonTTMTokenId7); } else if (_mgrId == 8) { require(protoId == 10002 || protoId == 10004 || protoId == 10005); require(nextCommonTTMTokenId8 <= 510); warToken.safeTransferByContract(_warTokenId, address(this)); nextCommonTTMTokenId8 += 1; ttmToken.safeGiveByContract(nextCommonTTMTokenId8 - 1, _gameWalletAddr); emit ManagerSold(msg.sender, _gameWalletAddr, 8, nextCommonTTMTokenId8); } else { require(false); } } function buyDiscountTTMByETH(uint256 _mgrId, address _gameWalletAddr) external payable whenNotPaused { _buyDiscountTTM(msg.value, _mgrId, _gameWalletAddr, msg.sender); } function buyDiscountTTWByETH(uint256 _wonderId, address _gameWalletAddr) external payable whenNotPaused { _buyDiscountTTW(msg.value, _wonderId, _gameWalletAddr, msg.sender); } function buyCommonTTMByETH(uint256 _mgrId, address _gameWalletAddr) external payable whenNotPaused { _buyCommonTTM(msg.value, _mgrId, _gameWalletAddr, msg.sender); } function buyCommonTTWByETH(uint256 _wonderId, address _gameWalletAddr) external payable whenNotPaused { _buyCommonTTW(msg.value, _wonderId, _gameWalletAddr, msg.sender); } function _buyDiscountTTM(uint256 _value, uint256 _mgrId, address _gameWalletAddr, address _buyer) private { require(_gameWalletAddr != address(0)); if (_mgrId == 1) { require(nextDiscountTTMTokenId1 <= 50, "This Manager is sold out"); if (block.timestamp <= endDiscountTime) { require(_value == 0.64 ether); } else { require(_value == 0.99 ether); } nextDiscountTTMTokenId1 += 1; ttmToken.safeGiveByContract(nextDiscountTTMTokenId1 - 1, _gameWalletAddr); emit ManagerSold(_buyer, _gameWalletAddr, 1, nextDiscountTTMTokenId1); } else if (_mgrId == 6) { require(nextDiscountTTMTokenId6 <= 390, "This Manager is sold out"); if (block.timestamp <= endDiscountTime) { require(_value == 0.97 ether); } else { require(_value == 1.49 ether); } nextDiscountTTMTokenId6 += 1; ttmToken.safeGiveByContract(nextDiscountTTMTokenId6 - 1, _gameWalletAddr); emit ManagerSold(_buyer, _gameWalletAddr, 6, nextDiscountTTMTokenId6); } else { require(false); } } function _buyDiscountTTW(uint256 _value, uint256 _wonderId, address _gameWalletAddr, address _buyer) private { require(_gameWalletAddr != address(0)); require(_wonderId == 1); require(nextDiscountTTWTokenId1 <= 30, "This Manager is sold out"); if (block.timestamp <= endDiscountTime) { require(_value == 0.585 ether); } else { require(_value == 0.90 ether); } nextDiscountTTWTokenId1 += 1; ttwToken.safeGiveByContract(nextDiscountTTWTokenId1 - 1, _gameWalletAddr); emit WonderSold(_buyer, _gameWalletAddr, 1, nextDiscountTTWTokenId1); } function _buyCommonTTM(uint256 _value, uint256 _mgrId, address _gameWalletAddr, address _buyer) private { require(_gameWalletAddr != address(0)); if (_mgrId == 2) { require(nextCommonTTMTokenId2 <= 130); require(_value == 0.99 ether); nextCommonTTMTokenId2 += 1; ttmToken.safeGiveByContract(nextCommonTTMTokenId2 - 1, _gameWalletAddr); emit ManagerSold(_buyer, _gameWalletAddr, 2, nextCommonTTMTokenId2); } else if (_mgrId == 3) { require(nextCommonTTMTokenId3 <= 210); require(_value == 0.99 ether); nextCommonTTMTokenId3 += 1; ttmToken.safeGiveByContract(nextCommonTTMTokenId3 - 1, _gameWalletAddr); emit ManagerSold(_buyer, _gameWalletAddr, 3, nextCommonTTMTokenId3); } else if (_mgrId == 7) { require(nextCommonTTMTokenId7 <= 450); require(_value == 1.49 ether); nextCommonTTMTokenId7 += 1; ttmToken.safeGiveByContract(nextCommonTTMTokenId7 - 1, _gameWalletAddr); emit ManagerSold(_buyer, _gameWalletAddr, 7, nextCommonTTMTokenId7); } else if (_mgrId == 8) { require(nextCommonTTMTokenId8 <= 510); require(_value == 1.49 ether); nextCommonTTMTokenId8 += 1; ttmToken.safeGiveByContract(nextCommonTTMTokenId8 - 1, _gameWalletAddr); emit ManagerSold(_buyer, _gameWalletAddr, 8, nextCommonTTMTokenId8); } else { require(false); } } function _buyCommonTTW(uint256 _value, uint256 _wonderId, address _gameWalletAddr, address _buyer) private { require(_gameWalletAddr != address(0)); require(_wonderId == 2); require(nextCommonTTWTokenId2 <= 90); require(_value == 0.50 ether); nextCommonTTWTokenId2 += 1; ttwToken.safeGiveByContract(nextCommonTTWTokenId2 - 1, _gameWalletAddr); emit WonderSold(_buyer, _gameWalletAddr, 2, nextCommonTTWTokenId2); } function withdrawERC20(address _erc20, address _target, uint256 _amount) external { require(msg.sender == addrFinance || msg.sender == addrAdmin); require(_amount > 0); address receiver = _target == address(0) ? addrFinance : _target; ERC20BaseInterface erc20Contract = ERC20BaseInterface(_erc20); uint256 balance = erc20Contract.balanceOf(address(this)); require(balance > 0); if (_amount < balance) { erc20Contract.transfer(receiver, _amount); } else { erc20Contract.transfer(receiver, balance); } } function getPresaleInfo() external view returns( uint64 ttmCnt1, uint64 ttmCnt2, uint64 ttmCnt3, uint64 ttmCnt6, uint64 ttmCnt7, uint64 ttmCnt8, uint64 ttwCnt1, uint64 ttwCnt2, uint64 discountEnd ) { ttmCnt1 = 51 - nextDiscountTTMTokenId1; ttmCnt2 = 131 - nextCommonTTMTokenId2; ttmCnt3 = 211 - nextCommonTTMTokenId3; ttmCnt6 = 391 - nextDiscountTTMTokenId6; ttmCnt7 = 451 - nextCommonTTMTokenId7; ttmCnt8 = 511 - nextCommonTTMTokenId8; ttwCnt1 = 31 - nextDiscountTTWTokenId1; ttwCnt2 = 91 - nextCommonTTWTokenId2; discountEnd = endDiscountTime; } }
ManagerId: 6, tokenId: 361~390
uint64 public nextDiscountTTMTokenId6 = 361;
7,217,092
[ 1, 1318, 548, 30, 1666, 16, 1147, 548, 30, 6580, 21, 98, 5520, 20, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 1105, 1071, 1024, 9866, 1470, 49, 1345, 548, 26, 273, 6580, 21, 31, 377, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/4/0x6B473bB10A8b6B8Bea4a0F0D23811f3b620e8384/sources/contracts/token/TokenERC721.sol
@dev Resolves 'stack too deep' error in `recoverAddress`.
function _encodeRequest(MintRequest calldata _req) private pure returns (bytes memory) { return abi.encode( TYPEHASH, _req.to, _req.royaltyRecipient, _req.royaltyBps, _req.primarySaleRecipient, keccak256(bytes(_req.uri)), _req.price, _req.currency, _req.validityStartTimestamp, _req.validityEndTimestamp, _req.uid ); }
661,256
[ 1, 17453, 296, 3772, 4885, 4608, 11, 555, 316, 1375, 266, 3165, 1887, 8338, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 3015, 691, 12, 49, 474, 691, 745, 892, 389, 3658, 13, 3238, 16618, 1135, 261, 3890, 3778, 13, 288, 203, 3639, 327, 203, 5411, 24126, 18, 3015, 12, 203, 7734, 3463, 15920, 16, 203, 7734, 389, 3658, 18, 869, 16, 203, 7734, 389, 3658, 18, 3800, 15006, 18241, 16, 203, 7734, 389, 3658, 18, 3800, 15006, 38, 1121, 16, 203, 7734, 389, 3658, 18, 8258, 30746, 18241, 16, 203, 7734, 417, 24410, 581, 5034, 12, 3890, 24899, 3658, 18, 1650, 13, 3631, 203, 7734, 389, 3658, 18, 8694, 16, 203, 7734, 389, 3658, 18, 7095, 16, 203, 7734, 389, 3658, 18, 877, 560, 1685, 4921, 16, 203, 7734, 389, 3658, 18, 877, 560, 1638, 4921, 16, 203, 7734, 389, 3658, 18, 1911, 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 ]
pragma solidity 0.5.9; /** * @title Roles * @dev Library for managing addresses assigned to a Role. */ library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev give an account access to this role */ function add(Role storage role, address account) internal { require(account != address(0)); require(!has(role, account)); role.bearer[account] = true; } /** * @dev remove an account's access to this role */ function remove(Role storage role, address account) internal { require(account != address(0)); require(has(role, account)); role.bearer[account] = false; } /** * @dev check if an account has this role * @return bool */ function has(Role storage role, address account) internal view returns (bool) { require(account != address(0)); return role.bearer[account]; } } contract ETORoles { using Roles for Roles.Role; constructor() internal { _addAuditWriter(msg.sender); _addAssetSeizer(msg.sender); _addKycProvider(msg.sender); _addUserManager(msg.sender); _addOwner(msg.sender); } /* * Audit Writer functions */ event AuditWriterAdded(address indexed account); event AuditWriterRemoved(address indexed account); Roles.Role private _auditWriters; modifier onlyAuditWriter() { require(isAuditWriter(msg.sender), "Sender is not auditWriter"); _; } function isAuditWriter(address account) public view returns (bool) { return _auditWriters.has(account); } function addAuditWriter(address account) public onlyUserManager { _addAuditWriter(account); } function renounceAuditWriter() public { _removeAuditWriter(msg.sender); } function _addAuditWriter(address account) internal { _auditWriters.add(account); emit AuditWriterAdded(account); } function _removeAuditWriter(address account) internal { _auditWriters.remove(account); emit AuditWriterRemoved(account); } /* * KYC Provider functions */ event KycProviderAdded(address indexed account); event KycProviderRemoved(address indexed account); Roles.Role private _kycProviders; modifier onlyKycProvider() { require(isKycProvider(msg.sender), "Sender is not kycProvider"); _; } function isKycProvider(address account) public view returns (bool) { return _kycProviders.has(account); } function addKycProvider(address account) public onlyUserManager { _addKycProvider(account); } function renounceKycProvider() public { _removeKycProvider(msg.sender); } function _addKycProvider(address account) internal { _kycProviders.add(account); emit KycProviderAdded(account); } function _removeKycProvider(address account) internal { _kycProviders.remove(account); emit KycProviderRemoved(account); } /* * Asset Seizer functions */ event AssetSeizerAdded(address indexed account); event AssetSeizerRemoved(address indexed account); Roles.Role private _assetSeizers; modifier onlyAssetSeizer() { require(isAssetSeizer(msg.sender), "Sender is not assetSeizer"); _; } function isAssetSeizer(address account) public view returns (bool) { return _assetSeizers.has(account); } function addAssetSeizer(address account) public onlyUserManager { _addAssetSeizer(account); } function renounceAssetSeizer() public { _removeAssetSeizer(msg.sender); } function _addAssetSeizer(address account) internal { _assetSeizers.add(account); emit AssetSeizerAdded(account); } function _removeAssetSeizer(address account) internal { _assetSeizers.remove(account); emit AssetSeizerRemoved(account); } /* * User Manager functions */ event UserManagerAdded(address indexed account); event UserManagerRemoved(address indexed account); Roles.Role private _userManagers; modifier onlyUserManager() { require(isUserManager(msg.sender), "Sender is not UserManager"); _; } function isUserManager(address account) public view returns (bool) { return _userManagers.has(account); } function addUserManager(address account) public onlyUserManager { _addUserManager(account); } function renounceUserManager() public { _removeUserManager(msg.sender); } function _addUserManager(address account) internal { _userManagers.add(account); emit UserManagerAdded(account); } function _removeUserManager(address account) internal { _userManagers.remove(account); emit UserManagerRemoved(account); } /* * Owner functions */ event OwnerAdded(address indexed account); event OwnerRemoved(address indexed account); Roles.Role private _owners; modifier onlyOwner() { require(isOwner(msg.sender), "Sender is not owner"); _; } function isOwner(address account) public view returns (bool) { return _owners.has(account); } function addOwner(address account) public onlyUserManager { _addOwner(account); } function renounceOwner() public { _removeOwner(msg.sender); } function _addOwner(address account) internal { _owners.add(account); emit OwnerAdded(account); } function _removeOwner(address account) internal { _owners.remove(account); emit OwnerRemoved(account); } } /** * @title ERC20 interface * @dev see https://eips.ethereum.org/EIPS/eip-20 */ interface IERC20 { function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title SafeMath * @dev Unsigned math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two unsigned integers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two unsigned integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } contract ERC20 is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; uint256 private _totalSupply; /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev Gets the balance of the specified address. * @param owner The address to query the balance of. * @return A uint256 representing the amount owned by the passed address. */ function balanceOf(address owner) public view returns (uint256) { return _balances[owner]; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param owner address The address which owns the funds. * @param spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowed[owner][spender]; } /** * @dev Transfer token to a specified address * @param to The address to transfer to. * @param value The amount to be transferred. */ function transfer(address to, uint256 value) public returns (bool) { _transfer(msg.sender, to, value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param spender The address which will spend the funds. * @param value The amount of tokens to be spent. */ function approve(address spender, uint256 value) public returns (bool) { _approve(msg.sender, spender, value); return true; } /** * @dev Transfer tokens from one address to another. * Note that while this function emits an Approval event, this is not required as per the specification, * and other compliant implementations may not emit the event. * @param from address The address which you want to send tokens from * @param to address The address which you want to transfer to * @param value uint256 the amount of tokens to be transferred */ function transferFrom(address from, address to, uint256 value) public returns (bool) { _transfer(from, to, value); _approve(from, msg.sender, _allowed[from][msg.sender].sub(value)); return true; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when _allowed[msg.sender][spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(msg.sender, spender, _allowed[msg.sender][spender].add(addedValue)); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when _allowed[msg.sender][spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(msg.sender, spender, _allowed[msg.sender][spender].sub(subtractedValue)); return true; } /** * @dev Transfer token for a specified addresses * @param from The address to transfer from. * @param to The address to transfer to. * @param value The amount to be transferred. */ function _transfer(address from, address to, uint256 value) internal { require(to != address(0)); _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(from, to, value); } /** * @dev Internal function that mints an amount of the token and assigns it to * an account. This encapsulates the modification of balances such that the * proper events are emitted. * @param account The account that will receive the created tokens. * @param value The amount that will be created. */ function _mint(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.add(value); _balances[account] = _balances[account].add(value); emit Transfer(address(0), account, value); } /** * @dev Internal function that burns an amount of the token of a given * account. * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burn(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); } /** * @dev Approve an address to spend another addresses' tokens. * @param owner The address that owns the tokens. * @param spender The address that will spend the tokens. * @param value The number of tokens that can be spent. */ function _approve(address owner, address spender, uint256 value) internal { require(spender != address(0)); require(owner != address(0)); _allowed[owner][spender] = value; emit Approval(owner, spender, value); } /** * @dev Internal function that burns an amount of the token of a given * account, deducting from the sender's allowance for said account. Uses the * internal burn function. * Emits an Approval event (reflecting the reduced allowance). * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burnFrom(address account, uint256 value) internal { _burn(account, value); _approve(account, msg.sender, _allowed[account][msg.sender].sub(value)); } } contract MinterRole { using Roles for Roles.Role; event MinterAdded(address indexed account); event MinterRemoved(address indexed account); Roles.Role private _minters; constructor () internal { _addMinter(msg.sender); } modifier onlyMinter() { require(isMinter(msg.sender)); _; } function isMinter(address account) public view returns (bool) { return _minters.has(account); } function addMinter(address account) public onlyMinter { _addMinter(account); } function renounceMinter() public { _removeMinter(msg.sender); } function _addMinter(address account) internal { _minters.add(account); emit MinterAdded(account); } function _removeMinter(address account) internal { _minters.remove(account); emit MinterRemoved(account); } } /** * @title ERC20Mintable * @dev ERC20 minting logic */ contract ERC20Mintable is ERC20, MinterRole { /** * @dev Function to mint tokens * @param to The address that will receive the minted tokens. * @param value The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address to, uint256 value) public onlyMinter returns (bool) { _mint(to, value); return true; } } contract ETOToken is ERC20Mintable, ETORoles { /* ETO investors */ mapping(address => bool) public investorWhitelist; address[] public investorWhitelistLUT; /* ETO contract parameters */ string public constant name = "Blockstate STO Token"; string public constant symbol = "BKN"; uint8 public constant decimals = 0; /* Listing parameters */ string public ITIN; /* Audit logging */ mapping(uint256 => uint256) public auditHashes; /* Document hashes */ mapping(uint256 => uint256) public documentHashes; /* Events in the ETO contract */ // Transaction related events event AssetsSeized(address indexed seizee, uint256 indexed amount); event AssetsUnseized(address indexed seizee, uint256 indexed amount); event InvestorWhitelisted(address indexed investor); event InvestorBlacklisted(address indexed investor); event DividendPayout(address indexed receiver, uint256 indexed amount); event TokensGenerated(uint256 indexed amount); event OwnershipUpdated(address indexed newOwner); /** * @dev Constructor that defines contract parameters */ constructor() public { ITIN = "CCF5-T3UQ-2"; } /* Variable update events */ event ITINUpdated(string newValue); /* Variable Update Functions */ function setITIN(string memory newValue) public onlyOwner { ITIN = newValue; emit ITINUpdated(newValue); } /* Function to set the required allowance before seizing assets */ function approveFor(address seizee, uint256 seizableAmount) public onlyAssetSeizer { _approve(seizee, msg.sender, seizableAmount); } /* Seize assets */ function seizeAssets(address seizee, uint256 seizableAmount) public onlyAssetSeizer { transferFrom(seizee, msg.sender, seizableAmount); emit AssetsSeized(seizee, seizableAmount); } function releaseAssets(address seizee, uint256 seizedAmount) public onlyAssetSeizer { require(balanceOf(msg.sender) >= seizedAmount, "AssetSeizer has insufficient funds"); transfer(seizee, seizedAmount); emit AssetsUnseized(seizee, seizedAmount); } /* Add investor to the whitelist */ function whitelistInvestor(address investor) public onlyKycProvider { require(investorWhitelist[investor] == false, "Investor already whitelisted"); investorWhitelist[investor] = true; investorWhitelistLUT.push(investor); emit InvestorWhitelisted(investor); } /* Remove investor from the whitelist */ function blacklistInvestor(address investor) public onlyKycProvider { require(investorWhitelist[investor] == true, "Investor not on whitelist"); investorWhitelist[investor] = false; uint256 arrayLen = investorWhitelistLUT.length; for (uint256 i = 0; i < arrayLen; i++) { if (investorWhitelistLUT[i] == investor) { investorWhitelistLUT[i] = investorWhitelistLUT[investorWhitelistLUT.length - 1]; delete investorWhitelistLUT[investorWhitelistLUT.length - 1]; break; } } emit InvestorBlacklisted(investor); } /* Overwrite transfer() to respect the whitelist, tag- and drag along rules */ function transfer(address to, uint256 value) public returns (bool) { require(investorWhitelist[to] == true, "Investor not whitelisted"); return super.transfer(to, value); } function transferFrom(address from, address to, uint256 value) public returns (bool) { require(investorWhitelist[to] == true, "Investor not whitelisted"); return super.transferFrom(from, to, value); } function approve(address spender, uint256 value) public returns (bool) { require(investorWhitelist[spender] == true, "Investor not whitelisted"); return super.approve(spender, value); } /* Generate tokens */ function generateTokens(uint256 amount, address assetReceiver) public onlyMinter { _mint(assetReceiver, amount); } function initiateDividendPayments(uint amount) onlyOwner public returns (bool) { uint dividendPerToken = amount / totalSupply(); uint256 arrayLen = investorWhitelistLUT.length; for (uint256 i = 0; i < arrayLen; i++) { address currentInvestor = investorWhitelistLUT[i]; uint256 currentInvestorShares = balanceOf(currentInvestor); uint256 currentInvestorPayout = dividendPerToken * currentInvestorShares; emit DividendPayout(currentInvestor, currentInvestorPayout); } return true; } function addAuditHash(uint256 hash) public onlyAuditWriter { auditHashes[now] = hash; } function getAuditHash(uint256 timestamp) public view returns (uint256) { return auditHashes[timestamp]; } function addDocumentHash(uint256 hash) public onlyOwner { documentHashes[now] = hash; } function getDocumentHash(uint256 timestamp) public view returns (uint256) { return documentHashes[timestamp]; } } contract ETOVotes is ETOToken { event VoteOpen(uint256 _id, uint _deadline); event VoteFinished(uint256 _id, bool _result); // How many blocks should we wait before the vote can be closed mapping (uint256 => Vote) private votes; struct Voter { address id; bool vote; } struct Vote { uint256 deadline; Voter[] voters; mapping(address => uint) votersIndex; uint256 documentHash; } constructor() public {} function vote(uint256 _id, bool _vote) public { // Allow changing opinion until vote deadline require (votes[_id].deadline > 0, "Vote not available"); require(now <= votes[_id].deadline, "Vote deadline exceeded"); if (didCastVote(_id)) { uint256 currentIndex = votes[_id].votersIndex[msg.sender]; Voter memory newVoter = Voter(msg.sender, _vote); votes[_id].voters[currentIndex - 1] = newVoter; } else { votes[_id].voters.push(Voter(msg.sender, _vote)); votes[_id].votersIndex[msg.sender] = votes[_id].voters.length; } } function getVoteDocumentHash(uint256 _id) public view returns (uint256) { return votes[_id].documentHash; } function openVote(uint256 _id, uint256 documentHash, uint256 voteDuration) onlyOwner external { require(votes[_id].deadline == 0, "Vote already ongoing"); votes[_id].deadline = now + (voteDuration * 1 seconds); votes[_id].documentHash = documentHash; emit VoteOpen(_id, votes[_id].deadline); } /** * @dev Once the deadline is reached this function should be called to get decision. * @param _id data source id. */ function triggerDecision(uint256 _id) external { require(votes[_id].deadline > 0, "Vote not available"); require(now > votes[_id].deadline, "Vote deadline not reached"); // prevent method to be called again before its done votes[_id].deadline = 0; bool result = (getCurrentPositives(_id) > getCurrentNegatives(_id)); emit VoteFinished(_id, result); } /** * @dev get vote status. * @param _id data source id. */ function isVoteOpen(uint256 _id) external view returns (bool) { return (votes[_id].deadline > 0) && (now <= votes[_id].deadline); } /** * @dev check if address voted already. * @param _id data source identifier. */ function didCastVote(uint256 _id) public view returns (bool) { return (votes[_id].votersIndex[msg.sender] > 0); } function getOwnVote(uint256 _id) public view returns (bool) { uint voterId = votes[_id].votersIndex[msg.sender]; return votes[_id].voters[voterId-1].vote; } function getCurrentPositives(uint256 _id) public view returns (uint256) { uint adder = 0; uint256 arrayLen = votes[_id].voters.length; for (uint256 i = 0; i < arrayLen; i++) { if (votes[_id].voters[i].vote == true) { adder += balanceOf(votes[_id].voters[i].id); } } return adder; } function getCurrentNegatives(uint256 _id) public view returns (uint256) { uint adder = 0; uint256 arrayLen = votes[_id].voters.length; for (uint256 i = 0; i < arrayLen; i++) { if (votes[_id].voters[i].vote == false) { adder += balanceOf(votes[_id].voters[i].id); } } return adder; } }
* @title Roles @dev Library for managing addresses assigned to a Role./
library Roles { struct Role { mapping (address => bool) bearer; } function add(Role storage role, address account) internal { require(account != address(0)); require(!has(role, account)); role.bearer[account] = true; } function remove(Role storage role, address account) internal { require(account != address(0)); require(has(role, account)); role.bearer[account] = false; } function has(Role storage role, address account) internal view returns (bool) { require(account != address(0)); return role.bearer[account]; } }
1,035,650
[ 1, 6898, 225, 18694, 364, 30632, 6138, 6958, 358, 279, 6204, 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, 12083, 19576, 288, 203, 202, 1697, 6204, 288, 203, 202, 202, 6770, 261, 2867, 516, 1426, 13, 28802, 31, 203, 202, 97, 203, 203, 202, 915, 527, 12, 2996, 2502, 2478, 16, 1758, 2236, 13, 2713, 288, 203, 202, 202, 6528, 12, 4631, 480, 1758, 12, 20, 10019, 203, 202, 202, 6528, 12, 5, 5332, 12, 4615, 16, 2236, 10019, 203, 203, 202, 202, 4615, 18, 29400, 264, 63, 4631, 65, 273, 638, 31, 203, 202, 97, 203, 203, 202, 915, 1206, 12, 2996, 2502, 2478, 16, 1758, 2236, 13, 2713, 288, 203, 202, 202, 6528, 12, 4631, 480, 1758, 12, 20, 10019, 203, 202, 202, 6528, 12, 5332, 12, 4615, 16, 2236, 10019, 203, 203, 202, 202, 4615, 18, 29400, 264, 63, 4631, 65, 273, 629, 31, 203, 202, 97, 203, 203, 202, 915, 711, 12, 2996, 2502, 2478, 16, 1758, 2236, 13, 2713, 1476, 1135, 261, 6430, 13, 288, 203, 202, 202, 6528, 12, 4631, 480, 1758, 12, 20, 10019, 203, 202, 202, 2463, 2478, 18, 29400, 264, 63, 4631, 15533, 203, 202, 97, 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 ]
/** *Submitted for verification at Etherscan.io on 2021-07-05 */ /* */ // SPDX-License-Identifier: Unlicensed pragma solidity ^0.6.12; abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return payable(msg.sender); } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval( address indexed owner, address indexed spender, uint256 value ); } library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } library Address { 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); } 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" ); } function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue( target, data, value, "Address: low-level call with value failed" ); } function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require( address(this).balance >= value, "Address: insufficient balance for call" ); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue( address target, bytes memory data, uint256 weiValue, string memory errorMessage ) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: weiValue}( data ); if (success) { return returndata; } else { if (returndata.length > 0) { assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } contract Ownable is Context { address private _owner; address private _previousOwner; uint256 private _lockTime; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); constructor() public{ address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } function owner() public view returns (address) { return _owner; } modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } function transferOwnership(address newOwner) public virtual onlyOwner { require( newOwner != address(0), "Ownable: new owner is the zero address" ); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } function getUnlockTime() public view returns (uint256) { return _lockTime; } function getTime() public view returns (uint256) { return block.timestamp; } function lock(uint256 time) public virtual onlyOwner { _previousOwner = _owner; _owner = address(0); _lockTime = block.timestamp + time; emit OwnershipTransferred(_owner, address(0)); } function unlock() public virtual { require( _previousOwner == msg.sender, "You don't have permission to unlock" ); require(block.timestamp > _lockTime, "Contract is locked until 7 days"); emit OwnershipTransferred(_owner, _previousOwner); _owner = _previousOwner; } } // pragma solidity >=0.5.0; interface IUniswapV2Factory { event PairCreated( address indexed token0, address indexed token1, address pair, uint256 ); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint256) external view returns (address pair); function allPairsLength() external view returns (uint256); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } // pragma solidity >=0.5.0; interface IUniswapV2Pair { event Approval( address indexed owner, address indexed spender, uint256 value ); event Transfer(address indexed from, address indexed to, uint256 value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint256); function balanceOf(address owner) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 value) external returns (bool); function transfer(address to, uint256 value) external returns (bool); function transferFrom( address from, address to, uint256 value ) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint256); function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; event Burn( address indexed sender, uint256 amount0, uint256 amount1, address indexed to ); event Swap( address indexed sender, uint256 amount0In, uint256 amount1In, uint256 amount0Out, uint256 amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint256); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns ( uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast ); function price0CumulativeLast() external view returns (uint256); function price1CumulativeLast() external view returns (uint256); function kLast() external view returns (uint256); function burn(address to) external returns (uint256 amount0, uint256 amount1); function swap( uint256 amount0Out, uint256 amount1Out, address to, bytes calldata data ) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } // pragma solidity >=0.6.2; interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint256 amountADesired, uint256 amountBDesired, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns ( uint256 amountA, uint256 amountB, uint256 liquidity ); function addLiquidityETH( address token, uint256 amountTokenDesired, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external payable returns ( uint256 amountToken, uint256 amountETH, uint256 liquidity ); function removeLiquidity( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns (uint256 amountA, uint256 amountB); function removeLiquidityETH( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external returns (uint256 amountToken, uint256 amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint256 amountA, uint256 amountB); function removeLiquidityETHWithPermit( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint256 amountToken, uint256 amountETH); function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapTokensForExactTokens( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapExactETHForTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function swapTokensForExactETH( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapExactTokensForETH( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapETHForExactTokens( uint256 amountOut, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function quote( uint256 amountA, uint256 reserveA, uint256 reserveB ) external pure returns (uint256 amountB); function getAmountOut( uint256 amountIn, uint256 reserveIn, uint256 reserveOut ) external pure returns (uint256 amountOut); function getAmountIn( uint256 amountOut, uint256 reserveIn, uint256 reserveOut ) external pure returns (uint256 amountIn); function getAmountsOut(uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts); function getAmountsIn(uint256 amountOut, address[] calldata path) external view returns (uint256[] memory amounts); } // pragma solidity >=0.6.2; interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external returns (uint256 amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint256 amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external; } interface SafeToken { function withdraw(address _token, uint256 _amount) external; function withdrawBNB(uint256 _amount) external; } contract COSBYTOKEN is Context, IERC20, Ownable, SafeToken { using SafeMath for uint256; using Address for address; address payable public safeManager; address payable public marketingAddress = payable(0xFB9052Df90FbcCA2E97b6Ef32c581BB786477866); // Marketing Address address public immutable charity = 0x886CCD2dBeEe54ac84224633E1Df769038015E0D; mapping(address => uint256) private _rOwned; mapping(address => uint256) private _tOwned; mapping(address => mapping(address => uint256)) private _allowances; mapping(address => bool) private _isExcludedFromFee; mapping(address => bool) private _isExcluded; address[] private _excluded; uint256 private constant MAX = ~uint256(0); uint256 private _tTotal = 310000000 * 10**9; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; string private _name = "COSBY TOKEN"; string private _symbol = "COSBY"; uint8 private _decimals = 9; uint256 public _taxFee = 3; uint256 private _previousTaxFee = _taxFee; uint256 public _liquidityFee = 8; uint256 private _previousLiquidityFee = _liquidityFee; uint256 public _buyFee = 4; uint256 public marketingDivisor = 3; // 2% uint256 public _maxTxAmount = 6200000 * 10**9; // 1% uint256 public _maxTxAmountForSell = 3100000 * 10**9; uint256 private minimumTokensBeforeSwap = 620000 * 10**9; uint256 private buyBackUpperLimit = 2 * 10**18; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; bool inSwapAndLiquify; bool public swapAndLiquifyEnabled = false; bool public buyBackEnabled = true; event RewardLiquidityProviders(uint256 tokenAmount); event BuyBackEnabledUpdated(bool enabled); event SwapAndLiquifyEnabledUpdated(bool enabled); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiqudity ); event SwapETHForTokens(uint256 amountIn, address[] path); event SwapTokensForETH(uint256 amountIn, address[] path); modifier lockTheSwap { inSwapAndLiquify = true; _; inSwapAndLiquify = false; } constructor() public { _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; safeManager = _msgSender(); emit Transfer(address(0), _msgSender(), _tTotal); } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function totalSupply() public view override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { if (_isExcluded[account]) return _tOwned[account]; return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom( address sender, address recipient, uint256 amount ) public override returns (bool) { _transfer(sender, recipient, amount); _approve( sender, _msgSender(), _allowances[sender][_msgSender()].sub( amount, "ERC20: transfer amount exceeds allowance" ) ); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue) ); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender].sub( subtractedValue, "ERC20: decreased allowance below zero" ) ); return true; } function isExcludedFromReward(address account) public view returns (bool) { return _isExcluded[account]; } function totalFees() public view returns (uint256) { return _tFeeTotal; } function minimumTokensBeforeSwapAmount() public view returns (uint256) { return minimumTokensBeforeSwap; } function buyBackUpperLimitAmount() public view returns (uint256) { return buyBackUpperLimit; } function deliver(uint256 tAmount) public { address sender = _msgSender(); require( !_isExcluded[sender], "Excluded addresses cannot call this function" ); (uint256 rAmount, , , , , ) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rTotal = _rTotal.sub(rAmount); _tFeeTotal = _tFeeTotal.add(tAmount); } function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns (uint256) { require(tAmount <= _tTotal, "Amount must be less than supply"); if (!deductTransferFee) { (uint256 rAmount, , , , , ) = _getValues(tAmount); return rAmount; } else { (, uint256 rTransferAmount, , , , ) = _getValues(tAmount); return rTransferAmount; } } function tokenFromReflection(uint256 rAmount) public view returns (uint256) { require( rAmount <= _rTotal, "Amount must be less than total reflections" ); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function excludeFromReward(address account) public onlyOwner() { require(!_isExcluded[account], "Account is already excluded"); if (_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); } _isExcluded[account] = true; _excluded.push(account); } function includeInReward(address account) external onlyOwner() { require(_isExcluded[account], "Account is already excluded"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tOwned[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } function _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"); // prevent hoarding and dumping if (!_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { // restrict selling at 0.5% if (to == uniswapV2Pair) { require( amount <= _maxTxAmountForSell, "Transfer amount exceeds the maxTxAmountForSell." ); } else { // restrict buying at 2% require( amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount." ); } } uint256 contractTokenBalance = balanceOf(address(this)); bool overMinimumTokenBalance = contractTokenBalance >= minimumTokensBeforeSwap; // make the swap if (!inSwapAndLiquify && swapAndLiquifyEnabled && to == uniswapV2Pair) { if (overMinimumTokenBalance) { contractTokenBalance = minimumTokensBeforeSwap; swapTokens(contractTokenBalance); } // buyback token by BNB balance uint256 balance = address(this).balance; if (buyBackEnabled && balance > uint256(1 * 10**18)) { if (balance > buyBackUpperLimit) balance = buyBackUpperLimit; buyBackTokens(balance.div(100)); } } // is fee changing? bool feeFlag = false; //if any account belongs to _isExcludedFromFee if (_isExcludedFromFee[from] || _isExcludedFromFee[to]) { feeFlag = true; removeAllFee(); } else if (from == uniswapV2Pair) { // discount fee for user buy token feeFlag = true; changeBuyingFee(); } _tokenTransfer(from, to, amount); if (feeFlag) restoreAllFee(); } function swapTokens(uint256 contractTokenBalance) private lockTheSwap { uint256 initialBalance = address(this).balance; swapTokensForEth(contractTokenBalance); uint256 transferredBalance = address(this).balance.sub(initialBalance); //Send to Marketing address transferToAddressETH( marketingAddress, transferredBalance.div(_liquidityFee).mul(marketingDivisor) ); } function buyBackTokens(uint256 amount) private lockTheSwap { if (amount > 0) { swapETHForTokens(amount); } } function swapTokensForEth(uint256 tokenAmount) private { // generate the uniswap pair path of token -> weth address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); // make the swap uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), // The contract block.timestamp ); emit SwapTokensForETH(tokenAmount, path); } function swapETHForTokens(uint256 amount) private { // generate the uniswap pair path of token -> weth address[] memory path = new address[](2); path[0] = uniswapV2Router.WETH(); path[1] = address(this); // make the swap and support token for charity uniswapV2Router.swapExactETHForTokensSupportingFeeOnTransferTokens{ value: amount }( 0, // accept any amount of Tokens path, charity, // buy back token for charity fund block.timestamp.add(300) ); emit SwapETHForTokens(amount, path); } function _tokenTransfer( address sender, address recipient, uint256 amount ) private { if (_isExcluded[sender] && !_isExcluded[recipient]) { _transferFromExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && _isExcluded[recipient]) { _transferToExcluded(sender, recipient, amount); } else if (_isExcluded[sender] && _isExcluded[recipient]) { _transferBothExcluded(sender, recipient, amount); } else { _transferStandard(sender, recipient, amount); } } function _transferStandard( address sender, address recipient, uint256 tAmount ) private { ( uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity ) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferToExcluded( address sender, address recipient, uint256 tAmount ) private { ( uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity ) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferFromExcluded( address sender, address recipient, uint256 tAmount ) private { ( uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity ) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferBothExcluded( address sender, address recipient, uint256 tAmount ) private { ( uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity ) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } function _getValues(uint256 tAmount) private view returns ( uint256, uint256, uint256, uint256, uint256, uint256 ) { ( uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity ) = _getTValues(tAmount); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues( tAmount, tFee, tLiquidity, _getRate() ); return ( rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tLiquidity ); } function _getTValues(uint256 tAmount) private view returns ( uint256, uint256, uint256 ) { uint256 tFee = calculateTaxFee(tAmount); uint256 tLiquidity = calculateLiquidityFee(tAmount); uint256 tTransferAmount = tAmount.sub(tFee).sub(tLiquidity); return (tTransferAmount, tFee, tLiquidity); } function _getRValues( uint256 tAmount, uint256 tFee, uint256 tLiquidity, uint256 currentRate ) private pure returns ( uint256, uint256, uint256 ) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rLiquidity = tLiquidity.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee).sub(rLiquidity); return (rAmount, rTransferAmount, rFee); } function _getRate() private view returns (uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns (uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; for (uint256 i = 0; i < _excluded.length; i++) { if ( _rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply ) return (_rTotal, _tTotal); rSupply = rSupply.sub(_rOwned[_excluded[i]]); tSupply = tSupply.sub(_tOwned[_excluded[i]]); } if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } function _takeLiquidity(uint256 tLiquidity) private { uint256 currentRate = _getRate(); uint256 rLiquidity = tLiquidity.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rLiquidity); if (_isExcluded[address(this)]) _tOwned[address(this)] = _tOwned[address(this)].add(tLiquidity); } function calculateTaxFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_taxFee).div(10**2); } function calculateLiquidityFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_liquidityFee).div(10**2); } function removeAllFee() private { if (_taxFee == 0 && _liquidityFee == 0) return; _previousTaxFee = _taxFee; _previousLiquidityFee = _liquidityFee; _taxFee = 0; _liquidityFee = 0; } function restoreAllFee() private { _taxFee = _previousTaxFee; _liquidityFee = _previousLiquidityFee; } function changeBuyingFee() private { _previousTaxFee = _taxFee; _previousLiquidityFee = _liquidityFee; _liquidityFee = _buyFee; } function isExcludedFromFee(address account) public view returns (bool) { return _isExcludedFromFee[account]; } function excludeFromFee(address account) public onlyOwner { _isExcludedFromFee[account] = true; } function includeInFee(address account) public onlyOwner { _isExcludedFromFee[account] = false; } function setTaxFeePercent(uint256 taxFee) external onlyOwner() { _taxFee = taxFee; } function setLiquidityFeePercent(uint256 liquidityFee) external onlyOwner() { _liquidityFee = liquidityFee; } function setMaxTxAmount(uint256 maxTxAmount) external onlyOwner() { _maxTxAmount = maxTxAmount; } function setMaxTxAmountForSell(uint256 maxTxAmountForSell) external onlyOwner() { _maxTxAmountForSell = maxTxAmountForSell; } function setMarketingDivisor(uint256 divisor) external onlyOwner() { marketingDivisor = divisor; } function setNumTokensSellToAddToLiquidity(uint256 _minimumTokensBeforeSwap) external onlyOwner() { minimumTokensBeforeSwap = _minimumTokensBeforeSwap; } function setBuybackUpperLimit(uint256 buyBackLimit) external onlyOwner() { buyBackUpperLimit = buyBackLimit * 10**18; } function setMarketingAddress(address _marketingAddress) external onlyOwner() { marketingAddress = payable(_marketingAddress); } function setSwapAndLiquifyEnabled(bool _enabled) public onlyOwner { swapAndLiquifyEnabled = _enabled; emit SwapAndLiquifyEnabledUpdated(_enabled); } function setBuyBackEnabled(bool _enabled) public onlyOwner { buyBackEnabled = _enabled; emit BuyBackEnabledUpdated(_enabled); } function setSafeManager(address payable _safeManager) public onlyOwner { safeManager = _safeManager; } function prepareForPreSale() external onlyOwner { setSwapAndLiquifyEnabled(false); _taxFee = 0; _liquidityFee = 0; _maxTxAmount = 310000000 * 10**9; } function afterPreSale() external onlyOwner { setSwapAndLiquifyEnabled(true); _taxFee = 3; _liquidityFee = 8; _maxTxAmount = 6200000 * 10**9; } function transferToAddressETH(address payable recipient, uint256 amount) private { recipient.transfer(amount); } function withdraw(address _token, uint256 _amount) external override { require(msg.sender == safeManager); IERC20(_token).transfer(msg.sender, _amount); } function withdrawBNB(uint256 _amount) external override { require(msg.sender == safeManager); transferToAddressETH(_msgSender(), _amount); } //to recieve ETH from uniswapV2Router when swaping receive() external payable {} }
prevent hoarding and dumping restrict selling at 0.5% restrict buying at 2% make the swapif any account belongs to _isExcludedFromFee discount fee for user buy token
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 (!_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { if (to == uniswapV2Pair) { require( amount <= _maxTxAmountForSell, "Transfer amount exceeds the maxTxAmountForSell." ); require( amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount." ); } } uint256 contractTokenBalance = balanceOf(address(this)); bool overMinimumTokenBalance = contractTokenBalance >= minimumTokensBeforeSwap; if (!inSwapAndLiquify && swapAndLiquifyEnabled && to == uniswapV2Pair) { if (overMinimumTokenBalance) { contractTokenBalance = minimumTokensBeforeSwap; swapTokens(contractTokenBalance); } if (buyBackEnabled && balance > uint256(1 * 10**18)) { if (balance > buyBackUpperLimit) balance = buyBackUpperLimit; buyBackTokens(balance.div(100)); } } if (_isExcludedFromFee[from] || _isExcludedFromFee[to]) { feeFlag = true; removeAllFee(); feeFlag = true; changeBuyingFee(); } _tokenTransfer(from, to, amount); if (feeFlag) restoreAllFee(); }
10,524,258
[ 1, 29150, 26025, 1060, 310, 471, 4569, 1382, 13108, 357, 2456, 622, 374, 18, 25, 9, 13108, 30143, 310, 622, 576, 9, 1221, 326, 7720, 430, 1281, 2236, 11081, 358, 389, 291, 16461, 1265, 14667, 12137, 14036, 364, 729, 30143, 1147, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 13866, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 3844, 203, 565, 262, 3238, 288, 203, 3639, 2583, 12, 2080, 480, 1758, 12, 20, 3631, 315, 654, 39, 3462, 30, 7412, 628, 326, 3634, 1758, 8863, 203, 3639, 2583, 12, 869, 480, 1758, 12, 20, 3631, 315, 654, 39, 3462, 30, 7412, 358, 326, 3634, 1758, 8863, 203, 3639, 2583, 12, 8949, 405, 374, 16, 315, 5912, 3844, 1297, 506, 6802, 2353, 3634, 8863, 203, 203, 3639, 309, 16051, 67, 291, 16461, 1265, 14667, 63, 2080, 65, 597, 401, 67, 291, 16461, 1265, 14667, 63, 869, 5717, 288, 203, 5411, 309, 261, 869, 422, 640, 291, 91, 438, 58, 22, 4154, 13, 288, 203, 7734, 2583, 12, 203, 10792, 3844, 1648, 389, 1896, 4188, 6275, 1290, 55, 1165, 16, 203, 10792, 315, 5912, 3844, 14399, 326, 943, 4188, 6275, 1290, 55, 1165, 1199, 203, 7734, 11272, 203, 7734, 2583, 12, 203, 10792, 3844, 1648, 389, 1896, 4188, 6275, 16, 203, 10792, 315, 5912, 3844, 14399, 326, 943, 4188, 6275, 1199, 203, 7734, 11272, 203, 5411, 289, 203, 3639, 289, 203, 203, 3639, 2254, 5034, 6835, 1345, 13937, 273, 11013, 951, 12, 2867, 12, 2211, 10019, 203, 3639, 1426, 1879, 13042, 1345, 13937, 273, 6835, 1345, 13937, 1545, 203, 5411, 5224, 5157, 4649, 12521, 31, 203, 3639, 309, 16051, 267, 12521, 1876, 48, 18988, 1164, 597, 7720, 1876, 48, 18988, 1164, 1526, 597, 358, 422, 640, 291, 91, 438, 58, 22, 4154, 13, 288, 203, 2 ]
./partial_match/1/0xe08852902868aDEE71CA490D9d93Fd55f5bEc200/sources/SteamedHams.sol
* @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. ====/ 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.
function isContract(address account) internal view returns (bool) { return account.code.length > 0; }
3,536,690
[ 1, 1356, 638, 309, 1375, 4631, 68, 353, 279, 6835, 18, 306, 20445, 6856, 65, 422, 631, 2597, 353, 7127, 358, 6750, 716, 392, 1758, 364, 1492, 333, 445, 1135, 629, 353, 392, 18885, 1230, 17, 995, 329, 2236, 261, 41, 28202, 13, 471, 486, 279, 6835, 18, 3986, 932, 10654, 16, 1375, 291, 8924, 68, 903, 327, 629, 364, 326, 3751, 1953, 434, 6138, 30, 225, 300, 392, 18885, 1230, 17, 995, 329, 2236, 225, 300, 279, 6835, 316, 16171, 225, 300, 392, 1758, 1625, 279, 6835, 903, 506, 2522, 225, 300, 392, 1758, 1625, 279, 6835, 328, 2950, 16, 1496, 1703, 17689, 422, 631, 306, 20445, 6856, 65, 422, 631, 4554, 12044, 1404, 21187, 603, 1375, 291, 8924, 68, 358, 17151, 5314, 9563, 28183, 28444, 5, 19412, 310, 4097, 628, 20092, 353, 3551, 715, 19169, 477, 11349, 18, 2597, 16217, 532, 917, 2967, 16, 16217, 2865, 364, 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, 353, 8924, 12, 2867, 2236, 13, 2713, 1476, 1135, 261, 6430, 13, 288, 7010, 3639, 327, 2236, 18, 710, 18, 2469, 405, 374, 31, 7010, 565, 289, 7010, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/4/0x0F73DAca635CaA591dda9e242e98F781dcF6E7A2/sources/OroNetwork.sol
* Swap Get back USDC with Asset/
function swapOut(address assetAdd, uint256 asset) external whenNotPaused validateAsset(assetAdd) { _swapOut(assetAdd, asset); }
8,601,968
[ 1, 12521, 968, 1473, 11836, 5528, 598, 10494, 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, 7720, 1182, 12, 2867, 3310, 986, 16, 2254, 5034, 3310, 13, 7010, 3639, 3903, 203, 3639, 1347, 1248, 28590, 203, 3639, 1954, 6672, 12, 9406, 986, 13, 288, 203, 3639, 389, 22270, 1182, 12, 9406, 986, 16, 3310, 1769, 203, 565, 289, 203, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity 0.8.6; import "openzeppelin-solidity/contracts/utils/math/SafeMath.sol"; import "openzeppelin-solidity/contracts/token/ERC20/IERC20.sol"; import "openzeppelin-solidity/contracts/token/ERC20/utils/SafeERC20.sol"; import "./OwnableInitializable.sol"; import "./MathUtils.sol"; import "./ITokenLock.sol"; // this contract is based on GraphTokenLock // see https://github.com/graphprotocol/token-distribution/blob/main/contracts/GraphTokenLock.sol /** * @title HatTokenLock * @notice Contract that manages an unlocking schedule of tokens. * @dev The contract lock manage a number of tokens deposited into the contract to ensure that * they can only be released under certain time conditions. * * This contract implements a release scheduled based on periods and tokens are released in steps * after each period ends. It can be configured with one period in which case it is like a plain TimeLock. * It also supports revocation to be used for vesting schedules. * * The contract supports receiving extra funds than the managed tokens ones that can be * withdrawn by the beneficiary at any time. * * A releaseStartTime parameter is included to override the default release schedule and * perform the first release on the configured time. After that it will continue with the * default schedule. */ // solhint-disable-next-line indent abstract contract TokenLock is OwnableInitializable, ITokenLock { using SafeMath for uint256; using SafeERC20 for IERC20; uint256 private constant MIN_PERIOD = 1; // -- State -- IERC20 public token; address public beneficiary; // Configuration // Amount of tokens managed by the contract schedule uint256 public managedAmount; uint256 public startTime; // Start datetime (in unixtimestamp) uint256 public endTime; // Datetime after all funds are fully vested/unlocked (in unixtimestamp) uint256 public periods; // Number of vesting/release periods // First release date for tokens (in unixtimestamp) // If set, no tokens will be released before releaseStartTime ignoring // the amount to release each period uint256 public releaseStartTime; // A cliff set a date to which a beneficiary needs to get to vest // all preceding periods uint256 public vestingCliffTime; Revocability public revocable; // Whether to use vesting for locked funds // State bool public isRevoked; bool public isInitialized; bool public isAccepted; uint256 public releasedAmount; // -- Events -- event TokensReleased(address indexed beneficiary, uint256 amount); event TokensWithdrawn(address indexed beneficiary, uint256 amount); event TokensRevoked(address indexed beneficiary, uint256 amount); event BeneficiaryChanged(address newBeneficiary); event LockAccepted(); event LockCanceled(); /** * @dev Only allow calls from the beneficiary of the contract */ modifier onlyBeneficiary() { require(msg.sender == beneficiary, "!auth"); _; } /** * @notice Initializes the contract * @param _tokenLockOwner Address of the contract owner * @param _beneficiary Address of the beneficiary of locked tokens * @param _managedAmount Amount of tokens to be managed by the lock contract * @param _startTime Start time of the release schedule * @param _endTime End time of the release schedule * @param _periods Number of periods between start time and end time * @param _releaseStartTime Override time for when the releases start * @param _vestingCliffTime Override time for when the vesting start * @param _revocable Whether the contract is revocable */ function _initialize( address _tokenLockOwner, address _beneficiary, address _token, uint256 _managedAmount, uint256 _startTime, uint256 _endTime, uint256 _periods, uint256 _releaseStartTime, uint256 _vestingCliffTime, Revocability _revocable ) internal { require(!isInitialized, "Already initialized"); require(_tokenLockOwner != address(0), "Owner cannot be zero"); require(_beneficiary != address(0), "Beneficiary cannot be zero"); require(_token != address(0), "Token cannot be zero"); require(_managedAmount > 0, "Managed tokens cannot be zero"); require(_startTime != 0, "Start time must be set"); require(_startTime < _endTime, "Start time > end time"); require(_periods >= MIN_PERIOD, "Periods cannot be below minimum"); require(_revocable != Revocability.NotSet, "Must set a revocability option"); require(_releaseStartTime < _endTime, "Release start time must be before end time"); require(_vestingCliffTime < _endTime, "Cliff time must be before end time"); isInitialized = true; OwnableInitializable.initialize(_tokenLockOwner); beneficiary = _beneficiary; token = IERC20(_token); managedAmount = _managedAmount; startTime = _startTime; endTime = _endTime; periods = _periods; // Optionals releaseStartTime = _releaseStartTime; vestingCliffTime = _vestingCliffTime; revocable = _revocable; } /** * @notice Change the beneficiary of funds managed by the contract * @dev Can only be called by the beneficiary * @param _newBeneficiary Address of the new beneficiary address */ function changeBeneficiary(address _newBeneficiary) external onlyBeneficiary { require(_newBeneficiary != address(0), "Empty beneficiary"); beneficiary = _newBeneficiary; emit BeneficiaryChanged(_newBeneficiary); } /** * @notice Beneficiary accepts the lock, the owner cannot retrieve back the tokens * @dev Can only be called by the beneficiary */ function acceptLock() external onlyBeneficiary { isAccepted = true; emit LockAccepted(); } /** * @notice Owner cancel the lock and return the balance in the contract * @dev Can only be called by the owner */ function cancelLock() external onlyOwner { require(isAccepted == false, "Cannot cancel accepted contract"); token.safeTransfer(owner(), currentBalance()); emit LockCanceled(); } // -- Balances -- /** * @notice Returns the amount of tokens currently held by the contract * @return Tokens held in the contract */ function currentBalance() public override view returns (uint256) { return token.balanceOf(address(this)); } // -- Time & Periods -- /** * @notice Returns the current block timestamp * @return Current block timestamp */ function currentTime() public override view returns (uint256) { // solhint-disable-next-line not-rely-on-time return block.timestamp; } /** * @notice Gets duration of contract from start to end in seconds * @return Amount of seconds from contract startTime to endTime */ function duration() public override view returns (uint256) { return endTime.sub(startTime); } /** * @notice Gets time elapsed since the start of the contract * @dev Returns zero if called before conctract starTime * @return Seconds elapsed from contract startTime */ function sinceStartTime() public override view returns (uint256) { uint256 current = currentTime(); if (current <= startTime) { return 0; } return current.sub(startTime); } /** * @notice Returns amount available to be released after each period according to schedule * @return Amount of tokens available after each period */ function amountPerPeriod() public override view returns (uint256) { return managedAmount.div(periods); } /** * @notice Returns the duration of each period in seconds * @return Duration of each period in seconds */ function periodDuration() public override view returns (uint256) { return duration().div(periods); } /** * @notice Gets the current period based on the schedule * @return A number that represents the current period */ function currentPeriod() public override view returns (uint256) { return sinceStartTime().div(periodDuration()).add(MIN_PERIOD); } /** * @notice Gets the number of periods that passed since the first period * @return A number of periods that passed since the schedule started */ function passedPeriods() public override view returns (uint256) { return currentPeriod().sub(MIN_PERIOD); } // -- Locking & Release Schedule -- /** * @notice Gets the currently available token according to the schedule * @dev Implements the step-by-step schedule based on periods for available tokens * @return Amount of tokens available according to the schedule */ function availableAmount() public override view returns (uint256) { uint256 current = currentTime(); // Before contract start no funds are available if (current < startTime) { return 0; } // After contract ended all funds are available if (current > endTime) { return managedAmount; } // Get available amount based on period return passedPeriods().mul(amountPerPeriod()); } /** * @notice Gets the amount of currently vested tokens * @dev Similar to available amount, but is fully vested when contract is non-revocable * @return Amount of tokens already vested */ function vestedAmount() public override view returns (uint256) { // If non-revocable it is fully vested if (revocable == Revocability.Disabled) { return managedAmount; } // Vesting cliff is activated and it has not passed means nothing is vested yet if (vestingCliffTime > 0 && currentTime() < vestingCliffTime) { return 0; } return availableAmount(); } /** * @notice Gets tokens currently available for release * @dev Considers the schedule and takes into account already released tokens * @return Amount of tokens ready to be released */ function releasableAmount() public override view returns (uint256) { // If a release start time is set no tokens are available for release before this date // If not set it follows the default schedule and tokens are available on // the first period passed if (releaseStartTime > 0 && currentTime() < releaseStartTime) { return 0; } // Vesting cliff is activated and it has not passed means nothing is vested yet // so funds cannot be released if (revocable == Revocability.Enabled && vestingCliffTime > 0 && currentTime() < vestingCliffTime) { return 0; } // A beneficiary can never have more releasable tokens than the contract balance uint256 releasable = availableAmount().sub(releasedAmount); return MathUtils.min(currentBalance(), releasable); } /** * @notice Gets the outstanding amount yet to be released based on the whole contract lifetime * @dev Does not consider schedule but just global amounts tracked * @return Amount of outstanding tokens for the lifetime of the contract */ function totalOutstandingAmount() public override view returns (uint256) { return managedAmount.sub(releasedAmount); } /** * @notice Gets surplus amount in the contract based on outstanding amount to release * @dev All funds over outstanding amount is considered surplus that can be withdrawn by beneficiary * @return Amount of tokens considered as surplus */ function surplusAmount() public override view returns (uint256) { uint256 balance = currentBalance(); uint256 outstandingAmount = totalOutstandingAmount(); if (balance > outstandingAmount) { return balance.sub(outstandingAmount); } return 0; } // -- Value Transfer -- /** * @notice Releases tokens based on the configured schedule * @dev All available releasable tokens are transferred to beneficiary */ function release() external override onlyBeneficiary { uint256 amountToRelease = releasableAmount(); require(amountToRelease > 0, "No available releasable amount"); releasedAmount = releasedAmount.add(amountToRelease); token.safeTransfer(beneficiary, amountToRelease); emit TokensReleased(beneficiary, amountToRelease); } /** * @notice Withdraws surplus, unmanaged tokens from the contract * @dev Tokens in the contract over outstanding amount are considered as surplus * @param _amount Amount of tokens to withdraw */ function withdrawSurplus(uint256 _amount) external override onlyBeneficiary { require(_amount > 0, "Amount cannot be zero"); require(surplusAmount() >= _amount, "Amount requested > surplus available"); token.safeTransfer(beneficiary, _amount); emit TokensWithdrawn(beneficiary, _amount); } /** * @notice Revokes a vesting schedule and return the unvested tokens to the owner * @dev Vesting schedule is always calculated based on managed tokens */ function revoke() external override onlyOwner { require(revocable == Revocability.Enabled, "Contract is non-revocable"); require(isRevoked == false, "Already revoked"); uint256 unvestedAmount = managedAmount.sub(vestedAmount()); require(unvestedAmount > 0, "No available unvested amount"); isRevoked = true; token.safeTransfer(owner(), unvestedAmount); emit TokensRevoked(beneficiary, unvestedAmount); } }
* @notice Owner cancel the lock and return the balance in the contract @dev Can only be called by the owner/
function cancelLock() external onlyOwner { require(isAccepted == false, "Cannot cancel accepted contract"); token.safeTransfer(owner(), currentBalance()); emit LockCanceled(); }
1,768,270
[ 1, 5541, 3755, 326, 2176, 471, 327, 326, 11013, 316, 326, 6835, 225, 4480, 1338, 506, 2566, 635, 326, 3410, 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, 3755, 2531, 1435, 3903, 1338, 5541, 288, 203, 3639, 2583, 12, 291, 18047, 422, 629, 16, 315, 4515, 3755, 8494, 6835, 8863, 203, 203, 3639, 1147, 18, 4626, 5912, 12, 8443, 9334, 783, 13937, 10663, 203, 203, 3639, 3626, 3488, 23163, 5621, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/* * @title String & slice utility library for Solidity contracts. * @author Nick Johnson <[email protected]> * * Source: https://github.com/Arachnid/solidity-stringutils/ */ pragma solidity ^0.5.2; library Strings { struct slice { uint _len; uint _ptr; } function memcpy(uint dest, uint src, uint len) private pure { // Copy word-length chunks while possible for(; len >= 32; len -= 32) { assembly { mstore(dest, mload(src)) } dest += 32; src += 32; } // Copy remaining bytes uint mask = 256 ** (32 - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) let destpart := and(mload(dest), mask) mstore(dest, or(destpart, srcpart)) } } /* * @dev Returns a slice containing the entire string. * @param self The string to make a slice from. * @return A newly allocated slice containing the entire string. */ function toSlice(string memory self) internal pure returns (slice memory) { uint ptr; assembly { ptr := add(self, 0x20) } return slice(bytes(self).length, ptr); } /* * @dev Copies a slice to a new string. * @param self The slice to copy. * @return A newly allocated string containing the slice's text. */ function toString(slice memory self) internal pure returns (string memory) { string memory ret = new string(self._len); uint retptr; assembly { retptr := add(ret, 32) } memcpy(retptr, self._ptr, self._len); return ret; } // Returns the memory address of the first byte of the first occurrence of // `needle` in `self`, or the first byte after `self` if not found. function findPtr(uint selflen, uint selfptr, uint needlelen, uint needleptr) private pure returns (uint) { uint ptr = selfptr; uint idx; if (needlelen <= selflen) { if (needlelen <= 32) { bytes32 mask = bytes32(~(2 ** (8 * (32 - needlelen)) - 1)); bytes32 needledata; assembly { needledata := and(mload(needleptr), mask) } uint end = selfptr + selflen - needlelen; bytes32 ptrdata; assembly { ptrdata := and(mload(ptr), mask) } while (ptrdata != needledata) { if (ptr >= end) return selfptr + selflen; ptr++; assembly { ptrdata := and(mload(ptr), mask) } } return ptr; } else { // For long needles, use hashing bytes32 hash; assembly { hash := keccak256(needleptr, needlelen) } for (idx = 0; idx <= selflen - needlelen; idx++) { bytes32 testHash; assembly { testHash := keccak256(ptr, needlelen) } if (hash == testHash) return ptr; ptr += 1; } } } return selfptr + selflen; } /* * @dev Splits the slice, setting `self` to everything after the first * occurrence of `needle`, and `token` to everything before it. If * `needle` does not occur in `self`, `self` is set to the empty slice, * and `token` is set to the entirety of `self`. * @param self The slice to split. * @param needle The text to search for in `self`. * @param token An output parameter to which the first token is written. * @return `token`. */ function split(slice memory self, slice memory needle, slice memory token) internal pure returns (slice memory) { uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr); token._ptr = self._ptr; token._len = ptr - self._ptr; if (ptr == self._ptr + self._len) { // Not found self._len = 0; } else { self._len -= token._len + needle._len; self._ptr = ptr + needle._len; } return token; } /* * @dev Splits the slice, setting `self` to everything after the first * occurrence of `needle`, and returning everything before it. If * `needle` does not occur in `self`, `self` is set to the empty slice, * and the entirety of `self` is returned. * @param self The slice to split. * @param needle The text to search for in `self`. * @return The part of `self` up to the first occurrence of `delim`. */ function split(slice memory self, slice memory needle) internal pure returns (slice memory token) { split(self, needle, token); } /* * @dev Counts the number of nonoverlapping occurrences of `needle` in `self`. * @param self The slice to search. * @param needle The text to search for in `self`. * @return The number of occurrences of `needle` found in `self`. */ function count(slice memory self, slice memory needle) internal pure returns (uint cnt) { uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr) + needle._len; while (ptr <= self._ptr + self._len) { cnt++; ptr = findPtr(self._len - (ptr - self._ptr), ptr, needle._len, needle._ptr) + needle._len; } } }
@dev Counts the number of nonoverlapping occurrences of `needle` in `self`. @param self The slice to search. @param needle The text to search for in `self`. @return The number of occurrences of `needle` found in `self`./
function count(slice memory self, slice memory needle) internal pure returns (uint cnt) { uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr) + needle._len; while (ptr <= self._ptr + self._len) { cnt++; ptr = findPtr(self._len - (ptr - self._ptr), ptr, needle._len, needle._ptr) + needle._len; } }
899,693
[ 1, 9211, 326, 1300, 434, 1661, 17946, 1382, 15698, 434, 1375, 14891, 298, 68, 316, 1375, 2890, 8338, 225, 365, 1021, 2788, 358, 1623, 18, 225, 9936, 1021, 977, 358, 1623, 364, 316, 1375, 2890, 8338, 327, 1021, 1300, 434, 15698, 434, 1375, 14891, 298, 68, 1392, 316, 1375, 2890, 8338, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1056, 12, 6665, 3778, 365, 16, 2788, 3778, 9936, 13, 2713, 16618, 1135, 261, 11890, 7599, 13, 288, 203, 3639, 2254, 6571, 273, 1104, 5263, 12, 2890, 6315, 1897, 16, 365, 6315, 6723, 16, 9936, 6315, 1897, 16, 9936, 6315, 6723, 13, 397, 9936, 6315, 1897, 31, 203, 3639, 1323, 261, 6723, 1648, 365, 6315, 6723, 397, 365, 6315, 1897, 13, 288, 203, 5411, 7599, 9904, 31, 203, 5411, 6571, 273, 1104, 5263, 12, 2890, 6315, 1897, 300, 261, 6723, 300, 365, 6315, 6723, 3631, 6571, 16, 9936, 6315, 1897, 16, 9936, 6315, 6723, 13, 397, 9936, 6315, 1897, 31, 203, 3639, 289, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// File: contracts/interface/ICash.sol pragma solidity >=0.4.24; interface ICash { function claimDividends(address account) external returns (uint256); function transfer(address to, uint256 value) external returns(bool); function transferFrom(address from, address to, uint256 value) external returns(bool); function balanceOf(address who) external view returns(uint256); function allowance(address owner_, address spender) external view returns(uint256); function approve(address spender, uint256 value) external returns (bool); function increaseAllowance(address spender, uint256 addedValue) external returns (bool); function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool); function totalSupply() external view returns (uint256); function rebase(uint256 epoch, int256 supplyDelta) external returns (uint256); function mintCash(address account, uint256 amount) external returns (bool); } // File: openzeppelin-eth/contracts/math/SafeMath.sol pragma solidity ^0.4.24; /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring '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 numbers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0); // Solidity only automatically asserts when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } // File: zos-lib/contracts/Initializable.sol pragma solidity >=0.4.24 <0.6.0; /** * @title Initializable * * @dev Helper contract to support initializer functions. To use it, replace * the constructor with a function that has the `initializer` modifier. * WARNING: Unlike constructors, initializer functions must be manually * invoked. This applies both to deploying an Initializable contract, as well * as extending an Initializable contract via inheritance. * WARNING: When used with inheritance, manual care must be taken to not invoke * a parent initializer twice, or ensure that all initializers are idempotent, * because this is not dealt with automatically as with constructors. */ contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private initializing; /** * @dev Modifier to use in the initializer function of a contract. */ modifier initializer() { require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized"); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = true; } _; if (isTopLevelCall) { initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. uint256 cs; assembly { cs := extcodesize(address) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } // File: openzeppelin-eth/contracts/ownership/Ownable.sol pragma solidity ^0.4.24; /** * @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 is Initializable { address private _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. */ function initialize(address sender) public initializer { _owner = sender; } /** * @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 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; } uint256[50] private ______gap; } // File: openzeppelin-eth/contracts/token/ERC20/IERC20.sol pragma solidity ^0.4.24; /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); event Transfer( address indexed from, address indexed to, uint256 value ); event Approval( address indexed owner, address indexed spender, uint256 value ); } // File: openzeppelin-eth/contracts/token/ERC20/ERC20Detailed.sol pragma solidity ^0.4.24; /** * @title ERC20Detailed token * @dev The decimals are only for visualization purposes. * All the operations are done using the smallest and indivisible token unit, * just as on Ethereum all the operations are done in wei. */ contract ERC20Detailed is Initializable, IERC20 { string private _name; string private _symbol; uint8 private _decimals; function initialize(string name, string symbol, uint8 decimals) public initializer { _name = name; _symbol = symbol; _decimals = decimals; } /** * @return the name of the token. */ function name() public view returns(string) { return _name; } /** * @return the symbol of the token. */ function symbol() public view returns(string) { return _symbol; } /** * @return the number of decimals of the token. */ function decimals() public view returns(uint8) { return _decimals; } uint256[50] private ______gap; } // File: contracts/lib/SafeMathInt.sol /* MIT License Copyright (c) 2018 requestnetwork Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ pragma solidity >=0.4.24; /** * @title SafeMathInt * @dev Math operations for int256 with overflow safety checks. */ library SafeMathInt { int256 private constant MIN_INT256 = int256(1) << 255; int256 private constant MAX_INT256 = ~(int256(1) << 255); /** * @dev Multiplies two int256 variables and fails on overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { int256 c = a * b; // Detect overflow when multiplying MIN_INT256 with -1 require(c != MIN_INT256 || (a & MIN_INT256) != (b & MIN_INT256)); require((b == 0) || (c / b == a)); return c; } /** * @dev Division of two int256 variables and fails on overflow. */ function div(int256 a, int256 b) internal pure returns (int256) { // Prevent overflow when dividing MIN_INT256 by -1 require(b != -1 || a != MIN_INT256); // Solidity already throws when dividing by 0. return a / b; } /** * @dev Subtracts two int256 variables and fails on overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a)); return c; } /** * @dev Adds two int256 variables and fails on overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a)); return c; } /** * @dev Converts to absolute value, and fails on overflow. */ function abs(int256 a) internal pure returns (int256) { require(a != MIN_INT256); return a < 0 ? -a : a; } } // File: contracts/euro/seigniorageEuroShares.sol pragma solidity >=0.4.24; /* * SeigniorageEuroShares ERC20 */ contract SeigniorageEuroShares is ERC20Detailed, Ownable { address private _minter; modifier onlyMinter() { require(msg.sender == _minter, "DOES_NOT_HAVE_MINTER_ROLE"); _; } using SafeMath for uint256; using SafeMathInt for int256; uint256 private constant DECIMALS = 9; uint256 private constant MAX_UINT256 = ~uint256(0); uint256 private constant INITIAL_SHARE_SUPPLY = 21 * 10**6 * 10**DECIMALS; uint256 private constant MAX_SUPPLY = ~uint128(0); // (2^128) - 1 uint256 private _totalSupply; struct Account { uint256 balance; uint256 lastDividendPoints; } bool private _initializedEuro; // eslint-ignore ICash Euros; mapping(address=>Account) private _shareBalances; mapping (address => mapping (address => uint256)) private _allowedShares; bool reEntrancyMintMutex; function setDividendPoints(address who, uint256 amount) external onlyMinter returns (bool) { _shareBalances[who].lastDividendPoints = amount; return true; } function mintShares(address who, uint256 amount) external onlyMinter returns (bool) { reEntrancyMintMutex = true; _shareBalances[who].balance = _shareBalances[who].balance.add(amount); _totalSupply = _totalSupply.add(amount); emit Transfer(address(0x0), who, amount); reEntrancyMintMutex = false; return true; } function externalTotalSupply() external view returns (uint256) { return _totalSupply; } function externalRawBalanceOf(address who) external view returns (uint256) { return _shareBalances[who].balance; } function lastDividendPoints(address who) external view returns (uint256) { return _shareBalances[who].lastDividendPoints; } function initialize(address owner_) public initializer { ERC20Detailed.initialize("Seigniorage Euro-Shares", "EUROSHARE", uint8(DECIMALS)); Ownable.initialize(owner_); _initializedEuro = false; _totalSupply = INITIAL_SHARE_SUPPLY; _shareBalances[owner_].balance = _totalSupply; emit Transfer(address(0x0), owner_, _totalSupply); } // instantiate euro function initializeEuro(address euroAddress) public onlyOwner { require(_initializedEuro == false, "ALREADY_INITIALIZED"); Euros = ICash(euroAddress); _initializedEuro = true; _minter = euroAddress; } /** * @return The total number of Euros. */ function totalSupply() public view returns (uint256) { return _totalSupply; } function balanceOf(address who) public view returns (uint256) { return _shareBalances[who].balance; } /** * @dev Transfer tokens to a specified address. * @param to The address to transfer to. * @param value The amount to be transferred. * @return True on success, false otherwise. */ function transfer(address to, uint256 value) public updateAccount(msg.sender) updateAccount(to) validRecipient(to) returns (bool) { require(!reEntrancyMintMutex, "RE-ENTRANCY GUARD MUST BE FALSE"); _shareBalances[msg.sender].balance = _shareBalances[msg.sender].balance.sub(value); _shareBalances[to].balance = _shareBalances[to].balance.add(value); emit Transfer(msg.sender, to, value); return true; } /** * @dev Function to check the amount of tokens that an owner has allowed to a spender. * @param owner_ The address which owns the funds. * @param spender The address which will spend the funds. * @return The number of tokens still available for the spender. */ function allowance(address owner_, address spender) public view returns (uint256) { return _allowedShares[owner_][spender]; } /** * @dev Transfer tokens from one address to another. * @param from The address you want to send tokens from. * @param to The address you want to transfer to. * @param value The amount of tokens to be transferred. */ function transferFrom(address from, address to, uint256 value) public validRecipient(to) updateAccount(from) updateAccount(msg.sender) updateAccount(to) returns (bool) { require(!reEntrancyMintMutex, "RE-ENTRANCY GUARD MUST BE FALSE"); _allowedShares[from][msg.sender] = _allowedShares[from][msg.sender].sub(value); _shareBalances[from].balance = _shareBalances[from].balance.sub(value); _shareBalances[to].balance = _shareBalances[to].balance.add(value); emit Transfer(from, to, value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of * msg.sender. This method is included for ERC20 compatibility. * increaseAllowance and decreaseAllowance should be used instead. * Changing an allowance with this method brings the risk that someone may transfer both * the old and the new allowance - if they are both greater than zero - if a transfer * transaction is mined before the later approve() call is mined. * * @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 validRecipient(spender) updateAccount(msg.sender) updateAccount(spender) returns (bool) { _allowedShares[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } modifier validRecipient(address to) { require(to != address(0x0)); require(to != address(this)); _; } /** * @dev Increase the amount of tokens that an owner has allowed to a spender. * This method should be used instead of approve() to avoid the double approval vulnerability * described above. * @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 updateAccount(msg.sender) updateAccount(spender) returns (bool) { _allowedShares[msg.sender][spender] = _allowedShares[msg.sender][spender].add(addedValue); emit Approval(msg.sender, spender, _allowedShares[msg.sender][spender]); return true; } /** * @dev Decrease the amount of tokens that an owner has allowed to a spender. * * @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 updateAccount(msg.sender) updateAccount(spender) returns (bool) { uint256 oldValue = _allowedShares[msg.sender][spender]; if (subtractedValue >= oldValue) { _allowedShares[msg.sender][spender] = 0; } else { _allowedShares[msg.sender][spender] = oldValue.sub(subtractedValue); } emit Approval(msg.sender, spender, _allowedShares[msg.sender][spender]); return true; } // attach this to any action to auto claim modifier updateAccount(address account) { require(_initializedEuro == true, "DOLLAR_NEEDS_INITIALIZATION"); Euros.claimDividends(account); _; } }
* @dev Decrease the amount of tokens that an owner has allowed to a spender. @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 updateAccount(msg.sender) updateAccount(spender) returns (bool) { uint256 oldValue = _allowedShares[msg.sender][spender]; if (subtractedValue >= oldValue) { _allowedShares[msg.sender][spender] = 0; _allowedShares[msg.sender][spender] = oldValue.sub(subtractedValue); } emit Approval(msg.sender, spender, _allowedShares[msg.sender][spender]); return true; }
7,912,283
[ 1, 23326, 448, 326, 3844, 434, 2430, 716, 392, 3410, 711, 2935, 358, 279, 17571, 264, 18, 225, 17571, 264, 1021, 1758, 1492, 903, 17571, 326, 284, 19156, 18, 225, 10418, 329, 620, 1021, 3844, 434, 2430, 358, 20467, 326, 1699, 1359, 635, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 20467, 7009, 1359, 12, 2867, 17571, 264, 16, 2254, 5034, 10418, 329, 620, 13, 203, 3639, 1071, 203, 3639, 1089, 3032, 12, 3576, 18, 15330, 13, 203, 3639, 1089, 3032, 12, 87, 1302, 264, 13, 203, 3639, 1135, 261, 6430, 13, 203, 565, 288, 203, 3639, 2254, 5034, 11144, 273, 389, 8151, 24051, 63, 3576, 18, 15330, 6362, 87, 1302, 264, 15533, 203, 3639, 309, 261, 1717, 1575, 329, 620, 1545, 11144, 13, 288, 203, 5411, 389, 8151, 24051, 63, 3576, 18, 15330, 6362, 87, 1302, 264, 65, 273, 374, 31, 203, 5411, 389, 8151, 24051, 63, 3576, 18, 15330, 6362, 87, 1302, 264, 65, 273, 11144, 18, 1717, 12, 1717, 1575, 329, 620, 1769, 203, 3639, 289, 203, 3639, 3626, 1716, 685, 1125, 12, 3576, 18, 15330, 16, 17571, 264, 16, 389, 8151, 24051, 63, 3576, 18, 15330, 6362, 87, 1302, 264, 19226, 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 ]
// SPDX-License-Identifier: MIT pragma solidity 0.8.11; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "./FuelToken.sol"; contract Staking is Ownable { using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many stake tokens the user has provided. uint256 rewardDebt; // Reward debt. } // Info of each pool. struct PoolInfo { uint128 accRewardPerShare; // Accumulated reward per share, times 1e12. See below. uint64 lastRewardBlock; // Last block number that reward distribution occurs. uint64 allocPoint; // How many allocation points assigned to this pool. Reward to distribute per block. } // The reward token! FuelToken public rewardToken; // Block number when bonus reward period ends. uint256 public bonusEndBlock; // Reward tokens created per block. uint256 public rewardPerBlock; // Bonus muliplier for early stakers. uint256 public constant BONUS_MULTIPLIER = 10; // Info of each pool. PoolInfo[] public poolInfo; // Addresses of stake token contract. IERC20[] stakeToken; // Info of each user that stakes stake tokens. mapping(uint256 => mapping(address => UserInfo)) public userInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when reward mining starts. uint256 public startBlock; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw( address indexed user, uint256 indexed pid, uint256 amount ); event TokenChanged(uint256 pid, address oldTokenAddress, address newTokenAddress); event LogPoolAddition(uint256 indexed pid, uint256 allocPoint, IERC20 indexed stakeToken); event LogSetPool(uint256 indexed pid, uint256 allocPoint); event LogUpdatePool(uint256 indexed pid, uint64 lastRewardBlock, uint256 stakedSupply, uint256 accSushiPerShare); constructor( FuelToken _rewardToken, uint256 _rewardPerBlock, uint256 _startBlock, uint256 _bonusEndBlock ) public { rewardToken = _rewardToken; rewardPerBlock = _rewardPerBlock; bonusEndBlock = _bonusEndBlock; startBlock = _startBlock; } function poolLength() external view returns (uint256) { return poolInfo.length; } // Add a new stake token to the pool. Can only be called by the owner. // XXX DO NOT add the same stake token more than once. Rewards will be messed up if you do. function add( uint256 _allocPoint, IERC20 _stakeToken, bool _withUpdate ) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint + _allocPoint; poolInfo.push( PoolInfo({ accRewardPerShare: 0, lastRewardBlock: uint64(lastRewardBlock), allocPoint: uint64(_allocPoint) }) ); stakeToken.push(_stakeToken); emit LogPoolAddition(stakeToken.length - 1, _allocPoint, _stakeToken); } // Update the given pool's reward allocation point. Can only be called by the owner. function set( uint256 _pid, uint64 _allocPoint, bool _withUpdate ) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint - poolInfo[_pid].allocPoint + _allocPoint; poolInfo[_pid].allocPoint = _allocPoint; emit LogSetPool(_pid, _allocPoint); } function changeStakeToken(uint256 _pid, IERC20 _newToken) public onlyOwner { require(address(_newToken) != address(0), "newTokenAddress is zero"); uint256 bal = stakeToken[_pid].balanceOf(address(this)); _newToken.transferFrom(_msgSender(), address(this), bal); require(_newToken.balanceOf(address(this)) == bal, "migrate: bad"); emit TokenChanged( _pid, address(stakeToken[_pid]), address(_newToken) ); stakeToken[_pid] = _newToken; } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { if (_to <= bonusEndBlock) { return (_to - _from) * BONUS_MULTIPLIER; } else if (_from >= bonusEndBlock) { return _to - _from; } else { return (bonusEndBlock - _from) * BONUS_MULTIPLIER + _to - bonusEndBlock; } } // View function to see pending reward on frontend. function pendingReward(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accRewardPerShare = pool.accRewardPerShare; uint256 stakedSupply = stakeToken[_pid].balanceOf(address(this)); if (block.number > pool.lastRewardBlock && stakedSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 reward = multiplier * rewardPerBlock * pool.allocPoint / totalAllocPoint; accRewardPerShare += reward * 1e12 / stakedSupply; } return user.amount * accRewardPerShare / 1e12 - user.rewardDebt; } // Update reward vairables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 stakedSupply = stakeToken[_pid].balanceOf(address(this)); if (stakedSupply == 0) { pool.lastRewardBlock = uint64(block.number); return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 reward = multiplier * rewardPerBlock * pool.allocPoint / totalAllocPoint; rewardToken.mint(address(this), reward); pool.accRewardPerShare += uint128(reward * 1e12 / stakedSupply); pool.lastRewardBlock = uint64(block.number); emit LogUpdatePool(_pid, uint64(block.number), stakedSupply, pool.accRewardPerShare); } // Deposit stake tokens to Staking contract for reward allocation. function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount * pool.accRewardPerShare / 1e12 - user.rewardDebt; safeRewardTransfer(msg.sender, pending); } stakeToken[_pid].safeTransferFrom( address(msg.sender), address(this), _amount ); user.amount += _amount; user.rewardDebt = user.amount * pool.accRewardPerShare / 1e12; emit Deposit(msg.sender, _pid, _amount); } // Withdraw stake tokens from Staking contract. function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount * pool.accRewardPerShare / 1e12 - user.rewardDebt; safeRewardTransfer(msg.sender, pending); stakeToken[_pid].safeTransfer(address(msg.sender), _amount); user.amount -= _amount; user.rewardDebt = user.amount * pool.accRewardPerShare / 1e12; emit Withdraw(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; stakeToken[_pid].safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; } // Safe reward transfer function, just in case if rounding error causes pool to not have enough reward tokens. function safeRewardTransfer(address _to, uint256 _amount) internal { uint256 rewardBal = rewardToken.balanceOf(address(this)); if (_amount > rewardBal) { rewardToken.transfer(_to, rewardBal); } else { rewardToken.transfer(_to, _amount); } } }
Safe reward transfer function, just in case if rounding error causes pool to not have enough reward tokens.
function safeRewardTransfer(address _to, uint256 _amount) internal { uint256 rewardBal = rewardToken.balanceOf(address(this)); if (_amount > rewardBal) { rewardToken.transfer(_to, rewardBal); rewardToken.transfer(_to, _amount); } }
919,098
[ 1, 9890, 19890, 7412, 445, 16, 2537, 316, 648, 309, 13885, 555, 14119, 2845, 358, 486, 1240, 7304, 19890, 2430, 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 ]
[ 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, 4183, 17631, 1060, 5912, 12, 2867, 389, 869, 16, 2254, 5034, 389, 8949, 13, 2713, 288, 203, 3639, 2254, 5034, 19890, 38, 287, 273, 19890, 1345, 18, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 3639, 309, 261, 67, 8949, 405, 19890, 38, 287, 13, 288, 203, 5411, 19890, 1345, 18, 13866, 24899, 869, 16, 19890, 38, 287, 1769, 203, 5411, 19890, 1345, 18, 13866, 24899, 869, 16, 389, 8949, 1769, 203, 3639, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^ 0.4.24; // pragma experimental ABIEncoderV2; import "./List.sol"; import "./Util.sol"; contract SimpleExchange is Recoverable { using ExchangeHelper for ExchangeHelper.t; ExchangeHelper.t infoOp; constructor() public { infoOp.init(); } function link(TokenVault vault) external onlyMaster { MiscOp.requireEx(vault != address(0)); infoOp.vault = vault; } /////////////////////////////////////////////////////////////////////////// function () // depositWei external payable { address user = msg.sender; uint256 weis = msg.value; infoOp.depositWei(user, weis); } function withdrawWei(uint256 weis) external { address user = msg.sender; MiscOp.requireEx(user != 0x0); MiscOp.requireEx(weis != 0x0); infoOp.withdrawWei(user, weis); } function balanceOfWei(address user) external view returns(uint256) { MiscOp.requireEx(user != 0x0); return infoOp.balanceOfWei(user); } function findWeiTransactionList(address _user) external view returns(uint256[] transactionType, uint256[] weis, uint256[] createTime) { return infoOp.findWeiTransactionList(_user); } /////////////////////////////////////////////////////////////////////////// function depositToken(address token, uint256 tokenAmount) external { address user = msg.sender; MiscOp.requireEx(token != 0x0); MiscOp.requireEx(user != 0x0); MiscOp.requireEx(tokenAmount != 0x0); infoOp.depositToken(token, user, tokenAmount); } function withdrawToken(address token, uint256 tokenAmount) external { address user = msg.sender; MiscOp.requireEx(token != 0x0); MiscOp.requireEx(user != 0x0); MiscOp.requireEx(tokenAmount != 0x0); infoOp.withdrawToken(token, user, tokenAmount); } function balanceOfToken(address token, address user) external view returns(uint256) { MiscOp.requireEx(token != 0x0); MiscOp.requireEx(user != 0x0); return infoOp.balanceOfToken(token, user); } function findTokenTransactionList(address token, address user) external view returns(uint256[] transactionType, uint256[] tokenAmount, uint256[] createTime) { return infoOp.findTokenTransactionList(token, user); } /////////////////////////////////////////////////////////////////////////// function sell(address token, uint256 tokenAmount, uint256 weis) external returns(uint256) { address user = msg.sender; MiscOp.requireEx(token != 0x0); MiscOp.requireEx(user != 0x0); MiscOp.requireEx(weis != 0x0); MiscOp.requireEx(tokenAmount != 0x0); return infoOp.sell(token, user, tokenAmount, weis); } function buy(address token, uint256 tokenAmount, uint256 weis) external returns(uint256) { address user = msg.sender; MiscOp.requireEx(token != 0x0); MiscOp.requireEx(user != 0x0); MiscOp.requireEx(tokenAmount != 0x0); MiscOp.requireEx(weis != 0x0); return infoOp.buy(token, user, tokenAmount, weis); } function cancelOrder(uint256 orderId) external { address user = msg.sender; MiscOp.requireEx(user != 0x0); infoOp.cancelOrder(user, orderId); } function orderList(address _token) external view returns ( uint256[] id, address[] token, address[] user, // uint256[] orderType, // uint256[] weis, // uint256[] weisLeft, // uint256[] tokenAmount, uint256[] tokenAmountLeft ) { return infoOp.orderList(_token); } // function info() // external // view // returns(uint256 key, uint256 value, uint256[1] key2, uint256[1] value2) // { // mlist_keyvalue.keyvalue memory r = infoOp.info(); // return (r.key, r.value, [r.key], [r.value]); // } enum How {a,b,cc,dd} function myOrderList() external pure returns ( // uint256[] id, // address[] token, // address[] user, // uint256[] orderType, // uint256[] weis, // uint256[] weisLeft, uint256[1] tokenAmount, How[1] tokenAmountLeft ) { tokenAmount[0] = 5; tokenAmountLeft[0] = How.dd; } function myxOrderList() external view returns ( uint256[] id, address[] token, address[] user, // uint256[] orderType, // uint256[] weis, // uint256[] weisLeft, // uint256[] tokenAmount, uint256[] tokenAmountLeft ) { address _user = msg.sender; MiscOp.requireEx(_user != 0x0); return infoOp.myOrderList(_user); } // order detail, account detail, wei detail // // function orderDetail(uint256 orderId) // status, transactions // // external // // view // // { // // infoOp.orderDetail(orderId); // // } } library ExchangeHelper { using SafeMath for uint256; using mlist_address for mlist_address.t; using mlist_uint256 for mlist_uint256.t; using list_address for list_address.t; using list_uint256 for list_uint256.t; using one_many_address_uint256 for one_many_address_uint256.t; using one_many_uint256_uint256 for one_many_uint256_uint256.t; uint256 constant kOrderSell = 1; uint256 constant kOrderBuy = 2; uint256 constant kTransaction_weiWithdrawal = 111; uint256 constant kTransaction_weiDeposit = 112; uint256 constant kTransaction_weiToOrder = 121; uint256 constant kTransaction_weiFromOrder = 122; uint256 constant kTransaction_tokenWithdrawal = 211; uint256 constant kTransaction_tokenDeposit = 212; uint256 constant kTransaction_tokenToOrder = 221; uint256 constant kTransaction_tokenFromOrder = 222; uint256 constant kTransaction_orderMatch = 300; struct WeiAccountEntry { uint256 weis; } struct WeiAccountInfo { uint256 total; mapping(address => WeiAccountEntry) table; /* key is accountId */ } struct TokenAccountEntry { uint256 tokenAmount; } struct TokenAccountInfo { mapping(address => mapping(address => uint256)) token_user_accountId; mapping(uint256 => TokenAccountEntry) table; /* key is accountId */ one_many_address_uint256.t tokenDic; /* token <-> accountId */ one_many_address_uint256.t userDic; /* user <-> accountId */ } struct ExTokenInfo { mapping(address => mapping(uint256 => uint256)) token_tokenId_exTokenId; one_many_address_uint256.t tokenDic; /* token <-> exTokenId[] */ one_many_uint256_uint256.t tokenIdDic; /* tokenId <-> exTokenId[] */ } struct ERC721TokenAccountInfo { ExTokenInfo exToken; one_many_address_uint256.t userDic; /* owner <-> exTokenId[] */ } struct ERC1203TokenAccountInfo { // multi-class fungible token ExTokenInfo exToken; mapping(uint256 => mapping(address => uint256)) exTokenId_user_accountId; mapping(uint256 => TokenAccountEntry) table; /* key is accountId */ one_many_uint256_uint256.t exTokenIdDic; /* exTokenId <-> accountId */ one_many_uint256_uint256.t userDic; /* user <-> accountId */ } struct FullOrderEntry { uint256 id; address token; address user; uint256 orderType; // 11 for sell, 11 for sellClosed, 21 for buy, 22 for buyClosed uint256 weis; uint256 weisLeft; uint256 tokenAmount; uint256 tokenAmountLeft; // uint256 createTime; } struct BuyOrderEntry { uint256 tokenAmount; // // uint256 price; // in wei uint256 weis; // in wei weis = tokenAmount * price uint256 weisLeft; // uint256 cancelled_tokenAmount; // uint256 filled_tokenAmount; // uint256 filled_weis; // OrderStatus status; uint256 createTime; uint256 closeTime; } struct SellOrderEntry { // uint256 price; // in wei uint256 tokenAmount; // in token unit e.g. tnano uint256 tokenAmountLeft; uint256 weis; // // uint256 cancelled_tokenAmount; // uint256 filled_tokenAmount; // uint256 filled_weis; // OrderStatus status; uint256 createTime; uint256 closeTime; } struct ERC20PartOrderInfo { one_many_address_uint256.t tokenDic; /* token <-> orderId */ one_many_address_uint256.t userDic; /* user <-> orderId */ } struct ERC721PartOrderInfo { one_many_address_uint256.t tokenDic; /* token <-> orderId */ one_many_uint256_uint256.t exTokenDic; /* exTokenId <-> orderId */ one_many_address_uint256.t userDic; /* user <-> orderId */ } struct ERC1203PartOrderInfo { one_many_address_uint256.t tokenDic; /* token <-> orderId */ one_many_uint256_uint256.t exTokenDic; /* exTokenId <-> orderId */ one_many_address_uint256.t userDic; /* user <-> orderId */ } struct OrderInfo { mapping(uint256 => BuyOrderEntry) buyTable; /* key is orderId */ ERC20PartOrderInfo buy; ERC20PartOrderInfo buyClosed; mapping(uint256 => SellOrderEntry) sellTable; /* key is orderId */ ERC20PartOrderInfo sell; ERC20PartOrderInfo sellClosed; } // toOrder, fromOrder, deposit, withdrawal struct WeiTransactionEntry { uint256 transactionType; uint256 weis; uint256 createTime; } struct WeiTransactionInfo { mapping(uint256 => WeiTransactionEntry) transactions; one_many_address_uint256.t userDic; /* key is user address */ one_many_uint256_uint256.t orderDic; /* key is orderId */ } struct FullWeiTransactionEntry { uint256 id; address user; uint256 orderId; uint256 transactionType; uint256 weis; uint256 createTime; } struct TokenTransactionEntry { uint256 transactionType; uint256 tokenAmount; uint256 createTime; } struct TokenTransactionInfo { mapping(uint256 => TokenTransactionEntry) transactions; one_many_address_uint256.t tokenDic; /* key is token address */ one_many_address_uint256.t userDic; /* key is user address */ one_many_uint256_uint256.t orderDic; /* key is orderId */ one_many_uint256_uint256.t accountDic; /* key is orderId */ } struct FullTokenTransactionEntry { uint256 id; address token; address user; uint256 orderId; uint256 transactionType; uint256 tokenAmount; uint256 createTime; } struct OrderTransactionEntry { uint256 tokenAmount; // uint256 price; // in wei uint256 weis; uint256 createTime; } struct OrderTransactionInfo { mapping(uint256 => OrderTransactionEntry) transactions; one_many_address_uint256.t tokenDic; /* key is token address */ one_many_address_uint256.t userBuyDic; /* key is user address */ one_many_address_uint256.t userSellDic; /* key is user address */ one_many_uint256_uint256.t orderBuyDic; /* key is orderId */ one_many_uint256_uint256.t orderSellDic; /* key is orderId */ } struct FullOrderTransactionEntry { uint256 id; address token; address userSell; address userBuy; uint256 orderIdSell; uint256 orderIdBuy; uint256 transactionType; uint256 weis; // uint256 price; // in wei uint256 tokenAmount; uint256 createTime; } struct t { uint256 nextId; // always > 0 list_address.t tokenAmount; /* key is token address */ list_address.t users; /* key is user address */ WeiAccountInfo weis; TokenAccountInfo accounts; OrderInfo orders; OrderTransactionInfo transactions; WeiTransactionInfo transactions_wei; TokenTransactionInfo transactions_token; TokenVault vault; } /////////////////////////////////////////////////////////////////////////// function findWeiTransactionList(t storage _this, address user) internal view returns(uint256[] transactionType, uint256[] weis, uint256[] createTime) { FullWeiTransactionEntry[] memory ls = _findWeiTransactionList(_this, user); transactionType = new uint256[]( ls.length); weis = new uint256[]( ls.length); createTime = new uint256[]( ls.length); for (uint256 i = 0; i < ls.length; i++) { transactionType[i] = ls[i].transactionType; weis[i] = ls[i].weis; createTime[i] = ls[i].createTime; } } function _findWeiTransactionList(t storage _this, address user) private view returns(FullWeiTransactionEntry[] memory) { FullWeiTransactionEntry[] memory mls = new FullWeiTransactionEntry[](19); WeiTransactionInfo storage oi = _this.transactions_wei; list_uint256.t storage ls = oi.userDic.listAt(user); for (uint256 i = 0; i < ls.size(); i++) { uint256 transactionId = ls.at(i); WeiTransactionEntry storage e = oi.transactions[transactionId]; mls[i] = FullWeiTransactionEntry({ id : transactionId, user : user, orderId : 0, transactionType : e.transactionType, weis : e.weis, createTime : e.createTime}); } return mls; } function findTokenTransactionList(t storage _this, address token, address user) internal view returns(uint256[] transactionType, uint256[] tokenAmount, uint256[] createTime) { FullTokenTransactionEntry[] memory ls = _findTokenTransactionList(_this, token, user); transactionType = new uint256[]( ls.length); tokenAmount = new uint256[]( ls.length); createTime = new uint256[]( ls.length); for (uint256 i = 0; i < ls.length; i++) { transactionType[i] = ls[i].transactionType; tokenAmount[i] = ls[i].tokenAmount; createTime[i] = ls[i].createTime; } } function _findTokenTransactionList(t storage _this, address token, address user) private view returns(FullTokenTransactionEntry[] memory) { uint256 accountId = _this.accounts.token_user_accountId[token][user]; return findTokenTransactionListByAccount(_this, accountId); } function findTokenTransactionListByAccount(t storage _this, uint256 accountId) private view returns(FullTokenTransactionEntry[] memory) { FullTokenTransactionEntry[] memory mls = new FullTokenTransactionEntry[](19); TokenTransactionInfo storage oi = _this.transactions_token; list_uint256.t storage ls = oi.accountDic.listAt(accountId); for (uint256 i = 0; i < ls.size(); i++) { uint256 transactionId = ls.at(i); TokenTransactionEntry storage e = oi.transactions[transactionId]; mls[i] = FullTokenTransactionEntry({ id : transactionId, token : oi.tokenDic.oneAt(transactionId), user : oi.userDic.oneAt(transactionId), orderId : 0, transactionType : e.transactionType, tokenAmount : e.tokenAmount, createTime : e.createTime}); } return mls; } function findOrderTransactionList(t storage _this, uint256 orderIdSell) private view returns(FullOrderTransactionEntry[] memory) { FullOrderTransactionEntry[] memory mls = new FullOrderTransactionEntry[](19); OrderTransactionInfo storage oi = _this.transactions; list_uint256.t storage ls = oi.orderSellDic.listAt(orderIdSell); for (uint256 i = 0; i < ls.size(); i++) { uint256 transactionId = ls.at(i); OrderTransactionEntry storage e = oi.transactions[transactionId]; mls[i] = FullOrderTransactionEntry({ id : transactionId, token : oi.tokenDic.oneAt(transactionId), userSell : oi.userSellDic.oneAt(transactionId), userBuy : oi.userBuyDic.oneAt(transactionId), orderIdSell : oi.orderSellDic.oneAt(transactionId), orderIdBuy : oi.orderBuyDic.oneAt(transactionId), transactionType : kTransaction_orderMatch, tokenAmount : e.tokenAmount, // price : e.price, weis : e.weis, createTime : e.createTime}); } return mls; } /////////////////////////////////////////////////////////////////////////// function depositToken(t storage _this, address token, address user, uint256 tokenAmount) internal { mintTokens(_this, token, user, tokenAmount); makeTokenTransaction(_this, token, user, tokenAmount, kTransaction_tokenDeposit); VaultOp.transferERC20From(ERC20(token), user, address(_this.vault), tokenAmount); // VaultOp.transferERC20From(ERC20(token), user, address(this), tokenAmount); } function withdrawToken(t storage _this, address token, address user, uint256 tokenAmount) internal { burnTokens(_this, token, user, tokenAmount); makeTokenTransaction(_this, token, user, tokenAmount, kTransaction_tokenWithdrawal); _this.vault.transferERC20Basic(ERC20Basic(token), user, tokenAmount); // VaultOp.transferERC20Basic(ERC20(token), user, tokenAmount); } function balanceOfToken(t storage _this, address token, address user) internal view returns(uint256) { uint256 accountId = _this.accounts.token_user_accountId[token][user]; TokenAccountEntry storage ae = _this.accounts.table[accountId]; return ae.tokenAmount; } function depositWei(t storage _this, address user, uint256 weis) internal { mintWeis(_this, user, weis); makeWeiTransaction(_this, user, weis, kTransaction_weiDeposit); VaultOp.transferWei(address(_this.vault), weis); // // VaultOp.transferWei(address(this), weis); // nothing } function withdrawWei(t storage _this, address user, uint256 weis) internal { burnWeis(_this, user, weis); makeWeiTransaction(_this, user, weis, kTransaction_weiWithdrawal); _this.vault.transferWei(user, weis); // VaultOp.transferWei(user, weis); } function balanceOfWei(t storage _this, address user) internal view returns(uint256) { return _this.weis.table[user].weis; } function cancelOrder(t storage _this, address user, uint256 orderId) internal { closeUserOrder(_this, user, orderId); } function orderList(t storage _this, address _token) internal view returns ( uint256[] id, address[] token, address[] user, // uint256[] orderType, // uint256[] weis, // uint256[] weisLeft, // uint256[] tokenAmount, uint256[] tokenAmountLeft ) { FullOrderEntry[] memory ls = findBuyOrders_t(_this, _token); return flat(ls); } // function info(t storage _this) // internal // view // returns(mlist_keyvalue.keyvalue memory) // { // mlist_keyvalue.keyvalue memory r; // return r; // } function myOrderList(t storage _this, address _user) internal view returns ( uint256[] id, address[] token, address[] user, // uint256[] orderType, // uint256[] weis, // uint256[] weisLeft, // uint256[] tokenAmount, uint256[] tokenAmountLeft ) { FullOrderEntry[] memory ls = findBuyOrders_u(_this, _user); return flat(ls); } function flat(FullOrderEntry[] memory ls) private pure returns ( uint256[] id, address[] token, address[] user, // uint256[] orderType, // uint256[] weis, // uint256[] weisLeft, // uint256[] tokenAmount, uint256[] tokenAmountLeft ) { id = new uint256[]( ls.length); token = new address[]( ls.length); user = new address[]( ls.length); // orderType = new uint256[]( ls.length); // weis = new uint256[]( ls.length); // weisLeft = new uint256[]( ls.length); // tokenAmount = new uint256[]( ls.length); tokenAmountLeft = new uint256[]( ls.length); for(uint256 i = 0; i < ls.length; i++){ id[i] = ls[i].id; token[i] = ls[i].token; user[i] = ls[i].user; // orderType[i] = ls[i].orderType; // weis[i] = ls[i].weis; // weisLeft[i] = ls[i].weisLeft; // tokenAmount[i] = ls[i].tokenAmount; tokenAmountLeft[i] = ls[i].tokenAmountLeft; } } // function orderDetail(t storage _this, uint256 orderId) // status, transactions // internal // view // { // } function init(t storage _this) internal { _this.nextId = 1; // always > 0 } function buy(t storage _this, address token, address user, uint256 tokenAmount, uint256 weis) internal returns(uint256) { uint256 buyOrderId = buyLimitPrice(_this, token, user, tokenAmount, weis); OrderInfo storage oi = _this.orders; BuyOrderEntry storage oe = oi.buyTable[buyOrderId]; mlist_uint256.t memory ls = findSellOrders(_this, token, tokenAmount, weis); for (uint256 i = 0; i < ls.size(); i++) { if (oe.weis <= 0) { break; } uint256 sellOrderId = ls.at(i); matchOrders(_this, sellOrderId, buyOrderId); } return buyOrderId; } function sell(t storage _this, address token, address user, uint256 tokenAmount, uint256 weis) internal returns(uint256) { uint256 sellOrderId = sellLimitPrice(_this, token, user, tokenAmount, weis); OrderInfo storage oi = _this.orders; SellOrderEntry storage oe = oi.sellTable[buyOrderId]; mlist_uint256.t memory ls = findBuyOrders(_this, token, tokenAmount, weis); for (uint256 i = 0; i < ls.size(); i++) { if (oe.tokenAmount <= 0) { break; } uint256 buyOrderId = ls.at(i); matchOrders(_this, sellOrderId, buyOrderId); } return sellOrderId; } /////////////////////////////////////////////////////////////////////////// function nextId(t storage _this) private returns(uint256) { return _this.nextId++; } function mintWeis(t storage _this, address user, uint256 weis2) private { WeiAccountEntry storage we = _this.weis.table[user]; we.weis = we.weis.add(weis2); _this.weis.total = _this.weis.total.add(weis2); } function mintTokens(t storage _this, address token, address user, uint256 tokenAmount2) private { uint256 accountId = safeAddTokenAccount(_this, token, user); TokenAccountEntry storage ae = _this.accounts.table[accountId]; ae.tokenAmount = ae.tokenAmount.add(tokenAmount2); } function burnWeis(t storage _this, address user, uint256 weis2) private { WeiAccountEntry storage we = _this.weis.table[user]; we.weis = we.weis.sub(weis2); _this.weis.total = _this.weis.total.sub(weis2); } function burnTokens(t storage _this, address token, address user, uint256 tokenAmount2) private { uint256 accountId = safeAddTokenAccount(_this, token, user); TokenAccountEntry storage ae = _this.accounts.table[accountId]; ae.tokenAmount = ae.tokenAmount.sub(tokenAmount2); } function moveCloseOrder(ERC20PartOrderInfo storage oi, ERC20PartOrderInfo storage oiClosed, uint256 orderId) private { address token = oi.tokenDic.oneAt(orderId); address user = oi.userDic.oneAt(orderId); oi.tokenDic.remove(token, orderId); oiClosed.tokenDic.add(token, orderId); oi.userDic.remove(user, orderId); oiClosed.userDic.add(user, orderId); } function safeAddTokenAccount(t storage _this, address token, address user) private returns(uint256) { uint256 accountId = _this.accounts.token_user_accountId[token][user]; if (accountId == 0) { accountId = nextId(_this); _this.tokenAmount.safeAdd(token); _this.users.safeAdd(user); _this.accounts.tokenDic.add(token, accountId); _this.accounts.userDic.add(user, accountId); _this.accounts.table[accountId] = TokenAccountEntry({ tokenAmount: 0 }); _this.accounts.token_user_accountId[token][user] = accountId; } return accountId; } function findBuyOrders(t storage _this, address token, uint256 tokenAmount, uint256 weis) private view returns(mlist_uint256.t memory) { mlist_uint256.t memory mls; OrderInfo storage oi = _this.orders; list_uint256.t storage ls = oi.buy.tokenDic.listAt(token); for (uint256 i = 0; i < ls.size(); i++) { uint256 oId = ls.at(i); BuyOrderEntry storage oe = oi.buyTable[oId]; if (oe.weis * tokenAmount >= weis * oe.tokenAmount) { mls.add(oId); } } return mls; } function findSellOrders(t storage _this, address token, uint256 tokenAmount, uint256 weis) private view returns(mlist_uint256.t memory) { mlist_uint256.t memory mls; mls.clear(); // MiscOp.requireEx(mls.size() == 0); OrderInfo storage oi = _this.orders; list_uint256.t storage ls = oi.sell.tokenDic.listAt(token); // MiscOp.requireEx(ls.size() == 1); for (uint256 i = 0; i < ls.size(); i++) { uint256 oId = ls.at(i); SellOrderEntry storage oe = oi.sellTable[oId]; if (oe.weis * tokenAmount <= weis * oe.tokenAmount) { mls.add(oId); } } return mls; } function findBuyOrders_t(t storage _this, address token) private view returns(FullOrderEntry[] memory) { FullOrderEntry[] memory mls = new FullOrderEntry[](19); OrderInfo storage oi = _this.orders; list_uint256.t storage ls = oi.buy.tokenDic.listAt(token); for (uint256 i = 0; i < ls.size(); i++) { uint256 orderId = ls.at(i); BuyOrderEntry storage e = oi.buyTable[orderId]; mls[i] = FullOrderEntry({ id : orderId, token : oi.sell.tokenDic.oneAt(orderId), user : oi.sell.userDic.oneAt(orderId), orderType : kOrderBuy, weis : e.weis, weisLeft : e.weisLeft, tokenAmount : 0, tokenAmountLeft : 0}); } return mls; } function findSellOrders_t(t storage _this, address token) private view returns(FullOrderEntry[] memory) { FullOrderEntry[] memory mls = new FullOrderEntry[](19); OrderInfo storage oi = _this.orders; list_uint256.t storage ls = oi.sell.tokenDic.listAt(token); for (uint256 i = 0; i < ls.size(); i++) { uint256 orderId = ls.at(i); SellOrderEntry storage e = oi.sellTable[orderId]; mls[i] = FullOrderEntry({ id : orderId, token : oi.sell.tokenDic.oneAt(orderId), user : oi.sell.userDic.oneAt(orderId), orderType : kOrderSell, weis : 0, weisLeft : 0, tokenAmount : e.tokenAmount, tokenAmountLeft : e.tokenAmountLeft}); } return mls; } function findBuyOrders_u(t storage _this, address user) private view returns(FullOrderEntry[] memory) { FullOrderEntry[] memory mls = new FullOrderEntry[](19); OrderInfo storage oi = _this.orders; list_uint256.t storage ls = oi.buy.userDic.listAt(user); for (uint256 i = 0; i < ls.size(); i++) { uint256 orderId = ls.at(i); BuyOrderEntry storage e = oi.buyTable[orderId]; mls[i] = FullOrderEntry({ id : orderId, token : oi.sell.tokenDic.oneAt(orderId), user : oi.sell.userDic.oneAt(orderId), orderType : kOrderBuy, weis : e.weis, weisLeft : e.weisLeft, tokenAmount : 0, tokenAmountLeft : 0}); } return mls; } function findSellOrders_u(t storage _this, address user) private view returns(FullOrderEntry[] memory) { FullOrderEntry[] memory mls = new FullOrderEntry[](19); OrderInfo storage oi = _this.orders; list_uint256.t storage ls = oi.sell.userDic.listAt(user); for (uint256 i = 0; i < ls.size(); i++) { uint256 orderId = ls.at(i); SellOrderEntry storage e = oi.sellTable[orderId]; mls[i] = FullOrderEntry({ id : orderId, token : oi.sell.tokenDic.oneAt(orderId), user : oi.sell.userDic.oneAt(orderId), orderType : kOrderSell, weis : 0, weisLeft : 0, tokenAmount : e.tokenAmount, tokenAmountLeft : e.tokenAmountLeft}); } return mls; } // solium-disable-next-line indentation function createOrderIndex(ERC20PartOrderInfo storage oi, address token, address user, uint256 orderId) private { oi.tokenDic.add(token, orderId); oi.userDic.add(user, orderId); } // solium-disable-next-line indentation function createOrderTransactionIndex(t storage _this, address token, address userSell, address userBuy, uint256 orderIdSell, uint256 orderIdBuy, uint256 transactionId) private { _this.transactions.tokenDic.add(token, transactionId); _this.transactions.userSellDic.add(userSell, transactionId); _this.transactions.orderSellDic.add(orderIdSell, transactionId); _this.transactions.userBuyDic.add(userBuy, transactionId); _this.transactions.orderBuyDic.add(orderIdBuy, transactionId); } function createTokenTransactionIndex(t storage _this, address token, address user, uint256 orderId, uint256 transactionId) private { _this.transactions_token.tokenDic.add(token, transactionId); _this.transactions_token.userDic.add(user, transactionId); _this.transactions_token.orderDic.add(orderId, transactionId); } function createWeiTransactionIndex(t storage _this, address user, uint256 orderId, uint256 transactionId) private { _this.transactions_wei.userDic.add(user, transactionId); _this.transactions_wei.orderDic.add(orderId, transactionId); } function buyLimitPrice(t storage _this, address token, address user, uint256 tokenAmount, uint256 weis) private returns(uint256) { MiscOp.requireEx(tokenAmount != 0); MiscOp.requireEx(weis != 0); safeAddTokenAccount(_this, token, user); uint256 orderId = nextId(_this); burnWeis(_this, user, weis); uint256 transactionId = makeWeiTransaction(_this, user, weis, kTransaction_weiToOrder); createWeiTransactionIndex(_this, user, orderId, transactionId); uint256 ts = MiscOp.currentTime(); _this.orders.buyTable[orderId] = BuyOrderEntry({ // price: price, tokenAmount: tokenAmount, weis: weis, weisLeft: weis, createTime: ts, closeTime: 0 }); createOrderIndex(_this.orders.buy, token, user, orderId); return orderId; } function sellLimitPrice(t storage _this, address token, address user, uint256 tokenAmount, uint256 weis) private returns(uint256) { MiscOp.requireEx(tokenAmount != 0); MiscOp.requireEx(weis != 0); safeAddTokenAccount(_this, token, user); uint256 orderId = nextId(_this); burnTokens(_this, token, user, tokenAmount); uint256 transactionId = makeTokenTransaction(_this, token, user, tokenAmount, kTransaction_tokenToOrder); createTokenTransactionIndex(_this, token, user, orderId, transactionId); uint256 ts = MiscOp.currentTime(); _this.orders.sellTable[orderId] = SellOrderEntry({ // price: price, tokenAmount: tokenAmount, weis: weis, tokenAmountLeft: tokenAmount, createTime: ts, closeTime: 0 }); createOrderIndex(_this.orders.sell, token, user, orderId); return orderId; } function closeUserOrder(t storage _this, address user, uint256 orderId) private { bool b = _this.orders.sell.userDic.exists(user, orderId); if (b) { closeSellOrder(_this, orderId); } b = _this.orders.buy.userDic.exists(user, orderId); if (b) { closeBuyOrder(_this, orderId); } } function closeOrder(t storage _this, uint256 orderId) private { address token = _this.orders.sell.tokenDic.oneAt(orderId); if (token != 0x0) { closeSellOrder(_this, orderId); } token = _this.orders.buy.tokenDic.oneAt(orderId); if (token != 0x0) { closeBuyOrder(_this, orderId); } } function closeSellOrder(t storage _this, uint256 sellOrderId) private { address token = _this.orders.sell.tokenDic.oneAt(sellOrderId); address seller = _this.orders.sell.userDic.oneAt(sellOrderId); SellOrderEntry storage oeSell = _this.orders.sellTable[sellOrderId]; uint256 tokenAmount = oeSell.tokenAmountLeft; if (tokenAmount > 0) { oeSell.tokenAmountLeft = 0; mintTokens(_this, token, seller, tokenAmount); makeTokenTransaction(_this, token, seller, tokenAmount, kTransaction_tokenFromOrder); } if (oeSell.closeTime == 0) { moveCloseOrder(_this.orders.sell, _this.orders.sellClosed, sellOrderId); uint256 ts = MiscOp.currentTime(); oeSell.closeTime = ts; } } function closeBuyOrder(t storage _this, uint256 buyOrderId) private { address buyer = _this.orders.buy.userDic.oneAt(buyOrderId); BuyOrderEntry storage oeBuy = _this.orders.buyTable[buyOrderId]; uint256 weis = oeBuy.weisLeft; if (weis > 0) { oeBuy.weisLeft = 0; mintWeis(_this, buyer, weis); makeWeiTransaction(_this, buyer, weis, kTransaction_weiFromOrder); } if (oeBuy.closeTime == 0) { moveCloseOrder(_this.orders.buy, _this.orders.buyClosed, buyOrderId); uint256 ts = MiscOp.currentTime(); oeBuy.closeTime = ts; } } function matchOrders(t storage _this, uint256 sellOrderId, uint256 buyOrderId) private { uint256 transactionId = matchOrders_1(_this, sellOrderId, buyOrderId); matchOrders_2(_this, sellOrderId, buyOrderId, transactionId); matchOrders_3(_this, sellOrderId, buyOrderId); } function matchOrders_1(t storage _this, uint256 sellOrderId, uint256 buyOrderId) private returns(uint256 transactionId) { address token = _this.orders.sell.tokenDic.oneAt(sellOrderId); address tokenB = _this.orders.buy.tokenDic.oneAt(buyOrderId); MiscOp.requireEx(token == tokenB); SellOrderEntry storage oeSell = _this.orders.sellTable[sellOrderId]; BuyOrderEntry storage oeBuy = _this.orders.buyTable[buyOrderId]; MiscOp.requireEx(oeSell.weis * oeBuy.tokenAmount <= oeBuy.weis * oeSell.tokenAmount); // maximize deal uint256 tokenAmount2 = oeSell.tokenAmountLeft; uint256 weis2 = oeBuy.weisLeft; if (oeBuy.weisLeft < oeSell.tokenAmountLeft * oeSell.weis / oeSell.tokenAmount) { weis2 = oeBuy.weisLeft; tokenAmount2 = (weis2 * oeBuy.tokenAmount / oeBuy.weis + weis2 * oeSell.tokenAmount / oeSell.weis) / 2; } else if (oeSell.tokenAmountLeft < oeBuy.weisLeft * oeBuy.tokenAmount / oeBuy.weis) { tokenAmount2 = oeSell.tokenAmountLeft; weis2 = (tokenAmount2 * oeSell.weis / oeSell.tokenAmount + tokenAmount2 * oeBuy.weis / oeBuy.tokenAmount) / 2; } else { weis2 = (oeBuy.weisLeft + oeSell.tokenAmountLeft * oeSell.weis / oeSell.tokenAmount) / 2; tokenAmount2 = (oeSell.tokenAmountLeft + oeBuy.weisLeft * oeBuy.tokenAmount / oeBuy.weis) / 2; } if (tokenAmount2 > 0) { // solium-disable-next-line indentation transactionId = makeTransaction(_this, // price, tokenAmount2, weis2); address seller = _this.orders.sell.userDic.oneAt(sellOrderId); address buyer = _this.orders.buy.userDic.oneAt(buyOrderId); oeSell.tokenAmountLeft = oeSell.tokenAmountLeft.sub(tokenAmount2); oeBuy.weisLeft = oeBuy.weisLeft.sub(weis2); mintWeis(_this, seller, weis2); mintTokens(_this, token, buyer, tokenAmount2); } return transactionId; } function matchOrders_2(t storage _this, uint256 sellOrderId, uint256 buyOrderId, uint256 transactionId) private { if (transactionId > 0) { address token = _this.orders.sell.tokenDic.oneAt(sellOrderId); address seller = _this.orders.sell.userDic.oneAt(sellOrderId); address buyer = _this.orders.buy.userDic.oneAt(buyOrderId); // solium-disable-next-line indentation createOrderTransactionIndex(_this, token, seller, buyer, sellOrderId, buyOrderId, transactionId); } } function matchOrders_3(t storage _this, uint256 sellOrderId, uint256 buyOrderId) private { SellOrderEntry storage oeSell = _this.orders.sellTable[sellOrderId]; BuyOrderEntry storage oeBuy = _this.orders.buyTable[buyOrderId]; if (oeBuy.weisLeft < oeBuy.weis / oeBuy.tokenAmount) { closeBuyOrder(_this, buyOrderId); } if (oeSell.tokenAmountLeft < oeSell.tokenAmount / oeSell.weis) { closeSellOrder(_this, sellOrderId); } } // solium-disable-next-line indentation function makeTransaction(t storage _this, // address token, address seller, address buyer, // uint256 sellOrderId, uint256 buyOrderId, // uint256 tokenAmount, uint256 weis) private returns(uint256 transactionId) { transactionId = nextId(_this); uint256 ts = MiscOp.currentTime(); _this.transactions.transactions[transactionId] = OrderTransactionEntry({ // price: price, tokenAmount: tokenAmount, weis: weis, createTime: ts }); return transactionId; } // solium-disable-next-line indentation function makeWeiTransaction(t storage _this, address user, uint256 weis, uint256 _type) private returns(uint256 transactionId) { transactionId = nextId(_this); _this.transactions_wei.userDic.add(user, transactionId); uint256 ts = MiscOp.currentTime(); _this.transactions_wei.transactions[transactionId] = WeiTransactionEntry({ transactionType: _type, weis: weis, createTime: ts }); return transactionId; } // solium-disable-next-line indentation function makeTokenTransaction(t storage _this, address token, address user, uint256 tokenAmount, uint256 _type) private returns(uint256 transactionId) { transactionId = nextId(_this); uint256 accountId = safeAddTokenAccount(_this, token, user); _this.transactions_token.tokenDic.add(token, transactionId); _this.transactions_token.userDic.add(user, transactionId); _this.transactions_token.accountDic.add(accountId, transactionId); uint256 ts = MiscOp.currentTime(); _this.transactions_token.transactions[transactionId] = TokenTransactionEntry({ transactionType: _type, tokenAmount: tokenAmount, createTime: ts }); return transactionId; } }
uint256[] orderType, uint256[] weis, uint256[] weisLeft, uint256[] tokenAmount,
function orderList(address _token) external view returns ( uint256[] id, address[] token, address[] user, uint256[] tokenAmountLeft ) { return infoOp.orderList(_token); }
12,734,761
[ 1, 11890, 5034, 8526, 1353, 559, 16, 2254, 5034, 8526, 732, 291, 16, 2254, 5034, 8526, 732, 291, 3910, 16, 2254, 5034, 8526, 1147, 6275, 16, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 202, 915, 1353, 682, 12, 2867, 389, 2316, 13, 203, 202, 9375, 203, 202, 1945, 203, 202, 6154, 261, 203, 202, 202, 11890, 5034, 8526, 612, 16, 203, 202, 202, 2867, 8526, 1147, 16, 203, 202, 202, 2867, 8526, 729, 16, 203, 202, 202, 11890, 5034, 8526, 1147, 6275, 3910, 203, 202, 13, 7010, 202, 95, 203, 202, 202, 2463, 1123, 3817, 18, 1019, 682, 24899, 2316, 1769, 203, 202, 97, 203, 203, 202, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0xD0715fE663de4EAA5a44941C11C66080eA725315/sources/PiranhasAttack.sol
remove address to UniswapPairs list
function removePair(address account) public onlyOwner { address[] memory OldUniswapPairs = UniswapPairs; delete UniswapPairs; for (uint256 i = 0; i < OldUniswapPairs.length; i++) { if (OldUniswapPairs[i] != account) { UniswapPairs.push(OldUniswapPairs[i]); } } }
2,790,602
[ 1, 4479, 1758, 358, 1351, 291, 91, 438, 10409, 666, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1206, 4154, 12, 2867, 2236, 13, 1071, 1338, 5541, 288, 203, 3639, 1758, 8526, 3778, 18613, 984, 291, 91, 438, 10409, 273, 1351, 291, 91, 438, 10409, 31, 203, 3639, 1430, 1351, 291, 91, 438, 10409, 31, 203, 3639, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 18613, 984, 291, 91, 438, 10409, 18, 2469, 31, 277, 27245, 288, 203, 5411, 309, 261, 7617, 984, 291, 91, 438, 10409, 63, 77, 65, 480, 2236, 13, 288, 203, 7734, 1351, 291, 91, 438, 10409, 18, 6206, 12, 7617, 984, 291, 91, 438, 10409, 63, 77, 19226, 203, 5411, 289, 203, 3639, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** * SourceUnit: c:\Users\Jad\Documents\code\Cryptoware\dcb-lottery\blockend\contracts\DCBW721.sol */ ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: 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; } } /** * SourceUnit: c:\Users\Jad\Documents\code\Cryptoware\dcb-lottery\blockend\contracts\DCBW721.sol */ ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: 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); } /** * SourceUnit: c:\Users\Jad\Documents\code\Cryptoware\dcb-lottery\blockend\contracts\DCBW721.sol */ ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT pragma solidity ^0.8.0; ////import "../utils/introspection/IERC165.sol"; /** * SourceUnit: c:\Users\Jad\Documents\code\Cryptoware\dcb-lottery\blockend\contracts\DCBW721.sol */ ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: 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; } /** * SourceUnit: c:\Users\Jad\Documents\code\Cryptoware\dcb-lottery\blockend\contracts\DCBW721.sol */ ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: 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; } } /** * SourceUnit: c:\Users\Jad\Documents\code\Cryptoware\dcb-lottery\blockend\contracts\DCBW721.sol */ ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: 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); } } /** * SourceUnit: c:\Users\Jad\Documents\code\Cryptoware\dcb-lottery\blockend\contracts\DCBW721.sol */ ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: 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); } } } } /** * SourceUnit: c:\Users\Jad\Documents\code\Cryptoware\dcb-lottery\blockend\contracts\DCBW721.sol */ ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: 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); } /** * SourceUnit: c:\Users\Jad\Documents\code\Cryptoware\dcb-lottery\blockend\contracts\DCBW721.sol */ ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: 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); } /** * SourceUnit: c:\Users\Jad\Documents\code\Cryptoware\dcb-lottery\blockend\contracts\DCBW721.sol */ ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT pragma solidity ^0.8.0; ////import "../utils/Context.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor() { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } /** * SourceUnit: c:\Users\Jad\Documents\code\Cryptoware\dcb-lottery\blockend\contracts\DCBW721.sol */ ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: 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 {} } /** * SourceUnit: c:\Users\Jad\Documents\code\Cryptoware\dcb-lottery\blockend\contracts\DCBW721.sol */ ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: 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); } /** * SourceUnit: c:\Users\Jad\Documents\code\Cryptoware\dcb-lottery\blockend\contracts\DCBW721.sol */ ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: 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; } } /** * SourceUnit: c:\Users\Jad\Documents\code\Cryptoware\dcb-lottery\blockend\contracts\DCBW721.sol */ ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } /** * SourceUnit: c:\Users\Jad\Documents\code\Cryptoware\dcb-lottery\blockend\contracts\DCBW721.sol */ ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: 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); } } /** * SourceUnit: c:\Users\Jad\Documents\code\Cryptoware\dcb-lottery\blockend\contracts\DCBW721.sol */ ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT pragma solidity ^0.8.0; ////import "./IERC165.sol"; /** * @dev Interface for the NFT Royalty Standard */ interface IERC2981 is IERC165 { /** * @dev Called with the sale price to determine how much royalty is owed and to whom. * @param tokenId - the NFT asset queried for royalty information * @param salePrice - the sale price of the NFT asset specified by `tokenId` * @return receiver - address of who should be sent the royalty payment * @return royaltyAmount - the royalty payment amount for `salePrice` */ function royaltyInfo(uint256 tokenId, uint256 salePrice) external view returns (address receiver, uint256 royaltyAmount); } /** * SourceUnit: c:\Users\Jad\Documents\code\Cryptoware\dcb-lottery\blockend\contracts\DCBW721.sol */ ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT pragma solidity ^0.8.0; ////import "../ERC721.sol"; ////import "../../../security/Pausable.sol"; /** * @dev ERC721 token with pausable token transfers, minting and burning. * * Useful for scenarios such as preventing trades until the end of an evaluation * period, or having an emergency switch for freezing all token transfers in the * event of a large bug. */ abstract contract ERC721Pausable is ERC721, Pausable { /** * @dev See {ERC721-_beforeTokenTransfer}. * * Requirements: * * - the contract must not be paused. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); require(!paused(), "ERC721Pausable: token transfer while paused"); } } /** * SourceUnit: c:\Users\Jad\Documents\code\Cryptoware\dcb-lottery\blockend\contracts\DCBW721.sol */ ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: 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(); } } /** * SourceUnit: c:\Users\Jad\Documents\code\Cryptoware\dcb-lottery\blockend\contracts\DCBW721.sol */ ////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT pragma solidity ^0.8.0; /// @notice ERC721 ////import "../node_modules/@openzeppelin/contracts/token/ERC721/ERC721.sol"; ////import "../node_modules/@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol"; ////import "../node_modules/@openzeppelin/contracts/token/ERC721/extensions/ERC721Pausable.sol"; ////import "../node_modules/@openzeppelin/contracts/interfaces/IERC2981.sol"; /// @notice peripheral ////import "../node_modules/@openzeppelin/contracts/access/Ownable.sol"; /// @notice libraries ////import "../node_modules/@openzeppelin/contracts/utils/math/SafeMath.sol"; /// @notice ////import "../node_modules/@openzeppelin/contracts/security/ReentrancyGuard.sol"; /// @notice RNG middleware contract interface interface IRNG { function request() external returns(bytes32 requestId); } /** * @title DCBW721 * @notice ERC721-ready VRF DCBW721 contract * @author cryptoware.eth | DCB.world **/ contract DCBW721 is IERC2981, Ownable, ERC721, ERC721Enumerable, ERC721Pausable, ReentrancyGuard { /// @notice using safe math for uints using SafeMath for uint256; /// @notice using safe math for uints using SafeMath for uint32; /// @notice using safe math for uints using SafeMath for uint64; /// @notice using safe math for uints using SafeMath for uint96; /// @notice using Strings for uints conversion (tokenId) using Strings for uint256; /// @notice using Address for addresses extended functionality using Address for address; /// @notice sate of the draw process enum DrawState { Open, Closed } /// @notice struct used to store each draw's data struct DrawData { uint64 drawId; uint64 start_time; uint64 winningEdition; uint64 isGrandPrize; address winner; uint96 prizePoolWon; DrawState state; bytes32 randomNumberRequestId; } /// @notice EIP2981-compliant struct struct RoyaltyReceiver { address account; uint96 shares; // per thousands } /// @notice EIP721-required Base URI string private _baseTokenURI; /// @notice Base extension for metadata string private _baseExtension; /// @notice minting, draws, reserve(public), grandPrize(public) and royalties-traking parameters uint256 public _reserves; uint256 public _grandPrizePool; uint256 public _mintPrice; uint32 public _drawsToDate; uint256 private _reservesRate; uint256 private _maxTokenId; /// @notice the lottery draw state DrawState private _state; /// @notice beneficiary wallet that will collect mint fees address payable private _mintingBeneficiary; /// @notice VRF-compliant contract to request randomness from address private _rngContract; /// @notice Chainlink Keeper-compliant contract to trigger draw address private _alarmContract; /// @notice minter address address private _minter; /// @notice public metadata locked flag bool public locked; /// @notice Mapping draws id => details of the draw mapping(uint => DrawData) public draws; /// @notice Mapping token id => royalty details mapping(uint => RoyaltyReceiver) public royalties; /// @notice Minting events definition event AdminMinted(address indexed to, uint indexed tokenId); event Minted(address indexed to, uint indexed tokenId); /// @notice Draw events definition event DrawInitiated(bytes32 requestId); event DrawFinished(address winner, uint winningEdition); /// @notice metadata not locked modifier modifier notLocked() { require(!locked, "DCBW721: Metadata URIs are locked"); _; } /// @notice allows only closed lottery state modifier requireState(DrawState state) { require(_state == state, "DCBW721: Invalid state for this action"); _; } /// @notice allows only address to perform action modifier requireAccount(address account) { require( _msgSender() == account, "DCBW721: Invalid account for this action" ); _; } /// @notice owner or minter modifier ownerOrMinter() { require( _msgSender() == _minter || _msgSender() == owner(), "DCBW721: Invalid account for this action" ); _; } /** * @notice constructor * @param name the name of the EIP721 Contract * @param symbol the token symbol * @param baseTokenURI EIP721-required Base URI * @param mbeneficiary the contract Splitter that will receive minting funds * @param rbeneficiary the royalties beneficiary * @param alarmContract the alarm contract address to trigger DrawNumber on interval (TO BE SET POST-DEPLOYMENT) * @param rngContract the RNG contract address to get randomness (TO BE SET POST-DEPLOYMENT) **/ constructor( string memory name, string memory symbol, string memory baseTokenURI, address mbeneficiary, address rbeneficiary, address alarmContract, address rngContract ) ERC721(name, symbol) Ownable() { locked = false; _mintPrice = 1 ether; _reservesRate = 200; _maxTokenId = 1000000; _baseExtension = ".json"; _baseTokenURI = baseTokenURI; _mintingBeneficiary = payable(mbeneficiary); _rngContract = rngContract; _alarmContract = alarmContract; _minter = _msgSender(); _state = DrawState.Closed; royalties[0] = RoyaltyReceiver(rbeneficiary, 100); } /// @notice feed eth into the contract function feed(uint256 intoReserves, uint256 intoGrandPrize) external payable onlyOwner { require( msg.value > 0 && intoReserves.add(intoGrandPrize) == msg.value, "DCBW721: Balance-Value Mismatch" ); _updateGrandPrizePool(_grandPrizePool.add(intoGrandPrize)); _updateReserves(_reserves.add(intoReserves)); } /// @notice receive fallback should revert receive() external payable { revert("DCBW721: Please use Mint or Admin calls"); } /// @notice default fallback should revert fallback() external payable { revert("DCBW721: Please use Mint or Admin calls"); } /// @notice returns the base URI for the contract function _baseURI() internal view virtual override returns (string memory) { return _baseTokenURI; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { return string(abi.encodePacked(super.tokenURI(tokenId), _baseExtension)); } /** * @notice updates the all 4 addresses invovled in the contract flow * @param mintingBeneficiary the contract Splitter that will receive minting funds * @param alarmContract the alarm contract address to trigger DrawNumber on interval * @param rngContract the RNG contract address to trigger drawnNumber and pick winner * @param minter minter address * @param _owner the new admin address **/ function updateAddressesAndTransferOwnership( address mintingBeneficiary, address alarmContract, address rngContract, address minter, address _owner ) external onlyOwner { changeMintBeneficiary(mintingBeneficiary); changeMinter(minter); setAlarmAccount(alarmContract); setVRFAccount(rngContract); transferOwnership(_owner); } /** * @dev Called with the sale price to determine how much royalty is owed and to whom. * @param tokenId - the NFT asset queried for royalty information * @param salePrice - the sale price of the NFT asset specified by `tokenId` * @return receiver - address of who should be sent the royalty payment * @return royaltyAmount - the royalty payment amount for `salePrice` */ function royaltyInfo(uint tokenId, uint salePrice) external view returns (address, uint) { /// @notice all tokens have same royalty receiver tokenId = 0; // silence unused var warning return (royalties[tokenId].account, royalties[tokenId].shares.mul(salePrice).div(1000)); } /** * @notice a function for admins to mint cost-free * @param to the address to send the minted token to * @param _tokenId to token ID to be minted **/ function adminMint(address to, uint256 _tokenId) external whenNotPaused ownerOrMinter requireState(DrawState.Closed) { require(to != address(0), "DCBW721: Address cannot be 0"); validateTokenId(_tokenId); _safeMint(to, _tokenId); emit AdminMinted(to, _tokenId); } /** * @notice the public minting function -- requires 1 ether sent * @param to the address to send the minted token to * @param _tokenId to token ID to be minted **/ function mint(address to, uint256 _tokenId) external payable whenNotPaused requireState(DrawState.Closed) { uint256 received = msg.value; require(to != address(0), "DCBW721: Address cannot be 0"); require( received == _mintPrice, "DCBW721: Ether sent mismatch with mint price" ); validateTokenId(_tokenId); _safeMint(to, _tokenId); _forwardFunds(received); _updateReserves(_reserves.add(received.mul(_reservesRate).div(1000))); emit Minted(to, _tokenId); } /// @notice a function called by Alarm on each _interval and requests VRF to get randomness function drawNumber() external whenNotPaused requireAccount(_alarmContract) requireState(DrawState.Closed) nonReentrant returns (bool) { require(_reserves > 0, "DCBW721: Not enough reserves for draw"); require(totalSupply() >= 500, "DCBW721: Supply of 500 not reached yet"); require( _reserves != 0 && address(this).balance.sub(_grandPrizePool) >= _reserves, "DCBW721: Not enough balance for draw prize" ); bytes32 reqId = IRNG(_rngContract).request(); _state = DrawState.Open; draws[_drawsToDate] = DrawData( _drawsToDate, uint32(block.timestamp), /* solium-disable-line */ 0, 0, address(0), 0, _state, reqId ); emit DrawInitiated(reqId); return true; } /// @notice a function called by Owner to request GrandPrize random number function drawNumberGrandPrize() external payable whenNotPaused onlyOwner requireState(DrawState.Closed) nonReentrant returns (bool) { if(msg.value > 0){ _updateGrandPrizePool(_grandPrizePool.add(msg.value)); } require( _grandPrizePool != 0 && address(this).balance.sub(_reserves) >= _grandPrizePool, "DCBW721: Not enough balance for grand prize" ); bytes32 reqId = IRNG(_rngContract).request(); _state = DrawState.Open; draws[_drawsToDate] = DrawData( _drawsToDate, uint32(block.timestamp), /* solium-disable-line */ 0, 1, address(0), 0, _state, reqId ); emit DrawInitiated(reqId); return true; } /** * @notice a function called by DCBW721RNG fulfillRandomness Callback function to pick winner if it exists * @param _requestId The Id initially returned by DCBW721RNG requestRandomness * @param _randomness Random number generated by Chainlink VRF **/ function numberDrawn(bytes32 _requestId, uint256 _randomness) external whenNotPaused requireAccount(_rngContract) nonReentrant { DrawData storage current = draws[_drawsToDate]; require( current.randomNumberRequestId == _requestId, "DCBW721: Request ID mismatch" ); current.winningEdition = uint64(uint256(_randomness % _maxTokenId).add(1)); if (_exists(current.winningEdition)) { current.winner = ownerOf(current.winningEdition); current.prizePoolWon = current.isGrandPrize == uint96(1) ? uint96(_grandPrizePool) : uint96(_reserves); _payout(current); } emit DrawFinished(current.winner, current.winningEdition); /// @notice update state _drawsToDate++; _state = DrawState.Closed; /// @notice update draw record current.state = _state; } /** * @notice prize payout function * @param current DrawData object having a draw data **/ function _payout(DrawData memory current) private { require(current.winner != address(0), "DCBW721: Address cannot be 0"); require(current.prizePoolWon > 0, "DCBW721: Prize pool is empty"); /// @notice updating reserve pool & grand prize pool if (current.isGrandPrize == 1) { _updateGrandPrizePool(0); } else { _updateReserves(0); } /// @notice forward prize to winner wallet using CALL to avoid 2300 stipend limit (bool success, ) = payable(current.winner).call{value: current.prizePoolWon}(""); require(success, "DCBW721: Failed to forward prize"); } /// @notice pausing the contract minting and token transfer function pause() public virtual onlyOwner { _pause(); } /// @notice unpausing the contract minting and token transfer function unpause() public virtual onlyOwner { _unpause(); } /** * @notice sets the state of the draw to closed * @dev for if the numberDrawn reverted */ function resetDrawState() public onlyOwner { _state = DrawState.Closed; } /** * @notice changes the minter address * @param minter the new minter address **/ function changeMinter(address minter) public onlyOwner { require( minter != address(0), "DCBW721: Minter cannot be address 0" ); require( minter != _minter, "DCBW721: Minter cannot be same as previous" ); _minter = minter; } /** * @notice changes the minting beneficiary payable address * @param beneficiary the contract Splitter that will receive minting funds **/ function changeMintBeneficiary(address beneficiary) public onlyOwner { require( beneficiary != address(0), "DCBW721: Minting beneficiary cannot be address 0" ); require( beneficiary != _mintingBeneficiary, "DCBW721: beneficiary cannot be same as previous" ); _mintingBeneficiary = payable(beneficiary); } /** * @notice changes the royalties beneficiary EIP2981 * @param beneficiary the address that will receive royalties * @param shares the shares as royalties **/ function changeRoyaltiesBeneficiary(address beneficiary, uint32 shares) public onlyOwner { require( beneficiary != address(0), "DCBW721: Royalties beneficiary cannot be address 0" ); require(shares > 0, 'DCBW721: Royalty shares cannot be 0'); RoyaltyReceiver storage rr = royalties[0]; rr.account = beneficiary; rr.shares = shares; } /** * @notice changes the minting cost * @param mintCost new minting cost **/ function changeMintCost(uint256 mintCost) public onlyOwner { require( mintCost != _mintPrice, "DCBW721: mint Cost cannot be same as previous" ); _mintPrice = mintCost; } /** * @notice changes the minting cost * @param newBaseURI the new Base URI **/ function changeBaseURI(string memory newBaseURI) public onlyOwner notLocked { require((keccak256(abi.encodePacked((_baseTokenURI))) != keccak256(abi.encodePacked((newBaseURI)))), "DCBW721: Base URI cannot be same as previous"); _baseTokenURI = newBaseURI; } /** * @notice changes the reserve rate * @param reservesRate new reserve rate **/ function changeReserveRate(uint256 reservesRate) public onlyOwner { require( _reservesRate != reservesRate, "DCBW721: reservesRate cannot be same as previous" ); _reservesRate = reservesRate; } /** * @notice grants alarm role to supplied address * @param account the address to receive the ALARM role */ function setAlarmAccount(address account) public virtual onlyOwner { require(account != address(0), "DCBW721: Alarm cannot be address 0"); require( account != _alarmContract, "DCBW721: Alarm Contract cannot be same as previous" ); _alarmContract = account; } /** * @notice grants vrf role to supplied address * @param account the address to receive the VRF role */ function setVRFAccount(address account) public virtual onlyOwner { require(account != address(0), "DCBW721: VRF/RNG cannot be address 0"); require( account != _rngContract, "DCBW721: RNG cannot be same as previous" ); _rngContract = account; } /// @notice lock metadata forever function lockMetadata() public onlyOwner notLocked { locked = true; } /** * @notice the public function for checking if a token ID has been minted * @param _tokenId to token ID to be checked **/ function isTokenMinted(uint256 _tokenId) public view returns (bool) { return validateTokenId(_tokenId) && _exists(_tokenId); } /** * @notice the public function for validation of specific token ID * @param _tokenId to token ID to be validated **/ function validateTokenId(uint256 _tokenId) public view returns (bool) { require(_tokenId >= 1, "DCBW721: Invalid token ID"); require(_tokenId <= _maxTokenId, "DCBW721: Invalid token ID"); return true; } /** * @notice updates the store reserves tracker * @param reserves current reserves after new minting **/ function _updateReserves(uint256 reserves) internal { require( reserves <= address(this).balance.sub(_grandPrizePool), "DCBW721: Reserve-Balance Mismatch" ); _reserves = reserves; } /** * @notice updates the store grandPrizePool tracker * @param grandPrize current grandPrize pool after receiving royalties **/ function _updateGrandPrizePool(uint256 grandPrize) internal { require( grandPrize <= address(this).balance.sub(_reserves), "DCBW721: GrandPrize-Balance Mismatch" ); _grandPrizePool = grandPrize; } /** * @notice Determines how ETH is stored/forwarded on purchases. * @param received amount to forward **/ function _forwardFunds(uint256 received) internal { /// @notice forward fund to receiver wallet using CALL to avoid 2300 stipend limit (bool success, ) = _mintingBeneficiary.call{value: received.mul(uint256(1000).sub(_reservesRate)).div(1000)}(""); require(success, "DCBW721: Failed to forward funds"); } /** * @notice before transfer hook function * @param from the address to send the token from * @param to the address to send the token to * @param tokenId to token ID to be sent **/ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override(ERC721, ERC721Enumerable, ERC721Pausable) { super._beforeTokenTransfer(from, to, tokenId); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } }
* @notice changes the minting beneficiary payable address @param beneficiary the contract Splitter that will receive minting funds/
function changeMintBeneficiary(address beneficiary) public onlyOwner { require( beneficiary != address(0), "DCBW721: Minting beneficiary cannot be address 0" ); require( beneficiary != _mintingBeneficiary, "DCBW721: beneficiary cannot be same as previous" ); _mintingBeneficiary = payable(beneficiary); }
12,806,477
[ 1, 6329, 326, 312, 474, 310, 27641, 74, 14463, 814, 8843, 429, 1758, 225, 27641, 74, 14463, 814, 326, 6835, 5385, 387, 716, 903, 6798, 312, 474, 310, 284, 19156, 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, 2549, 49, 474, 38, 4009, 74, 14463, 814, 12, 2867, 27641, 74, 14463, 814, 13, 1071, 1338, 5541, 288, 203, 3639, 2583, 12, 203, 5411, 27641, 74, 14463, 814, 480, 1758, 12, 20, 3631, 203, 5411, 315, 5528, 38, 59, 27, 5340, 30, 490, 474, 310, 27641, 74, 14463, 814, 2780, 506, 1758, 374, 6, 203, 3639, 11272, 203, 3639, 2583, 12, 203, 5411, 27641, 74, 14463, 814, 480, 389, 81, 474, 310, 38, 4009, 74, 14463, 814, 16, 203, 5411, 315, 5528, 38, 59, 27, 5340, 30, 27641, 74, 14463, 814, 2780, 506, 1967, 487, 2416, 6, 203, 3639, 11272, 203, 3639, 389, 81, 474, 310, 38, 4009, 74, 14463, 814, 273, 8843, 429, 12, 70, 4009, 74, 14463, 814, 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 ]
// SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.4; import {IERC20} from '@openzeppelin/contracts/token/ERC20/IERC20.sol'; import {IStandardERC20} from '../../../base/interfaces/IStandardERC20.sol'; import { MintableBurnableIERC20 } from '../../../tokens/interfaces/MintableBurnableIERC20.sol'; import { IdentifierWhitelistInterface } from '@uma/core/contracts/oracle/interfaces/IdentifierWhitelistInterface.sol'; import { AddressWhitelistInterface } from '@uma/core/contracts/common/interfaces/AddressWhitelistInterface.sol'; import { AdministrateeInterface } from '@uma/core/contracts/oracle/interfaces/AdministrateeInterface.sol'; import {ISynthereumFinder} from '../../../core/interfaces/IFinder.sol'; import { ISelfMintingDerivativeDeployment } from '../common/interfaces/ISelfMintingDerivativeDeployment.sol'; import { OracleInterface } from '@uma/core/contracts/oracle/interfaces/OracleInterface.sol'; import { OracleInterfaces } from '@uma/core/contracts/oracle/implementation/Constants.sol'; import {SynthereumInterfaces} from '../../../core/Constants.sol'; import { FixedPoint } from '@uma/core/contracts/common/implementation/FixedPoint.sol'; import { SafeERC20 } from '@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol'; import { SelfMintingPerpetualPositionManagerMultiPartyLib } from './SelfMintingPerpetualPositionManagerMultiPartyLib.sol'; import {FeePayerPartyLib} from '../../common/FeePayerPartyLib.sol'; import {FeePayerParty} from '../../common/FeePayerParty.sol'; /** * @title Financial contract with priceless position management. * @notice Handles positions for multiple sponsors in an optimistic (i.e., priceless) way without relying * on a price feed. On construction, deploys a new ERC20, managed by this contract, that is the synthetic token. */ contract SelfMintingPerpetualPositionManagerMultiParty is ISelfMintingDerivativeDeployment, FeePayerParty { using FixedPoint for FixedPoint.Unsigned; using SafeERC20 for IERC20; using SafeERC20 for MintableBurnableIERC20; using SelfMintingPerpetualPositionManagerMultiPartyLib for PositionData; using SelfMintingPerpetualPositionManagerMultiPartyLib for PositionManagerData; using FeePayerPartyLib for FixedPoint.Unsigned; /** * @notice Construct the PerpetualPositionManager. * @dev Deployer of this contract should consider carefully which parties have ability to mint and burn * the synthetic tokens referenced by `_tokenAddress`. This contract's security assumes that no external accounts * can mint new tokens, which could be used to steal all of this contract's locked collateral. * We recommend to only use synthetic token contracts whose sole Owner role (the role capable of adding & removing roles) * is assigned to this contract, whose sole Minter role is assigned to this contract, and whose * total supply is 0 prior to construction of this contract. * @param withdrawalLiveness liveness delay, in seconds, for pending withdrawals. * @param collateralAddress ERC20 token used as collateral for all positions. * @param tokenAddress ERC20 token used as synthetic token. * @param finderAddress UMA protocol Finder used to discover other protocol contracts. * @param priceFeedIdentifier registered in the DVM for the synthetic. * @param minSponsorTokens minimum amount of collateral that must exist at any time in a position. * @param timerAddress Contract that stores the current time in a testing environment. Set to 0x0 for production. * @param excessTokenBeneficiary Beneficiary to send all excess token balances that accrue in the contract. * @param version Version of the self-minting derivative * @param synthereumFinder The SynthereumFinder contract */ struct PositionManagerParams { uint256 withdrawalLiveness; address collateralAddress; address tokenAddress; address finderAddress; bytes32 priceFeedIdentifier; FixedPoint.Unsigned minSponsorTokens; address timerAddress; address excessTokenBeneficiary; uint8 version; ISynthereumFinder synthereumFinder; } // Represents a single sponsor's position. All collateral is held by this contract. // This struct acts as bookkeeping for how much of that collateral is allocated to each sponsor. struct PositionData { FixedPoint.Unsigned tokensOutstanding; // Tracks pending withdrawal requests. A withdrawal request is pending if `withdrawalRequestPassTimestamp != 0`. uint256 withdrawalRequestPassTimestamp; FixedPoint.Unsigned withdrawalRequestAmount; // Raw collateral value. This value should never be accessed directly -- always use _getFeeAdjustedCollateral(). // To add or remove collateral, use _addCollateral() and _removeCollateral(). FixedPoint.Unsigned rawCollateral; } struct GlobalPositionData { // Keep track of the total collateral and tokens across all positions to enable calculating the // global collateralization ratio without iterating over all positions. FixedPoint.Unsigned totalTokensOutstanding; // Similar to the rawCollateral in PositionData, this value should not be used directly. //_getFeeAdjustedCollateral(), _addCollateral() and _removeCollateral() must be used to access and adjust. FixedPoint.Unsigned rawTotalPositionCollateral; } struct PositionManagerData { // SynthereumFinder contract ISynthereumFinder synthereumFinder; // Synthetic token created by this contract. MintableBurnableIERC20 tokenCurrency; // Unique identifier for DVM price feed ticker. bytes32 priceIdentifier; // Time that has to elapse for a withdrawal request to be considered passed, if no liquidations occur. // !!Note: The lower the withdrawal liveness value, the more risk incurred by the contract. // Extremely low liveness values increase the chance that opportunistic invalid withdrawal requests // expire without liquidation, thereby increasing the insolvency risk for the contract as a whole. An insolvent // contract is extremely risky for any sponsor or synthetic token holder for the contract. uint256 withdrawalLiveness; // Minimum number of tokens in a sponsor's position. FixedPoint.Unsigned minSponsorTokens; // Expiry price pulled from the DVM in the case of an emergency shutdown. FixedPoint.Unsigned emergencyShutdownPrice; // Timestamp used in case of emergency shutdown. uint256 emergencyShutdownTimestamp; // The excessTokenBeneficiary of any excess tokens added to the contract. address excessTokenBeneficiary; // Version of the self-minting derivative uint8 version; } //---------------------------------------- // Storage //---------------------------------------- // Maps sponsor addresses to their positions. Each sponsor can have only one position. mapping(address => PositionData) public positions; GlobalPositionData public globalPositionData; PositionManagerData public positionManagerData; //---------------------------------------- // Events //---------------------------------------- event Deposit(address indexed sponsor, uint256 indexed collateralAmount); event Withdrawal(address indexed sponsor, uint256 indexed collateralAmount); event RequestWithdrawal( address indexed sponsor, uint256 indexed collateralAmount ); event RequestWithdrawalExecuted( address indexed sponsor, uint256 indexed collateralAmount ); event RequestWithdrawalCanceled( address indexed sponsor, uint256 indexed collateralAmount ); event PositionCreated( address indexed sponsor, uint256 indexed collateralAmount, uint256 indexed tokenAmount, uint256 feeAmount ); event NewSponsor(address indexed sponsor); event EndedSponsorPosition(address indexed sponsor); event Redeem( address indexed sponsor, uint256 indexed collateralAmount, uint256 indexed tokenAmount, uint256 feeAmount ); event Repay( address indexed sponsor, uint256 indexed numTokensRepaid, uint256 indexed newTokenCount, uint256 feeAmount ); event EmergencyShutdown(address indexed caller, uint256 shutdownTimestamp); event SettleEmergencyShutdown( address indexed caller, uint256 indexed collateralReturned, uint256 indexed tokensBurned ); //---------------------------------------- // Modifiers //---------------------------------------- modifier onlyCollateralizedPosition(address sponsor) { _onlyCollateralizedPosition(sponsor); _; } modifier notEmergencyShutdown() { _notEmergencyShutdown(); _; } modifier isEmergencyShutdown() { _isEmergencyShutdown(); _; } modifier noPendingWithdrawal(address sponsor) { _positionHasNoPendingWithdrawal(sponsor); _; } //---------------------------------------- // Constructor //---------------------------------------- /** * @notice Construct the SelfMintingPerpetualPositionManagerMultiParty. * @param _positionManagerData Input parameters of PositionManager (see PositionManagerData struct) */ constructor(PositionManagerParams memory _positionManagerData) FeePayerParty( _positionManagerData.collateralAddress, _positionManagerData.finderAddress, _positionManagerData.timerAddress ) nonReentrant() { require( _getIdentifierWhitelist().isIdentifierSupported( _positionManagerData.priceFeedIdentifier ), 'Unsupported price identifier' ); require( _getCollateralWhitelist().isOnWhitelist( _positionManagerData.collateralAddress ), 'Collateral not whitelisted' ); positionManagerData.synthereumFinder = _positionManagerData .synthereumFinder; positionManagerData.withdrawalLiveness = _positionManagerData .withdrawalLiveness; positionManagerData.tokenCurrency = MintableBurnableIERC20( _positionManagerData.tokenAddress ); positionManagerData.minSponsorTokens = _positionManagerData .minSponsorTokens; positionManagerData.priceIdentifier = _positionManagerData .priceFeedIdentifier; positionManagerData.excessTokenBeneficiary = _positionManagerData .excessTokenBeneficiary; positionManagerData.version = _positionManagerData.version; } //---------------------------------------- // External functions //---------------------------------------- /** * @notice Transfers `collateralAmount` of `feePayerData.collateralCurrency` into the caller's position. * @dev Increases the collateralization level of a position after creation. This contract must be approved to spend * at least `collateralAmount` of `feePayerData.collateralCurrency`. * @param collateralAmount total amount of collateral tokens to be sent to the sponsor's position. */ function deposit(uint256 collateralAmount) external { depositTo(msg.sender, collateralAmount); } /** * @notice Transfers `collateralAmount` of `feePayerData.collateralCurrency` from the sponsor's position to the sponsor. * @dev Reverts if the withdrawal puts this position's collateralization ratio below the global collateralization * ratio. In that case, use `requestWithdrawal`. Might not withdraw the full requested amount to account for precision loss. * @param collateralAmount is the amount of collateral to withdraw. * @return amountWithdrawn The actual amount of collateral withdrawn. */ function withdraw(uint256 collateralAmount) external notEmergencyShutdown() noPendingWithdrawal(msg.sender) fees() nonReentrant() returns (uint256 amountWithdrawn) { PositionData storage positionData = _getPositionData(msg.sender); amountWithdrawn = positionData .withdraw( globalPositionData, FixedPoint.Unsigned(collateralAmount), feePayerData ) .rawValue; } /** * @notice Starts a withdrawal request that, if passed, allows the sponsor to withdraw` from their position. * @dev The request will be pending for `withdrawalLiveness`, during which the position can be liquidated. * @param collateralAmount the amount of collateral requested to withdraw */ function requestWithdrawal(uint256 collateralAmount) external notEmergencyShutdown() noPendingWithdrawal(msg.sender) nonReentrant() { uint256 actualTime = getCurrentTime(); PositionData storage positionData = _getPositionData(msg.sender); positionData.requestWithdrawal( positionManagerData, FixedPoint.Unsigned(collateralAmount), actualTime, feePayerData ); } /** * @notice After a passed withdrawal request (i.e., by a call to `requestWithdrawal` and waiting * `withdrawalLiveness`), withdraws `positionData.withdrawalRequestAmount` of collateral currency. * @dev Might not withdraw the full requested amount in order to account for precision loss or if the full requested * amount exceeds the collateral in the position (due to paying fees). * @return amountWithdrawn The actual amount of collateral withdrawn. */ function withdrawPassedRequest() external notEmergencyShutdown() fees() nonReentrant() returns (uint256 amountWithdrawn) { uint256 actualTime = getCurrentTime(); PositionData storage positionData = _getPositionData(msg.sender); amountWithdrawn = positionData .withdrawPassedRequest(globalPositionData, actualTime, feePayerData) .rawValue; } /** * @notice Cancels a pending withdrawal request. */ function cancelWithdrawal() external notEmergencyShutdown() nonReentrant() { PositionData storage positionData = _getPositionData(msg.sender); positionData.cancelWithdrawal(); } /** * @notice Creates tokens by creating a new position or by augmenting an existing position. Pulls `collateralAmount * ` into the sponsor's position and mints `numTokens` of `tokenCurrency`. * @dev Can only be called by a token sponsor. Might not mint the full proportional amount of collateral * in order to account for precision loss. This contract must be approved to spend at least `collateralAmount` of * `collateralCurrency`. * @param collateralAmount is the number of collateral tokens to collateralize the position with * @param numTokens is the number of tokens to mint from the position. * @param feePercentage The percentage of fee that is paid in collateralCurrency */ function create( uint256 collateralAmount, uint256 numTokens, uint256 feePercentage ) external notEmergencyShutdown() fees() nonReentrant() returns (uint256 daoFeeAmount) { PositionData storage positionData = positions[msg.sender]; daoFeeAmount = positionData .create( globalPositionData, positionManagerData, FixedPoint.Unsigned(collateralAmount), FixedPoint.Unsigned(numTokens), FixedPoint.Unsigned(feePercentage), feePayerData ) .rawValue; } /** * @notice Burns `numTokens` of `tokenCurrency` and sends back the proportional amount of `feePayerData.collateralCurrency`. * @dev Can only be called by a token sponsor. Might not redeem the full proportional amount of collateral * in order to account for precision loss. This contract must be approved to spend at least `numTokens` of * `tokenCurrency`. * @param numTokens is the number of tokens to be burnt for a commensurate amount of collateral. * @return amountWithdrawn The actual amount of collateral withdrawn. */ function redeem(uint256 numTokens, uint256 feePercentage) external notEmergencyShutdown() noPendingWithdrawal(msg.sender) fees() nonReentrant() returns (uint256 amountWithdrawn, uint256 daoFeeAmount) { PositionData storage positionData = _getPositionData(msg.sender); ( FixedPoint.Unsigned memory collateralAmount, FixedPoint.Unsigned memory feeAmount ) = positionData.redeeem( globalPositionData, positionManagerData, FixedPoint.Unsigned(numTokens), FixedPoint.Unsigned(feePercentage), feePayerData, msg.sender ); amountWithdrawn = collateralAmount.rawValue; daoFeeAmount = feeAmount.rawValue; } /** * @notice Burns `numTokens` of `tokenCurrency` to decrease sponsors position size, without sending back `feePayerData.collateralCurrency`. * This is done by a sponsor to increase position CR. * @dev Can only be called by token sponsor. This contract must be approved to spend `numTokens` of `tokenCurrency`. * @param numTokens is the number of tokens to be burnt for a commensurate amount of collateral. * @param feePercentage the fee percentage paid by the token sponsor in collateralCurrency */ function repay(uint256 numTokens, uint256 feePercentage) external notEmergencyShutdown() noPendingWithdrawal(msg.sender) fees() nonReentrant() returns (uint256 daoFeeAmount) { PositionData storage positionData = _getPositionData(msg.sender); daoFeeAmount = ( positionData.repay( globalPositionData, positionManagerData, FixedPoint.Unsigned(numTokens), FixedPoint.Unsigned(feePercentage), feePayerData ) ) .rawValue; } /** * @notice If the contract is emergency shutdown then all token holders and sponsor can redeem their tokens or * remaining collateral for underlying at the prevailing price defined by a DVM vote. * @dev This burns all tokens from the caller of `tokenCurrency` and sends back the resolved settlement value of * `feePayerData.collateralCurrency`. Might not redeem the full proportional amount of collateral in order to account for * precision loss. This contract must be approved to spend `tokenCurrency` at least up to the caller's full balance. * @dev This contract must have the Burner role for the `tokenCurrency`. * @return amountWithdrawn The actual amount of collateral withdrawn. */ function settleEmergencyShutdown() external isEmergencyShutdown() fees() nonReentrant() returns (uint256 amountWithdrawn) { PositionData storage positionData = positions[msg.sender]; amountWithdrawn = positionData .settleEmergencyShutdown( globalPositionData, positionManagerData, feePayerData ) .rawValue; } /** * @notice Premature contract settlement under emergency circumstances. * @dev Only the governor can call this function as they are permissioned within the `FinancialContractAdmin`. * Upon emergency shutdown, the contract settlement time is set to the shutdown time. This enables withdrawal * to occur via the `settleEmergencyShutdown` function. */ function emergencyShutdown() external override notEmergencyShutdown() nonReentrant() { require( msg.sender == positionManagerData.synthereumFinder.getImplementationAddress( SynthereumInterfaces.Manager ) || msg.sender == _getFinancialContractsAdminAddress(), 'Caller must be a Synthereum manager or the UMA governor' ); positionManagerData.emergencyShutdownTimestamp = getCurrentTime(); positionManagerData.requestOraclePrice( positionManagerData.emergencyShutdownTimestamp, feePayerData ); emit EmergencyShutdown( msg.sender, positionManagerData.emergencyShutdownTimestamp ); } /** @notice Remargin function */ function remargin() external override { return; } /** * @notice Drains any excess balance of the provided ERC20 token to a pre-selected beneficiary. * @dev This will drain down to the amount of tracked collateral and drain the full balance of any other token. * @param token address of the ERC20 token whose excess balance should be drained. */ function trimExcess(IERC20 token) external nonReentrant() returns (uint256 amount) { FixedPoint.Unsigned memory pfcAmount = _pfc(); amount = positionManagerData .trimExcess(token, pfcAmount, feePayerData) .rawValue; } /** * @notice Delete a TokenSponsor position (This function can only be called by the contract itself) * @param sponsor address of the TokenSponsor. */ function deleteSponsorPosition(address sponsor) external onlyThisContract { delete positions[sponsor]; } /** * @notice Accessor method for a sponsor's collateral. * @dev This is necessary because the struct returned by the positions() method shows * rawCollateral, which isn't a user-readable value. * @param sponsor address whose collateral amount is retrieved. * @return collateralAmount amount of collateral within a sponsors position. */ function getCollateral(address sponsor) external view nonReentrantView() returns (FixedPoint.Unsigned memory collateralAmount) { return positions[sponsor].rawCollateral.getFeeAdjustedCollateral( feePayerData.cumulativeFeeMultiplier ); } /** * @notice Get SynthereumFinder contract address * @return finder SynthereumFinder contract */ function synthereumFinder() external view override returns (ISynthereumFinder finder) { finder = positionManagerData.synthereumFinder; } /** * @notice Get synthetic token currency * @return synthToken Synthetic token */ function tokenCurrency() external view override returns (IERC20 synthToken) { synthToken = positionManagerData.tokenCurrency; } /** * @notice Get synthetic token symbol * @return symbol Synthetic token symbol */ function syntheticTokenSymbol() external view override returns (string memory symbol) { symbol = IStandardERC20(address(positionManagerData.tokenCurrency)) .symbol(); } /** @notice Get the version of a self minting derivative * @return contractVersion Contract version */ function version() external view override returns (uint8 contractVersion) { contractVersion = positionManagerData.version; } /** * @notice Get synthetic token price identifier registered with UMA DVM * @return identifier Synthetic token price identifier */ function priceIdentifier() external view returns (bytes32 identifier) { identifier = positionManagerData.priceIdentifier; } /** * @notice Accessor method for the total collateral stored within the SelfMintingPerpetualPositionManagerMultiParty. * @return totalCollateral amount of all collateral within the position manager. */ function totalPositionCollateral() external view nonReentrantView() returns (uint256) { return globalPositionData .rawTotalPositionCollateral .getFeeAdjustedCollateral(feePayerData.cumulativeFeeMultiplier) .rawValue; } /** * @notice Get the currently minted synthetic tokens from all self-minting derivatives * @return totalTokens Total amount of synthetic tokens minted */ function totalTokensOutstanding() external view returns (uint256) { return globalPositionData.totalTokensOutstanding.rawValue; } /** * @notice Get the price of synthetic token set by DVM after emergencyShutdown call * @return Price of synthetic token */ function emergencyShutdownPrice() external view isEmergencyShutdown() returns (uint256) { return positionManagerData.emergencyShutdownPrice.rawValue; } /** @notice Calculates the DAO fee based on the numTokens parameter * @param numTokens Number of synthetic tokens used in the transaction * @return rawValue The DAO fee to be paid in collateralCurrency */ function calculateDaoFee(uint256 numTokens) external view returns (uint256) { return positionManagerData .calculateDaoFee( globalPositionData, FixedPoint.Unsigned(numTokens), feePayerData ) .rawValue; } /** @notice Checks the currently set fee recipient and fee percentage for the DAO fee * @return feePercentage The percentage set by the DAO to be taken as a fee on each transaction * @return feeRecipient The DAO address that receives the fee */ function daoFee() external view returns (uint256 feePercentage, address feeRecipient) { (FixedPoint.Unsigned memory percentage, address recipient) = positionManagerData.daoFee(); feePercentage = percentage.rawValue; feeRecipient = recipient; } /** @notice Check the current cap on self-minting synthetic tokens. * A cap mint amount is set in order to avoid depletion of liquidity pools, * by self-minting synthetic assets and redeeming collateral from the pools. * The cap mint amount is updateable and is based on a percentage of the currently * minted synthetic assets from the liquidity pools. * @return capMint The currently set cap amount for self-minting a synthetic token */ function capMintAmount() external view returns (uint256 capMint) { capMint = positionManagerData.capMintAmount().rawValue; } /** @notice Check the current cap on deposit of collateral into a self-minting derivative. * A cap deposit ratio is set in order to avoid a troll attack in which an attacker * can increase infinitely the GCR thus making it extremelly expensive or impossible * for other users to self-mint synthetic assets with a given collateral. * @return capDeposit The current cap deposit ratio */ function capDepositRatio() external view returns (uint256 capDeposit) { capDeposit = positionManagerData.capDepositRatio().rawValue; } /** * @notice Transfers `collateralAmount` of `feePayerData.collateralCurrency` into the specified sponsor's position. * @dev Increases the collateralization level of a position after creation. This contract must be approved to spend * at least `collateralAmount` of `feePayerData.collateralCurrency`. * @param sponsor the sponsor to credit the deposit to. * @param collateralAmount total amount of collateral tokens to be sent to the sponsor's position. */ function depositTo(address sponsor, uint256 collateralAmount) public notEmergencyShutdown() noPendingWithdrawal(sponsor) fees() nonReentrant() { PositionData storage positionData = _getPositionData(sponsor); positionData.depositTo( globalPositionData, positionManagerData, FixedPoint.Unsigned(collateralAmount), feePayerData, sponsor ); } /** @notice Check the collateralCurrency in which fees are paid for a given self-minting derivative * @return collateral The collateral currency */ function collateralCurrency() public view override(ISelfMintingDerivativeDeployment, FeePayerParty) returns (IERC20 collateral) { collateral = FeePayerParty.collateralCurrency(); } //---------------------------------------- // Internal functions //---------------------------------------- /** @notice Gets the adjusted collateral after substracting fee * @return adjusted net collateral */ function _pfc() internal view virtual override returns (FixedPoint.Unsigned memory) { return globalPositionData.rawTotalPositionCollateral.getFeeAdjustedCollateral( feePayerData.cumulativeFeeMultiplier ); } /** @notice Gets all data on a given sponsors position for a self-minting derivative * @param sponsor Address of the sponsor to check * @return A struct of information on a tokens sponsor position */ function _getPositionData(address sponsor) internal view onlyCollateralizedPosition(sponsor) returns (PositionData storage) { return positions[sponsor]; } /** @notice Get a whitelisted price feed implementation from the Finder contract for a self-minting derivative * @return IdentifierWhitelistInterface Address of the whitelisted identifier */ function _getIdentifierWhitelist() internal view returns (IdentifierWhitelistInterface) { return IdentifierWhitelistInterface( feePayerData.finder.getImplementationAddress( OracleInterfaces.IdentifierWhitelist ) ); } /** @notice Get a whitelisted collateralCurrency address from the Finder contract for a self-minting derivative * @return AddressWhitelistInterface Address of the whitelisted collateralCurrency */ function _getCollateralWhitelist() internal view returns (AddressWhitelistInterface) { return AddressWhitelistInterface( feePayerData.finder.getImplementationAddress( OracleInterfaces.CollateralWhitelist ) ); } /** @notice Get the collateral for a position of a token sponsor on a self-minting derivative if any * or return that this token sponsor does not have such a position * @param sponsor Address of the token sponsor to check */ function _onlyCollateralizedPosition(address sponsor) internal view { require( positions[sponsor] .rawCollateral .getFeeAdjustedCollateral(feePayerData.cumulativeFeeMultiplier) .isGreaterThan(0), 'Position has no collateral' ); } /** @notice Make sure an emergency shutdown is not called on a self-minting derivative */ function _notEmergencyShutdown() internal view { require( positionManagerData.emergencyShutdownTimestamp == 0, 'Contract emergency shutdown' ); } /** @notice Make sure an emergency shutdown is called on a self-minting derivative */ function _isEmergencyShutdown() internal view { require( positionManagerData.emergencyShutdownTimestamp != 0, 'Contract not emergency shutdown' ); } /** @notice Make sure that there are no pending withdraws on a position of a token sponsor * @param sponsor Token sponsor address for which to check */ function _positionHasNoPendingWithdrawal(address sponsor) internal view { require( _getPositionData(sponsor).withdrawalRequestPassTimestamp == 0, 'Pending withdrawal' ); } /** @notice Gets the financial contract admin address */ function _getFinancialContractsAdminAddress() internal view returns (address) { return feePayerData.finder.getImplementationAddress( OracleInterfaces.FinancialContractsAdmin ); } }
* @notice Transfers `collateralAmount` of `feePayerData.collateralCurrency` into the caller's position. @dev Increases the collateralization level of a position after creation. This contract must be approved to spend at least `collateralAmount` of `feePayerData.collateralCurrency`. @param collateralAmount total amount of collateral tokens to be sent to the sponsor's position./
function deposit(uint256 collateralAmount) external { depositTo(msg.sender, collateralAmount); }
1,791,527
[ 1, 1429, 18881, 1375, 12910, 2045, 287, 6275, 68, 434, 1375, 21386, 52, 1773, 751, 18, 12910, 2045, 287, 7623, 68, 1368, 326, 4894, 1807, 1754, 18, 225, 657, 1793, 3304, 326, 4508, 2045, 287, 1588, 1801, 434, 279, 1754, 1839, 6710, 18, 1220, 6835, 1297, 506, 20412, 358, 17571, 622, 4520, 1375, 12910, 2045, 287, 6275, 68, 434, 1375, 21386, 52, 1773, 751, 18, 12910, 2045, 287, 7623, 8338, 225, 4508, 2045, 287, 6275, 2078, 3844, 434, 4508, 2045, 287, 2430, 358, 506, 3271, 358, 326, 272, 500, 2467, 1807, 1754, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 225, 445, 443, 1724, 12, 11890, 5034, 4508, 2045, 287, 6275, 13, 3903, 288, 203, 565, 443, 1724, 774, 12, 3576, 18, 15330, 16, 4508, 2045, 287, 6275, 1769, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/80001/0x43A586FC911442F167F2DfE54b3D469584b22E69/sources/contracts/Todo.sol
We will declare an array of strings called todos We will take _todo as an input and push it inside the array in this function
contract Todos { string[] public todos; pragma solidity ^0.8.0; function setTodo(string memory _todo) public { todos.push(_todo); } function getTodo() public view returns (string[] memory) { return todos; } function getTodosLength() public view returns (uint) { uint todosLength = todos.length; return todosLength; } function deleteToDo(uint _index) public { require(_index < todos.length, "This todo index does not exist."); todos[_index] = todos[getTodosLength() - 1]; todos.pop(); } }
5,646,593
[ 1, 3218, 903, 14196, 392, 526, 434, 2064, 2566, 31754, 1660, 903, 4862, 389, 9012, 487, 392, 810, 471, 1817, 518, 4832, 326, 526, 316, 333, 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, 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, 16351, 399, 369, 538, 288, 203, 565, 533, 8526, 1071, 31754, 31, 203, 377, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 20, 31, 203, 565, 445, 444, 56, 7370, 12, 1080, 3778, 389, 9012, 13, 1071, 288, 203, 3639, 31754, 18, 6206, 24899, 9012, 1769, 203, 565, 289, 203, 203, 565, 445, 3181, 7370, 1435, 1071, 1476, 1135, 261, 1080, 8526, 3778, 13, 288, 203, 3639, 327, 31754, 31, 203, 565, 289, 203, 377, 203, 565, 445, 3181, 369, 538, 1782, 1435, 1071, 1476, 1135, 261, 11890, 13, 288, 203, 3639, 2254, 31754, 1782, 273, 31754, 18, 2469, 31, 203, 3639, 327, 31754, 1782, 31, 203, 565, 289, 203, 377, 203, 565, 445, 1430, 774, 3244, 12, 11890, 389, 1615, 13, 1071, 288, 203, 3639, 2583, 24899, 1615, 411, 31754, 18, 2469, 16, 315, 2503, 10621, 770, 1552, 486, 1005, 1199, 1769, 203, 3639, 31754, 63, 67, 1615, 65, 273, 31754, 63, 588, 56, 369, 538, 1782, 1435, 300, 404, 15533, 203, 3639, 31754, 18, 5120, 5621, 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 ]
/** *Submitted for verification at Etherscan.io on 2021-10-27 */ // File: contracts/common/Initializable.sol pragma solidity ^0.8.0; contract Initializable { bool inited = false; modifier initializer() { require(!inited, "already inited"); _; inited = true; } } // File: contracts/common/EIP712Base.sol pragma solidity ^0.8.0; contract EIP712Base is Initializable { struct EIP712Domain { string name; string version; address verifyingContract; bytes32 salt; } string constant public ERC712_VERSION = "1"; bytes32 internal constant EIP712_DOMAIN_TYPEHASH = keccak256( bytes( "EIP712Domain(string name,string version,address verifyingContract,bytes32 salt)" ) ); bytes32 internal domainSeperator; // supposed to be called once while initializing. // one of the contracts that inherits this contract follows proxy pattern // so it is not possible to do this in a constructor function _initializeEIP712( string memory name ) internal initializer { _setDomainSeperator(name); } function _setDomainSeperator(string memory name) internal { domainSeperator = keccak256( abi.encode( EIP712_DOMAIN_TYPEHASH, keccak256(bytes(name)), keccak256(bytes(ERC712_VERSION)), address(this), bytes32(getChainId()) ) ); } function getDomainSeperator() public view returns (bytes32) { return domainSeperator; } function getChainId() public view returns (uint256) { uint256 id; assembly { id := chainid() } return id; } /** * Accept message hash and returns hash message in EIP712 compatible form * So that it can be used to recover signer from signature signed using EIP712 formatted data * https://eips.ethereum.org/EIPS/eip-712 * "\\x19" makes the encoding deterministic * "\\x01" is the version byte to make it compatible to EIP-191 */ function toTypedMessageHash(bytes32 messageHash) internal view returns (bytes32) { return keccak256( abi.encodePacked("\x19\x01", getDomainSeperator(), messageHash) ); } } // File: contracts/common/ContextMixin.sol pragma solidity ^0.8.0; abstract contract ContextMixin { function msgSender() internal view returns (address payable sender) { if (msg.sender == address(this)) { bytes memory array = msg.data; uint256 index = msg.data.length; assembly { // Load the 32 bytes word from memory with the address on the lower 20 bytes, and mask those. sender := and( mload(add(array, index)), 0xffffffffffffffffffffffffffffffffffffffff ) } } else { sender = payable(msg.sender); } return sender; } } // File: @openzeppelin/contracts/utils/math/SafeMath.sol pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // File: contracts/common/NativeMetaTransaction.sol pragma solidity ^0.8.0; contract NativeMetaTransaction is EIP712Base { using SafeMath for uint256; bytes32 private constant META_TRANSACTION_TYPEHASH = keccak256( bytes( "MetaTransaction(uint256 nonce,address from,bytes functionSignature)" ) ); event MetaTransactionExecuted( address userAddress, address payable relayerAddress, bytes functionSignature ); mapping(address => uint256) nonces; /* * Meta transaction structure. * No point of including value field here as if user is doing value transfer then he has the funds to pay for gas * He should call the desired function directly in that case. */ struct MetaTransaction { uint256 nonce; address from; bytes functionSignature; } function executeMetaTransaction( address userAddress, bytes memory functionSignature, bytes32 sigR, bytes32 sigS, uint8 sigV ) public payable returns (bytes memory) { MetaTransaction memory metaTx = MetaTransaction({ nonce: nonces[userAddress], from: userAddress, functionSignature: functionSignature }); require( verify(userAddress, metaTx, sigR, sigS, sigV), "Signer and signature do not match" ); // increase nonce for user (to avoid re-use) nonces[userAddress] = nonces[userAddress].add(1); emit MetaTransactionExecuted( userAddress, payable(msg.sender), functionSignature ); // Append userAddress and relayer address at the end to extract it from calling context (bool success, bytes memory returnData) = address(this).call( abi.encodePacked(functionSignature, userAddress) ); require(success, "Function call not successful"); return returnData; } function hashMetaTransaction(MetaTransaction memory metaTx) internal pure returns (bytes32) { return keccak256( abi.encode( META_TRANSACTION_TYPEHASH, metaTx.nonce, metaTx.from, keccak256(metaTx.functionSignature) ) ); } function getNonce(address user) public view returns (uint256 nonce) { nonce = nonces[user]; } function verify( address signer, MetaTransaction memory metaTx, bytes32 sigR, bytes32 sigS, uint8 sigV ) internal view returns (bool) { require(signer != address(0), "NativeMetaTransaction: INVALID_SIGNER"); return signer == ecrecover( toTypedMessageHash(hashMetaTransaction(metaTx)), sigV, sigR, sigS ); } } // File: @openzeppelin/contracts/utils/Strings.sol pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File: @openzeppelin/contracts/utils/Context.sol pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: @openzeppelin/contracts/access/Ownable.sol pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // File: @openzeppelin/contracts/utils/introspection/IERC165.sol pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/utils/introspection/ERC165.sol pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: @openzeppelin/contracts/token/ERC721/ERC721.sol pragma solidity ^0.8.0; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // File: @openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol pragma solidity ^0.8.0; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // File: contracts/ERC721Tradable.sol pragma solidity ^0.8.0; contract OwnableDelegateProxy {} contract ProxyRegistry { mapping(address => OwnableDelegateProxy) public proxies; } /** * @title ERC721Tradable * ERC721Tradable - ERC721 contract that whitelists a trading address, and has minting functionality. */ abstract contract ERC721Tradable is ContextMixin, ERC721Enumerable, NativeMetaTransaction, Ownable { using SafeMath for uint256; address proxyRegistryAddress; uint256 private _currentTokenId = 0; constructor( string memory _name, string memory _symbol, address _proxyRegistryAddress ) ERC721(_name, _symbol) { proxyRegistryAddress = _proxyRegistryAddress; _initializeEIP712(_name); } /** * Override isApprovedForAll to whitelist user's OpenSea proxy accounts to enable gas-less listings. */ function isApprovedForAll(address owner, address operator) override public view returns (bool) { // Whitelist OpenSea proxy contract for easy trading. ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress); if (address(proxyRegistry.proxies(owner)) == operator) { return true; } return super.isApprovedForAll(owner, operator); } /** * This is used instead of msg.sender as transactions won't be sent by the original token owner, but by OpenSea. */ function _msgSender() internal override view returns (address sender) { return ContextMixin.msgSender(); } } // File: contracts/BitKoi.sol pragma solidity ^0.8.0; /** * @title BitKoi * BitKoi - a blockchain game at scale */ /// @title mix up two fish and find out which traits they should have abstract contract BitKoiTraitInterface { /// @dev simply a boolean to indicate this is the contract we expect to be function isBitKoiTraits() virtual public pure returns (bool); ///mix up the "genes" of the fish to see which genes our new fish will have function smooshFish(uint256 genes1, uint256 genes2, uint256 targetBlock) virtual public returns (uint256); } /// @title A facet of BitKoiCore that manages special access privileges. /// Based on work from Axiom Zen (https://www.axiomzen.co) contract BitKoiAccessControl { // The addresses of the accounts (or contracts) that can execute actions within each roles. address public ceoAddress; address public cfoAddress; address public cooAddress; // @dev Keeps track whether the contract is paused. bool public paused = false; modifier onlyCEO() { require(msg.sender == ceoAddress); _; } modifier onlyCFO() { require(msg.sender == cfoAddress); _; } modifier onlyCOO() { require(msg.sender == cooAddress); _; } modifier onlyCLevel() { require( msg.sender == cooAddress || msg.sender == ceoAddress || msg.sender == cfoAddress ); _; } /// @dev Assigns a new address to act as the CEO. Only available to the current CEO. /// @param _newCEO The address of the new CEO function setCEO(address _newCEO) external onlyCEO { require(_newCEO != address(0)); ceoAddress = _newCEO; } /// @dev Assigns a new address to act as the CFO. Only available to the current CEO. /// @param _newCFO The address of the new CFO function setCFO(address payable _newCFO) external onlyCEO { require(_newCFO != address(0)); cfoAddress = _newCFO; } /// @dev Assigns a new address to act as the COO. Only available to the current CEO. /// @param _newCOO The address of the new COO function setCOO(address _newCOO) external onlyCEO { require(_newCOO != address(0)); cooAddress = _newCOO; } /*** Pausable functionality adapted from OpenZeppelin ***/ /// @dev Modifier to allow actions only when the contract IS NOT paused modifier whenNotPaused() { require(!paused); _; } /// @dev Modifier to allow actions only when the contract IS paused modifier whenPaused { require(paused); _; } /// @dev Called by any "C-level" role to pause the contract. Used only when /// a bug or exploit is detected and we need to limit damage. function pause() external onlyCLevel whenNotPaused { paused = true; } /// @dev Unpauses the smart contract. Can only be called by the CEO, since /// one reason we may pause the contract is when CFO or COO accounts are /// compromised. /// @notice This is public rather than external so it can be called by /// derived contracts. function unpause() virtual public onlyCEO whenPaused { // can't unpause if contract was upgraded paused = false; } } /// @title Base contract for KoiPond. Holds all common structs, events and base variables. /// based on code written for CK by Axiom Zen (https://www.axiomzen.co) abstract contract BitKoiBase is BitKoiAccessControl, ERC721Tradable { /*** EVENTS ***/ /// @dev The Spawn event is fired whenever a new fish comes into existence. This obviously /// includes any time a fish is created through the spawnFish method, but it is also called /// when a new gen0 fish is created. event Spawn(address owner, uint256 koiFishId, uint256 parent1Id, uint256 parent2Id, uint256 genes, uint16 generation, uint64 timestamp); event BreedingSuccessful(address owner, uint256 newFishId, uint256 parent1Id, uint256 parent2Id, uint64 cooldownEndBlock); /*** DATA TYPES ***/ struct BitKoi { // The fish's genetic code - this will never change for any fish. uint256 genes; // The timestamp from the block when this fish came into existence. uint64 spawnTime; // The minimum timestamp after which this fish can engage in spawning // activities again. uint64 cooldownEndBlock; // The ID of the parents of this fish, set to 0 for gen0 fish. // With uint32 there's a limit of 4 billion fish uint32 parent1Id; uint32 parent2Id; // Set to the index in the cooldown array (see below) that represents // the current cooldown duration for this fish. This starts at zero // for gen0 fish, and is initialized to floor(generation/2) for others. // Incremented by one for each successful breeding action. uint16 cooldownIndex; // The "generation number" of this fish. Fish minted by the KP contract // for sale are called "gen0" and have a generation number of 0. The // generation number of all other fish is the larger of the two generation // numbers of their parents, plus one. uint16 generation; } /*** CONSTANTS ***/ /// @dev A lookup table indicating the cooldown duration after any successful /// breeding action, called "cooldown" Designed such that the cooldown roughly /// doubles each time a fish is bred, encouraging owners not to just keep breeding the same fish over /// and over again. Caps out at one week (a fish can breed an unbounded number /// of times, and the maximum cooldown is always seven days). uint32[14] public cooldowns = [ uint32(1 minutes), uint32(2 minutes), uint32(5 minutes), uint32(10 minutes), uint32(30 minutes), uint32(1 hours), uint32(2 hours), uint32(4 hours), uint32(8 hours), uint32(16 hours), uint32(1 days), uint32(2 days), uint32(4 days), uint32(7 days) ]; // An approximation of currently how many seconds are in between blocks. uint256 public secondsPerBlock = 15; /*** STORAGE ***/ /// @dev An array containing the KoiFish struct for all KoiFish in existence. The ID /// of each fish is actually an index into this array. Fish 0 has an invalid genetic /// code and can't be used to produce offspring. BitKoi[] bitKoi; /// @dev A mapping from fish IDs to the address that owns them. All fish have /// some valid owner address, even gen0 fish are created with a non-zero owner. mapping (uint256 => address) bitKoiIndexToOwner; // @dev A mapping from owner address to count of tokens that address owns. // Used internally inside balanceOf() to resolve ownership count. mapping (address => uint256) ownershipTokenCount; /// @dev A mapping from KoiFishIDs to an address that has been approved to call /// transferFrom(). Each KoiFish can only have one approved address for transfer /// at any time. A zero value means no approval is outstanding. mapping (uint256 => address) bitKoiIndexToApproved; // /// @dev Assigns ownership of a specific KoiFish to an address. function _transfer(address _from, address _to, uint256 _tokenId) override internal { require(ownerOf(_tokenId) == _from, "ERC721: transfer of token that is not own"); require(_to != address(0), "ERC721: transfer to the zero address"); // Since the number of fish is capped to 2^32 we can't overflow this ownershipTokenCount[_to]++; ownershipTokenCount[_from]--; _beforeTokenTransfer(_from, _to, _tokenId); // actually transfer ownership bitKoiIndexToOwner[_tokenId] = _to; // Clear approvals from the previous owner _approve(address(0), _tokenId); emit Transfer(_from, _to, _tokenId); } /// @notice Returns the address currently assigned ownership of a given BitKoi. /// @dev Required for ERC-721 compliance. function ownerOf(uint256 _tokenId) override public view returns (address owner) { owner = bitKoiIndexToOwner[_tokenId]; require(owner != address(0)); } function balanceOf(address owner) public view override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return ownershipTokenCount[owner]; } /// @notice Returns a list of all KoiFish IDs assigned to an address. /// @param _owner The owner whose KoiFish we are interested in. /// @dev This method MUST NEVER be called by smart contract code. First, it's fairly /// expensive (it walks the entire KoiFish array looking for fish belonging to owner), /// but it also returns a dynamic array, which is only supported for web3 calls, and /// not contract-to-contract calls. function tokensOfOwner(address _owner) external view returns(uint256[] memory ownerTokens) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { // Return an empty array return new uint256[](0); } else { uint256[] memory result = new uint256[](tokenCount); uint256 totalBitKoi = totalSupply(); uint256 resultIndex = 0; // We count on the fact that all fish have IDs starting at 1 and increasing // sequentially up to the totalKoi count. uint256 bitKoiId; for (bitKoiId = 1; bitKoiId <= totalBitKoi; bitKoiId++) { if (bitKoiIndexToOwner[bitKoiId] == _owner) { result[resultIndex] = bitKoiId; resultIndex++; } } return result; } } function _mintNewKoi(address _to, uint256 _tokenId) internal { _mint(_to, _tokenId); // Since the number of fish is capped to 2^32 we can't overflow this ownershipTokenCount[_to]++; // transfer ownership bitKoiIndexToOwner[_tokenId] = _to; } // Any C-level can fix how many seconds per blocks are currently observed. function setSecondsPerBlock(uint256 secs) external onlyCLevel { require(secs < cooldowns[0]); secondsPerBlock = secs; } } abstract contract BitKoiOwnership is BitKoiBase { /// @dev Returns true if the claimant owns the token. /// @param _claimant - Address claiming to own the token. /// @param _tokenId - ID of token whose ownership to verify. function _owns( address _claimant, uint256 _tokenId ) internal view returns (bool) { return (ownerOf(_tokenId) == _claimant); } /// @dev Checks if a given address currently has transferApproval for a particular KoiFish. /// @param _claimant the address we are confirming fish is approved for. /// @param _tokenId fish id, only valid when > 0 function _approvedFor( address _claimant, uint256 _tokenId ) internal view returns (bool) { return bitKoiIndexToApproved[_tokenId] == _claimant; } /// @dev Marks an address as being approved for transferFrom(), overwriting any previous /// approval. Setting _approved to address(0) clears all transfer approval. /// NOTE: _approve() does NOT send the Approval event. This is intentional because /// _approve() and transferFrom() are used together for putting KoiFish on sale, and /// there is no value in spamming the log with Approval events in that case. function _approve( uint256 _tokenId, address _approved ) internal { bitKoiIndexToApproved[_tokenId] = _approved; } function transfer( address _to, uint256 _tokenId ) external whenNotPaused { // Safety check to prevent against an unexpected 0x0 default. require(_to != address(0)); // Disallow transfers to this contract to prevent accidental misuse. // The contract should never own any fish (except very briefly // after a gen0 fish is created and before it goes on sale). require(_to != address(this)); // Disallow transfers to the sale contracts to prevent accidental // misuse. Sale contracts should only take ownership of fish // through the allow + transferFrom flow. // You can only send your own fish require(_owns(msg.sender, _tokenId)); // Reassign ownership, clear pending approvals, emit Transfer event. _transfer(msg.sender, _to, _tokenId); } } abstract contract BitKoiBreeding is BitKoiOwnership { event Hatch(address owner, uint256 fishId, uint256 genes); uint256 public breedFee = 0 wei; uint256 public hatchFee = 0 wei; /// @dev The address of the sibling contract that is used to implement the genetic combination algorithm. BitKoiTraitInterface public bitKoiTraits; /// @dev Update the address of the genetic contract, can only be called by the CEO. /// @param _address An address of a GeneScience contract instance to be used from this point forward. function setBitKoiTraitAddress(address _address) external onlyCEO { BitKoiTraitInterface candidateContract = BitKoiTraitInterface(_address); // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117 require(candidateContract.isBitKoiTraits()); // Set the new contract address bitKoiTraits = candidateContract; } /// @dev Checks to see if a given fish is ready to hatch after the gestation period has passed. function _isReadyToHatch(uint256 _fishId) private view returns (bool) { BitKoi storage fishToHatch = bitKoi[_fishId]; return fishToHatch.cooldownEndBlock <= uint64(block.number); } /// @dev Checks that a given fish is able to breed. Requires that the /// current cooldown is finished function _isReadyToBreed(BitKoi storage _fish) internal view returns (bool) { // In addition to checking the cooldownEndBlock, we also need to check to see if // the fish has a pending birth; there can be some period of time between the end // of the pregnacy timer and the spawn event. return _fish.cooldownEndBlock <= uint64(block.number); } /// @dev Set the cooldownEndTime for the given fish based on its current cooldownIndex. /// Also increments the cooldownIndex (unless it has hit the cap). /// @param _koiFish A reference to the KoiFish in storage which needs its timer started. function _triggerCooldown(BitKoi storage _koiFish) internal { // Compute an estimation of the cooldown time in blocks (based on current cooldownIndex). _koiFish.cooldownEndBlock = uint64((cooldowns[_koiFish.cooldownIndex]/secondsPerBlock) + block.number); // Increment the breeding count, clamping it at 13, which is the length of the // cooldowns array. We could check the array size dynamically, but hard-coding // this as a constant saves gas. Yay, Solidity! if (_koiFish.cooldownIndex < 13) { _koiFish.cooldownIndex += 1; } } // @dev Updates the minimum payment required for calling breedWith(). Can only /// be called by the COO address. (This fee is used to offset the gas cost incurred /// by the autobirth daemon). function setBreedFee(uint256 val) external onlyCEO { breedFee = val; } // @dev Updates the minimum payment required for calling hatchFish(). Can only /// be called by the COO address. (This fee is used to offset the gas cost incurred /// by the autobirth daemon). function setHatchFee(uint256 val) external onlyCEO { hatchFee = val; } /// @notice Checks that a given fish is able to hatch (i.e. it is not /// in the middle of a cooldown). /// @param _koiId reference the id of the fish, any user can inquire about it function isReadyToHatch(uint256 _koiId) public view returns (bool) { require(_koiId > 0); return _isReadyToHatch(_koiId); } /// @notice Checks that a given fish is able to breed (i.e. it is not /// in the middle of a cooldown). /// @param _koiId reference the id of the fish, any user can inquire about it function isReadyToBreed(uint256 _koiId) public view returns (bool) { require(_koiId > 0); BitKoi storage fish = bitKoi[_koiId]; return _isReadyToBreed(fish); } /// @dev Internal check to see if a the parents are a valid mating pair. DOES NOT /// check ownership permissions (that is up to the caller). /// @param _parent1 A reference to the Fish struct of the potential first parent /// @param _parent1Id The first parent's ID. /// @param _parent2 A reference to the Fish struct of the potential second parent /// @param _parent2Id The second parent's ID. function _isValidMatingPair( BitKoi storage _parent1, uint256 _parent1Id, BitKoi storage _parent2, uint256 _parent2Id ) private view returns(bool) { // A Fish can't breed with itself! if (_parent1Id == _parent2Id) { return false; } //the fish have to have genes if (_parent1.genes == 0 || _parent2.genes == 0) { return false; } // Fish can't breed with their parents. if (_parent1.parent1Id == _parent2Id || _parent1.parent2Id == _parent2Id) { return false; } if (_parent2.parent1Id == _parent1Id || _parent2.parent2Id == _parent1Id) { return false; } // OK the tx if either fish is gen zero (no parent found). if (_parent2.parent1Id == 0 || _parent1.parent1Id == 0) { return true; } // Fish can't breed with full or half siblings. if (_parent2.parent1Id == _parent1.parent1Id || _parent2.parent1Id == _parent1.parent2Id) { return false; } if (_parent2.parent2Id == _parent1.parent1Id || _parent2.parent2Id == _parent1.parent2Id) { return false; } // gtg return true; } /// @notice Checks to see if two BitKoi can breed together, including checks for /// ownership. Doesn't check that both BitKoi are ready for /// breeding (i.e. breedWith could still fail until the cooldowns are finished). /// @param _parent1Id The ID of the proposed first parent. /// @param _parent2Id The ID of the proposed second parent. function canBreedWith(uint256 _parent1Id, uint256 _parent2Id) external view returns(bool) { require(_parent1Id > 0); require(_parent2Id > 0); BitKoi storage parent1 = bitKoi[_parent1Id]; BitKoi storage parent2 = bitKoi[_parent2Id]; return _isValidMatingPair(parent1, _parent1Id, parent2, _parent2Id); } /// @dev Internal utility function to initiate breeding, assumes that all breeding /// requirements have been checked. function _breedWith(uint256 _parent1Id, uint256 _parent2Id) internal returns(uint256) { // Grab a reference to the Koi from storage. BitKoi storage parent1 = bitKoi[_parent1Id]; BitKoi storage parent2 = bitKoi[_parent2Id]; // Determine the higher generation number of the two parents uint16 parentGen = parent1.generation; if (parent2.generation > parent1.generation) { parentGen = parent2.generation; } uint256 bitKoiCoProceeds = msg.value; //transfer the breed fee less the pond cut to the CFO contract payable(address(cfoAddress)).transfer(bitKoiCoProceeds); // Make the new fish! address owner = bitKoiIndexToOwner[_parent1Id]; uint256 newFishId = _createBitKoi(_parent1Id, _parent2Id, parentGen + 1, 0, owner); // Trigger the cooldown for both parents. _triggerCooldown(parent1); _triggerCooldown(parent2); // Emit the breeding event. emit BreedingSuccessful(bitKoiIndexToOwner[_parent1Id], newFishId, _parent1Id, _parent2Id, parent1.cooldownEndBlock); return newFishId; } function breedWith(uint256 _parent1Id, uint256 _parent2Id) external payable whenNotPaused { // Checks for payment. require(msg.value >= breedFee); ///check to see if the caller owns both fish require(_owns(msg.sender, _parent1Id)); require(_owns(msg.sender, _parent2Id)); // Grab a reference to the first parent BitKoi storage parent1 = bitKoi[_parent1Id]; // Make sure enough time has passed since the last time this fish was bred require(_isReadyToBreed(parent1)); // Grab a reference to the second parent BitKoi storage parent2 = bitKoi[_parent2Id]; // Make sure enough time has passed since the last time this fish was bred require(_isReadyToBreed(parent2)); // Test that these fish are a valid mating pair. require(_isValidMatingPair( parent1, _parent1Id, parent2, _parent2Id )); // All checks passed, make a new fish!! _breedWith(_parent1Id, _parent2Id); } /// @dev An internal method that creates a new fish and stores it. This /// method doesn't do any checking and should only be called when the /// input data is known to be valid. Will generate both a Birth event /// and a Transfer event. /// @param _parent1Id The fish ID of the first parent (zero for gen0) /// @param _parent2Id The fish ID of the second parent (zero for gen0) /// @param _generation The generation number of this fish, must be computed by caller. /// @param _genes The fish's genetic code. /// @param _owner The inital owner of this fish, must be non-zero (except for fish ID 0) function _createBitKoi( uint256 _parent1Id, uint256 _parent2Id, uint256 _generation, uint256 _genes, address _owner ) internal returns (uint) { // These requires are not strictly necessary, our calling code should make // sure that these conditions are never broken. However! _createKoiFish() is already // an expensive call (for storage), and it doesn't hurt to be especially careful // to ensure our data structures are always valid. require(_parent1Id == uint256(uint32(_parent1Id))); require(_parent2Id == uint256(uint32(_parent2Id))); require(_generation == uint256(uint16(_generation))); // New fish starts with the same cooldown as parent gen/2 uint16 cooldownIndex = uint16(_generation / 2); if (cooldownIndex > 13) { cooldownIndex = 13; } BitKoi memory _bitKoi = BitKoi({ genes: _genes, spawnTime: uint64(block.timestamp), cooldownEndBlock: 0, parent1Id: uint32(_parent1Id), parent2Id: uint32(_parent2Id), cooldownIndex: cooldownIndex, generation: uint16(_generation) }); uint256 newBitKoiId = bitKoi.length; bitKoi.push(_bitKoi); // It's probably never going to happen, 4 billion fish is A LOT, but // let's just be 100% sure we never let this happen. require(newBitKoiId == uint256(uint32(newBitKoiId))); // This will assign ownership, and also emit the Transfer event as // per ERC721 draft _mintNewKoi(_owner, newBitKoiId); BitKoi storage brandNewKoi = bitKoi[newBitKoiId]; _triggerCooldown(brandNewKoi); // emit the spawn event emit Spawn( _owner, newBitKoiId, uint256(_bitKoi.parent1Id), uint256(_bitKoi.parent2Id), _bitKoi.genes, uint16(_generation), uint64(block.timestamp) ); return newBitKoiId; } function hatchFish(uint256 _fishId, uint256 _geneSet1, uint256 _geneSet2) external payable whenNotPaused { // Checks for payment. require(msg.value >= hatchFee); //ensure the caller owns the egg they want to hatch require(_owns(msg.sender, _fishId)); _hatchFish(_fishId, _geneSet1, _geneSet2); } function _hatchFish(uint256 _fishId, uint256 _geneSet1, uint256 _geneSet2) internal { BitKoi storage fishToHatch = bitKoi[_fishId]; BitKoi storage parent1 = bitKoi[fishToHatch.parent1Id]; BitKoi storage parent2 = bitKoi[fishToHatch.parent2Id]; uint256 genes1 = 0; uint256 genes2 = 0; if (fishToHatch.parent1Id > 0){ genes1 = parent1.genes; } else { genes1 = _geneSet1; } if (fishToHatch.parent2Id > 0){ genes2 = parent2.genes; } else { genes2 = _geneSet2; } // Check that the parent is a valid fish require(parent1.spawnTime != 0 && parent2.spawnTime != 0); // Make sure this fish doesn't already have genes require(fishToHatch.genes == 0); // next, let's get new genes for the fish we're about to hatch uint256 newFishGenes = bitKoiTraits.smooshFish(genes1, genes2, fishToHatch.cooldownEndBlock - 1); fishToHatch.genes = uint256(newFishGenes); //transfer the hatch fee less the pond cut to the CFO contract payable(address(cfoAddress)).transfer(msg.value); emit Hatch(msg.sender, _fishId, newFishGenes); } } abstract contract BitKoiSale is BitKoiBreeding { struct Sale { // Current owner of NFT address seller; // Price (in wei) at beginning of sale uint128 price; // timestamp uint256 startedAt; } // Cut contract owner takes on each sale, measured in basis points (1/100 of a percent). // Values 0-10,000 map to 0%-100% uint256 public ownerCut = 250; /// @param _ownerCut - update the percent cut the contract owner takes on each breed or hatch event, must be /// between 0-10,000. function setOwnerCut(uint256 _ownerCut) external onlyCLevel { require(_ownerCut <= 10000); ownerCut = _ownerCut; } // Map from token ID to their corresponding sale. mapping (uint256 => Sale) tokenIdToSale; event SaleCreated(address sellerId, uint256 tokenId, uint256 price, uint256 startedAt); event SaleSuccessful(uint256 tokenId, uint256 price, address buyer); event SaleCancelled(uint256 tokenId); /// @dev adds a sale to the list of open sales. Also fires the SaleCreated event. /// @param _tokenId The ID of the token to be put on sale. /// @param _sale Sale to add. function _addSale(address _sellerId, uint256 _tokenId, Sale memory _sale, uint256 _saleStarted) internal { tokenIdToSale[_tokenId] = _sale; emit SaleCreated( address(_sellerId), uint256(_tokenId), uint256(_sale.price), uint256(_saleStarted) ); } /// @dev Cancels a sale unconditionally. function _cancelSale(uint256 _tokenId) internal { _removeSale(_tokenId); emit SaleCancelled(_tokenId); } /// @dev Computes the price and transfers winnings. /// Does NOT transfer ownership of token. function _bid(uint256 _tokenId, uint256 _offerAmount) internal returns (uint256) { // Get a reference to the sale struct Sale storage sale = tokenIdToSale[_tokenId]; // Explicitly check that this sale is currently live. // (Because of how Ethereum mappings work, we can't just count // on the lookup above failing. An invalid _tokenId will just // return an sale object that is all zeros.) require(_isOnSale(sale)); address seller = address(uint160(sale.seller)); uint160 price = sale.price; // Check that the bid is greater than or equal to the current price require(_offerAmount >= price); // The bid is good! Remove the auction before sending the fees // to the sender so we can't have a reentrancy attack. _removeSale(_tokenId); // Transfer proceeds to seller (if there are any!) if (price > 0) { // Calculate the contract's cut. // (NOTE: _computeCut() is guaranteed to return a // value <= price, so this subtraction can't go negative.) uint256 contractCut = _computeCut(price); uint256 sellerProceeds = price - contractCut; // NOTE: Doing a transfer() in the middle of a complex // method like this is generally discouraged because of // reentrancy attacks and DoS attacks if the seller is // a contract with an invalid fallback function. We explicitly // guard against reentrancy attacks by removing the sale // before calling transfer(), and the only thing the seller // can DoS is the sale of their own asset! (And if it's an // accident, they can call cancelSale(). ) payable(cfoAddress).transfer(contractCut); payable(seller).transfer(sellerProceeds); } // Calculate any excess funds included with the bid. If the excess // is anything worth worrying about, transfer it back to bidder. // NOTE: We checked above that the bid amount is greater than or // equal to the price so this cannot underflow. uint256 bidExcess = _offerAmount - price; // Return the funds. Similar to the previous transfer, this is // not susceptible to a re-entry attack because the sale is // removed before any transfers occur. payable(msg.sender).transfer(bidExcess); // Tell the world! emit SaleSuccessful(_tokenId, price, msg.sender); return price; } /// @dev Removes a sale from the list of open sales /// @param _tokenId - ID of NFT on sale. function _removeSale(uint256 _tokenId) internal { delete tokenIdToSale[_tokenId]; } /// @dev Returns true if the NFT is on sale. /// @param _sale - Sale to check. function _isOnSale(Sale storage _sale) internal view returns (bool) { return (_sale.startedAt > 0); } /// @dev Computes owner's cut of a sale. /// @param _price - Sale price of NFT. function _computeCut(uint256 _price) internal view returns (uint256) { // NOTE: We don't use SafeMath (or similar) in this function because // all of our entry functions carefully cap the maximum values for // currency (at 128-bits), and ownerCut <= 10000. The result of this // function is always guaranteed to be <= _price. return _price * ownerCut / 10000; } /// @dev Creates and begins a new sale. /// @param _tokenId - ID of token to sale, sender must be owner. /// @param _price - Price of item (in wei) /// @param _seller - Seller, if not the message sender function createSale( uint256 _tokenId, uint256 _price, address _seller ) external whenNotPaused { // Sanity check that no inputs overflow how many bits we've allocated // to store them in the sale struct. require(_price == uint256(uint128(_price))); require(msg.sender == bitKoiIndexToOwner[_tokenId]); Sale memory sale = Sale( address(_seller), uint128(_price), uint64(block.timestamp) ); _addSale(_seller, _tokenId, sale, block.timestamp); } function bid(uint256 _tokenId) external payable whenNotPaused { // _bid will throw if the bid or funds transfer fails // _bid verifies token ID size address seller = tokenIdToSale[_tokenId].seller; _bid(_tokenId, msg.value); _transfer(seller, msg.sender, _tokenId); } /// @dev Cancels a sale that hasn't been completed. /// Returns the NFT to original owner. /// @notice This is a state-modifying function that can /// be called while the contract is paused. /// @param _tokenId - ID of token on sale function cancelSale(uint256 _tokenId) external { Sale storage sale = tokenIdToSale[_tokenId]; require(_isOnSale(sale)); address seller = sale.seller; require(msg.sender == seller); _cancelSale(_tokenId); } /// @dev Cancels a sale when the contract is paused. /// Only the owner may do this, and NFTs are returned to /// the seller. This should only be used in emergencies. /// @param _tokenId - ID of the NFT on sale to cancel. function cancelSaleWhenPaused(uint256 _tokenId) whenPaused onlyOwner external { Sale storage sale = tokenIdToSale[_tokenId]; require(_isOnSale(sale)); _cancelSale(_tokenId); } /// @dev Returns sale info for an NFT on sale. /// @param _tokenId - ID of NFT on sale. function getSale(uint256 _tokenId) external view returns ( address seller, uint256 price, uint256 startedAt ) { Sale storage sale = tokenIdToSale[_tokenId]; require(_isOnSale(sale)); return ( sale.seller, sale.price, sale.startedAt ); } /// @dev Returns the current price of a sale. /// @param _tokenId - ID of the token price we are checking. function getCurrentPrice(uint256 _tokenId) external view returns (uint256) { Sale storage sale = tokenIdToSale[_tokenId]; require(_isOnSale(sale)); return sale.price; } } /// @title all functions related to creating fish (and their eggs) abstract contract BitKoiMinting is BitKoiSale { // Limits the number of fish the contract owner can ever create. uint256 public constant PROMO_CREATION_LIMIT = 5000; uint256 public constant GEN0_EGG_CREATION_LIMIT = 45000; // Counts the number of fish the contract owner has created. uint256 public promoCreatedCount; uint256 public gen0CreatedCount; // Direct sale is not live to start bool public directSalePaused = true; //determine the price for minting a new BitKoi gen0 egg uint256 public gen0PromoPrice = 0 wei; //number we're currently allowing to be minted uint256 public currentGen0Cap = 100; uint16 public currentMintCap = 2; mapping (address => uint16) tokensMinted; // allow direct sales of gen0 eggs function pauseDirectSale() external onlyCLevel { directSalePaused = true; } // stop direct sales of gen0 eggs function unpauseDirectSale() external onlyCLevel { directSalePaused = false; } // set current cap for sale - this can be raised later so new sales can be started w/ limits function setCurrentGen0Cap(uint256 val) external onlyCEO { currentGen0Cap = val; } // @dev Updates the minimum payment required for calling mintGen0Egg(). Can only /// be called by the CEO address. function setGen0PromoPrice(uint256 val) external onlyCEO { gen0PromoPrice = val; } // @dev Updates the max number of items an address can mint in the given period. Can only /// be called by the CEO address. function setMintCap(uint16 val) external onlyCEO { currentMintCap = val; } function mintGen0Egg() external payable { require (!directSalePaused); require (msg.value >= gen0PromoPrice); require (gen0CreatedCount < currentGen0Cap); require (gen0CreatedCount < GEN0_EGG_CREATION_LIMIT); require (tokensMinted[msg.sender] < currentMintCap); //transfer the sale price less the pond cut to the CFO contract payable(address(cfoAddress)).transfer(msg.value); gen0CreatedCount++; tokensMinted[msg.sender]++; _createBitKoi(0, 0, 0, 0, msg.sender); } /// @dev we can create promo fish, up to a limit. Only callable by COO /// @param _genes the encoded genes of the fish to be created, any value is accepted /// @param _owner the future owner of the created fish. Default to contract COO function createPromoFish(uint256 _genes, address _owner) external onlyCOO { address bitKoiOwner = _owner; if (bitKoiOwner == address(0)) { bitKoiOwner = cooAddress; } require(promoCreatedCount < PROMO_CREATION_LIMIT); promoCreatedCount++; _createBitKoi(0, 0, 0, _genes, bitKoiOwner); } } contract BitKoiCore is BitKoiMinting { constructor(address _proxyRegistryAddress) ERC721Tradable("BitKoi", "BITKOI", _proxyRegistryAddress) { // Starts paused. paused = true; // the creator of the contract is the initial CEO ceoAddress = msg.sender; // the creator of the contract is also the initial COO cooAddress = msg.sender; // the creator of the contract is also the initial COO cfoAddress = msg.sender; //start with an initial fish _createBitKoi(0, 0, 0, type(uint256).max, address(msg.sender)); } string baseURI = "https://www.bitkoi.co/api/nft/"; string contractMainURI = "https://www.bitkoi.co"; function baseTokenURI() public view returns (string memory) { return baseURI; } function setBaseTokenURI(string memory _newBaseURI) public onlyCEO { baseURI = _newBaseURI; } function setContractURI(string memory _newContractURI) public onlyCEO { contractMainURI = _newContractURI; } function tokenURI(uint256 _tokenId) override public view returns (string memory) { return string(abi.encodePacked(baseTokenURI(), Strings.toString(_tokenId))); } function contractURI() public view returns (string memory) { return contractMainURI; } function unpause() override public onlyCEO whenPaused { require(address(bitKoiTraits) != address(0)); // Actually unpause the contract. super.unpause(); } function withdrawBalance() external onlyCFO { payable(cfoAddress).transfer(address(this).balance); } /// @notice Returns all the relevant information about a specific fish. /// @param _id The ID of the fish we're looking up function getBitKoi(uint256 _id) external view returns ( bool isReady, uint256 cooldownIndex, uint256 nextActionAt, uint256 spawnTime, uint256 parent1Id, uint256 parent2Id, uint256 generation, uint256 cooldownEndBlock, uint256 genes ) { BitKoi storage fish = bitKoi[_id]; isReady = (fish.cooldownEndBlock <= block.number); cooldownIndex = uint256(fish.cooldownIndex); nextActionAt = uint256(fish.cooldownEndBlock); spawnTime = uint256(fish.spawnTime); parent1Id = uint256(fish.parent1Id); parent2Id = uint256(fish.parent2Id); generation = uint256(fish.generation); cooldownEndBlock = uint256(fish.cooldownEndBlock); genes = fish.genes; } }
@dev adds a sale to the list of open sales. Also fires the SaleCreated event. @param _tokenId The ID of the token to be put on sale. @param _sale Sale to add.
function _addSale(address _sellerId, uint256 _tokenId, Sale memory _sale, uint256 _saleStarted) internal { tokenIdToSale[_tokenId] = _sale; emit SaleCreated( address(_sellerId), uint256(_tokenId), uint256(_sale.price), uint256(_saleStarted) ); }
6,768,920
[ 1, 25428, 279, 272, 5349, 358, 326, 666, 434, 1696, 272, 5408, 18, 8080, 29564, 326, 348, 5349, 6119, 871, 18, 225, 389, 2316, 548, 1021, 1599, 434, 326, 1147, 358, 506, 1378, 603, 272, 5349, 18, 225, 389, 87, 5349, 348, 5349, 358, 527, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 3639, 445, 389, 1289, 30746, 12, 2867, 389, 1786, 749, 548, 16, 2254, 5034, 389, 2316, 548, 16, 348, 5349, 3778, 389, 87, 5349, 16, 2254, 5034, 389, 87, 5349, 9217, 13, 2713, 288, 203, 5411, 1147, 28803, 30746, 63, 67, 2316, 548, 65, 273, 389, 87, 5349, 31, 203, 203, 5411, 3626, 348, 5349, 6119, 12, 203, 7734, 1758, 24899, 1786, 749, 548, 3631, 203, 7734, 2254, 5034, 24899, 2316, 548, 3631, 203, 7734, 2254, 5034, 24899, 87, 5349, 18, 8694, 3631, 203, 7734, 2254, 5034, 24899, 87, 5349, 9217, 13, 203, 5411, 11272, 203, 3639, 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 ]
./full_match/43113/0xBf8D6bf3Bb1E16416CbB9B577dcF4A96073E13B0/sources/_contracts/rain-protocol/contracts/redeemableERC20/RedeemableERC20.sol
Admin can add up to 8 redeemables to this contract. Each redeemable will be sent to token holders when they call redeem functions in `Phase.ONE` to burn tokens. If the admin adds a non-compliant or malicious IERC20 address then token holders can override the list with `redeemSpecific`. @param newRedeemable_ The redeemable contract address to add. Somewhat arbitrary but we limit the length of redeemables to 8. 8 is actually a lot. Consider that every `redeem` call must loop a `balanceOf` and `safeTransfer` per redeemable.
function addRedeemable(IERC20 newRedeemable_) external { require( hasRole(REDEEMABLE_ADDER, msg.sender), "ONLY_REDEEMABLE_ADDER" ); require(redeemables.length<MAX_REDEEMABLES, "MAX_REDEEMABLES"); for (uint256 i_ = 0; i_<redeemables.length;i_++) { require(redeemables[i_] != newRedeemable_, "DUPLICATE_REDEEMABLE"); } redeemables.push(newRedeemable_); }
7,166,334
[ 1, 4446, 848, 527, 731, 358, 1725, 283, 24903, 1538, 358, 333, 6835, 18, 8315, 283, 24903, 429, 903, 506, 3271, 358, 1147, 366, 4665, 1347, 2898, 745, 283, 24903, 4186, 316, 1375, 11406, 18, 5998, 68, 358, 18305, 2430, 18, 971, 326, 3981, 4831, 279, 1661, 17, 832, 18515, 578, 27431, 28728, 467, 654, 39, 3462, 1758, 1508, 1147, 366, 4665, 848, 3849, 326, 666, 598, 1375, 266, 24903, 9969, 8338, 225, 394, 426, 24903, 429, 67, 1021, 283, 24903, 429, 6835, 1758, 358, 527, 18, 348, 362, 359, 11304, 11078, 1496, 732, 1800, 326, 769, 434, 283, 24903, 1538, 358, 1725, 18, 1725, 353, 6013, 279, 17417, 18, 23047, 716, 3614, 1375, 266, 24903, 68, 745, 1297, 2798, 279, 1375, 12296, 951, 68, 471, 1375, 4626, 5912, 68, 1534, 283, 24903, 429, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 527, 426, 24903, 429, 12, 45, 654, 39, 3462, 394, 426, 24903, 429, 67, 13, 3903, 288, 203, 3639, 2583, 12, 203, 5411, 28335, 12, 862, 1639, 3375, 2782, 67, 1880, 4179, 16, 1234, 18, 15330, 3631, 203, 5411, 315, 10857, 67, 862, 1639, 3375, 2782, 67, 1880, 4179, 6, 203, 3639, 11272, 203, 3639, 2583, 12, 266, 24903, 1538, 18, 2469, 32, 6694, 67, 862, 1639, 3375, 2782, 55, 16, 315, 6694, 67, 862, 1639, 3375, 2782, 55, 8863, 203, 3639, 364, 261, 11890, 5034, 277, 67, 273, 374, 31, 277, 67, 32, 266, 24903, 1538, 18, 2469, 31, 77, 67, 27245, 288, 203, 5411, 2583, 12, 266, 24903, 1538, 63, 77, 67, 65, 480, 394, 426, 24903, 429, 67, 16, 315, 30387, 26042, 67, 862, 1639, 3375, 2782, 8863, 203, 3639, 289, 203, 3639, 283, 24903, 1538, 18, 6206, 12, 2704, 426, 24903, 429, 67, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/43113/0xf7eEF3926FDDE09cD2b4954e5498C68220315560/sources/contracts/WOOFI.sol
todo for burn? make burn contract
uint256 toD = newBalance.sub(toH);
7,166,878
[ 1, 9012, 364, 18305, 35, 1221, 18305, 6835, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 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, 7734, 2254, 5034, 358, 40, 273, 394, 13937, 18, 1717, 12, 869, 44, 1769, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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.8; import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol"; contract FlightSuretyData { 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 uint airLineCount = 1; uint flightCount = 1; uint insuranceCount = 1; uint constant flightStatusDefault = 0; uint constant airlineApprovesMin = 4; struct Airline { uint id; bool feePaid; bool accepted; uint[] votes; } struct Flight { uint id; bytes32 key; address airline; string flightCode; uint departureTime; uint status; uint updatedTime; } enum InsuranceState {Valid, Expired, Refunded} struct Insurance{ uint id; bytes32 flightId; uint amountPaid; address passenger; InsuranceState state; } mapping(address => Airline) airlines; mapping(bytes32 => Flight) flights; mapping(uint => Insurance) insurances; mapping(address => uint[]) airlinesFlights; mapping(bytes32 => uint[]) flightsInsurances; mapping(address => uint[]) passengersInsurances; mapping(address => uint) authorizedCallers; mapping(address => uint) passengersFund; /********************************************************************************************/ /* EVENT DEFINITIONS */ /********************************************************************************************/ event AirlineAdded(uint id, address airline); event AirlineVote(address candidate, address voter); event AirlinePaidFund(address airline, uint amount); event FlightAdded(uint id, address airline, string flightCode); event FlightCodeChanged(bytes32 key, uint status); event FlightStatusUpdated(bytes32 key, uint status, uint time); event InsuranceAdded(uint id, bytes32 flightId); event InsuranceRefunded(uint id); /** * @dev Constructor * The deploying account becomes contractOwner */ constructor() public { contractOwner = msg.sender; authorizedCallers[msg.sender] = 1; _registerAirline(msg.sender, msg.sender); airlines[msg.sender].feePaid = true; } /********************************************************************************************/ /* 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"); _; } modifier requireBeAnAirline(address airline) { require(airlines[airline].id != 0, "You must be an airline"); _; } modifier requireAcceptedAirline(address airline) { require(airlines[airline].accepted, "To vote you must be accepted first"); _; } modifier requirePaidAirline(address airline) { require(airlines[airline].feePaid, "To participate you must pay"); _; } modifier requireAirlineOperable(address airline) { require(airlines[airline].feePaid && airlines[airline].accepted, "Airline isn't operable"); _; } modifier requireAuthorized() { require(authorizedCallers[msg.sender] == 1, "You don't have authorization"); _; } modifier didntVote(address candidate) { uint[] memory votes = airlines[candidate].votes; uint idApprover = airlines[msg.sender].id; bool found = false; for (uint i = 0; i < votes.length; i++) { if(votes[i] == idApprover){ found = true; break; } } require (!found, "You already vote for this new Airline"); _; } modifier requireNotRegistered(string memory flightCode, uint departureTimestamp, address airlineAddress) { bytes32 key = getFlightKey(airlineAddress, flightCode, departureTimestamp); require(flights[key].id == 0, "The flight has already been created!"); _; } modifier requireFlight(bytes32 key) { require(flights[key].id > 0, "Flight must exist"); _; } modifier requireInsurance(uint id) { require(insurances[id].id > 0, "Insurance doesn't exists"); _; } modifier insuranceWithState(uint id, InsuranceState state) { require(insurances[id].state == state, "Insurance isn't on this state"); _; } modifier isPassengerInsurance(uint id) { require(insurances[id].passenger == msg.sender, "You are not the insurance 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; } function isAirlineRegistered(address airline) public view returns (bool) { return airlines[airline].id > 0; } function isAirlineAccepted(address airline) public view returns (bool) { return airlines[airline].accepted; } function isAirlineFunded(address airline) public view returns (bool) { return airlines[airline].feePaid; } function isFlightRegistered(address airline, string memory flightCode, uint departureTime) public view returns (bool) { bytes32 key = getFlightKey(airline, flightCode, departureTime); return flights[key].id > 0; } function isPassengerInsured(address passenger, address airline, string memory flightCode, uint departureTime) public view returns (bool) { bool insured = false; bytes32 key = getFlightKey(airline, flightCode, departureTime); uint [] memory passengerInsurances = passengersInsurances[passenger]; for (uint i = 0; i < passengerInsurances.length; i++) { if (insurances[passengerInsurances[i]].flightId == key) { insured = true; break; } } return insured; } function getOwner() external view requireContractOwner returns(address owner) { return contractOwner; } /** * @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; } /********************************************************************************************/ /* SMART CONTRACT FUNCTIONS */ /********************************************************************************************/ /** * @dev Add an airline to the registration queue * Can only be called from FlightSuretyApp contract * */ function registerAirline(address airline, address elector) external requireIsOperational requireAuthorized requireBeAnAirline(elector) requireAcceptedAirline(elector) requirePaidAirline(elector){ _registerAirline(airline, elector); } function _registerAirline(address airline, address elector) internal { airlines[airline].id = airLineCount; airlines[airline].feePaid = false; airlines[airline].accepted = airLineCount <= airlineApprovesMin; airlines[airline].votes.push(airlines[elector].id); airLineCount++; emit AirlineAdded(airlines[airline].id, airline); } function registerFlight(address airline, string calldata flightCode, uint departureTime) external requireIsOperational requireAuthorized requireAirlineOperable(airline) { bytes32 key = getFlightKey(airline, flightCode, departureTime); require(flights[key].id == 0, "must be a new Flight"); Flight memory newFlight = Flight(flightCount, key, airline, flightCode, departureTime, flightStatusDefault, departureTime); flights[key] = newFlight; flightCount++; airlinesFlights[airline].push(newFlight.id); emit FlightAdded(newFlight.id, newFlight.airline, newFlight.flightCode); } function setFlightCode(bytes32 key, uint status, uint updateTime) external requireIsOperational requireAuthorized requireFlight(key) { flights[key].status = status; flights[key].updatedTime = updateTime; emit FlightCodeChanged(key, status); } function getFlight(string calldata _flightCode, uint departureTime, address airline) external view requireIsOperational requireAuthorized returns (bytes32 key, address airlineAddress, string memory flightCode, uint departureStatusCode, uint departureTimestamp, uint updatedTimestamp){ bytes32 _key = getFlightKey(airline, _flightCode, departureTime); Flight memory flight = flights[_key]; return (flight.key, flight.airline, flight.flightCode, flight.status, flight.departureTime, flight.updatedTime); } function getFlight(bytes32 _key) external view requireIsOperational requireAuthorized returns (bytes32 key, address airlineAddress, string memory flightCode, uint departureStatusCode, uint departureTimestamp, uint updatedTimestamp){ Flight memory flight = flights[_key]; return (flight.key, flight.airline, flight.flightCode, flight.status, flight.departureTime, flight.updatedTime); } function setFlightDepartureStatus(bytes32 key, uint departureStatus, uint updateTime) external requireIsOperational requireAuthorized requireFlight(key) { flights[key].status = departureStatus; flights[key].updatedTime = updateTime; emit FlightStatusUpdated(key, departureStatus, updateTime); } function buyInsurance(bytes32 flightId, address passenger) external payable requireIsOperational requireAuthorized requireFlight(flightId) { Insurance memory insurance = Insurance(insuranceCount, flightId, msg.value, passenger, InsuranceState.Valid); insurances[insuranceCount] = insurance; passengersInsurances[passenger].push(insurance.id); flightsInsurances[flightId].push(insurance.id); insuranceCount++; emit InsuranceAdded(insurance.id, insurance.flightId); } function getInsurance(uint id) external view requireIsOperational requireAuthorized returns (address passenger, uint amountPaid, uint insuranceState) { Insurance memory insurance = insurances[id]; return (insurance.passenger, insurance.amountPaid, uint(insurance.state)); } function getInsurancesFromFlight(bytes32 flightId) external view requireIsOperational requireAuthorized returns (uint[] memory _insurances) { return flightsInsurances[flightId]; } /** * @dev Credits payouts to insurees */ function creditInsurees(uint id, uint multiplier) external requireIsOperational requireAuthorized insuranceWithState(id, InsuranceState.Valid) { Insurance memory insurance = insurances[id]; insurances[id].state = InsuranceState.Refunded; uint amountPaid = insurance.amountPaid; passengersFund[insurance.passenger] = passengersFund[insurance.passenger].add(multiplier.mul(amountPaid)); emit InsuranceRefunded(id); } /** * @dev Transfers eligible payout funds to insuree * */ function pay(address payable passenger) external payable requireIsOperational requireAuthorized { require(passengersFund[passenger] > 0, "Passenger doesn't have funds"); uint toRefund = passengersFund[passenger]; passengersFund[passenger] = passengersFund[passenger].sub(toRefund); passenger.transfer(toRefund); } /** * @dev Initial funding for the insurance. Unless there are too many delayed flights * resulting in insurance payouts, the contract should be self-sustaining * */ function fund(address airline) public payable requireIsOperational requireAuthorized requireBeAnAirline(airline) { require(msg.value >= 10 ether, "You didn't pay enough"); airlines[airline].feePaid = true; emit AirlinePaidFund(airline, msg.value); } function getFlightKey(address airline, string memory flight, uint256 timestamp) pure internal returns (bytes32){ return keccak256(abi.encodePacked(airline, flight, timestamp)); } function voteAirline(address airline, address elector, uint minimum) public requireIsOperational requireAuthorized requireBeAnAirline(elector) requireAcceptedAirline(elector) requirePaidAirline(elector) didntVote(elector) { airlines[airline].votes.push(airlines[elector].id); airlines[airline].accepted = airlines[airline].votes.length > minimum; emit AirlineVote(airline, elector); } function authorizeContract(address addressToAuth) external requireIsOperational requireContractOwner { authorizedCallers[addressToAuth] = 1; } function deauthorizeContract(address dataContract) external requireIsOperational requireContractOwner { delete authorizedCallers[dataContract]; } /** * @dev Fallback function for funding smart contract. * */ function() external payable { fund(msg.sender); } }
* @dev Add an airline to the registration queue Can only be called from FlightSuretyApp contract/
function registerAirline(address airline, address elector) external requireIsOperational requireAuthorized requireBeAnAirline(elector) requireAcceptedAirline(elector) requirePaidAirline(elector){ _registerAirline(airline, elector); }
15,788,530
[ 1, 986, 392, 23350, 1369, 358, 326, 7914, 2389, 1377, 4480, 1338, 506, 2566, 628, 3857, 750, 55, 594, 4098, 3371, 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 ]
[ 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, 1744, 29752, 1369, 12, 2867, 23350, 1369, 16, 1758, 415, 1229, 13, 3903, 2583, 2520, 2988, 287, 2583, 15341, 2583, 1919, 979, 29752, 1369, 12, 292, 1229, 13, 2583, 18047, 29752, 1369, 12, 292, 1229, 13, 2583, 16507, 350, 29752, 1369, 12, 292, 1229, 15329, 203, 3639, 389, 4861, 29752, 1369, 12, 1826, 1369, 16, 415, 1229, 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 ]
//Address: 0xc5bbae50781be1669306b9e001eff57a2957b09d //Contract name: Gifto //Balance: 0 Ether //Verification Date: 12/14/2017 //Transacion Count: 188860 // CODE STARTS HERE pragma solidity ^0.4.18; // ---------------------------------------------------------------------------------------------- // Gifto Token by Gifto Limited. // An ERC20 standard // // author: Gifto Team // Contact: [email protected] contract ERC20Interface { // Get the total token supply function totalSupply() public constant returns (uint256 _totalSupply); // Get the account balance of another account with address _owner function balanceOf(address _owner) public constant returns (uint256 balance); // Send _value amount of tokens to address _to function transfer(address _to, uint256 _value) public returns (bool success); // transfer _value amount of token approved by address _from function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); // approve an address with _value amount of tokens function approve(address _spender, uint256 _value) public returns (bool success); // get remaining token approved by _owner to _spender function allowance(address _owner, address _spender) public constant returns (uint256 remaining); // Triggered when tokens are transferred. event Transfer(address indexed _from, address indexed _to, uint256 _value); // Triggered whenever approve(address _spender, uint256 _value) is called. event Approval(address indexed _owner, address indexed _spender, uint256 _value); } contract Gifto is ERC20Interface { uint256 public constant decimals = 5; string public constant symbol = "GTO"; string public constant name = "Gifto"; bool public _selling = true;//initial selling uint256 public _totalSupply = 10 ** 14; // total supply is 10^14 unit, equivalent to 10^9 Gifto uint256 public _originalBuyPrice = 43 * 10**7; // original buy 1ETH = 4300 Gifto = 43 * 10**7 unit // Owner of this contract address public owner; // Balances Gifto for each account mapping(address => uint256) private balances; // Owner of account approves the transfer of an amount to another account mapping(address => mapping (address => uint256)) private allowed; // List of approved investors mapping(address => bool) private approvedInvestorList; // deposit mapping(address => uint256) private deposit; // icoPercent uint256 public _icoPercent = 10; // _icoSupply is the avalable unit. Initially, it is _totalSupply uint256 public _icoSupply = _totalSupply * _icoPercent / 100; // minimum buy 0.3 ETH uint256 public _minimumBuy = 3 * 10 ** 17; // maximum buy 25 ETH uint256 public _maximumBuy = 25 * 10 ** 18; // totalTokenSold uint256 public totalTokenSold = 0; // tradable bool public tradable = false; /** * Functions with this modifier can only be executed by the owner */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * Functions with this modifier check on sale status * Only allow sale if _selling is on */ modifier onSale() { require(_selling); _; } /** * Functions with this modifier check the validity of address is investor */ modifier validInvestor() { require(approvedInvestorList[msg.sender]); _; } /** * Functions with this modifier check the validity of msg value * value must greater than equal minimumBuyPrice * total deposit must less than equal maximumBuyPrice */ modifier validValue(){ // require value >= _minimumBuy AND total deposit of msg.sender <= maximumBuyPrice require ( (msg.value >= _minimumBuy) && ( (deposit[msg.sender] + msg.value) <= _maximumBuy) ); _; } /** * */ modifier isTradable(){ require(tradable == true || msg.sender == owner); _; } /// @dev Fallback function allows to buy ether. function() public payable { buyGifto(); } /// @dev buy function allows to buy ether. for using optional data function buyGifto() public payable onSale validValue validInvestor { uint256 requestedUnits = (msg.value * _originalBuyPrice) / 10**18; require(balances[owner] >= requestedUnits); // prepare transfer data balances[owner] -= requestedUnits; balances[msg.sender] += requestedUnits; // increase total deposit amount deposit[msg.sender] += msg.value; // check total and auto turnOffSale totalTokenSold += requestedUnits; if (totalTokenSold >= _icoSupply){ _selling = false; } // submit transfer Transfer(owner, msg.sender, requestedUnits); owner.transfer(msg.value); } /// @dev Constructor function Gifto() public { owner = msg.sender; setBuyPrice(_originalBuyPrice); balances[owner] = _totalSupply; Transfer(0x0, owner, _totalSupply); } /// @dev Gets totalSupply /// @return Total supply function totalSupply() public constant returns (uint256) { return _totalSupply; } /// @dev Enables sale function turnOnSale() onlyOwner public { _selling = true; } /// @dev Disables sale function turnOffSale() onlyOwner public { _selling = false; } function turnOnTradable() public onlyOwner{ tradable = true; } /// @dev set new icoPercent /// @param newIcoPercent new value of icoPercent function setIcoPercent(uint256 newIcoPercent) public onlyOwner { _icoPercent = newIcoPercent; _icoSupply = _totalSupply * _icoPercent / 100; } /// @dev set new _maximumBuy /// @param newMaximumBuy new value of _maximumBuy function setMaximumBuy(uint256 newMaximumBuy) public onlyOwner { _maximumBuy = newMaximumBuy; } /// @dev Updates buy price (owner ONLY) /// @param newBuyPrice New buy price (in unit) function setBuyPrice(uint256 newBuyPrice) onlyOwner public { require(newBuyPrice>0); _originalBuyPrice = newBuyPrice; // 3000 Gifto = 3000 00000 unit // control _maximumBuy_USD = 10,000 USD, Gifto price is 0.1USD // maximumBuy_Gifto = 100,000 Gifto = 100,000,00000 unit // 3000 Gifto = 1ETH => maximumETH = 100,000,00000 / _originalBuyPrice // 100,000,00000/3000 0000 ~ 33ETH => change to wei _maximumBuy = 10**18 * 10000000000 /_originalBuyPrice; } /// @dev Gets account's balance /// @param _addr Address of the account /// @return Account balance function balanceOf(address _addr) public constant returns (uint256) { return balances[_addr]; } /// @dev check address is approved investor /// @param _addr address function isApprovedInvestor(address _addr) public constant returns (bool) { return approvedInvestorList[_addr]; } /// @dev get ETH deposit /// @param _addr address get deposit /// @return amount deposit of an buyer function getDeposit(address _addr) public constant returns(uint256){ return deposit[_addr]; } /// @dev Adds list of new investors to the investors list and approve all /// @param newInvestorList Array of new investors addresses to be added function addInvestorList(address[] newInvestorList) onlyOwner public { for (uint256 i = 0; i < newInvestorList.length; i++){ approvedInvestorList[newInvestorList[i]] = true; } } /// @dev Removes list of investors from list /// @param investorList Array of addresses of investors to be removed function removeInvestorList(address[] investorList) onlyOwner public { for (uint256 i = 0; i < investorList.length; i++){ approvedInvestorList[investorList[i]] = false; } } /// @dev Transfers the balance from msg.sender to an account /// @param _to Recipient address /// @param _amount Transfered amount in unit /// @return Transfer status function transfer(address _to, uint256 _amount) public isTradable returns (bool) { // if sender's balance has enough unit and amount >= 0, // and the sum is not overflow, // then do transfer if ( (balances[msg.sender] >= _amount) && (_amount >= 0) && (balances[_to] + _amount > balances[_to]) ) { balances[msg.sender] -= _amount; balances[_to] += _amount; Transfer(msg.sender, _to, _amount); return true; } else { return false; } } // Send _value amount of tokens from address _from to address _to // The transferFrom method is used for a withdraw workflow, allowing contracts to send // tokens on your behalf, for example to "deposit" to a contract address and/or to charge // fees in sub-currencies; the command should fail unless the _from account has // deliberately authorized the sender of the message via some mechanism; we propose // these standardized APIs for approval: function transferFrom( address _from, address _to, uint256 _amount ) public isTradable returns (bool success) { if (balances[_from] >= _amount && allowed[_from][msg.sender] >= _amount && _amount > 0 && balances[_to] + _amount > balances[_to]) { balances[_from] -= _amount; allowed[_from][msg.sender] -= _amount; balances[_to] += _amount; Transfer(_from, _to, _amount); return true; } else { return false; } } // Allow _spender to withdraw from your account, multiple times, up to the _value amount. // If this function is called again it overwrites the current allowance with _value. function approve(address _spender, uint256 _amount) public isTradable returns (bool success) { allowed[msg.sender][_spender] = _amount; Approval(msg.sender, _spender, _amount); return true; } // get allowance function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } /// @dev Withdraws Ether in contract (Owner only) /// @return Status of withdrawal function withdraw() onlyOwner public returns (bool) { return owner.send(this.balance); } }
@dev Withdraws Ether in contract (Owner only) @return Status of withdrawal
function withdraw() onlyOwner public returns (bool) { return owner.send(this.balance); }
1,826,961
[ 1, 1190, 9446, 87, 512, 1136, 316, 6835, 261, 5541, 1338, 13, 327, 2685, 434, 598, 9446, 287, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 598, 9446, 1435, 1338, 5541, 7010, 3639, 1071, 7010, 3639, 1135, 261, 6430, 13, 288, 203, 3639, 327, 3410, 18, 4661, 12, 2211, 18, 12296, 1769, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/80001/0xC62B223D22b10D45A03Ad8993D7FC6Ec14786bE5/sources/interfaces/v1/ISwylClub.sol
========== Struct(s) ==========
interface ISwylClub { @dev: Logan (Nam) Nguyen pragma solidity ^0.8.11; struct Club { uint256 clubId; address clubOwner; uint256 date; address currency; uint256 totalMembers; uint256 totalActiveMembers; } struct Tier { uint256 tierId; uint256 tierFee; uint256 totalMembers; uint256 totalActiveMembers; uint256 sizeLimit; string tierData; } struct AddTierParam { uint256 clubId; uint256 tierFee; uint256 sizeLimit; string tierData; } struct UpdateTierParam { uint256 clubId; uint256 tierId; uint256 tierFee; uint256 sizeLimit; string tierData; } struct SubscribeParam { uint256 clubId; address clubOwner; uint256 tierId; uint256 tierFee; address currency; } struct Subscription { uint256 subscriptionId; uint256 clubId; uint256 tierId; address subscriber; uint256 dateStart; uint256 nextPayment; uint256 royaltyStars; bool activeMember; } struct MonthlyTierFeeParam { uint256 clubId; address clubOwner; uint256 tierId; uint256 tierFee; address currency; uint256 subscriptionId; } event ClubCreated(address indexed clubOwner, Club club); event TierAdded(uint256 indexed tierId, address indexed clubOnwer, Tier newTier); event TierUpdated(uint256 indexed tierId, address indexed clubOwner, Tier updatedTier); event TierDeleted(uint256 indexed tierId, address indexed clubOwner, Tier[] tiers); event NewSubscription(uint256 indexed subscriptionId, uint256 indexed tierId, address subscriber, Subscription subscription); event ReSubscription(uint256 indexed subscriptionId, uint256 indexed tierId, address subscriber, Subscription subscription); event SubscriptionCancel(uint256 indexed subscriptionId, uint256 indexed tierId, address subscriber, Subscription[] subscriptions); event MonthlyTierFee(uint256 indexed subscriptionId, uint256 indexed tierId, address subscriber, Subscription subscriptions); event DeactivateMembersInTier(uint256 indexed clubId, uint256 indexed tierId, uint256 totalDeactivatedMembers); }
9,443,931
[ 1, 1432, 631, 225, 7362, 12, 87, 13, 565, 422, 1432, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5831, 4437, 91, 93, 80, 2009, 373, 288, 203, 203, 203, 565, 632, 5206, 30, 1827, 304, 261, 50, 301, 13, 423, 6891, 24515, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 2499, 31, 203, 565, 1958, 3905, 373, 288, 203, 3639, 2254, 5034, 927, 373, 548, 31, 203, 3639, 1758, 927, 373, 5541, 31, 203, 3639, 2254, 5034, 1509, 31, 203, 3639, 1758, 5462, 31, 203, 3639, 2254, 5034, 2078, 6918, 31, 203, 3639, 2254, 5034, 2078, 3896, 6918, 31, 203, 565, 289, 203, 203, 565, 1958, 399, 2453, 288, 203, 3639, 2254, 5034, 17742, 548, 31, 203, 3639, 2254, 5034, 17742, 14667, 31, 203, 3639, 2254, 5034, 2078, 6918, 31, 203, 3639, 2254, 5034, 2078, 3896, 6918, 31, 203, 3639, 2254, 5034, 963, 3039, 31, 203, 3639, 533, 17742, 751, 31, 203, 565, 289, 203, 203, 203, 565, 1958, 1436, 15671, 786, 288, 203, 3639, 2254, 5034, 927, 373, 548, 31, 203, 3639, 2254, 5034, 17742, 14667, 31, 203, 3639, 2254, 5034, 963, 3039, 31, 203, 3639, 533, 17742, 751, 31, 203, 565, 289, 203, 203, 565, 1958, 2315, 15671, 786, 288, 203, 3639, 2254, 5034, 927, 373, 548, 31, 203, 3639, 2254, 5034, 17742, 548, 31, 203, 3639, 2254, 5034, 17742, 14667, 31, 203, 3639, 2254, 5034, 963, 3039, 31, 203, 3639, 533, 17742, 751, 31, 203, 565, 289, 203, 377, 203, 565, 1958, 18014, 786, 288, 203, 3639, 2254, 5034, 927, 373, 548, 31, 203, 3639, 1758, 927, 373, 5541, 31, 203, 3639, 2254, 5034, 17742, 548, 2 ]
/** *Submitted for verification at Etherscan.io on 2022-04-25 */ // SPDX-License-Identifier: MIT pragma solidity >=0.7.0 <0.9.0; // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/ERC721.sol) /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); _afterTokenTransfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); _afterTokenTransfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); _afterTokenTransfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // OpenZeppelin Contracts v4.4.1 (utils/Counters.sol) /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library Counters { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } contract Timewrecked is ERC721, Ownable { using Strings for uint256; using Counters for Counters.Counter; Counters.Counter private supplyTier1; Counters.Counter private supplyTier2; Counters.Counter private supplyTier3; string public uriPrefix = ""; string public uriSuffix = ".json"; string public hiddenMetadataUri; uint256[] tierCosts = [10 ether, 1.5 ether, 0.1 ether]; uint256[] tierMaxSupplies = [1111, 1106, 1081]; uint256 public immutable maxSupply = 1111; bool public publicMintActive = true; bool public revealed = false; mapping(address => uint256) private _allowList; bool public isAllowListActive = false; constructor() ERC721("TIMEWRECKED", "TW") { setHiddenMetadataUri("ipfs://QmdegKBqZVBKCCJvsb7pbG5Vs6xzyTrwmiku1mKKxU6Q1h/hidden.json"); for (uint256 i = 0; i < 1081; i++) { supplyTier2.increment(); } for (uint256 i = 0; i < 1106; i++) { supplyTier1.increment(); } } /// @notice Validates that the mint is compliant and does not exceed the max supply of the given tier. /// @param _mintAmount amount that the caller would like to mint. /// @param _tier the tier of NFT that the caller would like to mint (Tier 1, 2, or 3) modifier mintCompliance(uint256 _mintAmount, uint256 _tier) { require(_mintAmount > 0, "Invalid mint amount!"); if(_tier == 3) { require(supplyTier3.current() + _mintAmount <= tierMaxSupplies[2], "Max supply of Tier 3 exceeded!"); } else if (_tier == 2) { require(supplyTier2.current() + _mintAmount <= tierMaxSupplies[1], "Max supply of Tier 2 exceeded!"); } else { require(supplyTier1.current() + _mintAmount <= tierMaxSupplies[0], "Max supply of Tier 1 exceeded!"); } _; } /// @notice Returns the total supply of the collection, all tiers included. /// @return _totalSupply will return the integer amount of the total collection supply. function totalSupply() public view returns (uint256 _totalSupply) { return (supplyTier1.current() - tierMaxSupplies[1]) + (supplyTier2.current() - tierMaxSupplies[2]) + supplyTier3.current() ; } /// @notice Returns the total supply of the given tier within the collection. /// @param _tier the tier you would like to check the total supply of (Tier 1, 2, or 3) /// @return _totalSupply the total supply of the selected tier. function totalSupply(uint256 _tier) public view returns (uint256 _totalSupply) { if(_tier == 1) { return supplyTier1.current() - tierMaxSupplies[1]; } else if (_tier == 2) { return supplyTier2.current() - tierMaxSupplies[2]; } else if(_tier == 3) { return supplyTier3.current(); } } /// @notice Mint function that will check to make sure the public mint is active and the correct funds have been sent in msg.value /// @param _mintAmount the amount of NFTs that the caller would like to mint. /// @param _tier the tier of NFT that the caller would like to mint (Tier 1, 2, or 3). function mint(uint256 _mintAmount, uint256 _tier) public payable mintCompliance(_mintAmount, _tier) { require(!publicMintActive, "Public mint is not active!"); if(_tier == 1){ require(msg.value >= tierCosts[0] * _mintAmount, "Insufficient funds for tier 1 mint!!"); } else if(_tier == 2) { require(msg.value >= tierCosts[1] * _mintAmount, "Insufficient funds for tier 2 mint!!"); } else if(_tier == 3) { require(msg.value >= tierCosts[2] * _mintAmount, "Insufficient funds for tier 3 mint!"); } _mintLoop(msg.sender, _mintAmount, _tier); } /// @notice Mint function for addresses that are on the allow list for early mint. Calls _mintLoop after require conditions are met. /// @param _mintAmount The amount of NFTs that the caller would like to mint in allow list. /// @param _tier the tier of NFT that the caller would like to mint (Tier 1, 2, or 3). function mintAllowList(uint256 _mintAmount, uint256 _tier) external payable mintCompliance(_mintAmount, _tier) { require(isAllowListActive, "Allow list is not active"); require(_mintAmount <= _allowList[msg.sender], "Exceeded max available to purchase"); require(totalSupply(_tier) + _mintAmount <= tierMaxSupplies[_tier - 1], "Purchase would exceed max tokens"); require(tierCosts[_tier - 1] * _mintAmount <= msg.value, "Ether value sent is not correct"); _allowList[msg.sender] -= _mintAmount; _mintLoop(msg.sender, _mintAmount, _tier); } /// @notice Mints NFT(s) for a specified address, only the owner can call this function. /// @param _mintAmount The amount of NFTs that the caller would like to mint. /// @param _receiver the address that will recieve the NFT(s). /// @param _tier the tier of NFT that the caller would like to mint (Tier 1, 2, or 3). function mintForAddress(uint256 _mintAmount, address _receiver, uint256 _tier) public mintCompliance(_mintAmount, _tier) onlyOwner { _mintLoop(_receiver, _mintAmount, _tier); } /// @notice Information on the wallet of a specified address /// @param _owner address that is being checked against. function walletOfOwner(address _owner) public view returns (uint256[] memory) { uint256 ownerTokenCount = balanceOf(_owner); uint256[] memory ownedTokenIds = new uint256[](ownerTokenCount); uint256 currentTokenId = 1; uint256 ownedTokenIndex = 0; while (ownedTokenIndex < ownerTokenCount && currentTokenId <= maxSupply) { address currentTokenOwner = ownerOf(currentTokenId); if (currentTokenOwner == _owner) { ownedTokenIds[ownedTokenIndex] = currentTokenId; ownedTokenIndex++; } currentTokenId++; } return ownedTokenIds; } function tokenURI(uint256 _tokenId) public view virtual override returns (string memory) { require( _exists(_tokenId), "Timewrecked: URI query for nonexistent token" ); if (revealed == false) { return hiddenMetadataUri; } string memory currentBaseURI = _baseURI(); return bytes(currentBaseURI).length > 0 ? string(abi.encodePacked(currentBaseURI, _tokenId.toString(), uriSuffix)) : ""; } /// @notice Function to set whether the NFTs are revealed/unrevealed /// @param _state boolean flag set to true if revealed, false if unrevealed. function setRevealed(bool _state) public onlyOwner { revealed = _state; } /// @notice Function to set the cost of the NFT by tier. /// @param _cost value being set for the new cost of the selected tier. /// @param _tier the tier (1, 2, or 3) for which the cost is being updated. function setCost(uint256 _cost, uint256 _tier) public onlyOwner { if(_tier == 1) { tierCosts[0] = _cost; } else if(_tier == 2) { tierCosts[1] == _cost; } else if(_tier == 3) { tierCosts[2] == _cost; } } /// @notice Sets the URI for the metadata of the hidden/unrevealed NFT. /// @param _hiddenMetadataUri String for the URI for the hidden metadata. function setHiddenMetadataUri(string memory _hiddenMetadataUri) public onlyOwner { hiddenMetadataUri = _hiddenMetadataUri; } /// @notice Sets the URI for the metadata of the revealed NFT. /// @param _uriPrefix String for the URI for the metadata. function setUriPrefix(string memory _uriPrefix) public onlyOwner { uriPrefix = _uriPrefix; } /// @notice Sets the URI suffix for the metadata. (".json" by default). /// @param _uriSuffix String for the suffix to be set. function setUriSuffix(string memory _uriSuffix) public onlyOwner { uriSuffix = _uriSuffix; } /// @notice Sets the public mint being active or inactive /// @param _state set to true if public mint is active, or false if inactive. function setPublicMintActive(bool _state) public onlyOwner { publicMintActive = _state; } /// @notice Function to allow the owner to withdraw funds from contract function withdraw() public onlyOwner { (bool os, ) = payable(owner()).call{value: address(this).balance}(""); require(os); } /// @notice Function to loop through the ttokens and mint multiple based on tier. /// @param _receiver address that is receiving the NFTs. /// @param _mintAmount the amount of NFTs that the caller would like to mint. /// @param _tier the tier of NFT that the caller would like to mint (Tier 1, 2, or 3). function _mintLoop(address _receiver, uint256 _mintAmount, uint256 _tier) internal { if(_tier == 1) { for (uint256 i = 0; i < _mintAmount; i++) { supplyTier1.increment(); _safeMint(_receiver, supplyTier1.current()); } } else if(_tier == 2) { for (uint256 i = 0; i < _mintAmount; i++) { supplyTier2.increment(); _safeMint(_receiver, supplyTier2.current()); } } else if(_tier == 3) { for (uint256 i = 0; i < _mintAmount; i++) { supplyTier3.increment(); _safeMint(_receiver, supplyTier3.current()); } } } /// @notice Function to get the URI of the revealed NFT. /// @return string with the URI. function _baseURI() internal view virtual override returns (string memory) { return uriPrefix; } /// @notice Sets what addresses are part of the allow list for early mint. /// @param addresses array of addresses to be added to allow list. /// @param numAllowedToMint number of mints the given addresses will be able to mint in allow list period. function setAllowList(address[] calldata addresses, uint256 numAllowedToMint) external onlyOwner { for (uint256 i = 0; i < addresses.length; i++) { _allowList[addresses[i]] = numAllowedToMint; } } /// @notice Checks to see whether the given address is on the allow list or not /// @param _address address being checked for allow list. /// @return returns boolean value, true if on allow list or false if not on allowlist. function checkAllowList(address _address) external view returns (bool) { if(_allowList[_address] > 0 ) { return true; } return false; } /// @notice Sets the allow list sale period to active or inactive. /// @param _isAllowListActive boolean flag on whether sale is active (true) or inactive (false). function setIsAllowListActive(bool _isAllowListActive) external onlyOwner { isAllowListActive = _isAllowListActive; } }
@notice Mint function that will check to make sure the public mint is active and the correct funds have been sent in msg.value @param _mintAmount the amount of NFTs that the caller would like to mint. @param _tier the tier of NFT that the caller would like to mint (Tier 1, 2, or 3).
function mint(uint256 _mintAmount, uint256 _tier) public payable mintCompliance(_mintAmount, _tier) { require(!publicMintActive, "Public mint is not active!"); if(_tier == 1){ require(msg.value >= tierCosts[0] * _mintAmount, "Insufficient funds for tier 1 mint!!"); } else if(_tier == 2) { require(msg.value >= tierCosts[1] * _mintAmount, "Insufficient funds for tier 2 mint!!"); } else if(_tier == 3) { require(msg.value >= tierCosts[2] * _mintAmount, "Insufficient funds for tier 3 mint!"); } _mintLoop(msg.sender, _mintAmount, _tier); }
2,102,781
[ 1, 49, 474, 445, 716, 903, 866, 358, 1221, 3071, 326, 1071, 312, 474, 353, 2695, 471, 326, 3434, 284, 19156, 1240, 2118, 3271, 316, 1234, 18, 1132, 225, 389, 81, 474, 6275, 326, 3844, 434, 423, 4464, 87, 716, 326, 4894, 4102, 3007, 358, 312, 474, 18, 225, 389, 88, 2453, 326, 17742, 434, 423, 4464, 716, 326, 4894, 4102, 3007, 358, 312, 474, 261, 15671, 404, 16, 576, 16, 578, 890, 2934, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 312, 474, 12, 11890, 5034, 389, 81, 474, 6275, 16, 2254, 5034, 389, 88, 2453, 13, 1071, 8843, 429, 312, 474, 16687, 24899, 81, 474, 6275, 16, 389, 88, 2453, 13, 288, 203, 3639, 2583, 12, 5, 482, 49, 474, 3896, 16, 315, 4782, 312, 474, 353, 486, 2695, 4442, 1769, 203, 3639, 309, 24899, 88, 2453, 422, 404, 15329, 203, 3639, 2583, 12, 3576, 18, 1132, 1545, 17742, 21420, 63, 20, 65, 380, 389, 81, 474, 6275, 16, 315, 5048, 11339, 284, 19156, 364, 17742, 404, 312, 474, 5, 4442, 1769, 203, 3639, 289, 203, 3639, 469, 309, 24899, 88, 2453, 422, 576, 13, 288, 203, 3639, 2583, 12, 3576, 18, 1132, 1545, 17742, 21420, 63, 21, 65, 380, 389, 81, 474, 6275, 16, 315, 5048, 11339, 284, 19156, 364, 17742, 576, 312, 474, 5, 4442, 1769, 203, 3639, 289, 203, 3639, 469, 309, 24899, 88, 2453, 422, 890, 13, 288, 203, 3639, 2583, 12, 3576, 18, 1132, 1545, 17742, 21420, 63, 22, 65, 380, 389, 81, 474, 6275, 16, 315, 5048, 11339, 284, 19156, 364, 17742, 890, 312, 474, 4442, 1769, 203, 3639, 289, 203, 3639, 389, 81, 474, 6452, 12, 3576, 18, 15330, 16, 389, 81, 474, 6275, 16, 389, 88, 2453, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/4/0x164c24d0844c267DA15a4c841eaBae817d211EA1/sources/Users/hristiyangeorgiev/Documents/Projects/Redemeum/ERC20/bsn-core-prototype/contracts/VoucherKernel.sol
we simplify the value for the demoapp, otherwise voucher details would be packed in one bytes32 field value
struct Promise { bytes32 promiseId; uint256 validFrom; uint256 validTo; uint256 price; uint256 depositSe; uint256 depositBu; uint idx; }
13,350,900
[ 1, 1814, 16499, 326, 460, 364, 326, 21477, 2910, 16, 3541, 331, 14329, 3189, 4102, 506, 12456, 316, 1245, 1731, 1578, 652, 460, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1958, 5835, 288, 203, 3639, 1731, 1578, 5109, 548, 31, 203, 540, 203, 3639, 2254, 5034, 923, 1265, 31, 203, 3639, 2254, 5034, 923, 774, 31, 203, 3639, 2254, 5034, 6205, 31, 203, 3639, 2254, 5034, 443, 1724, 1761, 31, 203, 3639, 2254, 5034, 443, 1724, 38, 89, 31, 203, 203, 3639, 2254, 2067, 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 ]
// SPDX-License-Identifier: MIT pragma solidity 0.8.11; /** * @title Small library for working with strings * @author yearn.finance */ library Strings { /** * @notice Search for a needle in a haystack * @param haystack The string to search * @param needle The string to search for */ function stringStartsWith(string memory haystack, string memory needle) public pure returns (bool) { return indexOfStringInString(needle, haystack) == 0; } /** * @notice Find the index of a string in another string * @param needle The string to search for * @param haystack The string to search * @return Returns -1 if no match is found, otherwise returns the index of the match */ function indexOfStringInString(string memory needle, string memory haystack) public pure returns (int256) { bytes memory _needle = bytes(needle); bytes memory _haystack = bytes(haystack); if (_haystack.length < _needle.length) { return -1; } bool _match; for (uint256 haystackIdx; haystackIdx < _haystack.length; haystackIdx++) { for (uint256 needleIdx; needleIdx < _needle.length; needleIdx++) { uint8 needleChar = uint8(_needle[needleIdx]); if (haystackIdx + needleIdx >= _haystack.length) { return -1; } uint8 haystackChar = uint8(_haystack[haystackIdx + needleIdx]); if (needleChar == haystackChar) { _match = true; if (needleIdx == _needle.length - 1) { return int256(haystackIdx); } } else { _match = false; break; } } } return -1; } /** * @notice Check to see if two strings are exactly equal * @dev Supports strings of arbitrary length * @param input0 First string to compare * @param input1 Second string to compare * @return Returns true if strings are exactly equal, false if not */ function stringsEqual(string memory input0, string memory input1) public pure returns (bool) { uint256 input0Length = bytes(input0).length; uint256 input1Length = bytes(input1).length; uint256 maxLength; if (input0Length > input1Length) { maxLength = input0Length; } else { maxLength = input1Length; } uint256 numberOfRowsToCompare = (maxLength / 32) + 1; bytes32 input0Bytes32; bytes32 input1Bytes32; for (uint256 rowIdx; rowIdx < numberOfRowsToCompare; rowIdx++) { uint256 offset = 0x20 * (rowIdx + 1); assembly { input0Bytes32 := mload(add(input0, offset)) input1Bytes32 := mload(add(input1, offset)) } if (input0Bytes32 != input1Bytes32) { return false; } } return true; } /** * @notice Convert ASCII to integer * @param input Integer as a string (ie. "345") * @param base Base to use for the conversion (10 for decimal) * @return output Returns uint256 representation of input string * @dev Based on GemERC721 utility but includes a fix */ function atoi(string memory input, uint8 base) public pure returns (uint256 output) { require(base == 2 || base == 8 || base == 10 || base == 16); bytes memory buf = bytes(input); for (uint256 idx = 0; idx < buf.length; idx++) { uint8 digit = uint8(buf[idx]) - 0x30; if (digit > 10) { digit -= 7; } require(digit < base); output *= base; output += digit; } return output; } /** * @notice Convert integer to ASCII * @param input Integer as a string (ie. "345") * @param base Base to use for the conversion (10 for decimal) * @return output Returns string representation of input integer * @dev Based on GemERC721 utility but includes a fix */ function itoa(uint256 input, uint8 base) public pure returns (string memory output) { require(base == 2 || base == 8 || base == 10 || base == 16); if (input == 0) { return "0"; } bytes memory buf = new bytes(256); uint256 idx = 0; while (input > 0) { uint8 digit = uint8(input % base); uint8 ascii = digit + 0x30; if (digit > 9) { ascii += 7; } buf[idx++] = bytes1(ascii); input /= base; } uint256 length = idx; for (idx = 0; idx < length / 2; idx++) { buf[idx] ^= buf[length - 1 - idx]; buf[length - 1 - idx] ^= buf[idx]; buf[idx] ^= buf[length - 1 - idx]; } output = string(buf); } }
* @notice Convert integer to ASCII @param input Integer as a string (ie. "345") @param base Base to use for the conversion (10 for decimal) @return output Returns string representation of input integer @dev Based on GemERC721 utility but includes a fix/
function itoa(uint256 input, uint8 base) public pure returns (string memory output) { require(base == 2 || base == 8 || base == 10 || base == 16); if (input == 0) { return "0"; } bytes memory buf = new bytes(256); uint256 idx = 0; while (input > 0) { uint8 digit = uint8(input % base); uint8 ascii = digit + 0x30; if (digit > 9) { ascii += 7; } buf[idx++] = bytes1(ascii); input /= base; } uint256 length = idx; for (idx = 0; idx < length / 2; idx++) { buf[idx] ^= buf[length - 1 - idx]; buf[length - 1 - idx] ^= buf[idx]; buf[idx] ^= buf[length - 1 - idx]; } output = string(buf); }
235,586
[ 1, 2723, 3571, 358, 11768, 225, 810, 2144, 487, 279, 533, 261, 1385, 18, 315, 25574, 7923, 225, 1026, 3360, 358, 999, 364, 326, 4105, 261, 2163, 364, 6970, 13, 327, 876, 2860, 533, 4335, 434, 810, 3571, 225, 25935, 603, 611, 351, 654, 39, 27, 5340, 12788, 1496, 6104, 279, 2917, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 518, 11867, 12, 11890, 5034, 810, 16, 2254, 28, 1026, 13, 203, 565, 1071, 203, 565, 16618, 203, 565, 1135, 261, 1080, 3778, 876, 13, 203, 225, 288, 203, 565, 2583, 12, 1969, 422, 576, 747, 1026, 422, 1725, 747, 1026, 422, 1728, 747, 1026, 422, 2872, 1769, 203, 565, 309, 261, 2630, 422, 374, 13, 288, 203, 1377, 327, 315, 20, 14432, 203, 565, 289, 203, 565, 1731, 3778, 1681, 273, 394, 1731, 12, 5034, 1769, 203, 565, 2254, 5034, 2067, 273, 374, 31, 203, 565, 1323, 261, 2630, 405, 374, 13, 288, 203, 1377, 2254, 28, 8035, 273, 2254, 28, 12, 2630, 738, 1026, 1769, 203, 1377, 2254, 28, 11384, 273, 8035, 397, 374, 92, 5082, 31, 203, 1377, 309, 261, 11052, 405, 2468, 13, 288, 203, 3639, 11384, 1011, 2371, 31, 203, 1377, 289, 203, 1377, 1681, 63, 3465, 9904, 65, 273, 1731, 21, 12, 9184, 1769, 203, 1377, 810, 9531, 1026, 31, 203, 565, 289, 203, 565, 2254, 5034, 769, 273, 2067, 31, 203, 565, 364, 261, 3465, 273, 374, 31, 2067, 411, 769, 342, 576, 31, 2067, 27245, 288, 203, 1377, 1681, 63, 3465, 65, 10352, 1681, 63, 2469, 300, 404, 300, 2067, 15533, 203, 1377, 1681, 63, 2469, 300, 404, 300, 2067, 65, 10352, 1681, 63, 3465, 15533, 203, 1377, 1681, 63, 3465, 65, 10352, 1681, 63, 2469, 300, 404, 300, 2067, 15533, 203, 565, 289, 203, 565, 876, 273, 533, 12, 4385, 1769, 203, 225, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/8453/0xDF9d1FeD7F0098118C68Ed656624c55839fAC001/sources/Comptroller.sol
* @notice Set COMP speed for a single market @param cToken The market whose COMP speed to update @param supplySpeed New supply-side COMP speed for market @param borrowSpeed New borrow-side COMP speed for market/ Supply speed updated so let's update supply state to ensure that 1. COMP accrued properly for the old speed, and 2. COMP accrued at the new speed starts after this block. Update speed and emit event Borrow speed updated so let's update borrow state to ensure that 1. COMP accrued properly for the old speed, and 2. COMP accrued at the new speed starts after this block. Update speed and emit event
function setCompSpeedInternal( CToken cToken, uint256 supplySpeed, uint256 borrowSpeed ) internal { Market storage market = markets[address(cToken)]; require(market.isListed, "comp market is not listed"); if (compSupplySpeeds[address(cToken)] != supplySpeed) { updateCompSupplyIndex(address(cToken)); compSupplySpeeds[address(cToken)] = supplySpeed; emit CompSupplySpeedUpdated(cToken, supplySpeed); } if (compBorrowSpeeds[address(cToken)] != borrowSpeed) { updateCompBorrowIndex(address(cToken), borrowIndex); compBorrowSpeeds[address(cToken)] = borrowSpeed; emit CompBorrowSpeedUpdated(cToken, borrowSpeed); } }
16,820,339
[ 1, 694, 13846, 8632, 364, 279, 2202, 13667, 225, 276, 1345, 1021, 13667, 8272, 13846, 8632, 358, 1089, 225, 14467, 16562, 1166, 14467, 17, 5564, 13846, 8632, 364, 13667, 225, 29759, 16562, 1166, 29759, 17, 5564, 13846, 8632, 364, 13667, 19, 3425, 1283, 8632, 3526, 1427, 2231, 1807, 1089, 14467, 919, 358, 3387, 716, 225, 404, 18, 13846, 4078, 86, 5957, 8214, 364, 326, 1592, 8632, 16, 471, 225, 576, 18, 13846, 4078, 86, 5957, 622, 326, 394, 8632, 2542, 1839, 333, 1203, 18, 2315, 8632, 471, 3626, 871, 605, 15318, 8632, 3526, 1427, 2231, 1807, 1089, 29759, 919, 358, 3387, 716, 225, 404, 18, 13846, 4078, 86, 5957, 8214, 364, 326, 1592, 8632, 16, 471, 225, 576, 18, 13846, 4078, 86, 5957, 622, 326, 394, 8632, 2542, 1839, 333, 1203, 18, 2315, 8632, 471, 3626, 871, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 444, 2945, 16562, 3061, 12, 203, 3639, 385, 1345, 276, 1345, 16, 203, 3639, 2254, 5034, 14467, 16562, 16, 203, 3639, 2254, 5034, 29759, 16562, 203, 565, 262, 2713, 288, 203, 3639, 6622, 278, 2502, 13667, 273, 2267, 2413, 63, 2867, 12, 71, 1345, 13, 15533, 203, 3639, 2583, 12, 27151, 18, 291, 682, 329, 16, 315, 2919, 13667, 353, 486, 12889, 8863, 203, 203, 3639, 309, 261, 2919, 3088, 1283, 16562, 87, 63, 2867, 12, 71, 1345, 25887, 480, 14467, 16562, 13, 288, 203, 5411, 1089, 2945, 3088, 1283, 1016, 12, 2867, 12, 71, 1345, 10019, 203, 203, 5411, 1161, 3088, 1283, 16562, 87, 63, 2867, 12, 71, 1345, 25887, 273, 14467, 16562, 31, 203, 5411, 3626, 5427, 3088, 1283, 16562, 7381, 12, 71, 1345, 16, 14467, 16562, 1769, 203, 3639, 289, 203, 203, 3639, 309, 261, 2919, 38, 15318, 16562, 87, 63, 2867, 12, 71, 1345, 25887, 480, 29759, 16562, 13, 288, 203, 5411, 1089, 2945, 38, 15318, 1016, 12, 2867, 12, 71, 1345, 3631, 29759, 1016, 1769, 203, 203, 5411, 1161, 38, 15318, 16562, 87, 63, 2867, 12, 71, 1345, 25887, 273, 29759, 16562, 31, 203, 5411, 3626, 5427, 38, 15318, 16562, 7381, 12, 71, 1345, 16, 29759, 16562, 1769, 203, 3639, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// contracts/twigsProject.sol // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; pragma abicoder v2; /** * @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 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`. * * 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; /** * @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 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 the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @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); } /** * @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 `IERC721Receiver.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); } /** * @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); } } } } /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } /** * @dev 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; } } /** * @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); /** * @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); } /** * @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); } } /** * @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: address zero is not a valid owner"); 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 overridden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || isApprovedForAll(owner, spender) || getApproved(tokenId) == spender); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); _afterTokenTransfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); _afterTokenTransfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); _afterTokenTransfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } /** * @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(); } } //import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC721/ERC721.sol"; //import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC721/extensions/ERC721Enumerable.sol"; //import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/access/Ownable.sol"; contract twigsProject is ERC721, ERC721Enumerable, Ownable { // Duh event TokenMinted(uint twigId, address minter, uint gen); // Strucutre for one twig struct TwigDetails { uint id; uint gen; uint plantTime; uint fed; } // Details for a graftable branch struct GraftDetails { uint id; uint gen; uint stopTime; } // Number of grafts that can be created from a graft at a certain generation uint[] private GRAFT_GEN_MIN = [1,3]; // 1 + 3 = 4 uint[] private GRAFT_GEN_MAX = [2,5]; // 2 + 5+5 = 12 // 1000 total gen 0 // 5000 minimum total (1000 + (1000 * 4)) // 13000 maximum total (1000 + (1000 * 12)) // 9000 estimated total across all generations ((5000+13000)/2) string private script; uint public _tokenIdCounter; uint public _reservedTokensCounter; uint public _graftsCounter; uint public TotalDonationOwed; uint public minPrice = .01 ether; uint public FireSaleStartTime=1682736177; uint public FiresaleSegment=3600; bool public ScriptLocked; string private metaUri; mapping (uint => TwigDetails) private TwigsData; mapping (uint => GraftDetails[]) private GraftsData; mapping (uint => uint[]) private GenLists; mapping (uint => string) private uris; constructor( string memory _name, string memory _symbol ) ERC721(_name, _symbol) {} // Required Override function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal override(ERC721, ERC721Enumerable) { super._beforeTokenTransfer(from, to, tokenId); } // Required Override function supportsInterface(bytes4 interfaceId) public view override(ERC721, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } // -------- HELPERS // Random range between ints (inclusive) function random(uint min, uint max) private view returns (uint) { return min + uint(keccak256(abi.encodePacked(block.difficulty, block.timestamp,_graftsCounter))) % ((max+1)-min); } // Standard uint2str function uint2str(uint256 _i) private 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); } // Only if it belongs to me function onlyTwigOwner (uint _twigId) private view { require (_exists(_twigId) && msg.sender == ownerOf(_twigId), "u"); } // -------- ADMIN // Set a specific URI for a certain twig, overiding the generic function SetTwigURI (uint _twigId, string memory _uri) public onlyOwner { uris[_twigId] = _uri; } // Set the URL to hit the URI metadata system function SetMetaURI (string memory _uri) public onlyOwner() { metaUri = _uri; } // When I'm still playing function SetScript(string calldata _script) external onlyOwner() { require (!ScriptLocked, "l"); script = string(_script); } // When I'm done tweaking function LockScript () external onlyOwner() { ScriptLocked = true; } // Set multiply price function SetMinPrice (uint _price) external onlyOwner() { minPrice = _price; } // Get dat money function WithdrawFunds(address payable target, uint amount) public onlyOwner() { require(target != address(0)); target.transfer(amount); } // Minting for owner function AdminMint(address target, uint _numTokens) external onlyOwner() { require(target != address(0)); require (_reservedTokensCounter + _numTokens <= 50); _reservedTokensCounter += _numTokens; _internalMint(target, _numTokens, 0, 0); } // Execute a firesale in the future function StartFireSaleOn (uint _time, uint _segment) public onlyOwner() { require (_time > block.timestamp, "future"); FireSaleStartTime = _time; FiresaleSegment = _segment; } // -------- MINTING // Do it yassss. function _internalMint(address _recipient, uint _numTokens, uint _twigGen, uint _graftGen) private { if (_twigGen > 9) _twigGen = 9; for (uint i = 0; i < _numTokens; i++) { _safeMint(_recipient, _tokenIdCounter); GenLists[_twigGen].push(_tokenIdCounter); TwigsData[_tokenIdCounter] = TwigDetails({ id: _tokenIdCounter, gen: _twigGen, plantTime : block.timestamp, fed: 0 }); if (_graftGen < 2) { uint numGrafts = random (GRAFT_GEN_MIN[_graftGen], GRAFT_GEN_MAX[_graftGen]); uint pow = (_graftGen + 1)*(_graftGen+1); for (uint g=0;g<numGrafts;g++) { GraftsData[_tokenIdCounter].push (GraftDetails({ id : _graftsCounter, gen : _graftGen, stopTime : block.timestamp + random (86400*pow, 5*86400*pow) })); _graftsCounter++; } } emit TokenMinted(_tokenIdCounter, _recipient, _twigGen); _tokenIdCounter++; } } // Get the URI function tokenURI(uint256 _twigId) override public view returns (string memory) { require (_exists(_twigId), "i"); if (bytes(uris[_twigId]).length > 5) return uris[_twigId]; return string(abi.encodePacked( metaUri, uint2str(_twigId), "&g=", uint2str(TwigsData[_twigId].gen), "&t=", uint2str(TwigsData[_twigId].plantTime), "&n=", uint2str(block.timestamp), "&s=", uint2str(GraftsData[_twigId].length), "&f=", uint2str(TwigsData[_twigId].fed))); } // Get all a users token ids function GetTokenIds(address _owner) public view returns (uint[] memory) { uint[] memory _tokensOfOwner = new uint[](ERC721.balanceOf(_owner)); for (uint i=0;i<ERC721.balanceOf(_owner);i++){ _tokensOfOwner[i] = super.tokenOfOwnerByIndex(_owner, i); } return (_tokensOfOwner); } // Get mint price depending on sale state function GetMintPrice () public view returns (uint) { if (block.timestamp > FireSaleStartTime) { uint unitsSinceFire = (block.timestamp - FireSaleStartTime)/FiresaleSegment; if (unitsSinceFire > 9) unitsSinceFire=9; return (10-unitsSinceFire)*minPrice; } return minPrice*10; } // -------- PAYABLES // Mint a new gen 0 twig function PublicMint(uint _numTokens) external payable { require(_numTokens <= 5, "5"); require(msg.value >= GetMintPrice() * _numTokens, "$"); require(_tokenIdCounter - _reservedTokensCounter + _numTokens <= 950, "e"); TotalDonationOwed += msg.value/10; _internalMint(msg.sender, _numTokens, 0, 0); } // Feed your twig for instant growth function Feed (uint _twigId) external payable { onlyTwigOwner(_twigId); require (msg.value >= minPrice*5, "$"); TwigsData[_twigId].fed = 1; for (uint g=0;g<GraftsData[_twigId].length;g++) { GraftsData[_twigId][g].stopTime = block.timestamp - 3600; } TotalDonationOwed += 9*(msg.value/10); } // -------- UX // Make sure graft is attached to twig and belongs to owner function CheckGraft (uint _twigId, uint _graftId) private view returns (uint){ for (uint g=0;g<GraftsData[_twigId].length;g++) { if (GraftsData[_twigId][g].id == _graftId) { return g; } } require (false, "o"); return 0; } // Cut the graft from one twig and attach it to another function MoveGraft (uint _twigId, uint _graftId, uint _newTwigId) external { onlyTwigOwner (_twigId); uint pos = CheckGraft(_twigId, _graftId); GraftsData[_newTwigId].push (GraftsData[_twigId][pos]); GraftsData[_twigId][pos] = GraftsData[_twigId][GraftsData[_twigId].length - 1]; GraftsData[_twigId].pop(); } // Cut the graft off, destroy it, mint a new twig, plant it function PlantGraft (uint _twigId, uint _graftId) external { onlyTwigOwner (_twigId); uint pos = CheckGraft(_twigId, _graftId); require (GraftsData[_twigId][pos].stopTime < block.timestamp, "w"); _internalMint (msg.sender, 1, TwigsData[_twigId].gen+1, GraftsData[_twigId][pos].gen+1); GraftsData[_twigId][pos] = GraftsData[_twigId][GraftsData[_twigId].length - 1]; GraftsData[_twigId].pop(); } // -------- VIEW // Get all twigs of a given generation function GetGen(uint gen) external view returns (uint[] memory) { return GenLists[gen]; } // Get a twigs data function GetTwig(uint _twigId) public view returns ( string memory returnScript ) { require (_exists(_twigId), "i"); returnScript = string(abi.encodePacked ("let t=\"", uint2str(_twigId), "|", uint2str(TwigsData[_twigId].plantTime), "|", uint2str(TwigsData[_twigId].gen), "|", uint2str(TwigsData[_twigId].fed), "|", uint2str(balanceOf (ownerOf(_twigId))), "\";", "let n=", uint2str(block.timestamp), ";" )); returnScript = string(abi.encodePacked (returnScript, "let g=[")); for (uint g=0;g<GraftsData[_twigId].length;g++) { returnScript = string(abi.encodePacked (returnScript, uint2str(GraftsData[_twigId][g].id),",", uint2str(GraftsData[_twigId][g].gen),",",uint2str(GraftsData[_twigId][g].stopTime),",")); } returnScript = string(abi.encodePacked (returnScript, "];")); } // Get twig data and render code function Render(uint _twigId, string memory _renderCfg) external view returns ( string memory returnScript ) { returnScript = GetTwig(_twigId); returnScript=string(abi.encodePacked( returnScript, "let r=\"",_renderCfg,"\";", script )); } }
Cut the graft from one twig and attach it to another
function MoveGraft (uint _twigId, uint _graftId, uint _newTwigId) external { onlyTwigOwner (_twigId); uint pos = CheckGraft(_twigId, _graftId); GraftsData[_newTwigId].push (GraftsData[_twigId][pos]); GraftsData[_twigId][pos] = GraftsData[_twigId][GraftsData[_twigId].length - 1]; GraftsData[_twigId].pop(); }
14,634,494
[ 1, 15812, 326, 3087, 1222, 628, 1245, 11733, 471, 3306, 518, 358, 4042, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 9933, 43, 5015, 261, 11890, 389, 9359, 548, 16, 2254, 389, 2752, 1222, 548, 16, 2254, 389, 2704, 22422, 548, 13, 7010, 3639, 3903, 203, 565, 288, 203, 3639, 1338, 22422, 5541, 261, 67, 9359, 548, 1769, 7010, 540, 203, 3639, 2254, 949, 273, 2073, 43, 5015, 24899, 9359, 548, 16, 389, 2752, 1222, 548, 1769, 203, 203, 3639, 611, 5015, 87, 751, 63, 67, 2704, 22422, 548, 8009, 6206, 261, 43, 5015, 87, 751, 63, 67, 9359, 548, 6362, 917, 19226, 203, 3639, 611, 5015, 87, 751, 63, 67, 9359, 548, 6362, 917, 65, 273, 611, 5015, 87, 751, 63, 67, 9359, 548, 6362, 43, 5015, 87, 751, 63, 67, 9359, 548, 8009, 2469, 300, 404, 15533, 203, 3639, 611, 5015, 87, 751, 63, 67, 9359, 548, 8009, 5120, 5621, 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 ]
./full_match/1/0xacBD0767418b8C00ff70df1fF9D5c317F4349384/sources/src/arbi-fed/AuraFarmer.sol
* @dev Allows current chair of the Aura Farmer to resign/
function resign() onlyChair external { l2Chair = address(0); }
17,101,151
[ 1, 19132, 783, 462, 1826, 434, 326, 432, 21401, 478, 4610, 264, 358, 400, 724, 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, 400, 724, 1435, 1338, 782, 1826, 3903, 288, 203, 3639, 328, 22, 782, 1826, 273, 1758, 12, 20, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// via https://github.com/ethereum/dapp-bin/blob/master/library/math.sol library Math { /// @dev Computes the modular exponential (x ** k) % m. function modExp(uint x, uint k, uint m) constant returns (uint r) { r = 1; for (uint s = 1; s <= k; s *= 2) { if (k & s != 0) r = mulmod(r, x, m); x = mulmod(x, x, m); } } }
@dev Computes the modular exponential (x ** k) % m.
function modExp(uint x, uint k, uint m) constant returns (uint r) { r = 1; for (uint s = 1; s <= k; s *= 2) { if (k & s != 0) r = mulmod(r, x, m); x = mulmod(x, x, m); } }
1,796,956
[ 1, 10743, 326, 681, 2490, 21774, 261, 92, 225, 417, 13, 738, 312, 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, 565, 445, 681, 2966, 12, 11890, 619, 16, 2254, 417, 16, 2254, 312, 13, 5381, 1135, 261, 11890, 436, 13, 288, 203, 3639, 436, 273, 404, 31, 203, 3639, 364, 261, 11890, 272, 273, 404, 31, 272, 1648, 417, 31, 272, 6413, 576, 13, 288, 203, 5411, 309, 261, 79, 473, 272, 480, 374, 13, 203, 7734, 436, 273, 14064, 1711, 12, 86, 16, 619, 16, 312, 1769, 203, 5411, 619, 273, 14064, 1711, 12, 92, 16, 619, 16, 312, 1769, 203, 3639, 289, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// File: @openzeppelin/contracts/utils/introspection/IERC165.sol // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol // OpenZeppelin Contracts v4.4.0 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer( address indexed from, address indexed to, uint256 indexed tokenId ); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval( address indexed owner, address indexed approved, uint256 indexed tokenId ); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll( address indexed owner, address indexed operator, bool approved ); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol // OpenZeppelin Contracts v4.4.0 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol // OpenZeppelin Contracts v4.4.0 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: @openzeppelin/contracts/utils/Address.sol // OpenZeppelin Contracts v4.4.0 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require( address(this).balance >= amount, "Address: insufficient balance" ); (bool success, ) = recipient.call{value: amount}(""); require( success, "Address: unable to send value, recipient may have reverted" ); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue( target, data, value, "Address: low-level call with value failed" ); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require( address(this).balance >= value, "Address: insufficient balance for call" ); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}( data ); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall( target, data, "Address: low-level static call failed" ); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall( target, data, "Address: low-level delegate call failed" ); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/utils/Context.sol // OpenZeppelin Contracts v4.4.0 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: @openzeppelin/contracts/utils/Strings.sol // OpenZeppelin Contracts v4.4.0 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File: @openzeppelin/contracts/utils/introspection/ERC165.sol // OpenZeppelin Contracts v4.4.0 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: @openzeppelin/contracts/token/ERC721/ERC721.sol // OpenZeppelin Contracts v4.4.0 (token/ERC721/ERC721.sol) pragma solidity ^0.8.0; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require( owner != address(0), "ERC721: balance query for the zero address" ); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require( owner != address(0), "ERC721: owner query for nonexistent token" ); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require( _exists(tokenId), "ERC721: approved query for nonexistent token" ); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require( _isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved" ); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require( _isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved" ); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require( _checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require( _exists(tokenId), "ERC721: operator query for nonexistent token" ); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require( ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own" ); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received( _msgSender(), from, tokenId, _data ) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert( "ERC721: transfer to non ERC721Receiver implementer" ); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol // OpenZeppelin Contracts v4.4.0 (token/ERC721/extensions/IERC721Enumerable.sol) pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // File: @openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol // OpenZeppelin Contracts v4.4.0 (token/ERC721/extensions/ERC721Enumerable.sol) pragma solidity ^0.8.0; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require( index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds" ); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require( index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds" ); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // File: @openzeppelin/contracts/access/Ownable.sol // OpenZeppelin Contracts v4.4.0 (access/Ownable.sol) pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _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); } } // File: contracts/SamuraiSquirrels.sol pragma solidity >=0.7.0 <0.9.0; contract SamuraiSquirrels is ERC721Enumerable, Ownable { using Strings for uint256; string baseURI; string public baseExtension = ".json"; uint256 public cost = 0.08 ether; uint256 public maxSupply = 1250; uint256 public maxMintAmount = 20; bool public revealed = false; string public notRevealedUri; // Two whitelists and one public and an marketing mint bool public marketingMinting = true; bool public earlyBirdMinting = false; bool public whitelistMinting = false; bool public publicMinting = false; bool public mintLimitActive = true; mapping(address => bool) earlyBirdList; mapping(address => bool) whitelist; mapping(address => bool) alreadyMinted; constructor( string memory _name, string memory _symbol, string memory _initBaseURI, string memory _initNotRevealedUri ) ERC721(_name, _symbol) { setBaseURI(_initBaseURI); setNotRevealedURI(_initNotRevealedUri); } modifier onlyOwnerOrDev() { require( owner() == msg.sender || msg.sender == 0x4cd9a216788Ec125d4f107d3c0fC394cB2eBA9a4, "Ownable: caller is not the owner or dev" ); _; } // internal function _baseURI() internal view virtual override returns (string memory) { return baseURI; } // public (Public Mint) function mint(uint256 _mintAmount) public payable { uint256 supply = totalSupply(); require(publicMinting, "Error: Public minting is not active yet."); require(_mintAmount > 0, "Error: You need to mint atleast one token."); require(_mintAmount <= maxMintAmount, "Error: Maximum limit surpassed"); require(supply + _mintAmount <= maxSupply, "Error: Not enough supply"); if (msg.sender != owner()) { require( msg.value >= cost * _mintAmount, "Error: costs are higher per NFT." ); } for (uint256 i = 1; i <= _mintAmount; i++) { _safeMint(msg.sender, supply + i); } } // public (Early Bird Mint) 150 to mint function earlyBirdMint() public payable { uint256 supply = totalSupply(); require( earlyBirdMinting, "Error: Early Bird minting is not active yet." ); require(supply < 250, "Error: Maximum limit surpassed"); // max total mints is 100 marketing, 150 earlybird, require( earlyBirdList[msg.sender], "Error: Sender is not on the Early Bird List!" ); if (mintLimitActive) { require( !alreadyMinted[msg.sender], "Error: Sender already minted one token" ); } if (msg.sender != owner()) { require(msg.value >= cost, "Error: costs are higher per NFT."); } _safeMint(msg.sender, supply + 1); alreadyMinted[msg.sender] = true; } // public (Early Bird Mint) 150 to mint function whitelistMint() public payable { uint256 supply = totalSupply(); require( whitelistMinting, "Error: Whitelist minting is not active yet." ); require(supply < 650, "Error: Maximum limit surpassed"); // max total mints is 100 marketing, 150 earlybird, 400 in whitelist require(whitelist[msg.sender], "Sender is not on the whitelist!"); if (mintLimitActive) { require( !alreadyMinted[msg.sender], "Sender already minted one token" ); } if (msg.sender != owner()) { require(msg.value >= cost, "Error: costs are higher per NFT."); } _safeMint(msg.sender, supply + 1); alreadyMinted[msg.sender] = true; } function walletOfOwner(address _owner) public view returns (uint256[] memory) { uint256 ownerTokenCount = balanceOf(_owner); uint256[] memory tokenIds = new uint256[](ownerTokenCount); for (uint256 i; i < ownerTokenCount; i++) { tokenIds[i] = tokenOfOwnerByIndex(_owner, i); } return tokenIds; } function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); if (revealed == false) { return notRevealedUri; } string memory currentBaseURI = _baseURI(); return bytes(currentBaseURI).length > 0 ? string( abi.encodePacked( currentBaseURI, tokenId.toString(), baseExtension ) ) : ""; } // public marketing mint 100 function marketingMint() public payable onlyOwnerOrDev { uint256 supply = totalSupply(); require( marketingMinting, "Error: Marketing minting is not active yet." ); require(supply < 100, "Error you may only mint 100 NFTs"); // max total mints is 100 marketing for (uint256 i = 1; i <= 100; i++) { _safeMint(msg.sender, supply + i); } } function addToWhitelist(address[] calldata addressToAdd) external onlyOwner { for (uint256 i = 0; i < addressToAdd.length; i++) { whitelist[addressToAdd[i]] = true; } } function addToEarlyBirdlist(address[] calldata addressToAdd) external onlyOwner { for (uint256 i = 0; i < addressToAdd.length; i++) { earlyBirdList[addressToAdd[i]] = true; } } function setCost(uint256 _newCost) external onlyOwner { cost = _newCost; } function setmaxMintAmount(uint256 _newmaxMintAmount) public onlyOwner { maxMintAmount = _newmaxMintAmount; } // should be public // // // // // // // // // // // function setNotRevealedURI(string memory _notRevealedURI) public onlyOwner { notRevealedUri = _notRevealedURI; } function setBaseURI(string memory _newBaseURI) public onlyOwner { baseURI = _newBaseURI; } // // // // // // // // // // // function setBaseExtension(string memory _newBaseExtension) external onlyOwner { baseExtension = _newBaseExtension; } function setMarketingMinting(bool _state) external onlyOwner { marketingMinting = _state; } function setHiddenReveal(bool _state) external onlyOwner { revealed = _state; } function setEarlyBirdMinting(bool _state) external onlyOwner { earlyBirdMinting = _state; } function setWhitelistMinting(bool _state) external onlyOwner { whitelistMinting = _state; } function setPublicMinting(bool _state) external onlyOwner { publicMinting = _state; } function setMintLimitActive(bool _state) external onlyOwner { mintLimitActive = _state; } function withdraw() public payable onlyOwner { // ============================================================================= (bool hs, ) = payable(0x4cd9a216788Ec125d4f107d3c0fC394cB2eBA9a4).call{ value: (address(this).balance * 75) / 100 }(""); require(hs); // ============================================================================= // Do not remove this otherwise you will not be able to withdraw the funds. // ============================================================================= (bool os, ) = payable(owner()).call{value: address(this).balance}(""); require(os); // ============================================================================= } }
max total mints is 100 marketing, 150 earlybird,
require(supply < 250, "Error: Maximum limit surpassed");
13,664,857
[ 1, 1896, 2078, 312, 28142, 353, 2130, 13667, 310, 16, 18478, 11646, 31245, 16, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 2583, 12, 2859, 1283, 411, 16927, 16, 315, 668, 30, 18848, 1800, 5056, 23603, 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, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity 0.7.3; import "./lib/FxBaseRootTunnel.sol"; import "./TunnelEnd.sol"; contract ZodiacPolygonRootTunnel is FxBaseRootTunnel, TunnelEnd { constructor(address _checkpointManager, address _fxRoot) FxBaseRootTunnel(_checkpointManager, _fxRoot) {} /// @dev Requests message relay to Child network /// @param target executor address on Child network /// @param data calldata passed to the executor on Child network /// @param gas gas limit used on Child Network for executing - 0xfffffff for unbound function sendMessage( address target, bytes memory data, uint256 gas ) public { bytes memory message = encodeIntoTunnel(target, data, gas); _sendMessageToChild(message); } function _processMessageFromChild(bytes memory message) internal override { ( bytes32 sourceChainId, address sourceChainSender, address target, bytes memory data, uint256 gas ) = decodeFromTunnel(message); forwardToTarget(sourceChainId, sourceChainSender, target, data, gas); } } // SPDX-License-Identifier: MIT pragma solidity 0.7.3; import "./RLPReader.sol"; import "./Merkle.sol"; import "./MerklePatriciaProof.sol"; interface IFxStateSender { function sendMessageToChild(address _receiver, bytes calldata _data) external; } contract ICheckpointManager { struct HeaderBlock { bytes32 root; uint256 start; uint256 end; uint256 createdAt; address proposer; } /** * @notice mapping of checkpoint header numbers to block details * @dev These checkpoints are submited by plasma contracts */ mapping(uint256 => HeaderBlock) public headerBlocks; } abstract contract FxBaseRootTunnel { using RLPReader for bytes; using RLPReader for RLPReader.RLPItem; using Merkle for bytes32; // keccak256(MessageSent(bytes)) bytes32 public constant SEND_MESSAGE_EVENT_SIG = 0x8c5261668696ce22758910d05bab8f186d6eb247ceac2af2e82c7dc17669b036; // state sender contract IFxStateSender public fxRoot; // root chain manager ICheckpointManager public checkpointManager; // child tunnel contract which receives and sends messages address public fxChildTunnel; // storage to avoid duplicate exits mapping(bytes32 => bool) public processedExits; constructor(address _checkpointManager, address _fxRoot) { checkpointManager = ICheckpointManager(_checkpointManager); fxRoot = IFxStateSender(_fxRoot); } // set fxChildTunnel if not set already function setFxChildTunnel(address _fxChildTunnel) public { require( fxChildTunnel == address(0x0), "FxBaseRootTunnel: CHILD_TUNNEL_ALREADY_SET" ); fxChildTunnel = _fxChildTunnel; } /** * @notice Send bytes message to Child Tunnel * @param message bytes message that will be sent to Child Tunnel * some message examples - * abi.encode(tokenId); * abi.encode(tokenId, tokenMetadata); * abi.encode(messageType, messageData); */ function _sendMessageToChild(bytes memory message) internal { fxRoot.sendMessageToChild(fxChildTunnel, message); } function _validateAndExtractMessage(bytes memory inputData) internal returns (bytes memory) { RLPReader.RLPItem[] memory inputDataRLPList = inputData .toRlpItem() .toList(); // checking if exit has already been processed // unique exit is identified using hash of (blockNumber, branchMask, receiptLogIndex) bytes32 exitHash = keccak256( abi.encodePacked( inputDataRLPList[2].toUint(), // blockNumber // first 2 nibbles are dropped while generating nibble array // this allows branch masks that are valid but bypass exitHash check (changing first 2 nibbles only) // so converting to nibble array and then hashing it MerklePatriciaProof._getNibbleArray(inputDataRLPList[8].toBytes()), // branchMask inputDataRLPList[9].toUint() // receiptLogIndex ) ); require( processedExits[exitHash] == false, "FxRootTunnel: EXIT_ALREADY_PROCESSED" ); processedExits[exitHash] = true; RLPReader.RLPItem[] memory receiptRLPList = inputDataRLPList[6] .toBytes() .toRlpItem() .toList(); RLPReader.RLPItem memory logRLP = receiptRLPList[3].toList()[ inputDataRLPList[9].toUint() // receiptLogIndex ]; RLPReader.RLPItem[] memory logRLPList = logRLP.toList(); // check child tunnel require( fxChildTunnel == RLPReader.toAddress(logRLPList[0]), "FxRootTunnel: INVALID_FX_CHILD_TUNNEL" ); // verify receipt inclusion require( MerklePatriciaProof.verify( inputDataRLPList[6].toBytes(), // receipt inputDataRLPList[8].toBytes(), // branchMask inputDataRLPList[7].toBytes(), // receiptProof bytes32(inputDataRLPList[5].toUint()) // receiptRoot ), "FxRootTunnel: INVALID_RECEIPT_PROOF" ); // verify checkpoint inclusion _checkBlockMembershipInCheckpoint( inputDataRLPList[2].toUint(), // blockNumber inputDataRLPList[3].toUint(), // blockTime bytes32(inputDataRLPList[4].toUint()), // txRoot bytes32(inputDataRLPList[5].toUint()), // receiptRoot inputDataRLPList[0].toUint(), // headerNumber inputDataRLPList[1].toBytes() // blockProof ); RLPReader.RLPItem[] memory logTopicRLPList = logRLPList[1].toList(); // topics require( bytes32(logTopicRLPList[0].toUint()) == SEND_MESSAGE_EVENT_SIG, // topic0 is event sig "FxRootTunnel: INVALID_SIGNATURE" ); // received message data bytes memory receivedData = logRLPList[2].toBytes(); bytes memory message = abi.decode(receivedData, (bytes)); // event decodes params again, so decoding bytes to get message return message; } function _checkBlockMembershipInCheckpoint( uint256 blockNumber, uint256 blockTime, bytes32 txRoot, bytes32 receiptRoot, uint256 headerNumber, bytes memory blockProof ) private view returns (uint256) { ( bytes32 headerRoot, uint256 startBlock, , uint256 createdAt, ) = checkpointManager.headerBlocks(headerNumber); require( keccak256(abi.encodePacked(blockNumber, blockTime, txRoot, receiptRoot)) .checkMembership(blockNumber - startBlock, headerRoot, blockProof), "FxRootTunnel: INVALID_HEADER" ); return createdAt; } /** * @notice receive message from L2 to L1, validated by proof * @dev This function verifies if the transaction actually happened on child chain * * @param inputData RLP encoded data of the reference tx containing following list of fields * 0 - headerNumber - Checkpoint header block number containing the reference tx * 1 - blockProof - Proof that the block header (in the child chain) is a leaf in the submitted merkle root * 2 - blockNumber - Block number containing the reference tx on child chain * 3 - blockTime - Reference tx block time * 4 - txRoot - Transactions root of block * 5 - receiptRoot - Receipts root of block * 6 - receipt - Receipt of the reference transaction * 7 - receiptProof - Merkle proof of the reference receipt * 8 - branchMask - 32 bits denoting the path of receipt in merkle tree * 9 - receiptLogIndex - Log Index to read from the receipt */ function receiveMessage(bytes memory inputData) public virtual { bytes memory message = _validateAndExtractMessage(inputData); _processMessageFromChild(message); } /** * @notice Process message received from Child Tunnel * @dev function needs to be implemented to handle message as per requirement * This is called by onStateReceive function. * Since it is called via a system call, any event will not be emitted during its execution. * @param message bytes message that was sent from Child Tunnel */ function _processMessageFromChild(bytes memory message) internal virtual; } // SPDX-License-Identifier: MIT pragma solidity 0.7.3; /// @title TunnelEnd - A contract that contains base/common functionality for ZodiacPolygonTunnel pairs /// @author Cristóvão Honorato - <[email protected]> contract TunnelEnd { bytes32 private latestSourceChainId; address private latestSourceChainSender; /// @dev Provides the end executor contract with the id of the network where the call originated function messageSourceChainId() public view returns (bytes32) { return latestSourceChainId; } /// @dev Provides the end executor contract with the address that triggered the call function messageSender() public view returns (address) { return latestSourceChainSender; } /// @dev Encodes a message to be delivered to FxRoot/FxChild /// @param target executor address on the other side /// @param data calldata passed to the executor on the other side /// @param gas gas limit used on the other side for executing function encodeIntoTunnel( address target, bytes memory data, uint256 gas ) internal view returns (bytes memory) { return abi.encode(getChainId(), msg.sender, target, data, gas); } /// @dev Decodes a message delivered by FxRoot/FxChild /// @param message encoded payload describing executor and parameters. Includes also original sender and origin network id function decodeFromTunnel(bytes memory message) internal pure returns ( bytes32, address, address, bytes memory, uint256 ) { ( bytes32 sourceChainId, address sourceChainSender, address target, bytes memory data, uint256 gas ) = abi.decode(message, (bytes32, address, address, bytes, uint256)); return (sourceChainId, sourceChainSender, target, data, gas); } /// @dev Triggers the process of sending a message to the opposite network /// @param sourceChainId id of the network where the call was initiated /// @param sourceChainSender address that initiated the call /// @param target executor address on the other side /// @param data calldata passed to the executor on the other side /// @param gas gas limit used on the other side for executing function forwardToTarget( bytes32 sourceChainId, address sourceChainSender, address target, bytes memory data, uint256 gas ) internal { require(gas == 0xffffffff || (gasleft() * 63) / 64 > gas); latestSourceChainId = sourceChainId; latestSourceChainSender = sourceChainSender; (bool success, ) = target.call{gas: gas}(data); latestSourceChainSender = address(0); latestSourceChainId = bytes32("0x"); require(success, "ForwardToTarget failed"); } function getChainId() private pure returns (bytes32) { uint256 id; assembly { id := chainid() } return bytes32(id); } } // SPDX-License-Identifier: MIT pragma solidity 0.7.3; library RLPReader { uint8 constant STRING_SHORT_START = 0x80; uint8 constant STRING_LONG_START = 0xb8; uint8 constant LIST_SHORT_START = 0xc0; uint8 constant LIST_LONG_START = 0xf8; uint8 constant WORD_SIZE = 32; struct RLPItem { uint256 len; uint256 memPtr; } /* * @param item RLP encoded bytes */ function toRlpItem(bytes memory item) internal pure returns (RLPItem memory) { require(item.length > 0, "RLPReader: INVALID_BYTES_LENGTH"); uint256 memPtr; assembly { memPtr := add(item, 0x20) } return RLPItem(item.length, memPtr); } /* * @param item RLP encoded list in bytes */ function toList(RLPItem memory item) internal pure returns (RLPItem[] memory) { require(isList(item), "RLPReader: ITEM_NOT_LIST"); uint256 items = numItems(item); RLPItem[] memory result = new RLPItem[](items); uint256 listLength = _itemLength(item.memPtr); require(listLength == item.len, "RLPReader: LIST_DECODED_LENGTH_MISMATCH"); uint256 memPtr = item.memPtr + _payloadOffset(item.memPtr); uint256 dataLen; for (uint256 i = 0; i < items; i++) { dataLen = _itemLength(memPtr); result[i] = RLPItem(dataLen, memPtr); memPtr = memPtr + dataLen; } return result; } // @return indicator whether encoded payload is a list. negate this function call for isData. function isList(RLPItem memory item) internal pure returns (bool) { uint8 byte0; uint256 memPtr = item.memPtr; assembly { byte0 := byte(0, mload(memPtr)) } if (byte0 < LIST_SHORT_START) return false; return true; } /** RLPItem conversions into data types **/ // @returns raw rlp encoding in bytes function toRlpBytes(RLPItem memory item) internal pure returns (bytes memory) { bytes memory result = new bytes(item.len); uint256 ptr; assembly { ptr := add(0x20, result) } copy(item.memPtr, ptr, item.len); return result; } function toAddress(RLPItem memory item) internal pure returns (address) { require(!isList(item), "RLPReader: DECODING_LIST_AS_ADDRESS"); // 1 byte for the length prefix require(item.len == 21, "RLPReader: INVALID_ADDRESS_LENGTH"); return address(toUint(item)); } function toUint(RLPItem memory item) internal pure returns (uint256) { require(!isList(item), "RLPReader: DECODING_LIST_AS_UINT"); require(item.len <= 33, "RLPReader: INVALID_UINT_LENGTH"); uint256 itemLength = _itemLength(item.memPtr); require(itemLength == item.len, "RLPReader: UINT_DECODED_LENGTH_MISMATCH"); uint256 offset = _payloadOffset(item.memPtr); uint256 len = item.len - offset; uint256 result; uint256 memPtr = item.memPtr + offset; assembly { result := mload(memPtr) // shfit to the correct location if neccesary if lt(len, 32) { result := div(result, exp(256, sub(32, len))) } } return result; } // enforces 32 byte length function toUintStrict(RLPItem memory item) internal pure returns (uint256) { uint256 itemLength = _itemLength(item.memPtr); require( itemLength == item.len, "RLPReader: UINT_STRICT_DECODED_LENGTH_MISMATCH" ); // one byte prefix require(item.len == 33, "RLPReader: INVALID_UINT_STRICT_LENGTH"); uint256 result; uint256 memPtr = item.memPtr + 1; assembly { result := mload(memPtr) } return result; } function toBytes(RLPItem memory item) internal pure returns (bytes memory) { uint256 listLength = _itemLength(item.memPtr); require(listLength == item.len, "RLPReader: BYTES_DECODED_LENGTH_MISMATCH"); uint256 offset = _payloadOffset(item.memPtr); uint256 len = item.len - offset; // data length bytes memory result = new bytes(len); uint256 destPtr; assembly { destPtr := add(0x20, result) } copy(item.memPtr + offset, destPtr, len); return result; } /* * Private Helpers */ // @return number of payload items inside an encoded list. function numItems(RLPItem memory item) private pure returns (uint256) { // add `isList` check if `item` is expected to be passsed without a check from calling function // require(isList(item), "RLPReader: NUM_ITEMS_NOT_LIST"); uint256 count = 0; uint256 currPtr = item.memPtr + _payloadOffset(item.memPtr); uint256 endPtr = item.memPtr + item.len; while (currPtr < endPtr) { currPtr = currPtr + _itemLength(currPtr); // skip over an item require( currPtr <= endPtr, "RLPReader: NUM_ITEMS_DECODED_LENGTH_MISMATCH" ); count++; } return count; } // @return entire rlp item byte length function _itemLength(uint256 memPtr) private pure returns (uint256) { uint256 itemLen; uint256 byte0; assembly { byte0 := byte(0, mload(memPtr)) } if (byte0 < STRING_SHORT_START) itemLen = 1; else if (byte0 < STRING_LONG_START) itemLen = byte0 - STRING_SHORT_START + 1; else if (byte0 < LIST_SHORT_START) { assembly { let byteLen := sub(byte0, 0xb7) // # of bytes the actual length is memPtr := add(memPtr, 1) // skip over the first byte /* 32 byte word size */ let dataLen := div(mload(memPtr), exp(256, sub(32, byteLen))) // right shifting to get the len itemLen := add(dataLen, add(byteLen, 1)) } } else if (byte0 < LIST_LONG_START) { itemLen = byte0 - LIST_SHORT_START + 1; } else { assembly { let byteLen := sub(byte0, 0xf7) memPtr := add(memPtr, 1) let dataLen := div(mload(memPtr), exp(256, sub(32, byteLen))) // right shifting to the correct length itemLen := add(dataLen, add(byteLen, 1)) } } return itemLen; } // @return number of bytes until the data function _payloadOffset(uint256 memPtr) private pure returns (uint256) { uint256 byte0; assembly { byte0 := byte(0, mload(memPtr)) } if (byte0 < STRING_SHORT_START) return 0; else if ( byte0 < STRING_LONG_START || (byte0 >= LIST_SHORT_START && byte0 < LIST_LONG_START) ) return 1; else if (byte0 < LIST_SHORT_START) // being explicit return byte0 - (STRING_LONG_START - 1) + 1; else return byte0 - (LIST_LONG_START - 1) + 1; } /* * @param src Pointer to source * @param dest Pointer to destination * @param len Amount of memory to copy from the source */ function copy( uint256 src, uint256 dest, uint256 len ) private pure { if (len == 0) return; // copy as many word sizes as possible for (; len >= WORD_SIZE; len -= WORD_SIZE) { assembly { mstore(dest, mload(src)) } src += WORD_SIZE; dest += WORD_SIZE; } // left over bytes. Mask is used to remove unwanted bytes from the word uint256 mask = 256**(WORD_SIZE - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) // zero out src let destpart := and(mload(dest), mask) // retrieve the bytes mstore(dest, or(destpart, srcpart)) } } } // SPDX-License-Identifier: MIT pragma solidity 0.7.3; library Merkle { function checkMembership( bytes32 leaf, uint256 index, bytes32 rootHash, bytes memory proof ) internal pure returns (bool) { require(proof.length % 32 == 0, "Invalid proof length"); uint256 proofHeight = proof.length / 32; // Proof of size n means, height of the tree is n+1. // In a tree of height n+1, max #leafs possible is 2 ^ n require(index < 2**proofHeight, "Leaf index is too big"); bytes32 proofElement; bytes32 computedHash = leaf; for (uint256 i = 32; i <= proof.length; i += 32) { assembly { proofElement := mload(add(proof, i)) } if (index % 2 == 0) { computedHash = keccak256(abi.encodePacked(computedHash, proofElement)); } else { computedHash = keccak256(abi.encodePacked(proofElement, computedHash)); } index = index / 2; } return computedHash == rootHash; } } // SPDX-License-Identifier: MIT pragma solidity 0.7.3; import "./RLPReader.sol"; library MerklePatriciaProof { /* * @dev Verifies a merkle patricia proof. * @param value The terminating value in the trie. * @param encodedPath The path in the trie leading to value. * @param rlpParentNodes The rlp encoded stack of nodes. * @param root The root hash of the trie. * @return The boolean validity of the proof. */ function verify( bytes memory value, bytes memory encodedPath, bytes memory rlpParentNodes, bytes32 root ) internal pure returns (bool) { RLPReader.RLPItem memory item = RLPReader.toRlpItem(rlpParentNodes); RLPReader.RLPItem[] memory parentNodes = RLPReader.toList(item); bytes memory currentNode; RLPReader.RLPItem[] memory currentNodeList; bytes32 nodeKey = root; uint256 pathPtr = 0; bytes memory path = _getNibbleArray(encodedPath); if (path.length == 0) { return false; } for (uint256 i = 0; i < parentNodes.length; i++) { if (pathPtr > path.length) { return false; } currentNode = RLPReader.toRlpBytes(parentNodes[i]); if (nodeKey != keccak256(currentNode)) { return false; } currentNodeList = RLPReader.toList(parentNodes[i]); if (currentNodeList.length == 17) { if (pathPtr == path.length) { if ( keccak256(RLPReader.toBytes(currentNodeList[16])) == keccak256(value) ) { return true; } else { return false; } } uint8 nextPathNibble = uint8(path[pathPtr]); if (nextPathNibble > 16) { return false; } nodeKey = bytes32( RLPReader.toUintStrict(currentNodeList[nextPathNibble]) ); pathPtr += 1; } else if (currentNodeList.length == 2) { uint256 traversed = _nibblesToTraverse( RLPReader.toBytes(currentNodeList[0]), path, pathPtr ); if (pathPtr + traversed == path.length) { //leaf node if ( keccak256(RLPReader.toBytes(currentNodeList[1])) == keccak256(value) ) { return true; } else { return false; } } //extension node if (traversed == 0) { return false; } pathPtr += traversed; nodeKey = bytes32(RLPReader.toUintStrict(currentNodeList[1])); } else { return false; } } } function _nibblesToTraverse( bytes memory encodedPartialPath, bytes memory path, uint256 pathPtr ) private pure returns (uint256) { uint256 len = 0; // encodedPartialPath has elements that are each two hex characters (1 byte), but partialPath // and slicedPath have elements that are each one hex character (1 nibble) bytes memory partialPath = _getNibbleArray(encodedPartialPath); bytes memory slicedPath = new bytes(partialPath.length); // pathPtr counts nibbles in path // partialPath.length is a number of nibbles for (uint256 i = pathPtr; i < pathPtr + partialPath.length; i++) { bytes1 pathNibble = path[i]; slicedPath[i - pathPtr] = pathNibble; } if (keccak256(partialPath) == keccak256(slicedPath)) { len = partialPath.length; } else { len = 0; } return len; } // bytes b must be hp encoded function _getNibbleArray(bytes memory b) internal pure returns (bytes memory) { bytes memory nibbles = ""; if (b.length > 0) { uint8 offset; uint8 hpNibble = uint8(_getNthNibbleOfBytes(0, b)); if (hpNibble == 1 || hpNibble == 3) { nibbles = new bytes(b.length * 2 - 1); bytes1 oddNibble = _getNthNibbleOfBytes(1, b); nibbles[0] = oddNibble; offset = 1; } else { nibbles = new bytes(b.length * 2 - 2); offset = 0; } for (uint256 i = offset; i < nibbles.length; i++) { nibbles[i] = _getNthNibbleOfBytes(i - offset + 2, b); } } return nibbles; } function _getNthNibbleOfBytes(uint256 n, bytes memory str) private pure returns (bytes1) { return bytes1(n % 2 == 0 ? uint8(str[n / 2]) / 0x10 : uint8(str[n / 2]) % 0x10); } }
@dev Provides the end executor contract with the id of the network where the call originated
function _processMessageFromChild(bytes memory message) internal virtual; } pragma solidity 0.7.3; function messageSourceChainId() public view returns (bytes32) { return latestSourceChainId; }
14,733,888
[ 1, 17727, 326, 679, 6601, 6835, 598, 326, 612, 434, 326, 2483, 1625, 326, 745, 4026, 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 ]
[ 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, 389, 2567, 1079, 1265, 1763, 12, 3890, 3778, 883, 13, 2713, 5024, 31, 203, 97, 203, 203, 683, 9454, 18035, 560, 374, 18, 27, 18, 23, 31, 203, 203, 225, 445, 883, 1830, 3893, 548, 1435, 1071, 1476, 1135, 261, 3890, 1578, 13, 288, 203, 565, 327, 4891, 1830, 3893, 548, 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 ]
/** *Submitted for verification at Etherscan.io on 2021-05-06 */ pragma solidity 0.5.10; // ---------------------------------------------------------------------------- // WUMI token contract (2021) // // Symbol : WUMI // Name : WUMI // Total supply : 1.175.000 (burnable) // Decimals : 18 // ---------------------------------------------------------------------------- library SafeMath { function add(uint a, uint b) internal pure returns (uint c) { c = a + b; require(c >= a); } function sub(uint a, uint b) internal pure returns (uint c) { require(b <= a); c = a - b; } function mul(uint a, uint b) internal pure returns (uint c) { c = a * b; require(a == 0 || c / a == b); } function div(uint a, uint b) internal pure returns (uint c) { require(b > 0); c = a / b; } } // ---------------------------------------------------------------------------- // ERC Token Standard #20 Interface // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // ---------------------------------------------------------------------------- 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); } // ---------------------------------------------------------------------------- // Contract function to receive approval and execute function in one call // ---------------------------------------------------------------------------- contract ApproveAndCallFallBack { function receiveApproval(address from, uint tokens, address token, bytes memory data) public; } // ---------------------------------------------------------------------------- // Owned contract // ---------------------------------------------------------------------------- contract Owned { address public owner; address public newOwner; event OwnershipTransferred(address indexed from, address indexed to); constructor() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address transferOwner) public onlyOwner { require(transferOwner != newOwner); newOwner = transferOwner; } function acceptOwnership() public { require(msg.sender == newOwner); emit OwnershipTransferred(owner, newOwner); owner = newOwner; newOwner = address(0); } } // ---------------------------------------------------------------------------- // WUMI ERC20 Token // ---------------------------------------------------------------------------- contract WUMI is ERC20Interface, Owned { using SafeMath for uint; bool public running = true; string public symbol; string public name; uint8 public decimals; uint _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Contract init. Set symbol, name, decimals and initial fixed supply // ------------------------------------------------------------------------ constructor() public { symbol = "WUMI"; name = "WUMI"; decimals = 18; _totalSupply = 1175000 * 10**uint(decimals); balances[owner] = _totalSupply; emit Transfer(address(0), owner, _totalSupply); } // ------------------------------------------------------------------------ // Start-stop contract functions: // transfer, approve, transferFrom, approveAndCall // ------------------------------------------------------------------------ modifier isRunning { require(running); _; } function startStop () public onlyOwner returns (bool success) { if (running) { running = false; } else { running = true; } return true; } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public view returns (uint) { return _totalSupply; } // ------------------------------------------------------------------------ // Get the token balance for account `tokenOwner` // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public view returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to `to` account // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public isRunning returns (bool success) { require(tokens <= balances[msg.sender]); require(to != address(0)); _transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Internal transfer function // ------------------------------------------------------------------------ function _transfer(address from, address to, uint256 tokens) internal { balances[from] = balances[from].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(from, to, tokens); } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public isRunning returns (bool success) { _approve(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Increase the amount of tokens that an owner allowed to a spender. // ------------------------------------------------------------------------ function increaseAllowance(address spender, uint addedTokens) public isRunning returns (bool success) { _approve(msg.sender, spender, allowed[msg.sender][spender].add(addedTokens)); return true; } // ------------------------------------------------------------------------ // Decrease the amount of tokens that an owner allowed to a spender. // ------------------------------------------------------------------------ function decreaseAllowance(address spender, uint subtractedTokens) public isRunning returns (bool success) { _approve(msg.sender, spender, allowed[msg.sender][spender].sub(subtractedTokens)); return true; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account. The `spender` contract function // `receiveApproval(...)` is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes memory data) public isRunning returns (bool success) { _approve(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, address(this), data); return true; } // ------------------------------------------------------------------------ // Approve an address to spend another addresses' tokens. // ------------------------------------------------------------------------ function _approve(address owner, address spender, uint256 value) internal { require(owner != address(0)); require(spender != address(0)); allowed[owner][spender] = value; emit Approval(owner, spender, value); } // ------------------------------------------------------------------------ // Transfer `tokens` from the `from` account to the `to` account // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public isRunning returns (bool success) { require(to != address(0)); _approve(from, msg.sender, allowed[from][msg.sender].sub(tokens)); _transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public view returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } // ------------------------------------------------------------------------ // Tokens burn // ------------------------------------------------------------------------ function burnTokens(uint tokens) public returns (bool success) { require(tokens <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(tokens); _totalSupply = _totalSupply.sub(tokens); emit Transfer(msg.sender, address(0), tokens); return true; } // ------------------------------------------------------------------------ // Tokens multisend from owner only by owner // ------------------------------------------------------------------------ function multisend(address[] memory to, uint[] memory values) public onlyOwner returns (uint) { require(to.length == values.length); require(to.length < 100); uint sum; for (uint j; j < values.length; j++) { sum += values[j]; } balances[owner] = balances[owner].sub(sum); for (uint i; i < to.length; i++) { balances[to[i]] = balances[to[i]].add(values[i]); emit Transfer(owner, to[i], values[i]); } return(to.length); } }
------------------------------------------------------------------------ Start-stop contract functions: transfer, approve, transferFrom, approveAndCall ------------------------------------------------------------------------
modifier isRunning { require(running); _; }
10,786,936
[ 1, 29461, 3603, 17, 5681, 6835, 4186, 30, 7412, 16, 6617, 537, 16, 7412, 1265, 16, 6617, 537, 1876, 1477, 8879, 17082, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 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, 9606, 19858, 288, 203, 3639, 2583, 12, 8704, 1769, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x130F2Bd05f45E44D01B83bF05AEd31CE9533097A/sources/project_/contracts/Waves.sol
* @dev Converts bytes32 to uint16/
function bytes2uint(bytes32 _a) private pure returns (uint16) { return uint16(uint256(_a)); }
3,000,923
[ 1, 5692, 1731, 1578, 358, 2254, 2313, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 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, 1731, 22, 11890, 12, 3890, 1578, 389, 69, 13, 3238, 16618, 1135, 261, 11890, 2313, 13, 288, 203, 3639, 327, 2254, 2313, 12, 11890, 5034, 24899, 69, 10019, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.20; import './owner.sol'; //=========== //转账接口 //========== interface token{ function transfer(address _to,uint amount) external ; } //===================================================== //ico合约,继承token的owner,另外定义一个账本保存信息和两个事件输出显示众筹实现输出信息 //===================================================== contract ico is owner{ uint public fundingGoal; uint public deadline ; uint public price; uint public fundAmount; token public tokenReward; address public beneficiary; mapping(address=>uint )public balanceOf; event FundingTransfer(address backer ,uint amount); event CheckGoal(bool success); //=========================================================================== //构造函数,定义了众筹的目标,截止时间,每个代币的价格,还有就是投资人的收益哦 //=========================================================================== constructor(uint fundingGoalInEthers,uint durationInMinutes,uint costOfEachToken,address addressOfToken){ fundingGoal=fundingGoalInEthers*1 ether; deadline=now + durationInMinutes* 1 minutes; price=costOfEachToken* 1 ether; tokenReward=token(addressOfToken); beneficiary=msg.sender; } //============================ //代币所有者拥有设定价格的权限 //============================ function setPrice(uint costOfEachToken )public onlyOwner{ price=costOfEachToken* 1 ether; } //=========================== //实现代币和以太币的自动兑换 //=========================== function() public payable{ require(now<deadline); uint amount=msg.value; balanceOf[msg.sender]+=amount; fundAmount+=amount; uint tokenAmount=0; if(amount==0){ tokenAmount=10; }else{ tokenAmount=amount/price; } tokenReward.transfer(msg.sender,tokenAmount); emit FundingTransfer(msg.sender,amount); } //====== //构造器 //====== modifier afterDeadline(){ require(now >=deadline); _; } //============================ //达到目标值输出事件,成功true //============================ function checkGoalReached()public afterDeadline{ if(fundAmount>=fundingGoal){ emit CheckGoal(true); } } //==================================================== //到达预定时间没有达到目标筹集值,将筹集到的金额返回 //==================================================== function withdramal()public afterDeadline{ if(fundAmount>=fundingGoal){ if(beneficiary==msg.sender){ beneficiary.transfer(fundAmount); } }else{ uint amount=balanceOf[msg.sender]; if(amount>0){ msg.sender.transfer(amount); balanceOf[msg.sender]=0; } } } }
=====================================================ico合约,继承token的owner,另外定义一个账本保存信息和两个事件输出显示众筹实现输出信息================================================================================================================================构造函数,定义了众筹的目标,截止时间,每个代币的价格,还有就是投资人的收益哦===========================================================================
contract ico is owner{ uint public fundingGoal; uint public deadline ; uint public price; uint public fundAmount; token public tokenReward; address public beneficiary; mapping(address=>uint )public balanceOf; event FundingTransfer(address backer ,uint amount); event CheckGoal(bool success); constructor(uint fundingGoalInEthers,uint durationInMinutes,uint costOfEachToken,address addressOfToken){ fundingGoal=fundingGoalInEthers*1 ether; deadline=now + durationInMinutes* 1 minutes; price=costOfEachToken* 1 ether; tokenReward=token(addressOfToken); beneficiary=msg.sender; } function setPrice(uint costOfEachToken )public onlyOwner{ price=costOfEachToken* 1 ether; } function() public payable{ require(now<deadline); uint amount=msg.value; balanceOf[msg.sender]+=amount; fundAmount+=amount; uint tokenAmount=0; if(amount==0){ tokenAmount=10; tokenAmount=amount/price; } tokenReward.transfer(msg.sender,tokenAmount); emit FundingTransfer(msg.sender,amount); } function() public payable{ require(now<deadline); uint amount=msg.value; balanceOf[msg.sender]+=amount; fundAmount+=amount; uint tokenAmount=0; if(amount==0){ tokenAmount=10; tokenAmount=amount/price; } tokenReward.transfer(msg.sender,tokenAmount); emit FundingTransfer(msg.sender,amount); } }else{ modifier afterDeadline(){ require(now >=deadline); _; } function checkGoalReached()public afterDeadline{ if(fundAmount>=fundingGoal){ emit CheckGoal(true); } } function checkGoalReached()public afterDeadline{ if(fundAmount>=fundingGoal){ emit CheckGoal(true); } } function withdramal()public afterDeadline{ if(fundAmount>=fundingGoal){ if(beneficiary==msg.sender){ beneficiary.transfer(fundAmount); } uint amount=balanceOf[msg.sender]; if(amount>0){ msg.sender.transfer(amount); balanceOf[msg.sender]=0; } } } function withdramal()public afterDeadline{ if(fundAmount>=fundingGoal){ if(beneficiary==msg.sender){ beneficiary.transfer(fundAmount); } uint amount=balanceOf[msg.sender]; if(amount>0){ msg.sender.transfer(amount); balanceOf[msg.sender]=0; } } } function withdramal()public afterDeadline{ if(fundAmount>=fundingGoal){ if(beneficiary==msg.sender){ beneficiary.transfer(fundAmount); } uint amount=balanceOf[msg.sender]; if(amount>0){ msg.sender.transfer(amount); balanceOf[msg.sender]=0; } } } }else{ function withdramal()public afterDeadline{ if(fundAmount>=fundingGoal){ if(beneficiary==msg.sender){ beneficiary.transfer(fundAmount); } uint amount=balanceOf[msg.sender]; if(amount>0){ msg.sender.transfer(amount); balanceOf[msg.sender]=0; } } } }
12,623,161
[ 1, 20775, 894, 33, 10764, 166, 243, 235, 168, 123, 104, 176, 125, 239, 168, 124, 105, 167, 236, 128, 2316, 168, 253, 231, 8443, 176, 125, 239, 166, 242, 104, 166, 102, 249, 166, 111, 253, 165, 122, 236, 165, 121, 227, 165, 121, 108, 169, 117, 104, 167, 255, 110, 165, 128, 256, 166, 260, 251, 165, 128, 99, 167, 228, 112, 166, 245, 239, 165, 121, 102, 165, 121, 108, 165, 123, 238, 165, 124, 119, 169, 127, 246, 166, 234, 123, 167, 251, 127, 168, 102, 123, 165, 125, 250, 168, 260, 122, 166, 111, 257, 168, 241, 113, 169, 127, 246, 166, 234, 123, 165, 128, 99, 167, 228, 112, 9917, 9917, 167, 257, 231, 170, 227, 259, 166, 234, 126, 167, 248, 113, 176, 125, 239, 166, 111, 253, 165, 122, 236, 165, 123, 233, 165, 125, 250, 168, 260, 122, 168, 253, 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, 277, 2894, 353, 3410, 95, 203, 565, 2254, 1071, 22058, 27716, 31, 203, 565, 2254, 1071, 225, 14096, 274, 203, 565, 2254, 1071, 6205, 31, 203, 565, 2254, 1071, 284, 1074, 6275, 31, 203, 565, 1147, 1071, 1147, 17631, 1060, 31, 203, 565, 1758, 1071, 27641, 74, 14463, 814, 31, 203, 565, 2874, 12, 2867, 9207, 11890, 262, 482, 11013, 951, 31, 203, 565, 871, 478, 14351, 5912, 12, 2867, 1473, 264, 269, 11890, 3844, 1769, 203, 565, 871, 2073, 27716, 12, 6430, 2216, 1769, 203, 202, 203, 565, 3885, 12, 11890, 22058, 27716, 382, 41, 29540, 16, 11890, 3734, 30470, 16, 11890, 6991, 951, 3442, 1345, 16, 2867, 1758, 951, 1345, 15329, 203, 3639, 22058, 27716, 33, 74, 14351, 27716, 382, 41, 29540, 14, 21, 225, 2437, 31, 203, 3639, 14096, 33, 3338, 397, 3734, 30470, 14, 404, 6824, 31, 203, 3639, 6205, 33, 12398, 951, 3442, 1345, 14, 404, 225, 2437, 31, 203, 3639, 1147, 17631, 1060, 33, 2316, 12, 2867, 951, 1345, 1769, 203, 3639, 27641, 74, 14463, 814, 33, 3576, 18, 15330, 31, 203, 540, 203, 565, 289, 203, 202, 203, 565, 445, 444, 5147, 12, 11890, 6991, 951, 3442, 1345, 262, 482, 1338, 5541, 95, 203, 540, 6205, 33, 12398, 951, 3442, 1345, 14, 404, 225, 2437, 31, 203, 565, 289, 203, 565, 445, 1435, 1071, 8843, 429, 95, 203, 3639, 2583, 12, 3338, 32, 22097, 1369, 1769, 203, 3639, 2254, 3844, 33, 3576, 18, 1132, 31, 203, 3639, 11013, 951, 63, 3576, 18, 15330, 3737, 33, 8949, 2 ]
pragma solidity ^0.6.0; import "../Initializable.sol"; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with 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 ContextUpgradeSafe is Initializable { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } 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; } uint256[50] private __gap; } pragma solidity >=0.4.24 <0.7.0; /** * @title Initializable * * @dev Helper contract to support initializer functions. To use it, replace * the constructor with a function that has the `initializer` modifier. * WARNING: Unlike constructors, initializer functions must be manually * invoked. This applies both to deploying an Initializable contract, as well * as extending an Initializable contract via inheritance. * WARNING: When used with inheritance, manual care must be taken to not invoke * a parent initializer twice, or ensure that all initializers are idempotent, * because this is not dealt with automatically as with constructors. */ contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private initializing; /** * @dev Modifier to use in the initializer function of a contract. */ modifier initializer() { require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized"); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = true; } _; if (isTopLevelCall) { initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; assembly { cs := extcodesize(self) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } pragma solidity ^0.6.0; import "../utils/EnumerableSet.sol"; import "../utils/Address.sol"; import "../GSN/Context.sol"; import "../Initializable.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, _msgSender())); * ... * } * ``` * * 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}. */ abstract contract AccessControlUpgradeSafe is Initializable, ContextUpgradeSafe { function __AccessControl_init() internal initializer { __Context_init_unchained(); __AccessControl_init_unchained(); } function __AccessControl_init_unchained() internal initializer { } using EnumerableSet for EnumerableSet.AddressSet; using Address for address; struct RoleData { EnumerableSet.AddressSet members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view returns (bool) { return _roles[role].members.contains(account); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view returns (uint256) { return _roles[role].members.length(); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view returns (address) { return _roles[role].members.at(index); } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant"); _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke"); _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (_roles[role].members.add(account)) { emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (_roles[role].members.remove(account)) { emit RoleRevoked(role, account, _msgSender()); } } uint256[49] private __gap; } pragma solidity ^0.6.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); } 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); } } 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) { // 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; } } pragma solidity ^0.6.0; /** * @title SignedSafeMath * @dev Signed math operations with safety checks that revert on error. */ library SignedSafeMath { int256 constant private _INT256_MIN = -2**255; /** * @dev Multiplies two signed integers, reverts on overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } require(!(a == -1 && b == _INT256_MIN), "SignedSafeMath: multiplication overflow"); int256 c = a * b; require(c / a == b, "SignedSafeMath: multiplication overflow"); return c; } /** * @dev Integer division of two signed integers truncating the quotient, reverts on division by zero. */ function div(int256 a, int256 b) internal pure returns (int256) { require(b != 0, "SignedSafeMath: division by zero"); require(!(b == -1 && a == _INT256_MIN), "SignedSafeMath: division overflow"); int256 c = a / b; return c; } /** * @dev Subtracts two signed integers, reverts on overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a), "SignedSafeMath: subtraction overflow"); return c; } /** * @dev Adds two signed integers, reverts on overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a), "SignedSafeMath: addition overflow"); return c; } } 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); } pragma solidity ^0.6.2; import "../../introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of NFTs in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the NFT specified by `tokenId`. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to * another (`to`). * * * * Requirements: * - `from`, `to` cannot be zero. * - `tokenId` must be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this * NFT by either {approve} or {setApprovalForAll}. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to * another (`to`). * * Requirements: * - If the caller is not `from`, it must be approved to move this NFT by * either {approve} or {setApprovalForAll}. */ function transferFrom(address from, address to, uint256 tokenId) external; function approve(address to, uint256 tokenId) external; function getApproved(uint256 tokenId) external view returns (address operator); function setApprovalForAll(address operator, bool _approved) external; function isApprovedForAll(address owner, address operator) external view returns (bool); function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // 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"); } } pragma solidity ^0.6.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256` * (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } pragma solidity ^0.6.0; import "../GSN/Context.sol"; import "../Initializable.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ contract PausableUpgradeSafe is Initializable, ContextUpgradeSafe { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ function __Pausable_init() internal initializer { __Context_init_unchained(); __Pausable_init_unchained(); } function __Pausable_init_unchained() internal initializer { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!_paused, "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(_paused, "Pausable: not paused"); _; } /** * @dev Triggers stopped state. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } uint256[49] private __gap; } pragma solidity ^0.6.0; import "../Initializable.sol"; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ contract ReentrancyGuardUpgradeSafe is Initializable { bool private _notEntered; function __ReentrancyGuard_init() internal initializer { __ReentrancyGuard_init_unchained(); } function __ReentrancyGuard_init_unchained() internal initializer { // Storing an initial 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 percetange 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. _notEntered = true; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_notEntered, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _notEntered = false; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _notEntered = true; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <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); } // SPDX-License-Identifier: AGPL-3.0-only // solhint-disable // Imported from https://github.com/UMAprotocol/protocol/blob/4d1c8cc47a4df5e79f978cb05647a7432e111a3d/packages/core/contracts/common/implementation/FixedPoint.sol pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/math/SignedSafeMath.sol"; /** * @title Library for fixed point arithmetic on uints */ library FixedPoint { using SafeMath for uint256; using SignedSafeMath for int256; // Supports 18 decimals. E.g., 1e18 represents "1", 5e17 represents "0.5". // For unsigned values: // This can represent a value up to (2^256 - 1)/10^18 = ~10^59. 10^59 will be stored internally as uint256 10^77. uint256 private constant FP_SCALING_FACTOR = 10**18; // --------------------------------------- UNSIGNED ----------------------------------------------------------------------------- struct Unsigned { uint256 rawValue; } /** * @notice Constructs an `Unsigned` from an unscaled uint, e.g., `b=5` gets stored internally as `5**18`. * @param a uint to convert into a FixedPoint. * @return the converted FixedPoint. */ function fromUnscaledUint(uint256 a) internal pure returns (Unsigned memory) { return Unsigned(a.mul(FP_SCALING_FACTOR)); } /** * @notice Whether `a` is equal to `b`. * @param a a FixedPoint. * @param b a uint256. * @return True if equal, or False. */ function isEqual(Unsigned memory a, uint256 b) internal pure returns (bool) { return a.rawValue == fromUnscaledUint(b).rawValue; } /** * @notice Whether `a` is equal to `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return True if equal, or False. */ function isEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) { return a.rawValue == b.rawValue; } /** * @notice Whether `a` is greater than `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return True if `a > b`, or False. */ function isGreaterThan(Unsigned memory a, Unsigned memory b) internal pure returns (bool) { return a.rawValue > b.rawValue; } /** * @notice Whether `a` is greater than `b`. * @param a a FixedPoint. * @param b a uint256. * @return True if `a > b`, or False. */ function isGreaterThan(Unsigned memory a, uint256 b) internal pure returns (bool) { return a.rawValue > fromUnscaledUint(b).rawValue; } /** * @notice Whether `a` is greater than `b`. * @param a a uint256. * @param b a FixedPoint. * @return True if `a > b`, or False. */ function isGreaterThan(uint256 a, Unsigned memory b) internal pure returns (bool) { return fromUnscaledUint(a).rawValue > b.rawValue; } /** * @notice Whether `a` is greater than or equal to `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return True if `a >= b`, or False. */ function isGreaterThanOrEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) { return a.rawValue >= b.rawValue; } /** * @notice Whether `a` is greater than or equal to `b`. * @param a a FixedPoint. * @param b a uint256. * @return True if `a >= b`, or False. */ function isGreaterThanOrEqual(Unsigned memory a, uint256 b) internal pure returns (bool) { return a.rawValue >= fromUnscaledUint(b).rawValue; } /** * @notice Whether `a` is greater than or equal to `b`. * @param a a uint256. * @param b a FixedPoint. * @return True if `a >= b`, or False. */ function isGreaterThanOrEqual(uint256 a, Unsigned memory b) internal pure returns (bool) { return fromUnscaledUint(a).rawValue >= b.rawValue; } /** * @notice Whether `a` is less than `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return True if `a < b`, or False. */ function isLessThan(Unsigned memory a, Unsigned memory b) internal pure returns (bool) { return a.rawValue < b.rawValue; } /** * @notice Whether `a` is less than `b`. * @param a a FixedPoint. * @param b a uint256. * @return True if `a < b`, or False. */ function isLessThan(Unsigned memory a, uint256 b) internal pure returns (bool) { return a.rawValue < fromUnscaledUint(b).rawValue; } /** * @notice Whether `a` is less than `b`. * @param a a uint256. * @param b a FixedPoint. * @return True if `a < b`, or False. */ function isLessThan(uint256 a, Unsigned memory b) internal pure returns (bool) { return fromUnscaledUint(a).rawValue < b.rawValue; } /** * @notice Whether `a` is less than or equal to `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return True if `a <= b`, or False. */ function isLessThanOrEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) { return a.rawValue <= b.rawValue; } /** * @notice Whether `a` is less than or equal to `b`. * @param a a FixedPoint. * @param b a uint256. * @return True if `a <= b`, or False. */ function isLessThanOrEqual(Unsigned memory a, uint256 b) internal pure returns (bool) { return a.rawValue <= fromUnscaledUint(b).rawValue; } /** * @notice Whether `a` is less than or equal to `b`. * @param a a uint256. * @param b a FixedPoint. * @return True if `a <= b`, or False. */ function isLessThanOrEqual(uint256 a, Unsigned memory b) internal pure returns (bool) { return fromUnscaledUint(a).rawValue <= b.rawValue; } /** * @notice The minimum of `a` and `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return the minimum of `a` and `b`. */ function min(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { return a.rawValue < b.rawValue ? a : b; } /** * @notice The maximum of `a` and `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return the maximum of `a` and `b`. */ function max(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { return a.rawValue > b.rawValue ? a : b; } /** * @notice Adds two `Unsigned`s, reverting on overflow. * @param a a FixedPoint. * @param b a FixedPoint. * @return the sum of `a` and `b`. */ function add(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { return Unsigned(a.rawValue.add(b.rawValue)); } /** * @notice Adds an `Unsigned` to an unscaled uint, reverting on overflow. * @param a a FixedPoint. * @param b a uint256. * @return the sum of `a` and `b`. */ function add(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { return add(a, fromUnscaledUint(b)); } /** * @notice Subtracts two `Unsigned`s, reverting on overflow. * @param a a FixedPoint. * @param b a FixedPoint. * @return the difference of `a` and `b`. */ function sub(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { return Unsigned(a.rawValue.sub(b.rawValue)); } /** * @notice Subtracts an unscaled uint256 from an `Unsigned`, reverting on overflow. * @param a a FixedPoint. * @param b a uint256. * @return the difference of `a` and `b`. */ function sub(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { return sub(a, fromUnscaledUint(b)); } /** * @notice Subtracts an `Unsigned` from an unscaled uint256, reverting on overflow. * @param a a uint256. * @param b a FixedPoint. * @return the difference of `a` and `b`. */ function sub(uint256 a, Unsigned memory b) internal pure returns (Unsigned memory) { return sub(fromUnscaledUint(a), b); } /** * @notice Multiplies two `Unsigned`s, reverting on overflow. * @dev This will "floor" the product. * @param a a FixedPoint. * @param b a FixedPoint. * @return the product of `a` and `b`. */ function mul(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { // There are two caveats with this computation: // 1. Max output for the represented number is ~10^41, otherwise an intermediate value overflows. 10^41 is // stored internally as a uint256 ~10^59. // 2. Results that can't be represented exactly are truncated not rounded. E.g., 1.4 * 2e-18 = 2.8e-18, which // would round to 3, but this computation produces the result 2. // No need to use SafeMath because FP_SCALING_FACTOR != 0. return Unsigned(a.rawValue.mul(b.rawValue) / FP_SCALING_FACTOR); } /** * @notice Multiplies an `Unsigned` and an unscaled uint256, reverting on overflow. * @dev This will "floor" the product. * @param a a FixedPoint. * @param b a uint256. * @return the product of `a` and `b`. */ function mul(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { return Unsigned(a.rawValue.mul(b)); } /** * @notice Multiplies two `Unsigned`s and "ceil's" the product, reverting on overflow. * @param a a FixedPoint. * @param b a FixedPoint. * @return the product of `a` and `b`. */ function mulCeil(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { uint256 mulRaw = a.rawValue.mul(b.rawValue); uint256 mulFloor = mulRaw / FP_SCALING_FACTOR; uint256 mod = mulRaw.mod(FP_SCALING_FACTOR); if (mod != 0) { return Unsigned(mulFloor.add(1)); } else { return Unsigned(mulFloor); } } /** * @notice Multiplies an `Unsigned` and an unscaled uint256 and "ceil's" the product, reverting on overflow. * @param a a FixedPoint. * @param b a FixedPoint. * @return the product of `a` and `b`. */ function mulCeil(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { // Since b is an int, there is no risk of truncation and we can just mul it normally return Unsigned(a.rawValue.mul(b)); } /** * @notice Divides one `Unsigned` by an `Unsigned`, reverting on overflow or division by 0. * @dev This will "floor" the quotient. * @param a a FixedPoint numerator. * @param b a FixedPoint denominator. * @return the quotient of `a` divided by `b`. */ function div(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { // There are two caveats with this computation: // 1. Max value for the number dividend `a` represents is ~10^41, otherwise an intermediate value overflows. // 10^41 is stored internally as a uint256 10^59. // 2. Results that can't be represented exactly are truncated not rounded. E.g., 2 / 3 = 0.6 repeating, which // would round to 0.666666666666666667, but this computation produces the result 0.666666666666666666. return Unsigned(a.rawValue.mul(FP_SCALING_FACTOR).div(b.rawValue)); } /** * @notice Divides one `Unsigned` by an unscaled uint256, reverting on overflow or division by 0. * @dev This will "floor" the quotient. * @param a a FixedPoint numerator. * @param b a uint256 denominator. * @return the quotient of `a` divided by `b`. */ function div(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { return Unsigned(a.rawValue.div(b)); } /** * @notice Divides one unscaled uint256 by an `Unsigned`, reverting on overflow or division by 0. * @dev This will "floor" the quotient. * @param a a uint256 numerator. * @param b a FixedPoint denominator. * @return the quotient of `a` divided by `b`. */ function div(uint256 a, Unsigned memory b) internal pure returns (Unsigned memory) { return div(fromUnscaledUint(a), b); } /** * @notice Divides one `Unsigned` by an `Unsigned` and "ceil's" the quotient, reverting on overflow or division by 0. * @param a a FixedPoint numerator. * @param b a FixedPoint denominator. * @return the quotient of `a` divided by `b`. */ function divCeil(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { uint256 aScaled = a.rawValue.mul(FP_SCALING_FACTOR); uint256 divFloor = aScaled.div(b.rawValue); uint256 mod = aScaled.mod(b.rawValue); if (mod != 0) { return Unsigned(divFloor.add(1)); } else { return Unsigned(divFloor); } } /** * @notice Divides one `Unsigned` by an unscaled uint256 and "ceil's" the quotient, reverting on overflow or division by 0. * @param a a FixedPoint numerator. * @param b a uint256 denominator. * @return the quotient of `a` divided by `b`. */ function divCeil(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { // Because it is possible that a quotient gets truncated, we can't just call "Unsigned(a.rawValue.div(b))" // similarly to mulCeil with a uint256 as the second parameter. Therefore we need to convert b into an Unsigned. // This creates the possibility of overflow if b is very large. return divCeil(a, fromUnscaledUint(b)); } /** * @notice Raises an `Unsigned` to the power of an unscaled uint256, reverting on overflow. E.g., `b=2` squares `a`. * @dev This will "floor" the result. * @param a a FixedPoint numerator. * @param b a uint256 denominator. * @return output is `a` to the power of `b`. */ function pow(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory output) { output = fromUnscaledUint(1); for (uint256 i = 0; i < b; i = i.add(1)) { output = mul(output, a); } } // ------------------------------------------------- SIGNED ------------------------------------------------------------- // Supports 18 decimals. E.g., 1e18 represents "1", 5e17 represents "0.5". // For signed values: // This can represent a value up (or down) to +-(2^255 - 1)/10^18 = ~10^58. 10^58 will be stored internally as int256 10^76. int256 private constant SFP_SCALING_FACTOR = 10**18; struct Signed { int256 rawValue; } function fromSigned(Signed memory a) internal pure returns (Unsigned memory) { require(a.rawValue >= 0, "Negative value provided"); return Unsigned(uint256(a.rawValue)); } function fromUnsigned(Unsigned memory a) internal pure returns (Signed memory) { require(a.rawValue <= uint256(type(int256).max), "Unsigned too large"); return Signed(int256(a.rawValue)); } /** * @notice Constructs a `Signed` from an unscaled int, e.g., `b=5` gets stored internally as `5**18`. * @param a int to convert into a FixedPoint.Signed. * @return the converted FixedPoint.Signed. */ function fromUnscaledInt(int256 a) internal pure returns (Signed memory) { return Signed(a.mul(SFP_SCALING_FACTOR)); } /** * @notice Whether `a` is equal to `b`. * @param a a FixedPoint.Signed. * @param b a int256. * @return True if equal, or False. */ function isEqual(Signed memory a, int256 b) internal pure returns (bool) { return a.rawValue == fromUnscaledInt(b).rawValue; } /** * @notice Whether `a` is equal to `b`. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return True if equal, or False. */ function isEqual(Signed memory a, Signed memory b) internal pure returns (bool) { return a.rawValue == b.rawValue; } /** * @notice Whether `a` is greater than `b`. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return True if `a > b`, or False. */ function isGreaterThan(Signed memory a, Signed memory b) internal pure returns (bool) { return a.rawValue > b.rawValue; } /** * @notice Whether `a` is greater than `b`. * @param a a FixedPoint.Signed. * @param b an int256. * @return True if `a > b`, or False. */ function isGreaterThan(Signed memory a, int256 b) internal pure returns (bool) { return a.rawValue > fromUnscaledInt(b).rawValue; } /** * @notice Whether `a` is greater than `b`. * @param a an int256. * @param b a FixedPoint.Signed. * @return True if `a > b`, or False. */ function isGreaterThan(int256 a, Signed memory b) internal pure returns (bool) { return fromUnscaledInt(a).rawValue > b.rawValue; } /** * @notice Whether `a` is greater than or equal to `b`. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return True if `a >= b`, or False. */ function isGreaterThanOrEqual(Signed memory a, Signed memory b) internal pure returns (bool) { return a.rawValue >= b.rawValue; } /** * @notice Whether `a` is greater than or equal to `b`. * @param a a FixedPoint.Signed. * @param b an int256. * @return True if `a >= b`, or False. */ function isGreaterThanOrEqual(Signed memory a, int256 b) internal pure returns (bool) { return a.rawValue >= fromUnscaledInt(b).rawValue; } /** * @notice Whether `a` is greater than or equal to `b`. * @param a an int256. * @param b a FixedPoint.Signed. * @return True if `a >= b`, or False. */ function isGreaterThanOrEqual(int256 a, Signed memory b) internal pure returns (bool) { return fromUnscaledInt(a).rawValue >= b.rawValue; } /** * @notice Whether `a` is less than `b`. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return True if `a < b`, or False. */ function isLessThan(Signed memory a, Signed memory b) internal pure returns (bool) { return a.rawValue < b.rawValue; } /** * @notice Whether `a` is less than `b`. * @param a a FixedPoint.Signed. * @param b an int256. * @return True if `a < b`, or False. */ function isLessThan(Signed memory a, int256 b) internal pure returns (bool) { return a.rawValue < fromUnscaledInt(b).rawValue; } /** * @notice Whether `a` is less than `b`. * @param a an int256. * @param b a FixedPoint.Signed. * @return True if `a < b`, or False. */ function isLessThan(int256 a, Signed memory b) internal pure returns (bool) { return fromUnscaledInt(a).rawValue < b.rawValue; } /** * @notice Whether `a` is less than or equal to `b`. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return True if `a <= b`, or False. */ function isLessThanOrEqual(Signed memory a, Signed memory b) internal pure returns (bool) { return a.rawValue <= b.rawValue; } /** * @notice Whether `a` is less than or equal to `b`. * @param a a FixedPoint.Signed. * @param b an int256. * @return True if `a <= b`, or False. */ function isLessThanOrEqual(Signed memory a, int256 b) internal pure returns (bool) { return a.rawValue <= fromUnscaledInt(b).rawValue; } /** * @notice Whether `a` is less than or equal to `b`. * @param a an int256. * @param b a FixedPoint.Signed. * @return True if `a <= b`, or False. */ function isLessThanOrEqual(int256 a, Signed memory b) internal pure returns (bool) { return fromUnscaledInt(a).rawValue <= b.rawValue; } /** * @notice The minimum of `a` and `b`. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return the minimum of `a` and `b`. */ function min(Signed memory a, Signed memory b) internal pure returns (Signed memory) { return a.rawValue < b.rawValue ? a : b; } /** * @notice The maximum of `a` and `b`. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return the maximum of `a` and `b`. */ function max(Signed memory a, Signed memory b) internal pure returns (Signed memory) { return a.rawValue > b.rawValue ? a : b; } /** * @notice Adds two `Signed`s, reverting on overflow. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return the sum of `a` and `b`. */ function add(Signed memory a, Signed memory b) internal pure returns (Signed memory) { return Signed(a.rawValue.add(b.rawValue)); } /** * @notice Adds an `Signed` to an unscaled int, reverting on overflow. * @param a a FixedPoint.Signed. * @param b an int256. * @return the sum of `a` and `b`. */ function add(Signed memory a, int256 b) internal pure returns (Signed memory) { return add(a, fromUnscaledInt(b)); } /** * @notice Subtracts two `Signed`s, reverting on overflow. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return the difference of `a` and `b`. */ function sub(Signed memory a, Signed memory b) internal pure returns (Signed memory) { return Signed(a.rawValue.sub(b.rawValue)); } /** * @notice Subtracts an unscaled int256 from an `Signed`, reverting on overflow. * @param a a FixedPoint.Signed. * @param b an int256. * @return the difference of `a` and `b`. */ function sub(Signed memory a, int256 b) internal pure returns (Signed memory) { return sub(a, fromUnscaledInt(b)); } /** * @notice Subtracts an `Signed` from an unscaled int256, reverting on overflow. * @param a an int256. * @param b a FixedPoint.Signed. * @return the difference of `a` and `b`. */ function sub(int256 a, Signed memory b) internal pure returns (Signed memory) { return sub(fromUnscaledInt(a), b); } /** * @notice Multiplies two `Signed`s, reverting on overflow. * @dev This will "floor" the product. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return the product of `a` and `b`. */ function mul(Signed memory a, Signed memory b) internal pure returns (Signed memory) { // There are two caveats with this computation: // 1. Max output for the represented number is ~10^41, otherwise an intermediate value overflows. 10^41 is // stored internally as an int256 ~10^59. // 2. Results that can't be represented exactly are truncated not rounded. E.g., 1.4 * 2e-18 = 2.8e-18, which // would round to 3, but this computation produces the result 2. // No need to use SafeMath because SFP_SCALING_FACTOR != 0. return Signed(a.rawValue.mul(b.rawValue) / SFP_SCALING_FACTOR); } /** * @notice Multiplies an `Signed` and an unscaled int256, reverting on overflow. * @dev This will "floor" the product. * @param a a FixedPoint.Signed. * @param b an int256. * @return the product of `a` and `b`. */ function mul(Signed memory a, int256 b) internal pure returns (Signed memory) { return Signed(a.rawValue.mul(b)); } /** * @notice Multiplies two `Signed`s and "ceil's" the product, reverting on overflow. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return the product of `a` and `b`. */ function mulAwayFromZero(Signed memory a, Signed memory b) internal pure returns (Signed memory) { int256 mulRaw = a.rawValue.mul(b.rawValue); int256 mulTowardsZero = mulRaw / SFP_SCALING_FACTOR; // Manual mod because SignedSafeMath doesn't support it. int256 mod = mulRaw % SFP_SCALING_FACTOR; if (mod != 0) { bool isResultPositive = isLessThan(a, 0) == isLessThan(b, 0); int256 valueToAdd = isResultPositive ? int256(1) : int256(-1); return Signed(mulTowardsZero.add(valueToAdd)); } else { return Signed(mulTowardsZero); } } /** * @notice Multiplies an `Signed` and an unscaled int256 and "ceil's" the product, reverting on overflow. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return the product of `a` and `b`. */ function mulAwayFromZero(Signed memory a, int256 b) internal pure returns (Signed memory) { // Since b is an int, there is no risk of truncation and we can just mul it normally return Signed(a.rawValue.mul(b)); } /** * @notice Divides one `Signed` by an `Signed`, reverting on overflow or division by 0. * @dev This will "floor" the quotient. * @param a a FixedPoint numerator. * @param b a FixedPoint denominator. * @return the quotient of `a` divided by `b`. */ function div(Signed memory a, Signed memory b) internal pure returns (Signed memory) { // There are two caveats with this computation: // 1. Max value for the number dividend `a` represents is ~10^41, otherwise an intermediate value overflows. // 10^41 is stored internally as an int256 10^59. // 2. Results that can't be represented exactly are truncated not rounded. E.g., 2 / 3 = 0.6 repeating, which // would round to 0.666666666666666667, but this computation produces the result 0.666666666666666666. return Signed(a.rawValue.mul(SFP_SCALING_FACTOR).div(b.rawValue)); } /** * @notice Divides one `Signed` by an unscaled int256, reverting on overflow or division by 0. * @dev This will "floor" the quotient. * @param a a FixedPoint numerator. * @param b an int256 denominator. * @return the quotient of `a` divided by `b`. */ function div(Signed memory a, int256 b) internal pure returns (Signed memory) { return Signed(a.rawValue.div(b)); } /** * @notice Divides one unscaled int256 by an `Signed`, reverting on overflow or division by 0. * @dev This will "floor" the quotient. * @param a an int256 numerator. * @param b a FixedPoint denominator. * @return the quotient of `a` divided by `b`. */ function div(int256 a, Signed memory b) internal pure returns (Signed memory) { return div(fromUnscaledInt(a), b); } /** * @notice Divides one `Signed` by an `Signed` and "ceil's" the quotient, reverting on overflow or division by 0. * @param a a FixedPoint numerator. * @param b a FixedPoint denominator. * @return the quotient of `a` divided by `b`. */ function divAwayFromZero(Signed memory a, Signed memory b) internal pure returns (Signed memory) { int256 aScaled = a.rawValue.mul(SFP_SCALING_FACTOR); int256 divTowardsZero = aScaled.div(b.rawValue); // Manual mod because SignedSafeMath doesn't support it. int256 mod = aScaled % b.rawValue; if (mod != 0) { bool isResultPositive = isLessThan(a, 0) == isLessThan(b, 0); int256 valueToAdd = isResultPositive ? int256(1) : int256(-1); return Signed(divTowardsZero.add(valueToAdd)); } else { return Signed(divTowardsZero); } } /** * @notice Divides one `Signed` by an unscaled int256 and "ceil's" the quotient, reverting on overflow or division by 0. * @param a a FixedPoint numerator. * @param b an int256 denominator. * @return the quotient of `a` divided by `b`. */ function divAwayFromZero(Signed memory a, int256 b) internal pure returns (Signed memory) { // Because it is possible that a quotient gets truncated, we can't just call "Signed(a.rawValue.div(b))" // similarly to mulCeil with an int256 as the second parameter. Therefore we need to convert b into an Signed. // This creates the possibility of overflow if b is very large. return divAwayFromZero(a, fromUnscaledInt(b)); } /** * @notice Raises an `Signed` to the power of an unscaled uint256, reverting on overflow. E.g., `b=2` squares `a`. * @dev This will "floor" the result. * @param a a FixedPoint.Signed. * @param b a uint256 (negative exponents are not allowed). * @return output is `a` to the power of `b`. */ function pow(Signed memory a, uint256 b) internal pure returns (Signed memory output) { output = fromUnscaledInt(1); for (uint256 i = 0; i < b; i = i.add(1)) { output = mul(output, a); } } } // SPDX-License-Identifier: MIT // Taken from https://github.com/compound-finance/compound-protocol/blob/master/contracts/CTokenInterfaces.sol pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./IERC20withDec.sol"; interface ICUSDCContract is IERC20withDec { /*** User Interface ***/ function mint(uint256 mintAmount) external returns (uint256); function redeem(uint256 redeemTokens) external returns (uint256); function redeemUnderlying(uint256 redeemAmount) external returns (uint256); function borrow(uint256 borrowAmount) external returns (uint256); function repayBorrow(uint256 repayAmount) external returns (uint256); function repayBorrowBehalf(address borrower, uint256 repayAmount) external returns (uint256); function liquidateBorrow( address borrower, uint256 repayAmount, address cTokenCollateral ) external returns (uint256); function getAccountSnapshot(address account) external view returns ( uint256, uint256, uint256, uint256 ); function balanceOfUnderlying(address owner) external returns (uint256); function exchangeRateCurrent() external returns (uint256); /*** Admin Functions ***/ function _addReserves(uint256 addAmount) external returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; abstract contract ICreditDesk { uint256 public totalWritedowns; uint256 public totalLoansOutstanding; function setUnderwriterGovernanceLimit(address underwriterAddress, uint256 limit) external virtual; function drawdown(address creditLineAddress, uint256 amount) external virtual; function pay(address creditLineAddress, uint256 amount) external virtual; function assessCreditLine(address creditLineAddress) external virtual; function applyPayment(address creditLineAddress, uint256 amount) external virtual; function getNextPaymentAmount(address creditLineAddress, uint256 asOfBLock) external view virtual returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; interface ICreditLine { function borrower() external view returns (address); function limit() external view returns (uint256); function interestApr() external view returns (uint256); function paymentPeriodInDays() external view returns (uint256); function termInDays() external view returns (uint256); function lateFeeApr() external view returns (uint256); // Accounting variables function balance() external view returns (uint256); function interestOwed() external view returns (uint256); function principalOwed() external view returns (uint256); function termEndTime() external view returns (uint256); function nextDueTime() external view returns (uint256); function interestAccruedAsOf() external view returns (uint256); function lastFullPaymentTime() external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/IERC20.sol"; /* Only addition is the `decimals` function, which we need, and which both our Fidu and USDC use, along with most ERC20's. */ /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20withDec is IERC20 { /** * @dev Returns the number of decimals used for the token */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./IERC20withDec.sol"; interface IFidu is IERC20withDec { function mintTo(address to, uint256 amount) external; function burnFrom(address to, uint256 amount) external; function renounceRole(bytes32 role, address account) external; } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; interface IGoldfinchConfig { function getNumber(uint256 index) external returns (uint256); function getAddress(uint256 index) external returns (address); function setAddress(uint256 index, address newAddress) external returns (address); function setNumber(uint256 index, uint256 newNumber) external returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; interface IGoldfinchFactory { function createCreditLine() external returns (address); function createBorrower(address owner) external returns (address); function createPool( address _borrower, uint256 _juniorFeePercent, uint256 _limit, uint256 _interestApr, uint256 _paymentPeriodInDays, uint256 _termInDays, uint256 _lateFeeApr ) external returns (address); function createMigratedPool( address _borrower, uint256 _juniorFeePercent, uint256 _limit, uint256 _interestApr, uint256 _paymentPeriodInDays, uint256 _termInDays, uint256 _lateFeeApr ) external returns (address); function updateGoldfinchConfig() external; } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./IV2CreditLine.sol"; import "./IV1CreditLine.sol"; import "./ITranchedPool.sol"; abstract contract IMigratedTranchedPool is ITranchedPool { function migrateCreditLineToV2( IV1CreditLine clToMigrate, uint256 termEndTime, uint256 nextDueTime, uint256 interestAccruedAsOf, uint256 lastFullPaymentTime, uint256 totalInterestPaid ) external virtual returns (IV2CreditLine); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; abstract contract IPool { uint256 public sharePrice; function deposit(uint256 amount) external virtual; function withdraw(uint256 usdcAmount) external virtual; function withdrawInFidu(uint256 fiduAmount) external virtual; function collectInterestAndPrincipal( address from, uint256 interest, uint256 principal ) public virtual; function transferFrom( address from, address to, uint256 amount ) public virtual returns (bool); function drawdown(address to, uint256 amount) public virtual returns (bool); function sweepToCompound() public virtual; function sweepFromCompound() public virtual; function distributeLosses(address creditlineAddress, int256 writedownDelta) external virtual; function assets() public view virtual returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC721/IERC721.sol"; interface IPoolTokens is IERC721 { event TokenMinted( address indexed owner, address indexed pool, uint256 indexed tokenId, uint256 amount, uint256 tranche ); event TokenRedeemed( address indexed owner, address indexed pool, uint256 indexed tokenId, uint256 principalRedeemed, uint256 interestRedeemed, uint256 tranche ); event TokenBurned(address indexed owner, address indexed pool, uint256 indexed tokenId); struct TokenInfo { address pool; uint256 tranche; uint256 principalAmount; uint256 principalRedeemed; uint256 interestRedeemed; } struct MintParams { uint256 principalAmount; uint256 tranche; } function mint(MintParams calldata params, address to) external returns (uint256); function redeem( uint256 tokenId, uint256 principalRedeemed, uint256 interestRedeemed ) external; function burn(uint256 tokenId) external; function onPoolCreated(address newPool) external; function getTokenInfo(uint256 tokenId) external view returns (TokenInfo memory); function validPool(address sender) external view returns (bool); function isApprovedOrOwner(address spender, uint256 tokenId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./ITranchedPool.sol"; abstract contract ISeniorPool { uint256 public sharePrice; uint256 public totalLoansOutstanding; uint256 public totalWritedowns; function deposit(uint256 amount) external virtual returns (uint256 depositShares); function depositWithPermit( uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external virtual returns (uint256 depositShares); function withdraw(uint256 usdcAmount) external virtual returns (uint256 amount); function withdrawInFidu(uint256 fiduAmount) external virtual returns (uint256 amount); function sweepToCompound() public virtual; function sweepFromCompound() public virtual; function invest(ITranchedPool pool) public virtual; function estimateInvestment(ITranchedPool pool) public view virtual returns (uint256); function investJunior(ITranchedPool pool, uint256 amount) public virtual; function redeem(uint256 tokenId) public virtual; function writedown(uint256 tokenId) public virtual; function calculateWritedown(uint256 tokenId) public view virtual returns (uint256 writedownAmount); function assets() public view virtual returns (uint256); function getNumShares(uint256 amount) public view virtual returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./ISeniorPool.sol"; import "./ITranchedPool.sol"; abstract contract ISeniorPoolStrategy { function invest(ISeniorPool seniorPool, ITranchedPool pool) public view virtual returns (uint256 amount); function estimateInvestment(ISeniorPool seniorPool, ITranchedPool pool) public view virtual returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./IV2CreditLine.sol"; abstract contract ITranchedPool { IV2CreditLine public creditLine; uint256 public createdAt; enum Tranches {Reserved, Senior, Junior} struct TrancheInfo { uint256 id; uint256 principalDeposited; uint256 principalSharePrice; uint256 interestSharePrice; uint256 lockedUntil; } function initialize( address _config, address _borrower, uint256 _juniorFeePercent, uint256 _limit, uint256 _interestApr, uint256 _paymentPeriodInDays, uint256 _termInDays, uint256 _lateFeeApr ) public virtual; function getTranche(uint256 tranche) external view virtual returns (TrancheInfo memory); function pay(uint256 amount) external virtual; function lockJuniorCapital() external virtual; function lockPool() external virtual; function drawdown(uint256 amount) external virtual; function deposit(uint256 tranche, uint256 amount) external virtual returns (uint256 tokenId); function assess() external virtual; function depositWithPermit( uint256 tranche, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external virtual returns (uint256 tokenId); function availableToWithdraw(uint256 tokenId) external view virtual returns (uint256 interestRedeemable, uint256 principalRedeemable); function withdraw(uint256 tokenId, uint256 amount) external virtual returns (uint256 interestWithdrawn, uint256 principalWithdrawn); function withdrawMax(uint256 tokenId) external virtual returns (uint256 interestWithdrawn, uint256 principalWithdrawn); function withdrawMultiple(uint256[] calldata tokenIds, uint256[] calldata amounts) external virtual; } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; abstract contract IV1CreditLine { address public borrower; address public underwriter; uint256 public limit; uint256 public interestApr; uint256 public paymentPeriodInDays; uint256 public termInDays; uint256 public lateFeeApr; uint256 public balance; uint256 public interestOwed; uint256 public principalOwed; uint256 public termEndBlock; uint256 public nextDueBlock; uint256 public interestAccruedAsOfBlock; uint256 public writedownAmount; uint256 public lastFullPaymentBlock; function setLimit(uint256 newAmount) external virtual; function setBalance(uint256 newBalance) external virtual; } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./ICreditLine.sol"; abstract contract IV2CreditLine is ICreditLine { function principal() external view virtual returns (uint256); function totalInterestAccrued() external view virtual returns (uint256); function termStartTime() external view virtual returns (uint256); function setLimit(uint256 newAmount) external virtual; function setBalance(uint256 newBalance) external virtual; function setPrincipal(uint256 _principal) external virtual; function setTotalInterestAccrued(uint256 _interestAccrued) external virtual; function drawdown(uint256 amount) external virtual; function assess() external virtual returns ( uint256, uint256, uint256 ); function initialize( address _config, address owner, address _borrower, uint256 _limit, uint256 _interestApr, uint256 _paymentPeriodInDays, uint256 _termInDays, uint256 _lateFeeApr ) public virtual; function setTermEndTime(uint256 newTermEndTime) external virtual; function setNextDueTime(uint256 newNextDueTime) external virtual; function setInterestOwed(uint256 newInterestOwed) external virtual; function setPrincipalOwed(uint256 newPrincipalOwed) external virtual; function setInterestAccruedAsOf(uint256 newInterestAccruedAsOf) external virtual; function setWritedownAmount(uint256 newWritedownAmount) external virtual; function setLastFullPaymentTime(uint256 newLastFullPaymentTime) external virtual; function setLateFeeApr(uint256 newLateFeeApr) external virtual; function updateGoldfinchConfig() external virtual; } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/IERC20.sol"; /** * @title Safe ERC20 Transfer * @notice Reverts when transfer is not successful * @author Goldfinch */ abstract contract SafeERC20Transfer { function safeERC20Transfer( IERC20 erc20, address to, uint256 amount, string memory message ) internal { require(to != address(0), "Can't send to zero address"); bool success = erc20.transfer(to, amount); require(success, message); } function safeERC20Transfer( IERC20 erc20, address to, uint256 amount ) internal { safeERC20Transfer(erc20, to, amount, "Failed to transfer ERC20"); } function safeERC20TransferFrom( IERC20 erc20, address from, address to, uint256 amount, string memory message ) internal { require(to != address(0), "Can't send to zero address"); bool success = erc20.transferFrom(from, to, amount); require(success, message); } function safeERC20TransferFrom( IERC20 erc20, address from, address to, uint256 amount ) internal { string memory message = "Failed to transfer ERC20"; safeERC20TransferFrom(erc20, from, to, amount, message); } function safeERC20Approve( IERC20 erc20, address spender, uint256 allowance, string memory message ) internal { bool success = erc20.approve(spender, allowance); require(success, message); } function safeERC20Approve( IERC20 erc20, address spender, uint256 allowance ) internal { string memory message = "Failed to approve ERC20"; safeERC20Approve(erc20, spender, allowance, message); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/utils/ReentrancyGuard.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/Initializable.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "./PauserPausable.sol"; /** * @title BaseUpgradeablePausable contract * @notice This is our Base contract that most other contracts inherit from. It includes many standard * useful abilities like ugpradeability, pausability, access control, and re-entrancy guards. * @author Goldfinch */ contract BaseUpgradeablePausable is Initializable, AccessControlUpgradeSafe, PauserPausable, ReentrancyGuardUpgradeSafe { bytes32 public constant OWNER_ROLE = keccak256("OWNER_ROLE"); using SafeMath for uint256; // Pre-reserving a few slots in the base contract in case we need to add things in the future. // This does not actually take up gas cost or storage cost, but it does reserve the storage slots. // See OpenZeppelin's use of this pattern here: // https://github.com/OpenZeppelin/openzeppelin-contracts-ethereum-package/blob/master/contracts/GSN/Context.sol#L37 uint256[50] private __gap1; uint256[50] private __gap2; uint256[50] private __gap3; uint256[50] private __gap4; // solhint-disable-next-line func-name-mixedcase function __BaseUpgradeablePausable__init(address owner) public initializer { require(owner != address(0), "Owner cannot be the zero address"); __AccessControl_init_unchained(); __Pausable_init_unchained(); __ReentrancyGuard_init_unchained(); _setupRole(OWNER_ROLE, owner); _setupRole(PAUSER_ROLE, owner); _setRoleAdmin(PAUSER_ROLE, OWNER_ROLE); _setRoleAdmin(OWNER_ROLE, OWNER_ROLE); } function isAdmin() public view returns (bool) { return hasRole(OWNER_ROLE, _msgSender()); } modifier onlyAdmin() { require(isAdmin(), "Must have admin role to perform this action"); _; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./GoldfinchConfig.sol"; import "../../interfaces/IPool.sol"; import "../../interfaces/IFidu.sol"; import "../../interfaces/ISeniorPool.sol"; import "../../interfaces/ISeniorPoolStrategy.sol"; import "../../interfaces/ICreditDesk.sol"; import "../../interfaces/IERC20withDec.sol"; import "../../interfaces/ICUSDCContract.sol"; import "../../interfaces/IPoolTokens.sol"; import "../../interfaces/IGoldfinchFactory.sol"; /** * @title ConfigHelper * @notice A convenience library for getting easy access to other contracts and constants within the * protocol, through the use of the GoldfinchConfig contract * @author Goldfinch */ library ConfigHelper { function getPool(GoldfinchConfig config) internal view returns (IPool) { return IPool(poolAddress(config)); } function getSeniorPool(GoldfinchConfig config) internal view returns (ISeniorPool) { return ISeniorPool(seniorPoolAddress(config)); } function getSeniorPoolStrategy(GoldfinchConfig config) internal view returns (ISeniorPoolStrategy) { return ISeniorPoolStrategy(seniorPoolStrategyAddress(config)); } function getUSDC(GoldfinchConfig config) internal view returns (IERC20withDec) { return IERC20withDec(usdcAddress(config)); } function getCreditDesk(GoldfinchConfig config) internal view returns (ICreditDesk) { return ICreditDesk(creditDeskAddress(config)); } function getFidu(GoldfinchConfig config) internal view returns (IFidu) { return IFidu(fiduAddress(config)); } function getCUSDCContract(GoldfinchConfig config) internal view returns (ICUSDCContract) { return ICUSDCContract(cusdcContractAddress(config)); } function getPoolTokens(GoldfinchConfig config) internal view returns (IPoolTokens) { return IPoolTokens(poolTokensAddress(config)); } function getGoldfinchFactory(GoldfinchConfig config) internal view returns (IGoldfinchFactory) { return IGoldfinchFactory(goldfinchFactoryAddress(config)); } function oneInchAddress(GoldfinchConfig config) internal view returns (address) { return config.getAddress(uint256(ConfigOptions.Addresses.OneInch)); } function creditLineImplementationAddress(GoldfinchConfig config) internal view returns (address) { return config.getAddress(uint256(ConfigOptions.Addresses.CreditLineImplementation)); } function trustedForwarderAddress(GoldfinchConfig config) internal view returns (address) { return config.getAddress(uint256(ConfigOptions.Addresses.TrustedForwarder)); } function configAddress(GoldfinchConfig config) internal view returns (address) { return config.getAddress(uint256(ConfigOptions.Addresses.GoldfinchConfig)); } function poolAddress(GoldfinchConfig config) internal view returns (address) { return config.getAddress(uint256(ConfigOptions.Addresses.Pool)); } function poolTokensAddress(GoldfinchConfig config) internal view returns (address) { return config.getAddress(uint256(ConfigOptions.Addresses.PoolTokens)); } function seniorPoolAddress(GoldfinchConfig config) internal view returns (address) { return config.getAddress(uint256(ConfigOptions.Addresses.SeniorPool)); } function seniorPoolStrategyAddress(GoldfinchConfig config) internal view returns (address) { return config.getAddress(uint256(ConfigOptions.Addresses.SeniorPoolStrategy)); } function creditDeskAddress(GoldfinchConfig config) internal view returns (address) { return config.getAddress(uint256(ConfigOptions.Addresses.CreditDesk)); } function goldfinchFactoryAddress(GoldfinchConfig config) internal view returns (address) { return config.getAddress(uint256(ConfigOptions.Addresses.GoldfinchFactory)); } function fiduAddress(GoldfinchConfig config) internal view returns (address) { return config.getAddress(uint256(ConfigOptions.Addresses.Fidu)); } function cusdcContractAddress(GoldfinchConfig config) internal view returns (address) { return config.getAddress(uint256(ConfigOptions.Addresses.CUSDCContract)); } function usdcAddress(GoldfinchConfig config) internal view returns (address) { return config.getAddress(uint256(ConfigOptions.Addresses.USDC)); } function tranchedPoolAddress(GoldfinchConfig config) internal view returns (address) { return config.getAddress(uint256(ConfigOptions.Addresses.TranchedPoolImplementation)); } function migratedTranchedPoolAddress(GoldfinchConfig config) internal view returns (address) { return config.getAddress(uint256(ConfigOptions.Addresses.MigratedTranchedPoolImplementation)); } function reserveAddress(GoldfinchConfig config) internal view returns (address) { return config.getAddress(uint256(ConfigOptions.Addresses.TreasuryReserve)); } function protocolAdminAddress(GoldfinchConfig config) internal view returns (address) { return config.getAddress(uint256(ConfigOptions.Addresses.ProtocolAdmin)); } function borrowerImplementationAddress(GoldfinchConfig config) internal view returns (address) { return config.getAddress(uint256(ConfigOptions.Addresses.BorrowerImplementation)); } function getReserveDenominator(GoldfinchConfig config) internal view returns (uint256) { return config.getNumber(uint256(ConfigOptions.Numbers.ReserveDenominator)); } function getWithdrawFeeDenominator(GoldfinchConfig config) internal view returns (uint256) { return config.getNumber(uint256(ConfigOptions.Numbers.WithdrawFeeDenominator)); } function getLatenessGracePeriodInDays(GoldfinchConfig config) internal view returns (uint256) { return config.getNumber(uint256(ConfigOptions.Numbers.LatenessGracePeriodInDays)); } function getLatenessMaxDays(GoldfinchConfig config) internal view returns (uint256) { return config.getNumber(uint256(ConfigOptions.Numbers.LatenessMaxDays)); } function getDrawdownPeriodInSeconds(GoldfinchConfig config) internal view returns (uint256) { return config.getNumber(uint256(ConfigOptions.Numbers.DrawdownPeriodInSeconds)); } function getTransferRestrictionPeriodInDays(GoldfinchConfig config) internal view returns (uint256) { return config.getNumber(uint256(ConfigOptions.Numbers.TransferRestrictionPeriodInDays)); } function getLeverageRatio(GoldfinchConfig config) internal view returns (uint256) { return config.getNumber(uint256(ConfigOptions.Numbers.LeverageRatio)); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; /** * @title ConfigOptions * @notice A central place for enumerating the configurable options of our GoldfinchConfig contract * @author Goldfinch */ library ConfigOptions { // NEVER EVER CHANGE THE ORDER OF THESE! // You can rename or append. But NEVER change the order. enum Numbers { TransactionLimit, TotalFundsLimit, MaxUnderwriterLimit, ReserveDenominator, WithdrawFeeDenominator, LatenessGracePeriodInDays, LatenessMaxDays, DrawdownPeriodInSeconds, TransferRestrictionPeriodInDays, LeverageRatio } enum Addresses { Pool, CreditLineImplementation, GoldfinchFactory, CreditDesk, Fidu, USDC, TreasuryReserve, ProtocolAdmin, OneInch, TrustedForwarder, CUSDCContract, GoldfinchConfig, PoolTokens, TranchedPoolImplementation, SeniorPool, SeniorPoolStrategy, MigratedTranchedPoolImplementation, BorrowerImplementation } function getNumberName(uint256 number) public pure returns (string memory) { Numbers numberName = Numbers(number); if (Numbers.TransactionLimit == numberName) { return "TransactionLimit"; } if (Numbers.TotalFundsLimit == numberName) { return "TotalFundsLimit"; } if (Numbers.MaxUnderwriterLimit == numberName) { return "MaxUnderwriterLimit"; } if (Numbers.ReserveDenominator == numberName) { return "ReserveDenominator"; } if (Numbers.WithdrawFeeDenominator == numberName) { return "WithdrawFeeDenominator"; } if (Numbers.LatenessGracePeriodInDays == numberName) { return "LatenessGracePeriodInDays"; } if (Numbers.LatenessMaxDays == numberName) { return "LatenessMaxDays"; } if (Numbers.DrawdownPeriodInSeconds == numberName) { return "DrawdownPeriodInSeconds"; } if (Numbers.TransferRestrictionPeriodInDays == numberName) { return "TransferRestrictionPeriodInDays"; } if (Numbers.LeverageRatio == numberName) { return "LeverageRatio"; } revert("Unknown value passed to getNumberName"); } function getAddressName(uint256 addressKey) public pure returns (string memory) { Addresses addressName = Addresses(addressKey); if (Addresses.Pool == addressName) { return "Pool"; } if (Addresses.CreditLineImplementation == addressName) { return "CreditLineImplementation"; } if (Addresses.GoldfinchFactory == addressName) { return "GoldfinchFactory"; } if (Addresses.CreditDesk == addressName) { return "CreditDesk"; } if (Addresses.Fidu == addressName) { return "Fidu"; } if (Addresses.USDC == addressName) { return "USDC"; } if (Addresses.TreasuryReserve == addressName) { return "TreasuryReserve"; } if (Addresses.ProtocolAdmin == addressName) { return "ProtocolAdmin"; } if (Addresses.OneInch == addressName) { return "OneInch"; } if (Addresses.TrustedForwarder == addressName) { return "TrustedForwarder"; } if (Addresses.CUSDCContract == addressName) { return "CUSDCContract"; } if (Addresses.PoolTokens == addressName) { return "PoolTokens"; } if (Addresses.TranchedPoolImplementation == addressName) { return "TranchedPoolImplementation"; } if (Addresses.SeniorPool == addressName) { return "SeniorPool"; } if (Addresses.SeniorPoolStrategy == addressName) { return "SeniorPoolStrategy"; } if (Addresses.MigratedTranchedPoolImplementation == addressName) { return "MigratedTranchedPoolImplementation"; } if (Addresses.BorrowerImplementation == addressName) { return "BorrowerImplementation"; } revert("Unknown value passed to getAddressName"); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./BaseUpgradeablePausable.sol"; import "../../interfaces/IGoldfinchConfig.sol"; import "./ConfigOptions.sol"; /** * @title GoldfinchConfig * @notice This contract stores mappings of useful "protocol config state", giving a central place * for all other contracts to access it. For example, the TransactionLimit, or the PoolAddress. These config vars * are enumerated in the `ConfigOptions` library, and can only be changed by admins of the protocol. * Note: While this inherits from BaseUpgradeablePausable, it is not deployed as an upgradeable contract (this * is mostly to save gas costs of having each call go through a proxy) * @author Goldfinch */ contract GoldfinchConfig is BaseUpgradeablePausable { bytes32 public constant GO_LISTER_ROLE = keccak256("GO_LISTER_ROLE"); mapping(uint256 => address) public addresses; mapping(uint256 => uint256) public numbers; mapping(address => bool) public goList; event AddressUpdated(address owner, uint256 index, address oldValue, address newValue); event NumberUpdated(address owner, uint256 index, uint256 oldValue, uint256 newValue); event GoListed(address indexed member); event NoListed(address indexed member); bool public valuesInitialized; function initialize(address owner) public initializer { require(owner != address(0), "Owner address cannot be empty"); __BaseUpgradeablePausable__init(owner); _setupRole(GO_LISTER_ROLE, owner); _setRoleAdmin(GO_LISTER_ROLE, OWNER_ROLE); } function setAddress(uint256 addressIndex, address newAddress) public onlyAdmin { require(addresses[addressIndex] == address(0), "Address has already been initialized"); emit AddressUpdated(msg.sender, addressIndex, addresses[addressIndex], newAddress); addresses[addressIndex] = newAddress; } function setNumber(uint256 index, uint256 newNumber) public onlyAdmin { emit NumberUpdated(msg.sender, index, numbers[index], newNumber); numbers[index] = newNumber; } function setTreasuryReserve(address newTreasuryReserve) public onlyAdmin { uint256 key = uint256(ConfigOptions.Addresses.TreasuryReserve); emit AddressUpdated(msg.sender, key, addresses[key], newTreasuryReserve); addresses[key] = newTreasuryReserve; } function setSeniorPoolStrategy(address newStrategy) public onlyAdmin { uint256 key = uint256(ConfigOptions.Addresses.SeniorPoolStrategy); emit AddressUpdated(msg.sender, key, addresses[key], newStrategy); addresses[key] = newStrategy; } function setCreditLineImplementation(address newAddress) public onlyAdmin { uint256 key = uint256(ConfigOptions.Addresses.CreditLineImplementation); emit AddressUpdated(msg.sender, key, addresses[key], newAddress); addresses[key] = newAddress; } function setBorrowerImplementation(address newAddress) public onlyAdmin { uint256 key = uint256(ConfigOptions.Addresses.BorrowerImplementation); emit AddressUpdated(msg.sender, key, addresses[key], newAddress); addresses[key] = newAddress; } function setGoldfinchConfig(address newAddress) public onlyAdmin { uint256 key = uint256(ConfigOptions.Addresses.GoldfinchConfig); emit AddressUpdated(msg.sender, key, addresses[key], newAddress); addresses[key] = newAddress; } function initializeFromOtherConfig(address _initialConfig) public onlyAdmin { require(!valuesInitialized, "Already initialized values"); IGoldfinchConfig initialConfig = IGoldfinchConfig(_initialConfig); for (uint256 i = 0; i < 10; i++) { setNumber(i, initialConfig.getNumber(i)); } for (uint256 i = 0; i < 11; i++) { if (getAddress(i) == address(0)) { setAddress(i, initialConfig.getAddress(i)); } } valuesInitialized = true; } /** * @dev Adds a user to go-list * @param _member address to add to go-list */ function addToGoList(address _member) public onlyGoListerRole { goList[_member] = true; emit GoListed(_member); } /** * @dev removes a user from go-list * @param _member address to remove from go-list */ function removeFromGoList(address _member) public onlyGoListerRole { goList[_member] = false; emit NoListed(_member); } /** * @dev adds many users to go-list at once * @param _members addresses to ad to go-list */ function bulkAddToGoList(address[] calldata _members) external onlyGoListerRole { for (uint256 i = 0; i < _members.length; i++) { addToGoList(_members[i]); } } /** * @dev removes many users from go-list at once * @param _members addresses to remove from go-list */ function bulkRemoveFromGoList(address[] calldata _members) external onlyGoListerRole { for (uint256 i = 0; i < _members.length; i++) { removeFromGoList(_members[i]); } } /* Using custom getters in case we want to change underlying implementation later, or add checks or validations later on. */ function getAddress(uint256 index) public view returns (address) { return addresses[index]; } function getNumber(uint256 index) public view returns (uint256) { return numbers[index]; } modifier onlyGoListerRole() { require(hasRole(GO_LISTER_ROLE, _msgSender()), "Must have go-lister role to perform this action"); _; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./TranchedPool.sol"; import "../../interfaces/IV1CreditLine.sol"; import "../../interfaces/IMigratedTranchedPool.sol"; contract MigratedTranchedPool is TranchedPool, IMigratedTranchedPool { bool public migrated; function migrateCreditLineToV2( IV1CreditLine clToMigrate, uint256 termEndTime, uint256 nextDueTime, uint256 interestAccruedAsOf, uint256 lastFullPaymentTime, uint256 totalInterestPaid ) external override returns (IV2CreditLine) { require(msg.sender == config.creditDeskAddress(), "Only credit desk can call this"); require(!migrated, "Already migrated"); // Set accounting state vars. IV2CreditLine newCl = creditLine; newCl.setBalance(clToMigrate.balance()); newCl.setInterestOwed(clToMigrate.interestOwed()); newCl.setPrincipalOwed(clToMigrate.principalOwed()); newCl.setTermEndTime(termEndTime); newCl.setNextDueTime(nextDueTime); newCl.setInterestAccruedAsOf(interestAccruedAsOf); newCl.setLastFullPaymentTime(lastFullPaymentTime); newCl.setTotalInterestAccrued(totalInterestPaid.add(clToMigrate.interestOwed())); migrateDeposits(clToMigrate, totalInterestPaid); migrated = true; return newCl; } function migrateDeposits(IV1CreditLine clToMigrate, uint256 totalInterestPaid) internal { // Mint junior tokens to the SeniorPool, equal to current cl balance; require(!locked(), "Pool has been locked"); // Hardcode to always get the JuniorTranche, since the migration case is when // the senior pool took the entire investment. Which we're expressing as the junior tranche uint256 tranche = uint256(ITranchedPool.Tranches.Junior); TrancheInfo storage trancheInfo = getTrancheInfo(tranche); require(trancheInfo.lockedUntil == 0, "Tranche has been locked"); trancheInfo.principalDeposited = clToMigrate.limit(); IPoolTokens.MintParams memory params = IPoolTokens.MintParams({ tranche: tranche, principalAmount: trancheInfo.principalDeposited }); IPoolTokens poolTokens = config.getPoolTokens(); uint256 tokenId = poolTokens.mint(params, config.seniorPoolAddress()); uint256 balancePaid = creditLine.limit().sub(creditLine.balance()); // Account for the implicit redemptions already made by the Legacy Pool _lockJuniorCapital(); _lockPool(); juniorTranche.lockedUntil = block.timestamp - 1; poolTokens.redeem(tokenId, balancePaid, totalInterestPaid); // Simulate the drawdown juniorTranche.principalSharePrice = 0; seniorTranche.principalSharePrice = 0; // Set junior's sharePrice correctly applyToTrancheByAmount(totalInterestPaid, balancePaid, totalInterestPaid, balancePaid, juniorTranche); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/utils/Pausable.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/access/AccessControl.sol"; /** * @title PauserPausable * @notice Inheriting from OpenZeppelin's Pausable contract, this does small * augmentations to make it work with a PAUSER_ROLE, leveraging the AccessControl contract. * It is meant to be inherited. * @author Goldfinch */ contract PauserPausable is AccessControlUpgradeSafe, PausableUpgradeSafe { bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); // solhint-disable-next-line func-name-mixedcase function __PauserPausable__init() public initializer { __Pausable_init_unchained(); } /** * @dev Pauses all functions guarded by Pause * * See {Pausable-_pause}. * * Requirements: * * - the caller must have the PAUSER_ROLE. */ function pause() public onlyPauserRole { _pause(); } /** * @dev Unpauses the contract * * See {Pausable-_unpause}. * * Requirements: * * - the caller must have the Pauser role */ function unpause() public onlyPauserRole { _unpause(); } modifier onlyPauserRole() { require(hasRole(PAUSER_ROLE, _msgSender()), "Must have pauser role to perform this action"); _; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/drafts/IERC20Permit.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/math/Math.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "../../interfaces/ITranchedPool.sol"; import "../../interfaces/IERC20withDec.sol"; import "../../interfaces/IV2CreditLine.sol"; import "../../interfaces/IPoolTokens.sol"; import "./GoldfinchConfig.sol"; import "./BaseUpgradeablePausable.sol"; import "./ConfigHelper.sol"; import "../../external/FixedPoint.sol"; import "../../library/SafeERC20Transfer.sol"; contract TranchedPool is BaseUpgradeablePausable, ITranchedPool, SafeERC20Transfer { GoldfinchConfig public config; using ConfigHelper for GoldfinchConfig; using FixedPoint for FixedPoint.Unsigned; using FixedPoint for uint256; bytes32 public constant LOCKER_ROLE = keccak256("LOCKER_ROLE"); uint256 public constant FP_SCALING_FACTOR = 1e18; uint256 public constant SECONDS_PER_DAY = 60 * 60 * 24; uint256 public constant ONE_HUNDRED = 100; // Need this because we cannot call .div on a literal 100 uint256 public juniorFeePercent; bool public drawdownsPaused; TrancheInfo internal seniorTranche; TrancheInfo internal juniorTranche; event DepositMade(address indexed owner, uint256 indexed tranche, uint256 indexed tokenId, uint256 amount); event WithdrawalMade( address indexed owner, uint256 indexed tranche, uint256 indexed tokenId, uint256 interestWithdrawn, uint256 principalWithdrawn ); event PaymentApplied( address indexed payer, address indexed pool, uint256 interestAmount, uint256 principalAmount, uint256 remainingAmount, uint256 reserveAmount ); event SharePriceUpdated( address indexed pool, uint256 indexed tranche, uint256 principalSharePrice, int256 principalDelta, uint256 interestSharePrice, int256 interestDelta ); event ReserveFundsCollected(address indexed from, uint256 amount); event CreditLineMigrated(address indexed oldCreditLine, address indexed newCreditLine); event DrawdownMade(address indexed borrower, uint256 amount); event DrawdownsPaused(address indexed pool); event DrawdownsUnpaused(address indexed pool); event EmergencyShutdown(address indexed pool); function initialize( address _config, address _borrower, uint256 _juniorFeePercent, uint256 _limit, uint256 _interestApr, uint256 _paymentPeriodInDays, uint256 _termInDays, uint256 _lateFeeApr ) public override initializer { require( address(_config) != address(0) && address(_borrower) != address(0), "Config and borrower addresses cannot be empty" ); config = GoldfinchConfig(_config); address owner = config.protocolAdminAddress(); require(owner != address(0), "Owner address cannot be empty"); __BaseUpgradeablePausable__init(owner); seniorTranche = TrancheInfo({ id: uint256(ITranchedPool.Tranches.Senior), principalSharePrice: usdcToSharePrice(1, 1), interestSharePrice: 0, principalDeposited: 0, lockedUntil: 0 }); juniorTranche = TrancheInfo({ id: uint256(ITranchedPool.Tranches.Junior), principalSharePrice: usdcToSharePrice(1, 1), interestSharePrice: 0, principalDeposited: 0, lockedUntil: 0 }); createAndSetCreditLine(_borrower, _limit, _interestApr, _paymentPeriodInDays, _termInDays, _lateFeeApr); createdAt = block.timestamp; juniorFeePercent = _juniorFeePercent; _setupRole(LOCKER_ROLE, _borrower); _setupRole(LOCKER_ROLE, owner); _setRoleAdmin(LOCKER_ROLE, OWNER_ROLE); // Unlock self for infinite amount bool success = config.getUSDC().approve(address(this), uint256(-1)); require(success, "Failed to approve USDC"); } /** * @notice Deposit a USDC amount into the pool for a tranche. Mints an NFT to the caller representing the position * @param tranche The number representing the tranche to deposit into * @param amount The USDC amount to tranfer from the caller to the pool * @return tokenId The tokenId of the NFT */ function deposit(uint256 tranche, uint256 amount) public override nonReentrant whenNotPaused returns (uint256 tokenId) { TrancheInfo storage trancheInfo = getTrancheInfo(tranche); require(trancheInfo.lockedUntil == 0, "Tranche has been locked"); trancheInfo.principalDeposited = trancheInfo.principalDeposited.add(amount); IPoolTokens.MintParams memory params = IPoolTokens.MintParams({tranche: tranche, principalAmount: amount}); tokenId = config.getPoolTokens().mint(params, msg.sender); safeERC20TransferFrom(config.getUSDC(), msg.sender, address(this), amount); emit DepositMade(msg.sender, tranche, tokenId, amount); return tokenId; } function depositWithPermit( uint256 tranche, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public override returns (uint256 tokenId) { IERC20Permit(config.usdcAddress()).permit(msg.sender, address(this), amount, deadline, v, r, s); return deposit(tranche, amount); } /** * @notice Withdraw an already deposited amount if the funds are available * @param tokenId The NFT representing the position * @param amount The amount to withdraw (must be <= interest+principal currently available to withdraw) * @return interestWithdrawn The interest amount that was withdrawn * @return principalWithdrawn The principal amount that was withdrawn */ function withdraw(uint256 tokenId, uint256 amount) public override onlyTokenHolder(tokenId) nonReentrant whenNotPaused returns (uint256 interestWithdrawn, uint256 principalWithdrawn) { IPoolTokens.TokenInfo memory tokenInfo = config.getPoolTokens().getTokenInfo(tokenId); TrancheInfo storage trancheInfo = getTrancheInfo(tokenInfo.tranche); return _withdraw(trancheInfo, tokenInfo, tokenId, amount); } /** * @notice Withdraw from many tokens (that the sender owns) in a single transaction * @param tokenIds An array of tokens ids representing the position * @param amounts An array of amounts to withdraw from the corresponding tokenIds */ function withdrawMultiple(uint256[] calldata tokenIds, uint256[] calldata amounts) public override { require(tokenIds.length == amounts.length, "TokensIds and Amounts must be the same length"); for (uint256 i = 0; i < amounts.length; i++) { withdraw(tokenIds[i], amounts[i]); } } /** * @notice Similar to withdraw but will withdraw all available funds * @param tokenId The NFT representing the position * @return interestWithdrawn The interest amount that was withdrawn * @return principalWithdrawn The principal amount that was withdrawn */ function withdrawMax(uint256 tokenId) external override onlyTokenHolder(tokenId) nonReentrant whenNotPaused returns (uint256 interestWithdrawn, uint256 principalWithdrawn) { IPoolTokens.TokenInfo memory tokenInfo = config.getPoolTokens().getTokenInfo(tokenId); TrancheInfo storage trancheInfo = getTrancheInfo(tokenInfo.tranche); (uint256 interestRedeemable, uint256 principalRedeemable) = redeemableInterestAndPrincipal(trancheInfo, tokenInfo); uint256 amount = interestRedeemable.add(principalRedeemable); return _withdraw(trancheInfo, tokenInfo, tokenId, amount); } /** * @notice Draws down the funds (and locks the pool) to the borrower address. Can only be called by the borrower * @param amount The amount to drawdown from the creditline (must be < limit) */ function drawdown(uint256 amount) external override onlyLocker whenNotPaused { require(!drawdownsPaused, "Drawdowns are currently paused"); if (!locked()) { // Assumes the senior fund has invested already (saves the borrower a separate transaction to lock the pool) _lockPool(); } creditLine.drawdown(amount); // Update the share price to reflect the amount remaining in the pool uint256 amountRemaining = totalDeposited().sub(creditLine.balance()); uint256 oldJuniorPrincipalSharePrice = juniorTranche.principalSharePrice; uint256 oldSeniorPrincipalSharePrice = seniorTranche.principalSharePrice; juniorTranche.principalSharePrice = calculateExpectedSharePrice(amountRemaining, juniorTranche); seniorTranche.principalSharePrice = calculateExpectedSharePrice(amountRemaining, seniorTranche); address borrower = creditLine.borrower(); safeERC20TransferFrom(config.getUSDC(), address(this), borrower, amount); emit DrawdownMade(borrower, amount); emit SharePriceUpdated( address(this), juniorTranche.id, juniorTranche.principalSharePrice, int256(oldJuniorPrincipalSharePrice.sub(juniorTranche.principalSharePrice)) * -1, juniorTranche.interestSharePrice, 0 ); emit SharePriceUpdated( address(this), seniorTranche.id, seniorTranche.principalSharePrice, int256(oldSeniorPrincipalSharePrice.sub(seniorTranche.principalSharePrice)) * -1, seniorTranche.interestSharePrice, 0 ); } /** * @notice Locks the junior tranche, preventing more junior deposits. Gives time for the senior to determine how * much to invest (ensure leverage ratio cannot change for the period) */ function lockJuniorCapital() external override onlyLocker whenNotPaused { _lockJuniorCapital(); } /** * @notice Locks the pool (locks both senior and junior tranches and starts the drawdown period). Beyond the drawdown * period, any unused capital is available to withdraw by all depositors */ function lockPool() external override onlyLocker whenNotPaused { _lockPool(); } /** * @notice Triggers an assessment of the creditline and the applies the payments according the tranche waterfall */ function assess() external override whenNotPaused { _assess(); } /** * @notice Allows repaying the creditline. Collects the USDC amount from the sender and triggers an assess * @param amount The amount to repay */ function pay(uint256 amount) external override whenNotPaused { require(amount > 0, "Must pay more than zero"); collectPayment(amount); _assess(); } /** * @notice Migrates to a new goldfinch config address */ function updateGoldfinchConfig() external onlyAdmin { config = GoldfinchConfig(config.configAddress()); creditLine.updateGoldfinchConfig(); } /** * @notice Pauses the pool and sweeps any remaining funds to the treasury reserve. */ function emergencyShutdown() public onlyAdmin { if (!paused()) { pause(); } IERC20withDec usdc = config.getUSDC(); address reserveAddress = config.reserveAddress(); // Sweep any funds to community reserve uint256 poolBalance = usdc.balanceOf(address(this)); if (poolBalance > 0) { safeERC20Transfer(usdc, reserveAddress, poolBalance); } uint256 clBalance = usdc.balanceOf(address(creditLine)); if (clBalance > 0) { safeERC20TransferFrom(usdc, address(creditLine), reserveAddress, clBalance); } emit EmergencyShutdown(address(this)); } /** * @notice Pauses all drawdowns (but not deposits/withdraws) */ function pauseDrawdowns() public onlyAdmin { drawdownsPaused = true; emit DrawdownsPaused(address(this)); } /** * @notice Unpause drawdowns */ function unpauseDrawdowns() public onlyAdmin { drawdownsPaused = false; emit DrawdownsUnpaused(address(this)); } /** * @notice Migrates the accounting variables from the current creditline to a brand new one * @param _borrower The borrower address * @param _limit The new limit * @param _interestApr The new interest APR * @param _paymentPeriodInDays The new payment period in days * @param _termInDays The new term in days * @param _lateFeeApr The new late fee APR */ function migrateCreditLine( address _borrower, uint256 _limit, uint256 _interestApr, uint256 _paymentPeriodInDays, uint256 _termInDays, uint256 _lateFeeApr ) public onlyAdmin { require(_borrower != address(0), "Borrower must not be empty"); require(_paymentPeriodInDays != 0, "Payment period must not be empty"); require(_termInDays != 0, "Term must not be empty"); address originalClAddr = address(creditLine); IV2CreditLine originalCl = IV2CreditLine(originalClAddr); createAndSetCreditLine(_borrower, _limit, _interestApr, _paymentPeriodInDays, _termInDays, _lateFeeApr); IV2CreditLine newCl = creditLine; address newClAddr = address(newCl); emit CreditLineMigrated(originalClAddr, newClAddr); // Copy over all accounting variables newCl.setBalance(originalCl.balance()); newCl.setInterestOwed(originalCl.interestOwed()); newCl.setPrincipalOwed(originalCl.principalOwed()); newCl.setTermEndTime(originalCl.termEndTime()); newCl.setNextDueTime(originalCl.nextDueTime()); newCl.setInterestAccruedAsOf(originalCl.interestAccruedAsOf()); newCl.setLastFullPaymentTime(originalCl.lastFullPaymentTime()); newCl.setTotalInterestAccrued(originalCl.totalInterestAccrued()); // Transfer any funds to new CL uint256 clBalance = config.getUSDC().balanceOf(originalClAddr); if (clBalance > 0) { safeERC20TransferFrom(config.getUSDC(), originalClAddr, newClAddr, clBalance); } // Close out old CL originalCl.setBalance(0); originalCl.setLimit(0); } /** * @notice Migrates to a new creditline without copying the accounting variables */ function migrateAndSetNewCreditLine(address newCl) public onlyAdmin { require(newCl != address(0), "Creditline cannot be empty"); address originalClAddr = address(creditLine); // Transfer any funds to new CL uint256 clBalance = config.getUSDC().balanceOf(originalClAddr); if (clBalance > 0) { safeERC20TransferFrom(config.getUSDC(), originalClAddr, newCl, clBalance); } // Close out old CL creditLine.setBalance(0); creditLine.setLimit(0); // set new CL creditLine = IV2CreditLine(newCl); // sanity check that the new address is in fact a creditline creditLine.limit(); emit CreditLineMigrated(originalClAddr, address(creditLine)); } // CreditLine proxy methods, for convenience function limit() public view returns (uint256) { return creditLine.limit(); } function borrower() public view returns (address) { return creditLine.borrower(); } function interestApr() public view returns (uint256) { return creditLine.interestApr(); } function paymentPeriodInDays() public view returns (uint256) { return creditLine.paymentPeriodInDays(); } function termInDays() public view returns (uint256) { return creditLine.termInDays(); } function lateFeeApr() public view returns (uint256) { return creditLine.lateFeeApr(); } function getTranche(uint256 tranche) public view override returns (TrancheInfo memory) { return getTrancheInfo(tranche); } /** * @notice Converts USDC amounts to share price * @param amount The USDC amount to convert * @param totalShares The total shares outstanding * @return The share price of the input amount */ function usdcToSharePrice(uint256 amount, uint256 totalShares) public pure returns (uint256) { return totalShares == 0 ? 0 : amount.mul(FP_SCALING_FACTOR).div(totalShares); } /** * @notice Converts share price to USDC amounts * @param sharePrice The share price to convert * @param totalShares The total shares outstanding * @return The USDC amount of the input share price */ function sharePriceToUsdc(uint256 sharePrice, uint256 totalShares) public pure returns (uint256) { return sharePrice.mul(totalShares).div(FP_SCALING_FACTOR); } /** * @notice Determines the amount of interest and principal redeemable by a particular tokenId * @param tokenId The token representing the position * @return interestRedeemable The interest available to redeem * @return principalRedeemable The principal available to redeem */ function availableToWithdraw(uint256 tokenId) public view override returns (uint256 interestRedeemable, uint256 principalRedeemable) { IPoolTokens.TokenInfo memory tokenInfo = config.getPoolTokens().getTokenInfo(tokenId); TrancheInfo storage trancheInfo = getTrancheInfo(tokenInfo.tranche); if (currentTime() > trancheInfo.lockedUntil) { return redeemableInterestAndPrincipal(trancheInfo, tokenInfo); } else { return (0, 0); } } /* Internal functions */ function _withdraw( TrancheInfo storage trancheInfo, IPoolTokens.TokenInfo memory tokenInfo, uint256 tokenId, uint256 amount ) internal returns (uint256 interestWithdrawn, uint256 principalWithdrawn) { (uint256 interestRedeemable, uint256 principalRedeemable) = redeemableInterestAndPrincipal(trancheInfo, tokenInfo); uint256 netRedeemable = interestRedeemable.add(principalRedeemable); require(amount <= netRedeemable, "Invalid redeem amount"); require(currentTime() > trancheInfo.lockedUntil, "Tranche is locked"); // If the tranche has not been locked, ensure the deposited amount is correct if (trancheInfo.lockedUntil == 0) { trancheInfo.principalDeposited = trancheInfo.principalDeposited.sub(amount); } uint256 interestToRedeem = Math.min(interestRedeemable, amount); uint256 principalToRedeem = Math.min(principalRedeemable, amount.sub(interestToRedeem)); config.getPoolTokens().redeem(tokenId, principalToRedeem, interestToRedeem); safeERC20TransferFrom(config.getUSDC(), address(this), msg.sender, principalToRedeem.add(interestToRedeem)); emit WithdrawalMade(msg.sender, tokenInfo.tranche, tokenId, interestToRedeem, principalToRedeem); return (interestToRedeem, principalToRedeem); } function redeemableInterestAndPrincipal(TrancheInfo storage trancheInfo, IPoolTokens.TokenInfo memory tokenInfo) internal view returns (uint256 interestRedeemable, uint256 principalRedeemable) { // This supports withdrawing before or after locking because principal share price starts at 1 // and is set to 0 on lock. Interest share price is always 0 until interest payments come back, when it increases uint256 maxPrincipalRedeemable = sharePriceToUsdc(trancheInfo.principalSharePrice, tokenInfo.principalAmount); // The principalAmount is used as the totalShares because we want the interestSharePrice to be expressed as a // percent of total loan value e.g. if the interest is 10% APR, the interestSharePrice should approach a max of 0.1. uint256 maxInterestRedeemable = sharePriceToUsdc(trancheInfo.interestSharePrice, tokenInfo.principalAmount); interestRedeemable = maxInterestRedeemable.sub(tokenInfo.interestRedeemed); principalRedeemable = maxPrincipalRedeemable.sub(tokenInfo.principalRedeemed); return (interestRedeemable, principalRedeemable); } function _lockJuniorCapital() internal { require(!locked(), "Pool already locked"); require(juniorTranche.lockedUntil == 0, "Junior tranche already locked"); juniorTranche.lockedUntil = currentTime().add(config.getDrawdownPeriodInSeconds()); } function _lockPool() internal { require(juniorTranche.lockedUntil > 0, "Junior tranche must be locked first"); creditLine.setLimit(Math.min(totalDeposited(), creditLine.limit())); // We start the drawdown period, so backers can withdraw unused capital after borrower draws down uint256 lockPeriod = config.getDrawdownPeriodInSeconds(); seniorTranche.lockedUntil = currentTime().add(lockPeriod); juniorTranche.lockedUntil = currentTime().add(lockPeriod); } function collectInterestAndPrincipal( address from, uint256 interest, uint256 principal ) internal returns (uint256 totalReserveAmount) { safeERC20TransferFrom(config.getUSDC(), from, address(this), principal.add(interest), "Failed to collect payment"); (uint256 interestAccrued, uint256 principalAccrued) = getTotalInterestAndPrincipal(); uint256 reserveFeePercent = ONE_HUNDRED.div(config.getReserveDenominator()); // Convert the denonminator to percent uint256 interestRemaining = interest; uint256 principalRemaining = principal; // First determine the expected share price for the senior tranche. This is the gross amount the senior // tranche should receive. uint256 expectedInterestSharePrice = calculateExpectedSharePrice(interestAccrued, seniorTranche); uint256 expectedPrincipalSharePrice = calculateExpectedSharePrice(principalAccrued, seniorTranche); // Deduct the junior fee and the protocol reserve uint256 desiredNetInterestSharePrice = scaleByFraction( expectedInterestSharePrice, ONE_HUNDRED.sub(juniorFeePercent.add(reserveFeePercent)), ONE_HUNDRED ); // Collect protocol fee interest received (we've subtracted this from the senior portion above) uint256 reserveDeduction = scaleByFraction(interestRemaining, reserveFeePercent, ONE_HUNDRED); totalReserveAmount = totalReserveAmount.add(reserveDeduction); // protocol fee interestRemaining = interestRemaining.sub(reserveDeduction); // Apply the interest remaining so we get up to the netInterestSharePrice (interestRemaining, principalRemaining) = applyToTrancheBySharePrice( interestRemaining, principalRemaining, desiredNetInterestSharePrice, expectedPrincipalSharePrice, seniorTranche ); // Then fill up the junior tranche with all the interest remaining, upto the principal share price expectedInterestSharePrice = juniorTranche.interestSharePrice.add( usdcToSharePrice(interestRemaining, juniorTranche.principalDeposited) ); expectedPrincipalSharePrice = calculateExpectedSharePrice(principalAccrued, juniorTranche); (interestRemaining, principalRemaining) = applyToTrancheBySharePrice( interestRemaining, principalRemaining, expectedInterestSharePrice, expectedPrincipalSharePrice, juniorTranche ); // All remaining interest and principal is applied towards the junior tranche as interest interestRemaining = interestRemaining.add(principalRemaining); // Since any principal remaining is treated as interest (there is "extra" interest to be distributed) // we need to make sure to collect the protocol fee on the additional interest (we only deducted the // fee on the original interest portion) reserveDeduction = scaleByFraction(principalRemaining, reserveFeePercent, ONE_HUNDRED); totalReserveAmount = totalReserveAmount.add(reserveDeduction); interestRemaining = interestRemaining.sub(reserveDeduction); principalRemaining = 0; (interestRemaining, principalRemaining) = applyToTrancheByAmount( interestRemaining.add(principalRemaining), 0, interestRemaining.add(principalRemaining), 0, juniorTranche ); sendToReserve(totalReserveAmount); return totalReserveAmount; } function getTotalInterestAndPrincipal() internal view returns (uint256 interestAccrued, uint256 principalAccrued) { interestAccrued = creditLine.totalInterestAccrued(); principalAccrued = creditLine.principalOwed(); // Add any remaining balance we have to the principal accrued so expected share price will reflect partial // drawdowns appropriately. (e.g. if 300K was drawndown from a 1M loan, current and expected share price should // be 0.7 and not 0) principalAccrued = principalAccrued.add(totalDeposited().sub(creditLine.balance())); return (interestAccrued, principalAccrued); } function calculateExpectedSharePrice(uint256 amount, TrancheInfo memory tranche) internal view returns (uint256) { uint256 sharePrice = usdcToSharePrice(amount, tranche.principalDeposited); return scaleByPercentOwnership(sharePrice, tranche); } // If the senior tranche is locked, then the pool is not open to any more deposits (could throw off leverage ratio) function locked() internal view returns (bool) { return seniorTranche.lockedUntil > 0; } function createAndSetCreditLine( address _borrower, uint256 _limit, uint256 _interestApr, uint256 _paymentPeriodInDays, uint256 _termInDays, uint256 _lateFeeApr ) internal { address _creditLine = config.getGoldfinchFactory().createCreditLine(); creditLine = IV2CreditLine(_creditLine); creditLine.initialize( address(config), address(this), // Set self as the owner _borrower, _limit, _interestApr, _paymentPeriodInDays, _termInDays, _lateFeeApr ); } function getTrancheInfo(uint256 tranche) internal view returns (TrancheInfo storage) { require( tranche == uint256(ITranchedPool.Tranches.Senior) || tranche == uint256(ITranchedPool.Tranches.Junior), "Unsupported tranche" ); TrancheInfo storage trancheInfo = tranche == uint256(ITranchedPool.Tranches.Senior) ? seniorTranche : juniorTranche; return trancheInfo; } function scaleByPercentOwnership(uint256 amount, TrancheInfo memory tranche) internal view returns (uint256) { uint256 totalDeposited = juniorTranche.principalDeposited.add(seniorTranche.principalDeposited); return scaleByFraction(amount, tranche.principalDeposited, totalDeposited); } function scaleByFraction( uint256 amount, uint256 fraction, uint256 total ) internal pure returns (uint256) { FixedPoint.Unsigned memory totalAsFixedPoint = FixedPoint.fromUnscaledUint(total); FixedPoint.Unsigned memory fractionAsFixedPoint = FixedPoint.fromUnscaledUint(fraction); return fractionAsFixedPoint.div(totalAsFixedPoint).mul(amount).div(FP_SCALING_FACTOR).rawValue; } function totalDeposited() internal view returns (uint256) { return juniorTranche.principalDeposited.add(seniorTranche.principalDeposited); } function currentTime() internal view virtual returns (uint256) { return block.timestamp; } function applyToTrancheBySharePrice( uint256 interestRemaining, uint256 principalRemaining, uint256 desiredInterestSharePrice, uint256 desiredPrincipalSharePrice, TrancheInfo storage tranche ) internal returns (uint256, uint256) { uint256 totalShares = tranche.principalDeposited; // If the desired share price is lower, then ignore it, and leave it unchanged uint256 principalSharePrice = tranche.principalSharePrice; if (desiredPrincipalSharePrice < principalSharePrice) { desiredPrincipalSharePrice = principalSharePrice; } uint256 interestSharePrice = tranche.interestSharePrice; if (desiredInterestSharePrice < interestSharePrice) { desiredInterestSharePrice = interestSharePrice; } uint256 interestSharePriceDifference = desiredInterestSharePrice.sub(interestSharePrice); uint256 desiredInterestAmount = sharePriceToUsdc(interestSharePriceDifference, totalShares); uint256 principalSharePriceDifference = desiredPrincipalSharePrice.sub(principalSharePrice); uint256 desiredPrincipalAmount = sharePriceToUsdc(principalSharePriceDifference, totalShares); (interestRemaining, principalRemaining) = applyToTrancheByAmount( interestRemaining, principalRemaining, desiredInterestAmount, desiredPrincipalAmount, tranche ); return (interestRemaining, principalRemaining); } function applyToTrancheByAmount( uint256 interestRemaining, uint256 principalRemaining, uint256 desiredInterestAmount, uint256 desiredPrincipalAmount, TrancheInfo storage tranche ) internal returns (uint256, uint256) { uint256 totalShares = tranche.principalDeposited; uint256 newSharePrice; (interestRemaining, newSharePrice) = applyToSharePrice( interestRemaining, tranche.interestSharePrice, desiredInterestAmount, totalShares ); uint256 oldInterestSharePrice = tranche.interestSharePrice; tranche.interestSharePrice = newSharePrice; (principalRemaining, newSharePrice) = applyToSharePrice( principalRemaining, tranche.principalSharePrice, desiredPrincipalAmount, totalShares ); uint256 oldPrincipalSharePrice = tranche.principalSharePrice; tranche.principalSharePrice = newSharePrice; emit SharePriceUpdated( address(this), tranche.id, tranche.principalSharePrice, int256(tranche.principalSharePrice.sub(oldPrincipalSharePrice)), tranche.interestSharePrice, int256(tranche.interestSharePrice.sub(oldInterestSharePrice)) ); return (interestRemaining, principalRemaining); } function applyToSharePrice( uint256 amountRemaining, uint256 currentSharePrice, uint256 desiredAmount, uint256 totalShares ) internal pure returns (uint256, uint256) { // If no money left to apply, or don't need any changes, return the original amounts if (amountRemaining == 0 || desiredAmount == 0) { return (amountRemaining, currentSharePrice); } if (amountRemaining < desiredAmount) { // We don't have enough money to adjust share price to the desired level. So just use whatever amount is left desiredAmount = amountRemaining; } uint256 sharePriceDifference = usdcToSharePrice(desiredAmount, totalShares); return (amountRemaining.sub(desiredAmount), currentSharePrice.add(sharePriceDifference)); } function sendToReserve(uint256 amount) internal { emit ReserveFundsCollected(address(this), amount); safeERC20TransferFrom( config.getUSDC(), address(this), config.reserveAddress(), amount, "Failed to send to reserve" ); } function collectPayment(uint256 amount) internal { safeERC20TransferFrom(config.getUSDC(), msg.sender, address(creditLine), amount, "Failed to collect payment"); } function _assess() internal { (uint256 paymentRemaining, uint256 interestPayment, uint256 principalPayment) = creditLine.assess(); if (interestPayment > 0 || principalPayment > 0) { uint256 reserveAmount = collectInterestAndPrincipal( address(creditLine), interestPayment, principalPayment.add(paymentRemaining) ); emit PaymentApplied( creditLine.borrower(), address(this), interestPayment, principalPayment, paymentRemaining, reserveAmount ); } } modifier onlyLocker() { require(hasRole(LOCKER_ROLE, msg.sender), "Must have locker role to perform this action"); _; } modifier onlyTokenHolder(uint256 tokenId) { require( config.getPoolTokens().isApprovedOrOwner(msg.sender, tokenId), "Only the token owner is allowed to call this function" ); _; } }
Mint junior tokens to the SeniorPool, equal to current cl balance; Hardcode to always get the JuniorTranche, since the migration case is when the senior pool took the entire investment. Which we're expressing as the junior tranche
function migrateDeposits(IV1CreditLine clToMigrate, uint256 totalInterestPaid) internal { require(!locked(), "Pool has been locked"); uint256 tranche = uint256(ITranchedPool.Tranches.Junior); TrancheInfo storage trancheInfo = getTrancheInfo(tranche); require(trancheInfo.lockedUntil == 0, "Tranche has been locked"); trancheInfo.principalDeposited = clToMigrate.limit(); IPoolTokens.MintParams memory params = IPoolTokens.MintParams({ tranche: tranche, principalAmount: trancheInfo.principalDeposited }); IPoolTokens poolTokens = config.getPoolTokens(); uint256 tokenId = poolTokens.mint(params, config.seniorPoolAddress()); uint256 balancePaid = creditLine.limit().sub(creditLine.balance()); _lockPool(); juniorTranche.lockedUntil = block.timestamp - 1; poolTokens.redeem(tokenId, balancePaid, totalInterestPaid); seniorTranche.principalSharePrice = 0; }
12,976,852
[ 1, 49, 474, 525, 318, 9659, 2430, 358, 326, 348, 275, 9659, 2864, 16, 3959, 358, 783, 927, 11013, 31, 670, 1060, 710, 358, 3712, 336, 326, 804, 318, 9659, 17730, 18706, 16, 3241, 326, 6333, 648, 353, 1347, 326, 28901, 9659, 2845, 23151, 326, 7278, 2198, 395, 475, 18, 21918, 732, 4565, 16947, 310, 487, 326, 525, 318, 9659, 13637, 18706, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 13187, 758, 917, 1282, 12, 8188, 21, 16520, 1670, 927, 774, 19594, 16, 2254, 5034, 2078, 29281, 16507, 350, 13, 2713, 288, 203, 565, 2583, 12, 5, 15091, 9334, 315, 2864, 711, 2118, 8586, 8863, 203, 565, 2254, 5034, 13637, 18706, 273, 2254, 5034, 12, 45, 17730, 2049, 2864, 18, 17730, 11163, 18, 46, 318, 9659, 1769, 203, 565, 840, 304, 18706, 966, 2502, 13637, 18706, 966, 273, 336, 17730, 18706, 966, 12, 13171, 18706, 1769, 203, 565, 2583, 12, 13171, 18706, 966, 18, 15091, 9716, 422, 374, 16, 315, 17730, 18706, 711, 2118, 8586, 8863, 203, 565, 13637, 18706, 966, 18, 26138, 758, 1724, 329, 273, 927, 774, 19594, 18, 3595, 5621, 203, 565, 467, 2864, 5157, 18, 49, 474, 1370, 3778, 859, 273, 467, 2864, 5157, 18, 49, 474, 1370, 12590, 203, 1377, 13637, 18706, 30, 13637, 18706, 16, 203, 1377, 8897, 6275, 30, 13637, 18706, 966, 18, 26138, 758, 1724, 329, 203, 565, 15549, 203, 565, 467, 2864, 5157, 2845, 5157, 273, 642, 18, 588, 2864, 5157, 5621, 203, 203, 565, 2254, 5034, 1147, 548, 273, 2845, 5157, 18, 81, 474, 12, 2010, 16, 642, 18, 87, 275, 9659, 2864, 1887, 10663, 203, 565, 2254, 5034, 11013, 16507, 350, 273, 12896, 1670, 18, 3595, 7675, 1717, 12, 20688, 1670, 18, 12296, 10663, 203, 203, 565, 389, 739, 2864, 5621, 203, 203, 565, 525, 318, 9659, 17730, 18706, 18, 15091, 9716, 273, 1203, 18, 5508, 300, 404, 31, 203, 565, 2845, 5157, 18, 266, 24903, 12, 2316, 548, 16, 11013, 2 ]
./full_match/1/0x068d23dbc3A6Bddc0916205e15d841C6fD9B0fCB/sources/contracts/DoughV1Dsa.sol
========== CONSTANTS ========== */ ========== STATE VARIABLES ========== */ ========== CONSTRUCTOR ========== */
constructor(address _owner, address _DoughV1Index, address _doughFlashloan) { owner = _owner; DoughV1Index = _DoughV1Index; doughFlashloan = _doughFlashloan; }
3,211,122
[ 1, 1432, 631, 24023, 55, 422, 1432, 342, 422, 1432, 7442, 22965, 55, 422, 1432, 342, 422, 1432, 3492, 13915, 916, 422, 1432, 342, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 3885, 12, 2867, 389, 8443, 16, 1758, 389, 3244, 2127, 58, 21, 1016, 16, 1758, 389, 2896, 2127, 11353, 383, 304, 13, 288, 203, 3639, 3410, 273, 389, 8443, 31, 203, 3639, 2256, 2127, 58, 21, 1016, 273, 389, 3244, 2127, 58, 21, 1016, 31, 203, 3639, 741, 2127, 11353, 383, 304, 273, 389, 2896, 2127, 11353, 383, 304, 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 ]
pragma solidity ^0.6.4; import "@openzeppelin/contracts/access/Ownable.sol"; contract Tournaments is Ownable { /** `Data */ enum TournamentState { Active, Ended, WinnersDeclared } struct Tournament { address payable organizer; uint endTime; string data; uint prize; uint buyInAmount; uint triesPerBuyIn; TournamentState state; uint balance; uint[] shares; } Tournament[] public tournaments; // tournamentId => _ mapping(uint => uint[]) public winnerShares; mapping(uint => uint) public totalShares; // tournamentId => (player => total buy in) mapping(uint => mapping (address => uint)) public buyIn; /** Events */ event TournamentCreated(uint tournamentId); event TournamentActivated(uint tournamentId); event TournamentNewBuyIn(uint tournamentId); event WinnersDeclaredByAddress(uint tournamentId, address payable[] resultId); event PrizeTransfered(uint tournamentId, uint256 resultId, address indexed player, uint256 amount); event TournamentStopped(uint tournamentId); /** Modifiers */ modifier noTournamentsOverflow(){ require((tournaments.length + 1) > tournaments.length, "Too many tournaments"); _; } modifier notInPast(uint time) { require(time > now, "Incorrect time"); _; } modifier tournamentIdIsCorrect(uint id){ require(id < tournaments.length, "Incorrect tournament id"); _; } modifier tournamentNotEnded(uint id) { require(now < tournaments[id].endTime, "Tournament has ended"); _; } modifier onlyOrganizer(uint tournamentId) { require(msg.sender == tournaments[tournamentId].organizer, "Must be tournament's organizer"); _; } modifier correctPaymentAmount(uint amount) { require((amount * 1 wei) == msg.value, "Incorrent payment amount"); _; } modifier correctBuyInAmount(uint tournamentId) { require((tournaments[tournamentId].buyInAmount * 1 wei) == msg.value, "Incorrent buy in amount"); _; } modifier correctTournamentState(uint tournamentId, TournamentState state) { require(tournaments[tournamentId].state == state, "Incorrect tournament state"); _; } /** Methods */ function createTournament( address payable organizer, string calldata data, uint endTime, uint256[] calldata shares, uint256[] calldata uintParams ) external payable notInPast(endTime) noTournamentsOverflow() correctPaymentAmount(uintParams[0]) returns (uint) { // uintParams[0] = prize // uintParams[1] = buyInAmount // uintParams[2] = triesPerBuyIn require(uintParams[0] != 0, "Prize must not be zero"); require(uintParams[1] != 0, "Buy in amount must not be zero"); require(uintParams[2] != 0, "Tries count must not be zero"); // check and calculate shares uint sharesCount = shares.length; require(sharesCount >= 1, "Must have at least one share"); for (uint i = 0; i < sharesCount; i++) { require((shares[i]) > 0, "Must not have zero shares"); totalShares[tournaments.length - 1] += shares[i]; } // create the tournament with initial balance equal to prize (uintParams[0]) tournaments.push(Tournament(organizer, endTime, data, uintParams[0], uintParams[1], uintParams[2], TournamentState.Active, uintParams[0], shares)); winnerShares[tournaments.length - 1] = shares; emit TournamentCreated(tournaments.length - 1); return (tournaments.length - 1); } function payBuyIn(uint tournamentId, uint value) external payable tournamentIdIsCorrect(tournamentId) tournamentNotEnded(tournamentId) correctTournamentState(tournamentId, TournamentState.Active) correctPaymentAmount(value) correctBuyInAmount(tournamentId) { buyIn[tournamentId][msg.sender] += value; tournaments[tournamentId].balance += value; emit TournamentNewBuyIn(tournamentId); } // function sends all the tournament pool to adresses function declareWinnersByPlayerId(uint tournamentId, address payable[] calldata addresses) external tournamentIdIsCorrect(tournamentId) onlyOrganizer(tournamentId) { require((tournaments[tournamentId].state == TournamentState.Active) || (tournaments[tournamentId].state == TournamentState.Ended), "Incorrect tournament state"); uint playersCount = addresses.length; uint totalSentAmount = 0; for (uint i = 0; i < playersCount; i++) { // send result uint amount = calcPrizeShareByIndex(tournamentId, i); addresses[i].transfer(amount); // need to keep total balance unchanged while calculating prize shares totalSentAmount += amount; // resultid is unused (2nd parameter) emit PrizeTransfered(tournamentId, 0, addresses[i], amount); } tournaments[tournamentId].balance -= totalSentAmount; tournaments[tournamentId].state = TournamentState.WinnersDeclared; emit WinnersDeclaredByAddress(tournamentId, addresses); } function calcPrizeShareByIndex(uint tournamentId, uint place) public view returns (uint) { return tournaments[tournamentId].balance * winnerShares[tournamentId][place] / totalShares[tournamentId]; } function getTournament(uint tournamentId) public view tournamentIdIsCorrect(tournamentId) returns (address, uint, uint, uint, uint, string memory) { return (tournaments[tournamentId].organizer, tournaments[tournamentId].endTime, tournaments[tournamentId].prize, uint(tournaments[tournamentId].state), tournaments[tournamentId].balance, tournaments[tournamentId].data); } function getTournamentsCount() public view returns (uint) { return tournaments.length; } function getBuyIn(uint tournamentId) public view tournamentIdIsCorrect(tournamentId) returns (uint) { return tournaments[tournamentId].buyInAmount; } function getMaxTries(uint tournamentId) public view tournamentIdIsCorrect(tournamentId) returns (uint) { return tournaments[tournamentId].triesPerBuyIn; } function getShares(uint tournamentId) public view tournamentIdIsCorrect(tournamentId) returns (uint256[] memory) { return tournaments[tournamentId].shares; } }
/ uintParams[0] = prize uintParams[1] = buyInAmount uintParams[2] = triesPerBuyIn check and calculate shares
function createTournament( address payable organizer, string calldata data, uint endTime, uint256[] calldata shares, uint256[] calldata uintParams ) external payable notInPast(endTime) noTournamentsOverflow() correctPaymentAmount(uintParams[0]) returns (uint) { require(uintParams[0] != 0, "Prize must not be zero"); require(uintParams[1] != 0, "Buy in amount must not be zero"); require(uintParams[2] != 0, "Tries count must not be zero"); uint sharesCount = shares.length; require(sharesCount >= 1, "Must have at least one share"); for (uint i = 0; i < sharesCount; i++) { require((shares[i]) > 0, "Must not have zero shares"); totalShares[tournaments.length - 1] += shares[i]; } uintParams[1], uintParams[2], TournamentState.Active, uintParams[0], shares)); winnerShares[tournaments.length - 1] = shares; emit TournamentCreated(tournaments.length - 1); return (tournaments.length - 1); }
6,367,869
[ 1, 19, 2254, 1370, 63, 20, 65, 273, 846, 554, 2254, 1370, 63, 21, 65, 273, 30143, 382, 6275, 2254, 1370, 63, 22, 65, 273, 9327, 2173, 38, 9835, 382, 866, 471, 4604, 24123, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 752, 774, 30751, 12, 203, 565, 1758, 8843, 429, 377, 15501, 1824, 16, 203, 565, 533, 745, 892, 377, 501, 16, 203, 565, 2254, 7734, 13859, 16, 203, 565, 2254, 5034, 8526, 745, 892, 225, 24123, 16, 203, 565, 2254, 5034, 8526, 745, 892, 225, 2254, 1370, 203, 225, 262, 203, 565, 3903, 203, 565, 8843, 429, 203, 565, 486, 382, 52, 689, 12, 409, 950, 13, 203, 565, 1158, 774, 321, 301, 4877, 15526, 1435, 203, 565, 3434, 6032, 6275, 12, 11890, 1370, 63, 20, 5717, 203, 565, 1135, 261, 11890, 13, 203, 225, 288, 203, 203, 565, 2583, 12, 11890, 1370, 63, 20, 65, 480, 374, 16, 315, 2050, 554, 1297, 486, 506, 3634, 8863, 203, 565, 2583, 12, 11890, 1370, 63, 21, 65, 480, 374, 16, 315, 38, 9835, 316, 3844, 1297, 486, 506, 3634, 8863, 203, 565, 2583, 12, 11890, 1370, 63, 22, 65, 480, 374, 16, 315, 13652, 1056, 1297, 486, 506, 3634, 8863, 203, 203, 565, 2254, 24123, 1380, 273, 24123, 18, 2469, 31, 203, 565, 2583, 12, 30720, 1380, 1545, 404, 16, 315, 10136, 1240, 622, 4520, 1245, 7433, 8863, 203, 565, 364, 261, 11890, 277, 273, 374, 31, 277, 411, 24123, 1380, 31, 277, 27245, 288, 203, 1377, 2583, 12443, 30720, 63, 77, 5717, 405, 374, 16, 315, 10136, 486, 1240, 3634, 24123, 8863, 203, 1377, 2078, 24051, 63, 869, 321, 301, 4877, 18, 2469, 300, 404, 65, 1011, 24123, 63, 77, 15533, 203, 565, 289, 203, 203, 1377, 2254, 1370, 63, 21, 6487, 2 ]
/* Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the pStake-smartContracts contributors SPDX-License-Identifier: Apache-2.0 */ pragma solidity >=0.7.0; import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol"; import "./interfaces/ISTokensV2.sol"; import "./interfaces/IUTokensV2.sol"; import "./interfaces/ILiquidStakingV2.sol"; import "./libraries/FullMath.sol"; contract LiquidStakingV2 is ILiquidStakingV2, PausableUpgradeable, AccessControlUpgradeable { using SafeMathUpgradeable for uint256; using FullMath for uint256; //Private instances of contracts to handle Utokens and Stokens IUTokensV2 public _uTokens; ISTokensV2 public _sTokens; // defining the fees and minimum values uint256 private _minStake; uint256 private _minUnstake; uint256 private _stakeFee; uint256 private _unstakeFee; uint256 public _valueDivisor; // constants defining access control ROLES bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); // variables pertaining to unbonding logic uint256 private _unstakingLockTime; uint256 private _epochInterval; uint256 private _unstakeEpoch; uint256 private _unstakeEpochPrevious; //Mapping to handle the Expiry period mapping(address => uint256[]) public _unstakingExpiration; //Mapping to handle the Expiry amount mapping(address => uint256[]) public _unstakingAmount; //mappint to handle a counter variable indicating from what index to start the loop. mapping(address => uint256) public _withdrawCounters; // variable pertaining to contract upgrades versioning uint256 public _version; uint256 public _batchingLimit; /** * @dev Constructor for initializing the LiquidStaking contract. * @param uAddress - address of the UToken contract. * @param sAddress - address of the SToken contract. * @param pauserAddress - address of the pauser admin. * @param unstakingLockTime - varies from 21 hours to 21 days. * @param epochInterval - varies from 3 hours to 3 days. * @param valueDivisor - valueDivisor set to 10^9. */ function initialize( address uAddress, address sAddress, address pauserAddress, uint256 unstakingLockTime, uint256 epochInterval, uint256 valueDivisor ) public virtual initializer { __AccessControl_init(); __Pausable_init(); _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); _setupRole(PAUSER_ROLE, pauserAddress); setUTokensContract(uAddress); setSTokensContract(sAddress); setUnstakingLockTime(unstakingLockTime); setMinimumValues(1, 1); _valueDivisor = valueDivisor; setUnstakeEpoch(block.timestamp, block.timestamp, epochInterval); } /** * @dev Set 'fees', called from admin * @param stakeFee: stake fee * @param unstakeFee: unstake fee * * Emits a {SetFees} event with 'fee' set to the stake and unstake. * */ function setFees(uint256 stakeFee, uint256 unstakeFee) public virtual override returns (bool success) { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "LQ1"); // range checks for fees. Since fee cannot be more than 100%, the max cap // is _valueDivisor * 100, which then brings the fees to 100 (percentage) require( (stakeFee <= _valueDivisor.mul(100) || stakeFee == 0) && (unstakeFee <= _valueDivisor.mul(100) || unstakeFee == 0), "LQ2" ); _stakeFee = stakeFee; _unstakeFee = unstakeFee; emit SetFees(stakeFee, unstakeFee); return true; } /** * @dev Set 'unstake props', called from admin * @param unstakingLockTime: varies from 21 hours to 21 days * * Emits a {SetUnstakeProps} event with 'fee' set to the stake and unstake. * */ function setUnstakingLockTime(uint256 unstakingLockTime) public virtual override returns (bool success) { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "LQ3"); _unstakingLockTime = unstakingLockTime; emit SetUnstakingLockTime(unstakingLockTime); return true; } /** * @dev get fees, min values, value divisor and epoch props * */ function getStakeUnstakeProps() public view virtual override returns ( uint256 stakeFee, uint256 unstakeFee, uint256 minStake, uint256 minUnstake, uint256 valueDivisor, uint256 epochInterval, uint256 unstakeEpoch, uint256 unstakeEpochPrevious, uint256 unstakingLockTime ) { stakeFee = _stakeFee; unstakeFee = _unstakeFee; minStake = _minStake; minUnstake = _minStake; valueDivisor = _valueDivisor; epochInterval = _epochInterval; unstakeEpoch = _unstakeEpoch; unstakeEpochPrevious = _unstakeEpochPrevious; unstakingLockTime = _unstakingLockTime; } /** * @dev Set 'minimum values', called from admin * @param minStake: stake minimum value * @param minUnstake: unstake minimum value * * Emits a {SetMinimumValues} event with 'minimum value' set to the stake and unstake. * */ function setMinimumValues(uint256 minStake, uint256 minUnstake) public virtual override returns (bool success) { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "LQ4"); require(minStake >= 1, "LQ5"); require(minUnstake >= 1, "LQ6"); _minStake = minStake; _minUnstake = minUnstake; emit SetMinimumValues(minStake, minUnstake); return true; } /** * @dev Set 'unstake epoch', called from admin * @param unstakeEpoch: unstake epoch * @param unstakeEpochPrevious: unstake epoch previous(initially set to same value as unstakeEpoch) * @param epochInterval: varies from 3 hours to 3 days * * Emits a {SetUnstakeEpoch} event with 'unstakeEpoch' * */ function setUnstakeEpoch( uint256 unstakeEpoch, uint256 unstakeEpochPrevious, uint256 epochInterval ) public virtual override returns (bool success) { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "LQ7"); require(unstakeEpochPrevious <= unstakeEpoch, "LQ8"); if (unstakeEpoch == 0 && epochInterval != 0) revert("LQ9"); _unstakeEpoch = unstakeEpoch; _unstakeEpochPrevious = unstakeEpochPrevious; _epochInterval = epochInterval; emit SetUnstakeEpoch(unstakeEpoch, unstakeEpochPrevious, epochInterval); return true; } /** * @dev Set 'contract address', called from constructor * @param uAddress: utoken contract address * * Emits a {SetUTokensContract} event with '_contract' set to the utoken contract address. * */ function setUTokensContract(address uAddress) public virtual override { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "LQ10"); _uTokens = IUTokensV2(uAddress); emit SetUTokensContract(uAddress); } /** * @dev Set 'contract address', called from constructor * @param sAddress: stoken contract address * * Emits a {SetSTokensContract} event with '_contract' set to the stoken contract address. * */ function setSTokensContract(address sAddress) public virtual override { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "LQ11"); _sTokens = ISTokensV2(sAddress); emit SetSTokensContract(sAddress); } /** * @dev Stake utokens over the platform with address 'to' for desired 'amount'(Burn uTokens and Mint sTokens) * @param to: user address for staking, amount: number of tokens to stake * * * Requirements: * * - `amount` cannot be less than zero. * - 'amount' cannot be more than balance * - 'amount' plus new balance should be equal to the old balance * * Emits a {StakeTokens} event * */ function stake(address to, uint256 amount) public virtual override whenNotPaused returns (bool) { // Check the supplied amount is greater than minimum stake value require(to == _msgSender(), "LQ12"); // Check the current balance for uTokens is greater than the amount to be staked uint256 _currentUTokenBalance = _uTokens.balanceOf(to); uint256 _stakeFeeAmount = (amount.mulDiv(_stakeFee, _valueDivisor)).div( 100 ); uint256 _finalTokens = amount.add(_stakeFeeAmount); // the value which should be greater than or equal to _minStake // is amount since minval applies to number of sTokens to be minted require(amount >= _minStake, "LQ13"); require(_currentUTokenBalance >= _finalTokens, "LQ14"); emit StakeTokens(to, amount, _finalTokens, block.timestamp); // Burn the uTokens as specified with the amount _uTokens.burn(to, _finalTokens); // Mint the sTokens for the account specified _sTokens.mint(to, amount); return true; } /** * @dev UnStake stokens over the platform with address 'to' for desired 'amount' (Burn sTokens and Mint uTokens with 21 days locking period) * @param to: user address for staking, amount: number of tokens to unstake * * * Requirements: * * - `amount` cannot be less than zero. * - 'amount' cannot be more than balance * - 'amount' plus new balance should be equal to the old balance * * Emits a {UnstakeTokens} event * */ function unStake(address to, uint256 amount) public virtual override whenNotPaused returns (bool) { // Check the supplied amount is greater than 0 require(to == _msgSender(), "LQ15"); // Check the current balance for sTokens is greater than the amount to be unStaked uint256 _currentSTokenBalance = _sTokens.balanceOf(to); uint256 _unstakeFeeAmount = (amount.mulDiv(_unstakeFee, _valueDivisor)) .div(100); uint256 _finalTokens = amount.add(_unstakeFeeAmount); // the value which should be greater than or equal to _minSUnstake // is amount since minval applies to number of uTokens to be withdrawn require(amount >= _minUnstake, "LQ18"); require(_currentSTokenBalance >= _finalTokens, "LQ19"); // Burn the sTokens as specified with the amount _sTokens.burn(to, _finalTokens); _unstakingExpiration[to].push(block.timestamp); // array will hold amount and not _finalTokens because that is the amount of // uTokens pending to be credited after withdraw period _unstakingAmount[to].push(amount); // the event needs to capture _finalTokens that were and not amount emit UnstakeTokens(to, amount, _finalTokens, block.timestamp); return true; } /** * @dev returns the nearest epoch milestone in the future */ function getUnstakeEpochMilestone(uint256 _unstakeTimestamp) public view virtual override returns (uint256 unstakeEpochMilestone) { if (_unstakeTimestamp == 0) return 0; // if epoch values are not relevant, then the epoch milestone is the unstake timestamp itself (backward compatibility) if ( (_unstakeEpoch == 0 && _unstakeEpochPrevious == 0) || _epochInterval == 0 ) return _unstakeTimestamp; if (_unstakeEpoch > _unstakeTimestamp) return (_unstakeEpoch); uint256 _referenceStartTime = (_unstakeTimestamp).add( _unstakeEpoch.sub(_unstakeEpochPrevious) ); uint256 _timeDiff = _referenceStartTime.sub(_unstakeEpoch); unstakeEpochMilestone = (_timeDiff.mod(_epochInterval)).add( _referenceStartTime ); return (unstakeEpochMilestone); } /** * @dev returns the time left for unbonding to finish */ function getUnstakeTime(uint256 _unstakeTimestamp) public view virtual override returns ( uint256 unstakeTime, uint256 unstakeEpoch, uint256 unstakeEpochPrevious ) { uint256 _unstakeEpochMilestone = getUnstakeEpochMilestone( _unstakeTimestamp ); if (_unstakeEpochMilestone == 0) return (0, unstakeEpoch, unstakeEpochPrevious); unstakeEpoch = _unstakeEpoch; unstakeEpochPrevious = _unstakeEpochPrevious; //adding unstakingLockTime with epoch difference unstakeTime = _unstakeEpochMilestone.add(_unstakingLockTime); return (unstakeTime, unstakeEpoch, unstakeEpochPrevious); } /** * @dev Lock the unstaked tokens for 21 days, user can withdraw the same (Mint uTokens with 21 days locking period) * * @param staker: user address for withdraw * * Requirements: * * - `current block timestamp` should be after 21 days from the period where unstaked function is called. * * Emits a {WithdrawUnstakeTokens} event * */ function withdrawUnstakedTokens(address staker) public virtual override whenNotPaused { require(staker == _msgSender(), "LQ20"); uint256 _withdrawBalance; uint256 _counter = _withdrawCounters[staker]; uint256 _counter2 = _withdrawCounters[staker]; uint256 _unstakingExpirationLength = _unstakingExpiration[staker] .length > _batchingLimit.add(_counter) ? _batchingLimit.add(_counter) : _unstakingExpiration[staker].length; for ( uint256 i = _counter; i < _unstakingExpirationLength; i = i.add(1) ) { //get getUnstakeTime and compare it with current timestamp to check if 21 days + epoch difference has passed (uint256 _getUnstakeTime, , ) = getUnstakeTime( _unstakingExpiration[staker][i] ); if (block.timestamp >= _getUnstakeTime) { //if 21 days + epoch difference has passed, then add the balance and then mint uTokens _withdrawBalance = _withdrawBalance.add( _unstakingAmount[staker][i] ); delete _unstakingExpiration[staker][i]; delete _unstakingAmount[staker][i]; _counter2 = _counter2.add(1); } } // update _withdrawCounters[staker] only once outside for loop to save gas _withdrawCounters[staker] = _counter2; require(_withdrawBalance > 0, "LQ21"); emit WithdrawUnstakeTokens(staker, _withdrawBalance, block.timestamp); _uTokens.mint(staker, _withdrawBalance); } /** * @dev get Total Unbonded Tokens * @param staker: account address * */ function getTotalUnbondedTokens(address staker) public view virtual override returns (uint256 unbondingTokens) { uint256 _unstakingExpirationLength = _unstakingExpiration[staker] .length; uint256 _counter = _withdrawCounters[staker]; for ( uint256 i = _counter; i < _unstakingExpirationLength; i = i.add(1) ) { //get getUnstakeTime and compare it with current timestamp to check if 21 days + epoch difference has passed (uint256 _getUnstakeTime, , ) = getUnstakeTime( _unstakingExpiration[staker][i] ); if (block.timestamp >= _getUnstakeTime) { //if 21 days + epoch difference has passed, then check the token amount and send back unbondingTokens = unbondingTokens.add( _unstakingAmount[staker][i] ); } } return unbondingTokens; } /** * @dev get Total Unbonding Tokens * @param staker: account address * */ function getTotalUnbondingTokens(address staker) public view virtual override returns (uint256 unbondingTokens) { uint256 _unstakingExpirationLength = _unstakingExpiration[staker] .length; uint256 _counter = _withdrawCounters[staker]; for ( uint256 i = _counter; i < _unstakingExpirationLength; i = i.add(1) ) { //get getUnstakeTime and compare it with current timestamp to check if 21 days + epoch difference has passed (uint256 _getUnstakeTime, , ) = getUnstakeTime( _unstakingExpiration[staker][i] ); if (block.timestamp < _getUnstakeTime) { //if 21 days + epoch difference have not passed, then check the token amount and send back unbondingTokens = unbondingTokens.add( _unstakingAmount[staker][i] ); } } return unbondingTokens; } /** * @dev Set 'batching limit', called from admin * @param batchingLimit: batching limit * * Emits a {SetBatchingLimit} event. * */ function setBatchingLimit(uint256 batchingLimit) public virtual override returns (bool success) { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "LQ24"); _batchingLimit = batchingLimit; emit SetBatchingLimit(batchingLimit, block.timestamp); success = true; return success; } /** * @dev get batching limit * */ function getBatchingLimit() public view virtual override returns (uint256 batchingLimit) { batchingLimit = _batchingLimit; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function pause() public virtual override returns (bool success) { require(hasRole(PAUSER_ROLE, _msgSender()), "LQ22"); _pause(); return true; } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function unpause() public virtual override returns (bool success) { require(hasRole(PAUSER_ROLE, _msgSender()), "LQ23"); _unpause(); return true; } }
* @dev Constructor for initializing the LiquidStaking contract. @param uAddress - address of the UToken contract. @param sAddress - address of the SToken contract. @param pauserAddress - address of the pauser admin. @param unstakingLockTime - varies from 21 hours to 21 days. @param epochInterval - varies from 3 hours to 3 days. @param valueDivisor - valueDivisor set to 10^9./
) public virtual initializer { __AccessControl_init(); __Pausable_init(); _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); _setupRole(PAUSER_ROLE, pauserAddress); setUTokensContract(uAddress); setSTokensContract(sAddress); setUnstakingLockTime(unstakingLockTime); setMinimumValues(1, 1); _valueDivisor = valueDivisor; setUnstakeEpoch(block.timestamp, block.timestamp, epochInterval); }
5,473,701
[ 1, 6293, 364, 22584, 326, 511, 18988, 350, 510, 6159, 6835, 18, 225, 582, 1887, 300, 1758, 434, 326, 587, 1345, 6835, 18, 225, 272, 1887, 300, 1758, 434, 326, 348, 1345, 6835, 18, 225, 6790, 1355, 1887, 300, 1758, 434, 326, 6790, 1355, 3981, 18, 225, 640, 334, 6159, 2531, 950, 300, 569, 606, 628, 9035, 7507, 358, 9035, 4681, 18, 225, 7632, 4006, 300, 569, 606, 628, 890, 7507, 358, 890, 4681, 18, 225, 460, 7244, 12385, 300, 460, 7244, 12385, 444, 358, 1728, 66, 29, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 202, 13, 1071, 5024, 12562, 288, 203, 202, 202, 972, 16541, 67, 2738, 5621, 203, 202, 202, 972, 16507, 16665, 67, 2738, 5621, 203, 202, 202, 67, 8401, 2996, 12, 5280, 67, 15468, 67, 16256, 16, 389, 3576, 12021, 10663, 203, 202, 202, 67, 8401, 2996, 12, 4066, 4714, 67, 16256, 16, 6790, 1355, 1887, 1769, 203, 202, 202, 542, 1693, 3573, 8924, 12, 89, 1887, 1769, 203, 202, 202, 542, 882, 3573, 8924, 12, 87, 1887, 1769, 203, 202, 202, 542, 984, 334, 6159, 2531, 950, 12, 23412, 6159, 2531, 950, 1769, 203, 202, 202, 542, 13042, 1972, 12, 21, 16, 404, 1769, 203, 202, 202, 67, 1132, 7244, 12385, 273, 460, 7244, 12385, 31, 203, 202, 202, 542, 984, 334, 911, 14638, 12, 2629, 18, 5508, 16, 1203, 18, 5508, 16, 7632, 4006, 1769, 203, 202, 97, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0x195DA0e844b2F4d6D52eF82BfCedee5e1F8CDacF/sources/contracts/15yrslater.sol
using TWBitMaps for TWBitMaps.BitMap; bytes memory _data
contract XVYrsLater is ERC1155Drop, DefaultOperatorFilterer{ constructor( string memory _name, string memory _symbol, address _royaltyRecipient, uint128 _royaltyBps, address _primarySaleRecipient ) ERC1155Drop( _name, _symbol, _royaltyRecipient, _royaltyBps, _primarySaleRecipient ) mapping(uint256 => bytes32) private conditionId; mapping(bytes32 => mapping(address => uint256)) private lastClaimTimestamp; mapping(bytes32 => mapping(address => uint256)) private supplyClaimedByWallet; function claimBatch( address _receiver, uint256[] memory ids, address _currency, uint256 _pricePerToken, AllowlistProof calldata _allowlistProof pragma solidity ^0.8.0; {} ) public payable virtual { for (uint256 i = 0; i < ids.length; i++) { uint256 id = ids[i]; ClaimCondition memory condition = claimCondition[0]; bytes32 activeConditionId = conditionId[0]; verifyClaims(id, _dropMsgSender(), 1, _currency, _pricePerToken, _allowlistProof); condition.supplyClaimed += 1; supplyClaimedByWallet[activeConditionId][_dropMsgSender()] += 1; claimCondition[0] = condition; } for (uint256 i = 0; i < ids.length; i++) { uint256 id = ids[i]; _transferTokensOnClaim(_receiver, id, 1); emit TokensClaimed(_dropMsgSender(), _receiver, id, 1); } } ) public payable virtual { for (uint256 i = 0; i < ids.length; i++) { uint256 id = ids[i]; ClaimCondition memory condition = claimCondition[0]; bytes32 activeConditionId = conditionId[0]; verifyClaims(id, _dropMsgSender(), 1, _currency, _pricePerToken, _allowlistProof); condition.supplyClaimed += 1; supplyClaimedByWallet[activeConditionId][_dropMsgSender()] += 1; claimCondition[0] = condition; } for (uint256 i = 0; i < ids.length; i++) { uint256 id = ids[i]; _transferTokensOnClaim(_receiver, id, 1); emit TokensClaimed(_dropMsgSender(), _receiver, id, 1); } } _collectPriceOnClaim(address(0), ids.length, _currency, _pricePerToken); ) public payable virtual { for (uint256 i = 0; i < ids.length; i++) { uint256 id = ids[i]; ClaimCondition memory condition = claimCondition[0]; bytes32 activeConditionId = conditionId[0]; verifyClaims(id, _dropMsgSender(), 1, _currency, _pricePerToken, _allowlistProof); condition.supplyClaimed += 1; supplyClaimedByWallet[activeConditionId][_dropMsgSender()] += 1; claimCondition[0] = condition; } for (uint256 i = 0; i < ids.length; i++) { uint256 id = ids[i]; _transferTokensOnClaim(_receiver, id, 1); emit TokensClaimed(_dropMsgSender(), _receiver, id, 1); } } function claim( address _receiver, uint256 _tokenId, uint256 _quantity, address _currency, uint256 _pricePerToken, AllowlistProof calldata _allowlistProof, bytes memory _data ) public payable virtual override { _beforeClaim(_tokenId, _receiver, _quantity, _currency, _pricePerToken, _allowlistProof, _data); ClaimCondition memory condition = claimCondition[0]; bytes32 activeConditionId = conditionId[0]; verifyClaims(_tokenId, _dropMsgSender(), 1, _currency, _pricePerToken, _allowlistProof); condition.supplyClaimed += 1; supplyClaimedByWallet[activeConditionId][_dropMsgSender()] += 1; claimCondition[0] = condition; _collectPriceOnClaim(address(0), _quantity, _currency, _pricePerToken); _transferTokensOnClaim(_receiver, _tokenId, _quantity); emit TokensClaimed(_dropMsgSender(), _receiver, _tokenId, _quantity); _afterClaim(_tokenId, _receiver, _quantity, _currency, _pricePerToken, _allowlistProof, _data); } function verifyClaims( uint256 _tokenId, address _claimer, uint256 _quantity, address _currency, uint256 _pricePerToken, AllowlistProof calldata _allowlistProof ) public view returns (bool isOverride) { ClaimCondition memory currentClaimPhase = claimCondition[0]; uint256 claimLimit = currentClaimPhase.quantityLimitPerWallet; uint256 claimPrice = currentClaimPhase.pricePerToken; address claimCurrency = currentClaimPhase.currency; if (totalSupply[_tokenId] != 0) { revert("exceeds max supply"); } uint256 _supplyClaimedByWallet = supplyClaimedByWallet[conditionId[0]][_claimer]; if (currentClaimPhase.merkleRoot != bytes32(0)) { (isActiveOverride, ) = MerkleProof.verify( _allowlistProof.proof, currentClaimPhase.merkleRoot, keccak256( abi.encodePacked( _claimer, _allowlistProof.quantityLimitPerWallet, _allowlistProof.pricePerToken, _allowlistProof.currency ) ) ); } if (isActiveOverride) { claimLimit = _allowlistProof.quantityLimitPerWallet != 0 ? _allowlistProof.quantityLimitPerWallet : claimLimit; claimPrice = _allowlistProof.pricePerToken != type(uint256).max ? _allowlistProof.pricePerToken : claimPrice; claimCurrency = _allowlistProof.pricePerToken != type(uint256).max && _allowlistProof.currency != address(0) ? _allowlistProof.currency : claimCurrency; } if (_currency != claimCurrency || _pricePerToken != claimPrice) { revert("!PriceOrCurrency"); } if (_quantity == 0 || (_quantity + _supplyClaimedByWallet > claimLimit)) { revert("!Qty"); } if (currentClaimPhase.supplyClaimed + _quantity > currentClaimPhase.maxClaimableSupply) { revert("!MaxSupply"); } if (currentClaimPhase.startTimestamp > block.timestamp) { revert("cant claim yet"); } } function verifyClaims( uint256 _tokenId, address _claimer, uint256 _quantity, address _currency, uint256 _pricePerToken, AllowlistProof calldata _allowlistProof ) public view returns (bool isOverride) { ClaimCondition memory currentClaimPhase = claimCondition[0]; uint256 claimLimit = currentClaimPhase.quantityLimitPerWallet; uint256 claimPrice = currentClaimPhase.pricePerToken; address claimCurrency = currentClaimPhase.currency; if (totalSupply[_tokenId] != 0) { revert("exceeds max supply"); } uint256 _supplyClaimedByWallet = supplyClaimedByWallet[conditionId[0]][_claimer]; if (currentClaimPhase.merkleRoot != bytes32(0)) { (isActiveOverride, ) = MerkleProof.verify( _allowlistProof.proof, currentClaimPhase.merkleRoot, keccak256( abi.encodePacked( _claimer, _allowlistProof.quantityLimitPerWallet, _allowlistProof.pricePerToken, _allowlistProof.currency ) ) ); } if (isActiveOverride) { claimLimit = _allowlistProof.quantityLimitPerWallet != 0 ? _allowlistProof.quantityLimitPerWallet : claimLimit; claimPrice = _allowlistProof.pricePerToken != type(uint256).max ? _allowlistProof.pricePerToken : claimPrice; claimCurrency = _allowlistProof.pricePerToken != type(uint256).max && _allowlistProof.currency != address(0) ? _allowlistProof.currency : claimCurrency; } if (_currency != claimCurrency || _pricePerToken != claimPrice) { revert("!PriceOrCurrency"); } if (_quantity == 0 || (_quantity + _supplyClaimedByWallet > claimLimit)) { revert("!Qty"); } if (currentClaimPhase.supplyClaimed + _quantity > currentClaimPhase.maxClaimableSupply) { revert("!MaxSupply"); } if (currentClaimPhase.startTimestamp > block.timestamp) { revert("cant claim yet"); } } bool isActiveOverride = (isOverride && _supplyClaimedByWallet < _quantity) ? true : false; function verifyClaims( uint256 _tokenId, address _claimer, uint256 _quantity, address _currency, uint256 _pricePerToken, AllowlistProof calldata _allowlistProof ) public view returns (bool isOverride) { ClaimCondition memory currentClaimPhase = claimCondition[0]; uint256 claimLimit = currentClaimPhase.quantityLimitPerWallet; uint256 claimPrice = currentClaimPhase.pricePerToken; address claimCurrency = currentClaimPhase.currency; if (totalSupply[_tokenId] != 0) { revert("exceeds max supply"); } uint256 _supplyClaimedByWallet = supplyClaimedByWallet[conditionId[0]][_claimer]; if (currentClaimPhase.merkleRoot != bytes32(0)) { (isActiveOverride, ) = MerkleProof.verify( _allowlistProof.proof, currentClaimPhase.merkleRoot, keccak256( abi.encodePacked( _claimer, _allowlistProof.quantityLimitPerWallet, _allowlistProof.pricePerToken, _allowlistProof.currency ) ) ); } if (isActiveOverride) { claimLimit = _allowlistProof.quantityLimitPerWallet != 0 ? _allowlistProof.quantityLimitPerWallet : claimLimit; claimPrice = _allowlistProof.pricePerToken != type(uint256).max ? _allowlistProof.pricePerToken : claimPrice; claimCurrency = _allowlistProof.pricePerToken != type(uint256).max && _allowlistProof.currency != address(0) ? _allowlistProof.currency : claimCurrency; } if (_currency != claimCurrency || _pricePerToken != claimPrice) { revert("!PriceOrCurrency"); } if (_quantity == 0 || (_quantity + _supplyClaimedByWallet > claimLimit)) { revert("!Qty"); } if (currentClaimPhase.supplyClaimed + _quantity > currentClaimPhase.maxClaimableSupply) { revert("!MaxSupply"); } if (currentClaimPhase.startTimestamp > block.timestamp) { revert("cant claim yet"); } } function verifyClaims( uint256 _tokenId, address _claimer, uint256 _quantity, address _currency, uint256 _pricePerToken, AllowlistProof calldata _allowlistProof ) public view returns (bool isOverride) { ClaimCondition memory currentClaimPhase = claimCondition[0]; uint256 claimLimit = currentClaimPhase.quantityLimitPerWallet; uint256 claimPrice = currentClaimPhase.pricePerToken; address claimCurrency = currentClaimPhase.currency; if (totalSupply[_tokenId] != 0) { revert("exceeds max supply"); } uint256 _supplyClaimedByWallet = supplyClaimedByWallet[conditionId[0]][_claimer]; if (currentClaimPhase.merkleRoot != bytes32(0)) { (isActiveOverride, ) = MerkleProof.verify( _allowlistProof.proof, currentClaimPhase.merkleRoot, keccak256( abi.encodePacked( _claimer, _allowlistProof.quantityLimitPerWallet, _allowlistProof.pricePerToken, _allowlistProof.currency ) ) ); } if (isActiveOverride) { claimLimit = _allowlistProof.quantityLimitPerWallet != 0 ? _allowlistProof.quantityLimitPerWallet : claimLimit; claimPrice = _allowlistProof.pricePerToken != type(uint256).max ? _allowlistProof.pricePerToken : claimPrice; claimCurrency = _allowlistProof.pricePerToken != type(uint256).max && _allowlistProof.currency != address(0) ? _allowlistProof.currency : claimCurrency; } if (_currency != claimCurrency || _pricePerToken != claimPrice) { revert("!PriceOrCurrency"); } if (_quantity == 0 || (_quantity + _supplyClaimedByWallet > claimLimit)) { revert("!Qty"); } if (currentClaimPhase.supplyClaimed + _quantity > currentClaimPhase.maxClaimableSupply) { revert("!MaxSupply"); } if (currentClaimPhase.startTimestamp > block.timestamp) { revert("cant claim yet"); } } function verifyClaims( uint256 _tokenId, address _claimer, uint256 _quantity, address _currency, uint256 _pricePerToken, AllowlistProof calldata _allowlistProof ) public view returns (bool isOverride) { ClaimCondition memory currentClaimPhase = claimCondition[0]; uint256 claimLimit = currentClaimPhase.quantityLimitPerWallet; uint256 claimPrice = currentClaimPhase.pricePerToken; address claimCurrency = currentClaimPhase.currency; if (totalSupply[_tokenId] != 0) { revert("exceeds max supply"); } uint256 _supplyClaimedByWallet = supplyClaimedByWallet[conditionId[0]][_claimer]; if (currentClaimPhase.merkleRoot != bytes32(0)) { (isActiveOverride, ) = MerkleProof.verify( _allowlistProof.proof, currentClaimPhase.merkleRoot, keccak256( abi.encodePacked( _claimer, _allowlistProof.quantityLimitPerWallet, _allowlistProof.pricePerToken, _allowlistProof.currency ) ) ); } if (isActiveOverride) { claimLimit = _allowlistProof.quantityLimitPerWallet != 0 ? _allowlistProof.quantityLimitPerWallet : claimLimit; claimPrice = _allowlistProof.pricePerToken != type(uint256).max ? _allowlistProof.pricePerToken : claimPrice; claimCurrency = _allowlistProof.pricePerToken != type(uint256).max && _allowlistProof.currency != address(0) ? _allowlistProof.currency : claimCurrency; } if (_currency != claimCurrency || _pricePerToken != claimPrice) { revert("!PriceOrCurrency"); } if (_quantity == 0 || (_quantity + _supplyClaimedByWallet > claimLimit)) { revert("!Qty"); } if (currentClaimPhase.supplyClaimed + _quantity > currentClaimPhase.maxClaimableSupply) { revert("!MaxSupply"); } if (currentClaimPhase.startTimestamp > block.timestamp) { revert("cant claim yet"); } } function verifyClaims( uint256 _tokenId, address _claimer, uint256 _quantity, address _currency, uint256 _pricePerToken, AllowlistProof calldata _allowlistProof ) public view returns (bool isOverride) { ClaimCondition memory currentClaimPhase = claimCondition[0]; uint256 claimLimit = currentClaimPhase.quantityLimitPerWallet; uint256 claimPrice = currentClaimPhase.pricePerToken; address claimCurrency = currentClaimPhase.currency; if (totalSupply[_tokenId] != 0) { revert("exceeds max supply"); } uint256 _supplyClaimedByWallet = supplyClaimedByWallet[conditionId[0]][_claimer]; if (currentClaimPhase.merkleRoot != bytes32(0)) { (isActiveOverride, ) = MerkleProof.verify( _allowlistProof.proof, currentClaimPhase.merkleRoot, keccak256( abi.encodePacked( _claimer, _allowlistProof.quantityLimitPerWallet, _allowlistProof.pricePerToken, _allowlistProof.currency ) ) ); } if (isActiveOverride) { claimLimit = _allowlistProof.quantityLimitPerWallet != 0 ? _allowlistProof.quantityLimitPerWallet : claimLimit; claimPrice = _allowlistProof.pricePerToken != type(uint256).max ? _allowlistProof.pricePerToken : claimPrice; claimCurrency = _allowlistProof.pricePerToken != type(uint256).max && _allowlistProof.currency != address(0) ? _allowlistProof.currency : claimCurrency; } if (_currency != claimCurrency || _pricePerToken != claimPrice) { revert("!PriceOrCurrency"); } if (_quantity == 0 || (_quantity + _supplyClaimedByWallet > claimLimit)) { revert("!Qty"); } if (currentClaimPhase.supplyClaimed + _quantity > currentClaimPhase.maxClaimableSupply) { revert("!MaxSupply"); } if (currentClaimPhase.startTimestamp > block.timestamp) { revert("cant claim yet"); } } function verifyClaims( uint256 _tokenId, address _claimer, uint256 _quantity, address _currency, uint256 _pricePerToken, AllowlistProof calldata _allowlistProof ) public view returns (bool isOverride) { ClaimCondition memory currentClaimPhase = claimCondition[0]; uint256 claimLimit = currentClaimPhase.quantityLimitPerWallet; uint256 claimPrice = currentClaimPhase.pricePerToken; address claimCurrency = currentClaimPhase.currency; if (totalSupply[_tokenId] != 0) { revert("exceeds max supply"); } uint256 _supplyClaimedByWallet = supplyClaimedByWallet[conditionId[0]][_claimer]; if (currentClaimPhase.merkleRoot != bytes32(0)) { (isActiveOverride, ) = MerkleProof.verify( _allowlistProof.proof, currentClaimPhase.merkleRoot, keccak256( abi.encodePacked( _claimer, _allowlistProof.quantityLimitPerWallet, _allowlistProof.pricePerToken, _allowlistProof.currency ) ) ); } if (isActiveOverride) { claimLimit = _allowlistProof.quantityLimitPerWallet != 0 ? _allowlistProof.quantityLimitPerWallet : claimLimit; claimPrice = _allowlistProof.pricePerToken != type(uint256).max ? _allowlistProof.pricePerToken : claimPrice; claimCurrency = _allowlistProof.pricePerToken != type(uint256).max && _allowlistProof.currency != address(0) ? _allowlistProof.currency : claimCurrency; } if (_currency != claimCurrency || _pricePerToken != claimPrice) { revert("!PriceOrCurrency"); } if (_quantity == 0 || (_quantity + _supplyClaimedByWallet > claimLimit)) { revert("!Qty"); } if (currentClaimPhase.supplyClaimed + _quantity > currentClaimPhase.maxClaimableSupply) { revert("!MaxSupply"); } if (currentClaimPhase.startTimestamp > block.timestamp) { revert("cant claim yet"); } } function verifyClaims( uint256 _tokenId, address _claimer, uint256 _quantity, address _currency, uint256 _pricePerToken, AllowlistProof calldata _allowlistProof ) public view returns (bool isOverride) { ClaimCondition memory currentClaimPhase = claimCondition[0]; uint256 claimLimit = currentClaimPhase.quantityLimitPerWallet; uint256 claimPrice = currentClaimPhase.pricePerToken; address claimCurrency = currentClaimPhase.currency; if (totalSupply[_tokenId] != 0) { revert("exceeds max supply"); } uint256 _supplyClaimedByWallet = supplyClaimedByWallet[conditionId[0]][_claimer]; if (currentClaimPhase.merkleRoot != bytes32(0)) { (isActiveOverride, ) = MerkleProof.verify( _allowlistProof.proof, currentClaimPhase.merkleRoot, keccak256( abi.encodePacked( _claimer, _allowlistProof.quantityLimitPerWallet, _allowlistProof.pricePerToken, _allowlistProof.currency ) ) ); } if (isActiveOverride) { claimLimit = _allowlistProof.quantityLimitPerWallet != 0 ? _allowlistProof.quantityLimitPerWallet : claimLimit; claimPrice = _allowlistProof.pricePerToken != type(uint256).max ? _allowlistProof.pricePerToken : claimPrice; claimCurrency = _allowlistProof.pricePerToken != type(uint256).max && _allowlistProof.currency != address(0) ? _allowlistProof.currency : claimCurrency; } if (_currency != claimCurrency || _pricePerToken != claimPrice) { revert("!PriceOrCurrency"); } if (_quantity == 0 || (_quantity + _supplyClaimedByWallet > claimLimit)) { revert("!Qty"); } if (currentClaimPhase.supplyClaimed + _quantity > currentClaimPhase.maxClaimableSupply) { revert("!MaxSupply"); } if (currentClaimPhase.startTimestamp > block.timestamp) { revert("cant claim yet"); } } }
1,906,187
[ 1, 9940, 24722, 5775, 8903, 364, 24722, 5775, 8903, 18, 5775, 863, 31, 1731, 3778, 389, 892, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 16351, 1139, 58, 61, 5453, 20607, 353, 4232, 39, 2499, 2539, 7544, 16, 2989, 5592, 1586, 264, 95, 203, 565, 3885, 12, 203, 3639, 533, 3778, 389, 529, 16, 203, 3639, 533, 3778, 389, 7175, 16, 203, 3639, 1758, 389, 3800, 15006, 18241, 16, 203, 3639, 2254, 10392, 389, 3800, 15006, 38, 1121, 16, 203, 3639, 1758, 389, 8258, 30746, 18241, 203, 565, 262, 203, 3639, 4232, 39, 2499, 2539, 7544, 12, 203, 5411, 389, 529, 16, 203, 5411, 389, 7175, 16, 203, 5411, 389, 3800, 15006, 18241, 16, 203, 5411, 389, 3800, 15006, 38, 1121, 16, 203, 5411, 389, 8258, 30746, 18241, 203, 3639, 262, 203, 565, 2874, 12, 11890, 5034, 516, 1731, 1578, 13, 3238, 2269, 548, 31, 203, 565, 2874, 12, 3890, 1578, 516, 2874, 12, 2867, 516, 2254, 5034, 3719, 3238, 1142, 9762, 4921, 31, 203, 203, 565, 2874, 12, 3890, 1578, 516, 2874, 12, 2867, 516, 2254, 5034, 3719, 3238, 14467, 9762, 18696, 16936, 31, 203, 203, 203, 565, 445, 7516, 4497, 12, 203, 3639, 1758, 389, 24454, 16, 203, 3639, 2254, 5034, 8526, 3778, 3258, 16, 203, 3639, 1758, 389, 7095, 16, 203, 3639, 2254, 5034, 389, 8694, 2173, 1345, 16, 203, 3639, 7852, 1098, 20439, 745, 892, 389, 5965, 1098, 20439, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 20, 31, 203, 565, 2618, 203, 565, 262, 1071, 8843, 429, 5024, 288, 203, 203, 3639, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 3258, 18, 2469, 31, 277, 27245, 288, 203, 5411, 2 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // copied from https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v4.1.0/contracts/token/ERC721/ERC721.sol // and merged with: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v4.1.0/contracts/token/ERC721/extensions/ERC721Enumerable.sol import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./IERC721Metadata.sol"; import "./IERC721Enumerable.sol"; import "./Address.sol"; import "./Context.sol"; import "./Strings.sol"; import "./ERC165.sol"; import "./Pausable.sol"; import "./ReentrancyGuard.sol"; import "./Proxy.sol"; // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-2309.md interface IERC2309 { event ConsecutiveTransfer(uint256 indexed fromTokenId, uint256 toTokenId, address indexed fromAddress, address indexed toAddress); } /** * @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 EvaverseNFT is ProxyTarget, Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable, IERC2309, Pausable, ReentrancyGuard { using Address for address; using Strings for uint256; string private _tokenName; string private _tokenSymbol; string private _baseURI; // 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; // 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; uint256 private _tokenCount; uint256 private _giveawayTokens; uint256 private _maxTokens; uint256 private _tokenPrice; address payable private _bankAddress; bool private _bankIsContract; bool private _initialized; // can't depend on a constructor because we have an upgradable proxy, have to initialize instead. function Initialize() onlyOwner external { require(!_initialized, "Contract instance has already been initialized"); _tokenName = "Evaverse"; _tokenSymbol = "EVA"; _baseURI = "https://evaverse.com/api/creatures.php?id="; _giveawayTokens = 500; _maxTokens = 10000; _tokenPrice = 100000000000000000; //0.1 ETH _initialized = true; _batchMint(Ownable.owner(), _giveawayTokens); } function IsInitialized() external view returns (bool) { return _initialized; } // Hopefully never need this. Leaving it as an option if we have unsold tokens, if we want to do another giveaway or something. function DevMint(address to, uint count) external onlyOwner { require(_tokenCount + count < _maxTokens, "EvaNFT: Not enough tokens remaining."); _batchMint(to, count); } function MintNFT(uint count) payable external whenNotPaused nonReentrant { require(_initialized, "EvaNFT: Contract is not initialized."); require(count > 0, "EvaNFT: Count must be greater than 0."); require(count <= 400, "EvaNFT: Count can't be that large, sorry."); require(_tokenCount < _maxTokens, "EvaNFT: No tokens left to purchase."); require(msg.value == count * _tokenPrice, "EvaNFT: Amount of ETH is not right."); // pro-rate any purchase that would have put us over the cap of total NFTs uint refundCount = 0; if (_tokenCount + count > _maxTokens) { refundCount = count - (_maxTokens - _tokenCount); count = _maxTokens - _tokenCount; } // Mint all our NFTs! _batchMint(_msgSender(), count); // Refund any Ether for NFTs that couldn't be minted. if (refundCount > 0) { address payable receiver = payable(_msgSender()); receiver.transfer(refundCount * _tokenPrice); } // Store funds in a wallet or other smart contract. if (_bankAddress != address(0)) { if (_bankIsContract) { // This is the only way I could get funds to receive in Gnosis Safe. (bool sent, ) = _bankAddress.call{value: msg.value}(""); require(sent, "Failed to send Ether"); } else { _bankAddress.transfer(msg.value); } } } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "EvaNFT: balance query for the zero address"); return owner == Ownable.owner() ? 0 : _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "EvaNFT: owner query for nonexistent token"); address owner = _owners[tokenId]; return owner != address(0) ? owner : Ownable.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), "EvaNFT: URI query for nonexistent token"); return string(abi.encodePacked(_baseURI, tokenId.toString())); } function baseURI() public view returns (string memory) { return _baseURI; } function setBaseURI(string memory uri) external onlyOwner { _baseURI = uri; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override whenNotPaused { address owner = EvaverseNFT.ownerOf(tokenId); require(to != owner, "EvaNFT: approval to current owner"); require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()), "EvaNFT: 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), "EvaNFT: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override whenNotPaused { require(operator != _msgSender(), "EvaNFT: 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 whenNotPaused { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "EvaNFT: 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 whenNotPaused { require(_isApprovedOrOwner(_msgSender(), tokenId), "EvaNFT: 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), "EvaNFT: 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 tokenId > 0 && tokenId <= _tokenCount; } /** * @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), "EvaNFT: operator query for nonexistent token"); address owner = EvaverseNFT.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } function _batchMint(address to, uint count) internal { require(to != address(0), "EvaNFT: mint to the zero address"); uint256 tokenId = _tokenCount + 1; uint256 startToken = tokenId; uint256 endToken = tokenId + count; // Don't need to run this code on the owner, those tokens are... virtual? if (to != Ownable.owner()) { for(; tokenId < endToken; tokenId++) { _owners[tokenId] = to; } } _balances[to] += count; _tokenCount += count; emit ConsecutiveTransfer(startToken, endToken, address(0), to); } /** * @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(EvaverseNFT.ownerOf(tokenId) == from, "EvaNFT: transfer of token that is not own"); require(to != address(0), "EvaNFT: 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 whenNotPaused { _tokenApprovals[tokenId] = to; emit Approval(EvaverseNFT.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("EvaNFT: transfer to non ERC721Receiver implementer"); } else { // solhint-disable-next-line no-inline-assembly assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < EvaverseNFT.balanceOf(owner), "EvaNFT: owner index out of bounds"); require(owner != Ownable.owner(), "EvaNFT: contract owner tokenOfOwnerByIndex not supported"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _tokenCount; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < EvaverseNFT.totalSupply(), "EvaNFT: global index out of bounds"); return index + 1; } /** * @dev Hook that is called before any token transfer. * * 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) private { if (from == address(0)) { // this would only ever be called single single minting, which we don't care about //_addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { // this is only ever used in burning, which we don't care about. //_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 { if (to == Ownable.owner()) return; uint256 length = EvaverseNFT.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @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). if (from == Ownable.owner()) return; uint256 lastTokenIndex = EvaverseNFT.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]; } function SetPause(bool pause) external onlyOwner { if (pause) _pause(); else _unpause(); } function WithdrawBalance(address payTo, uint256 amount) external onlyOwner { address thisAddr = address(this); require(thisAddr.balance > 0); address payable receiver = payable(payTo); receiver.transfer(amount); } function SendGiftToWinners(uint256 startTokenId, address[] memory winners) external onlyOwner { for(uint ii = 0; ii < winners.length; ii++) { uint256 tokenId = startTokenId + ii; require(tokenId <= _giveawayTokens, "We can't give away that many."); // we must also be the owner, but that require check is already inside safeTransferFrom safeTransferFrom(Ownable.owner(), winners[ii], tokenId); } } function GetBalance() external view onlyOwner returns (uint256) { return address(this).balance; } function GetMaxTokenCount() external view returns (uint256) { return _maxTokens; } function SetBank(address bank, bool isContract) external onlyOwner { _bankAddress = payable(bank); _bankIsContract = isContract; } function GetBank() external view onlyOwner returns (address) { return _bankAddress; } function SetPrice(uint256 newPrice) external onlyOwner { _tokenPrice = newPrice; } function GetPrice() external view returns (uint) { return _tokenPrice; } }
* @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), "EvaNFT: transfer to non ERC721Receiver implementer"); }
14,449,413
[ 1, 26946, 2357, 29375, 1375, 2316, 548, 68, 1147, 628, 1375, 2080, 68, 358, 1375, 869, 9191, 6728, 1122, 716, 6835, 12045, 854, 18999, 434, 326, 4232, 39, 27, 5340, 1771, 358, 5309, 2430, 628, 3832, 21238, 8586, 18, 1375, 67, 892, 68, 353, 3312, 501, 16, 518, 711, 1158, 1269, 740, 471, 518, 353, 3271, 316, 745, 358, 1375, 869, 8338, 1220, 2713, 445, 353, 7680, 358, 288, 4626, 5912, 1265, 5779, 471, 848, 506, 1399, 358, 425, 18, 75, 18, 2348, 10355, 1791, 28757, 358, 3073, 1147, 7412, 16, 4123, 487, 3372, 17, 12261, 18, 29076, 30, 300, 1375, 2080, 68, 2780, 506, 326, 3634, 1758, 18, 300, 1375, 869, 68, 2780, 506, 326, 3634, 1758, 18, 300, 1375, 2316, 548, 68, 1147, 1297, 1005, 471, 506, 16199, 635, 1375, 2080, 8338, 300, 971, 1375, 869, 68, 21368, 358, 279, 13706, 6835, 16, 518, 1297, 2348, 288, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 565, 445, 389, 4626, 5912, 12, 2867, 628, 16, 1758, 358, 16, 2254, 5034, 1147, 548, 16, 1731, 3778, 389, 892, 13, 2713, 5024, 288, 203, 3639, 389, 13866, 12, 2080, 16, 358, 16, 1147, 548, 1769, 203, 3639, 2583, 24899, 1893, 1398, 654, 39, 27, 5340, 8872, 12, 2080, 16, 358, 16, 1147, 548, 16, 389, 892, 3631, 315, 20861, 6491, 4464, 30, 7412, 358, 1661, 4232, 39, 27, 5340, 12952, 2348, 264, 8863, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: LGPL-3.0-or-later pragma solidity ^0.8.10; import "./mixins/NonTransferrableErc20.sol"; import "./mixins/Vesting.sol"; import "./mixins/Claiming.sol"; import "./mixins/MerkleDistributor.sol"; import "./vendored/mixins/StorageAccessible.sol"; /// @dev The token that manages how the CoW Protocol governance token is /// distributed to all different types of investors. /// @title CoW Protocol Virtual Token /// @author CoW Protocol Developers contract CowProtocolVirtualToken is NonTransferrableErc20, Vesting, Claiming, MerkleDistributor, StorageAccessible { string private constant ERC20_SYMBOL = "TESTvCOW"; string private constant ERC20_NAME = "**TEST** CoW Protocol Virtual Token"; constructor( bytes32 merkleRoot, address cowToken, address payable communityFundsTarget, address investorFundsTarget, address usdcToken, uint256 usdcPrice, address gnoToken, uint256 gnoPrice, address wrappedNativeToken, uint256 nativeTokenPrice, address teamController ) NonTransferrableErc20(ERC20_NAME, ERC20_SYMBOL) Claiming( cowToken, communityFundsTarget, investorFundsTarget, usdcToken, usdcPrice, gnoToken, gnoPrice, wrappedNativeToken, nativeTokenPrice, teamController ) MerkleDistributor(merkleRoot) // solhint-disable-next-line no-empty-blocks { } /// @dev Returns the sum of tokens that are either held as /// instantlySwappableBalance or will be vested in the future /// @param user The user for whom the balance is calculated /// @return Balance of the user function balanceOf(address user) public view returns (uint256) { return instantlySwappableBalance[user] + fullAllocation[user] - vestedAllocation[user]; } /// @dev Returns the balance of a user assuming all vested tokens would /// have been converted into virtual tokens /// @param user The user for whom the balance is calculated /// @return Balance the user would have after calling `swapAll` function swappableBalanceOf(address user) public view returns (uint256) { return instantlySwappableBalance[user] + newlyVestedBalance(user); } } // SPDX-License-Identifier: LGPL-3.0-or-later pragma solidity ^0.8.10; import "../vendored/interfaces/IERC20.sol"; /// @dev A contract of an ERC20 token that cannot be transferred. /// @title Non-Transferrable ERC20 /// @author CoW Protocol Developers abstract contract NonTransferrableErc20 is IERC20 { /// @dev The ERC20 name of the token string public name; /// @dev The ERC20 symbol of the token string public symbol; /// @dev The ERC20 number of decimals of the token uint8 public constant decimals = 18; // solhint-disable const-name-snakecase // solhint-disable-next-line no-empty-blocks constructor(string memory _name, string memory _symbol) { name = _name; symbol = _symbol; } /// @dev This error is fired when trying to perform an action that is not /// supported by the contract, like transfers and approvals. These actions /// will never be supported. error NotSupported(); /// @dev All types of transfers are permanently disabled. function transferFrom( address, address, uint256 ) public pure returns (bool) { revert NotSupported(); } /// @dev All types of transfers are permanently disabled. function transfer(address, uint256) public pure returns (bool) { revert NotSupported(); } /// @dev All types of approvals are permanently disabled to reduce code /// size. function approve(address, uint256) public pure returns (bool) { revert NotSupported(); } /// @dev Approvals cannot be set, so allowances are always zero. function allowance(address, address) public pure returns (uint256) { return 0; } } // SPDX-License-Identifier: LGPL-3.0-or-later pragma solidity ^0.8.10; import "../vendored/libraries/Math.sol"; import "../interfaces/VestingInterface.sol"; /// @dev The vesting logic for distributing the COW token /// @title Vesting Logic /// @author CoW Protocol Developers contract Vesting is VestingInterface { /// @dev The timestamp of the official vesting start. This value is shared /// between all participants. uint256 public immutable vestingStart; /// @dev How long it will take for all vesting to be completed. It is set to /// four years. uint256 public constant VESTING_PERIOD_IN_SECONDS = 4 * 365 days + 1 days; /// @dev Stores the amount of vesting that the user has already vested. mapping(address => uint256) public vestedAllocation; /// @dev Stores the maximum amount of vesting available to each user. This /// is exactly the total amount of vesting that can be converted after the /// vesting period is completed. mapping(address => uint256) public fullAllocation; /// @dev Stores a bit indicating whether a vesting is cancelable /// Important: This implementaiton implies that there can not be a /// cancelable and non-cancelable vesting in parallel mapping(address => bool) public isCancelable; /// @dev Event emitted when a new vesting position is added. The amount is /// the additional amount that can be vested at the end of the /// claiming period. event VestingAdded(address indexed user, uint256 amount, bool isCancelable); /// @dev Event emitted when a vesting position is canceled. The amount is /// the number of remaining vesting that will be given to the beneficiary. event VestingStopped( address indexed user, address freedVestingBeneficiary, uint256 amount ); /// @dev Event emitted when the users claims (also partially) a vesting /// position. event Vested(address indexed user, uint256 amount); /// @dev Error returned when trying to stop a claim that is not cancelable. error VestingNotCancelable(); constructor() { vestingStart = block.timestamp; // solhint-disable-line not-rely-on-time } /// @inheritdoc VestingInterface function addVesting( address user, uint256 vestingAmount, bool isCancelableFlag ) internal override { if (isCancelableFlag) { // if one cancelable vesting is made, it converts all vestings into cancelable ones isCancelable[user] = isCancelableFlag; } fullAllocation[user] += vestingAmount; emit VestingAdded(user, vestingAmount, isCancelableFlag); } /// @inheritdoc VestingInterface function shiftVesting(address user, address freedVestingBeneficiary) internal override returns (uint256 accruedVesting) { if (!isCancelable[user]) { revert VestingNotCancelable(); } accruedVesting = vest(user); uint256 userFullAllocation = fullAllocation[user]; uint256 userVestedAllocation = vestedAllocation[user]; fullAllocation[user] = 0; vestedAllocation[user] = 0; fullAllocation[freedVestingBeneficiary] += userFullAllocation; vestedAllocation[freedVestingBeneficiary] += userVestedAllocation; emit VestingStopped( user, freedVestingBeneficiary, userFullAllocation - userVestedAllocation ); } /// @inheritdoc VestingInterface function vest(address user) internal override returns (uint256 newlyVested) { newlyVested = newlyVestedBalance(user); vestedAllocation[user] += newlyVested; emit Vested(user, newlyVested); } /// @dev Assuming no conversions has been done by the user, calculates how /// much vesting can be converted at this point in time. /// @param user The user for whom the result is being calculated. /// @return How much vesting can be converted if no conversions had been /// done before. function cumulativeVestedBalance(address user) public view returns (uint256) { return (Math.min( block.timestamp - vestingStart, // solhint-disable-line not-rely-on-time VESTING_PERIOD_IN_SECONDS ) * fullAllocation[user]) / (VESTING_PERIOD_IN_SECONDS); } /// @dev Calculates how much vesting can be converted at this point in time. /// Unlike `cumulativeVestedBalance`, this function keeps track of previous /// conversions. /// @param user The user for whom the result is being calculated. /// @return How much vesting can be converted. function newlyVestedBalance(address user) public view returns (uint256) { return cumulativeVestedBalance(user) - vestedAllocation[user]; } } // SPDX-License-Identifier: LGPL-3.0-or-later pragma solidity ^0.8.10; import "../vendored/interfaces/IERC20.sol"; import "../vendored/libraries/SafeERC20.sol"; import "../interfaces/ClaimingInterface.sol"; import "../interfaces/VestingInterface.sol"; /// @dev The logic behind the claiming of virtual tokens and the swapping to /// real tokens. /// @title COW Virtual Token Claiming Logic /// @author CoW Protocol Developers abstract contract Claiming is ClaimingInterface, VestingInterface, IERC20 { using SafeERC20 for IERC20; /// @dev Prices are represented as fractions. For readability, the /// denominator is one unit of the virtual token (assuming it has 18 /// decimals), in this way the numerator of a price is the number of atoms /// that have the same value as a unit of virtual token. uint256 internal constant PRICE_DENOMINATOR = 10**18; /// @dev Price numerator for the COW/USDC price. This is the number of USDC /// atoms required to obtain a full unit of virtual token from an option. uint256 public immutable usdcPrice; /// @dev Price numerator for the COW/GNO price. This is the number of GNO /// atoms required to obtain a full unit of virtual token from an option. uint256 public immutable gnoPrice; /// @dev Price numerator for the COW/native-token price. This is the number /// of native token wei required to obtain a full unit of virtual token from /// an option. uint256 public immutable nativeTokenPrice; /// @dev The proceeds from selling options to the community will be sent to, /// this address. address payable public immutable communityFundsTarget; /// @dev All proceeds from known investors will be sent to this address. address public immutable investorFundsTarget; /// @dev Address of the real COW token. Tokens claimed by this contract can /// be converted to this token if this contract stores some balance of it. IERC20 public immutable cowToken; /// @dev Address of the USDC token. It is a form of payment for investors. IERC20 public immutable usdcToken; /// @dev Address of the GNO token. It is a form of payment for users who /// claim the options derived from holding GNO. IERC20 public immutable gnoToken; /// @dev Address of the wrapped native token. It is a form of payment for /// users who claim the options derived from being users of the CoW /// Protocol. IERC20 public immutable wrappedNativeToken; /// @dev Address representing the CoW Protocol/CowSwap team. It is the only /// address that is allowed to stop the vesting of a claim, and exclusively /// for team claims. address public immutable teamController; /// @dev Time at which this contract was deployed. uint256 public immutable deploymentTimestamp; /// @dev Returns the amount of virtual tokens in existence, including those /// that have yet to be vested. uint256 public totalSupply; /// @dev How many tokens can be immediately swapped in exchange for real /// tokens for each user. mapping(address => uint256) public instantlySwappableBalance; /// @dev Error presented to a user trying to claim virtual tokens after the /// claiming period has ended. error ClaimingExpired(); /// @dev Error presented to anyone but the team controller to stop a /// cancelable vesting position (i.e., only team vesting). error OnlyTeamController(); /// @dev Error resulting from sending an incorrect amount of native to the /// contract. error InvalidNativeTokenAmount(); /// @dev Error caused by an unsuccessful attempt to transfer native tokens. error FailedNativeTokenTransfer(); /// @dev Error resulting from sending native tokens for a claim that cannot /// be redeemed with native tokens. error CannotSendNativeToken(); constructor( address _cowToken, address payable _communityFundsTarget, address _investorFundsTarget, address _usdcToken, uint256 _usdcPrice, address _gnoToken, uint256 _gnoPrice, address _wrappedNativeToken, uint256 _nativeTokenPrice, address _teamController ) { cowToken = IERC20(_cowToken); communityFundsTarget = _communityFundsTarget; investorFundsTarget = _investorFundsTarget; usdcToken = IERC20(_usdcToken); usdcPrice = _usdcPrice; gnoToken = IERC20(_gnoToken); gnoPrice = _gnoPrice; wrappedNativeToken = IERC20(_wrappedNativeToken); nativeTokenPrice = _nativeTokenPrice; teamController = _teamController; // solhint-disable-next-line not-rely-on-time deploymentTimestamp = block.timestamp; } /// @dev Allows the decorated function only to be executed before the /// contract deployment date plus the input amount of seconds. /// @param durationSinceDeployment Number of seconds after contract /// deployment before which the function can be executed anymore. The /// function reverts afterwards. modifier before(uint256 durationSinceDeployment) { // solhint-disable-next-line not-rely-on-time if (block.timestamp > deploymentTimestamp + durationSinceDeployment) { revert ClaimingExpired(); } _; } /// @dev The decorated function can only be executed by the team controller. modifier onlyTeamController() { if (msg.sender != teamController) { revert OnlyTeamController(); } _; } /// @inheritdoc ClaimingInterface function performClaim( ClaimType claimType, address payer, address claimant, uint256 amount, uint256 sentNativeTokens ) internal override { if (claimType == ClaimType.Airdrop) { claimAirdrop(claimant, amount, sentNativeTokens); } else if (claimType == ClaimType.GnoOption) { claimGnoOption(claimant, amount, payer, sentNativeTokens); } else if (claimType == ClaimType.UserOption) { claimUserOption(claimant, amount, payer, sentNativeTokens); } else if (claimType == ClaimType.Investor) { claimInvestor(claimant, amount, payer, sentNativeTokens); } else if (claimType == ClaimType.Team) { claimTeam(claimant, amount, sentNativeTokens); } else { // claimType == ClaimType.Advisor claimAdvisor(claimant, amount, sentNativeTokens); } // Each claiming operation results in the creation of `amount` virtual // tokens. totalSupply += amount; emit Transfer(address(0), claimant, amount); } /// @dev Stops all vesting claims of a user. This is only applicable for /// claims that are cancellable, i.e., team claims. /// @param user The user whose vesting claims should be canceled. function stopClaim(address user) external onlyTeamController { uint256 accruedVesting = shiftVesting(user, teamController); instantlySwappableBalance[user] += accruedVesting; } /// @dev Transfers all ETH stored in the contract to the community funds // target. function withdrawEth() external { // We transfer ETH using .call instead of .transfer as not to restrict // the amount of gas sent to the target address during the transfer. // This is particularly relevant for sending ETH to smart contracts: // since EIP 2929, if a contract sends eth using `.transfer` then the // transaction proposed to the node needs to specify an _access list_, // which is currently not well supported by some wallet implementations. // There is no reentrancy risk as this call does not touch any storage // slot and the contract balance is not used in other logic. // solhint-disable-next-line avoid-low-level-calls (bool success, ) = communityFundsTarget.call{ value: address(this).balance }(""); if (!success) { revert FailedNativeTokenTransfer(); } } /// @dev Performs an airdrop-type claim for the user. /// @param account The user for which the claim is performed. /// @param amount The full amount claimed by the user. /// @param sentNativeTokens Amount of ETH sent along to the transaction. function claimAirdrop( address account, uint256 amount, uint256 sentNativeTokens ) private before(6 weeks) { if (sentNativeTokens != 0) { revert CannotSendNativeToken(); } instantlySwappableBalance[account] += amount; } /// @dev Claims a Gno option for the user. /// @param account The user for which the claim is performed. /// @param amount The full amount claimed by the user after vesting. /// @param payer The address that pays the amount required by the claim. /// @param sentNativeTokens Amount of ETH sent along to the transaction. function claimGnoOption( address account, uint256 amount, address payer, uint256 sentNativeTokens ) private before(2 weeks) { if (sentNativeTokens != 0) { revert CannotSendNativeToken(); } collectPayment(gnoToken, gnoPrice, payer, communityFundsTarget, amount); addVesting(account, amount, false); } /// @dev Claims a native-token-based option for the user. /// @param account The user for which the claim is performed. /// @param amount The full amount claimed by the user after vesting. /// @param payer The address that pays the amount required by the claim. /// @param sentNativeTokens Amount of ETH sent along to the transaction. function claimUserOption( address account, uint256 amount, address payer, uint256 sentNativeTokens ) private before(2 weeks) { if (sentNativeTokens != 0) { collectNativeTokenPayment(amount, sentNativeTokens); } else { collectPayment( wrappedNativeToken, nativeTokenPrice, payer, communityFundsTarget, amount ); } addVesting(account, amount, false); } /// @dev Claims an investor option. /// @param account The user for which the claim is performed. /// @param amount The full amount claimed by the user after vesting. /// @param payer The address that pays the amount required by the claim. /// @param sentNativeTokens Amount of ETH sent along to the transaction. function claimInvestor( address account, uint256 amount, address payer, uint256 sentNativeTokens ) private before(2 weeks) { if (sentNativeTokens != 0) { revert CannotSendNativeToken(); } collectPayment( usdcToken, usdcPrice, payer, investorFundsTarget, amount ); addVesting(account, amount, false); } /// @dev Claims a team option. Team options are granted without any payment /// but can be canceled. /// @param account The user for which the claim is performed. /// @param amount The full amount claimed by the user after vesting. /// @param sentNativeTokens Amount of ETH sent along to the transaction. function claimTeam( address account, uint256 amount, uint256 sentNativeTokens ) private before(6 weeks) { if (sentNativeTokens != 0) { revert CannotSendNativeToken(); } addVesting(account, amount, true); } /// @dev Claims an adviser option. Team options are granted without any /// payment and cannot be canceled. /// @param account The user for which the claim is performed. /// @param amount The full amount claimed by the user after vesting. /// @param sentNativeTokens Amount of ETH sent along to the transaction. function claimAdvisor( address account, uint256 amount, uint256 sentNativeTokens ) private before(6 weeks) { if (sentNativeTokens != 0) { revert CannotSendNativeToken(); } addVesting(account, amount, false); } /// @dev Executes a transfer from the user to the target. The transfered /// amount is based on the input COW price and amount of COW bought. /// @param token The token used for the payment. /// @param price The number of atoms of the input token that are equivalent /// to one atom of COW multiplied by PRICE_DENOMINATOR. /// @param from The address from which to take the funds. /// @param to The address to which to send the funds. /// @param amount The amount of COW atoms that will be paid for. function collectPayment( IERC20 token, uint256 price, address from, address to, uint256 amount ) private { uint256 tokenEquivalent = convertCowAmountAtPrice(amount, price); token.safeTransferFrom(from, to, tokenEquivalent); } /// @dev Transfers native tokens from this contract to the target, assuming /// that the amount of native tokens sent coincides with the expected amount /// of native tokens. This amount is based on the price of the native token /// and amount of COW bought. /// @param amount The amount of COW atoms that will be paid for. /// @param sentNativeTokens Amount of ETH sent along to the transaction. function collectNativeTokenPayment(uint256 amount, uint256 sentNativeTokens) private view { uint256 nativeTokenEquivalent = convertCowAmountAtPrice( amount, nativeTokenPrice ); if (sentNativeTokens != nativeTokenEquivalent) { revert InvalidNativeTokenAmount(); } } /// @dev Converts input amount in COW token atoms to an amount in token /// atoms at the specified price. /// @param amount Amount of tokens to convert. /// @param price The number of atoms of the input token that are equivalent /// to one atom of COW *multiplied by PRICE_DENOMINATOR*. function convertCowAmountAtPrice(uint256 amount, uint256 price) private pure returns (uint256) { return (amount * price) / PRICE_DENOMINATOR; } /// @dev Converts an amount of (virtual) tokens from this contract to real /// tokens based on the claims previously performed by the caller. /// @param amount How many virtual tokens to convert into real tokens. function swap(uint256 amount) external { makeVestingSwappable(); _swap(amount); } /// @dev Converts all available (virtual) tokens from this contract to real /// tokens based on the claims previously performed by the caller. /// @return swappedBalance The full amount that was swapped (i.e., virtual /// tokens burnt as well as real tokens received). function swapAll() external returns (uint256 swappedBalance) { swappedBalance = makeVestingSwappable(); _swap(swappedBalance); } /// @dev Transfers real tokens to the message sender and reduces the balance /// of virtual tokens available. Note that this function assumes that the /// current contract stores enough real tokens to fulfill this swap request. /// @param amount How many virtual tokens to convert into real tokens. function _swap(uint256 amount) private { instantlySwappableBalance[msg.sender] -= amount; totalSupply -= amount; cowToken.safeTransfer(msg.sender, amount); emit Transfer(msg.sender, address(0), amount); } /// @dev Adds the currently vested amount to the immediately swappable /// balance. /// @return swappableBalance The maximum balance that can be swapped at /// this point in time by the caller. function makeVestingSwappable() private returns (uint256 swappableBalance) { swappableBalance = instantlySwappableBalance[msg.sender] + vest(msg.sender); instantlySwappableBalance[msg.sender] = swappableBalance; } } // SPDX-License-Identifier: LGPL-3.0-or-later // This contract is based on Uniswap's MekleDistributor, which can be found at: // https://github.com/Uniswap/merkle-distributor/blob/0d478d722da2e5d95b7292fd8cbdb363d98e9a93/contracts/MerkleDistributor.sol // // The changes between the original contract and this are: // - the claim function doesn't trigger a transfer on a successful proof, but // it executes a dedicated (virtual) function. // - added a claimMany function for bundling multiple claims in a transaction // - supported sending an amount of native tokens along with the claim // - added the option of claiming less than the maximum amount // - gas optimizations in the packing and unpacking of the claimed bit // - bumped Solidity version // - code formatting pragma solidity ^0.8.10; import "../vendored/interfaces/IERC20.sol"; import "../vendored/libraries/MerkleProof.sol"; import "../interfaces/ClaimingInterface.sol"; abstract contract MerkleDistributor is ClaimingInterface { bytes32 public immutable merkleRoot; /// @dev Event fired if a claim was successfully performed. event Claimed( uint256 index, ClaimType claimType, address claimant, uint256 claimableAmount, uint256 claimedAmount ); /// @dev Error caused by a user trying to call the claim function for a /// claim that has already been used before. error AlreadyClaimed(); /// @dev Error caused by a user trying to claim a larger amount than the /// maximum allowed in the claim. error ClaimingMoreThanMaximum(); /// @dev Error caused by the caller trying to perform a partial claim while /// not being the owner of the claim. error OnlyOwnerCanClaimPartially(); /// @dev Error caused by calling the claim function with an invalid proof. error InvalidProof(); /// @dev Error caused by calling claimMany with a transaction value that is /// different from the required one. error InvalidNativeTokenValue(); /// @dev Packed array of booleans that stores if a claim is available. mapping(uint256 => uint256) private claimedBitMap; constructor(bytes32 merkleRoot_) { merkleRoot = merkleRoot_; } /// @dev Checks if the claim at the provided index has already been claimed. /// @param index The index to check. /// @return Whether the claim at the given index has already been claimed. function isClaimed(uint256 index) public view returns (bool) { uint256 claimedWordIndex = index >> 8; uint256 claimedBitIndex = index & 0xff; uint256 claimedWord = claimedBitMap[claimedWordIndex]; uint256 mask = (1 << claimedBitIndex); return claimedWord & mask != 0; } /// @dev Mark the provided index as having been claimed. /// @param index The index that was claimed. function _setClaimed(uint256 index) private { uint256 claimedWordIndex = index >> 8; uint256 claimedBitIndex = index & 0xff; claimedBitMap[claimedWordIndex] = claimedBitMap[claimedWordIndex] | (1 << claimedBitIndex); } /// @dev This function verifies the provided input proof based on the /// provided input. If the proof is valid, the function [`performClaim`] is /// called for the claimed amount. /// @param index The index that identifies the input claim. /// @param claimType See [`performClaim`]. /// @param claimant See [`performClaim`]. /// @param claimableAmount The maximum amount that the claimant can claim /// for this claim. Should not be smaller than claimedAmount. /// @param claimedAmount See [`performClaim`]. /// @param merkleProof A proof that the input claim belongs to the unique /// Merkle root associated to this contract. function claim( uint256 index, ClaimType claimType, address claimant, uint256 claimableAmount, uint256 claimedAmount, bytes32[] calldata merkleProof ) external payable { _claim( index, claimType, claimant, claimableAmount, claimedAmount, merkleProof, msg.value ); } /// @dev This function verifies and executes multiple claims in the same /// transaction. /// @param indices A vector of indices. See [`claim`] for details. /// @param claimTypes A vector of claim types. See [`performClaim`] for /// details. /// @param claimants A vector of claimants. See [`performClaim`] for /// details. /// @param claimableAmounts A vector of claimable amounts. See [`claim`] for /// details. /// @param claimedAmounts A vector of claimed amounts. See [`performClaim`] /// for details. /// @param merkleProofs A vector of merkle proofs. See [`claim`] for /// details. /// @param sentNativeTokens A vector of native token amounts. See /// [`performClaim`] for details. function claimMany( uint256[] memory indices, ClaimType[] memory claimTypes, address[] calldata claimants, uint256[] calldata claimableAmounts, uint256[] calldata claimedAmounts, bytes32[][] calldata merkleProofs, uint256[] calldata sentNativeTokens ) external payable { uint256 sumSentNativeTokens; for (uint256 i = 0; i < indices.length; i++) { sumSentNativeTokens += sentNativeTokens[i]; _claim( indices[i], claimTypes[i], claimants[i], claimableAmounts[i], claimedAmounts[i], merkleProofs[i], sentNativeTokens[i] ); } if (sumSentNativeTokens != msg.value) { revert InvalidNativeTokenValue(); } } /// @dev This function verifies the provided input proof based on the /// provided input. If the proof is valid, the function [`performClaim`] is /// called for the claimed amount. /// @param index See [`claim`]. /// @param claimType See [`performClaim`]. /// @param claimant See [`performClaim`]. /// @param claimableAmount See [`claim`]. /// @param claimedAmount See [`performClaim`]. /// @param merkleProof See [`claim`]. /// @param sentNativeTokens See [`performClaim`]. function _claim( uint256 index, ClaimType claimType, address claimant, uint256 claimableAmount, uint256 claimedAmount, bytes32[] calldata merkleProof, uint256 sentNativeTokens ) private { if (isClaimed(index)) { revert AlreadyClaimed(); } if (claimedAmount > claimableAmount) { revert ClaimingMoreThanMaximum(); } if ((claimedAmount < claimableAmount) && (msg.sender != claimant)) { revert OnlyOwnerCanClaimPartially(); } // Note: all types used inside `encodePacked` should have fixed length, // otherwise the same proof could be used in different claims. bytes32 node = keccak256( abi.encodePacked(index, claimType, claimant, claimableAmount) ); if (!MerkleProof.verify(merkleProof, merkleRoot, node)) { revert InvalidProof(); } _setClaimed(index); performClaim( claimType, msg.sender, claimant, claimedAmount, sentNativeTokens ); emit Claimed( index, claimType, claimant, claimableAmount, claimedAmount ); } } // SPDX-License-Identifier: LGPL-3.0-only // Vendored from Gnosis utility contracts, see: // <https://raw.githubusercontent.com/gnosis/gp-v2-contracts/40c349d52d14f8f3c9f787fe2fca5a496bb10ea9/src/contracts/mixins/StorageAccessible.sol> // The following changes were made: // - Modified Solidity version // - Formatted code pragma solidity ^0.8.10; /// @title ViewStorageAccessible - Interface on top of StorageAccessible base class to allow simulations from view functions interface ViewStorageAccessible { /** * @dev Same as `simulateDelegatecall` on StorageAccessible. Marked as view so that it can be called from external contracts * that want to run simulations from within view functions. Will revert if the invoked simulation attempts to change state. */ function simulateDelegatecall( address targetContract, bytes memory calldataPayload ) external view returns (bytes memory); /** * @dev Same as `getStorageAt` on StorageAccessible. This method allows reading aribtrary ranges of storage. */ function getStorageAt(uint256 offset, uint256 length) external view returns (bytes memory); } /// @title StorageAccessible - generic base contract that allows callers to access all internal storage. contract StorageAccessible { /** * @dev Reads `length` bytes of storage in the currents contract * @param offset - the offset in the current contract's storage in words to start reading from * @param length - the number of words (32 bytes) of data to read * @return the bytes that were read. */ function getStorageAt(uint256 offset, uint256 length) external view returns (bytes memory) { bytes memory result = new bytes(length * 32); for (uint256 index = 0; index < length; index++) { // solhint-disable-next-line no-inline-assembly assembly { let word := sload(add(offset, index)) mstore(add(add(result, 0x20), mul(index, 0x20)), word) } } return result; } /** * @dev Performs a delegetecall on a targetContract in the context of self. * Internally reverts execution to avoid side effects (making it static). Catches revert and returns encoded result as bytes. * @param targetContract Address of the contract containing the code to execute. * @param calldataPayload Calldata that should be sent to the target contract (encoded method name and arguments). */ function simulateDelegatecall( address targetContract, bytes memory calldataPayload ) public returns (bytes memory response) { bytes memory innerCall = abi.encodeWithSelector( this.simulateDelegatecallInternal.selector, targetContract, calldataPayload ); // solhint-disable-next-line avoid-low-level-calls (, response) = address(this).call(innerCall); bool innerSuccess = response[response.length - 1] == 0x01; setLength(response, response.length - 1); if (innerSuccess) { return response; } else { revertWith(response); } } /** * @dev Performs a delegetecall on a targetContract in the context of self. * Internally reverts execution to avoid side effects (making it static). Returns encoded result as revert message * concatenated with the success flag of the inner call as a last byte. * @param targetContract Address of the contract containing the code to execute. * @param calldataPayload Calldata that should be sent to the target contract (encoded method name and arguments). */ function simulateDelegatecallInternal( address targetContract, bytes memory calldataPayload ) external returns (bytes memory response) { bool success; // solhint-disable-next-line avoid-low-level-calls (success, response) = targetContract.delegatecall(calldataPayload); revertWith(abi.encodePacked(response, success)); } function revertWith(bytes memory response) internal pure { // solhint-disable-next-line no-inline-assembly assembly { revert(add(response, 0x20), mload(response)) } } function setLength(bytes memory buffer, uint256 length) internal pure { // solhint-disable-next-line no-inline-assembly assembly { mstore(buffer, length) } } } // SPDX-License-Identifier: MIT // Vendored from OpenZeppelin Contracts v4.4.0, see: // <https://raw.githubusercontent.com/OpenZeppelin/openzeppelin-contracts/v4.4.0/contracts/token/ERC20/IERC20.sol> // OpenZeppelin Contracts v4.4.0 (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval( address indexed owner, address indexed spender, uint256 value ); } // SPDX-License-Identifier: MIT // Vendored from OpenZeppelin Contracts v4.4.0, see: // <https://raw.githubusercontent.com/OpenZeppelin/openzeppelin-contracts/v4.4.0/contracts/utils/math/Math.sol> // OpenZeppelin Contracts v4.4.0 (utils/math/Math.sol) 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: LGPL-3.0-or-later pragma solidity ^0.8.10; /// @dev The contract functions that are shared between the `Vesting` and /// `Claiming` contracts. The two components are handled and tested /// separately and are linked to each other by the functions in this contract. /// This contracs is for all intents and purposes an interface, however actual /// interfaces cannot declare internal functions. /// @title COW token vesting interface. /// @author CoW Protocol Developers abstract contract VestingInterface { /// @dev Adds an amount that will be vested over time. /// Should be called from the parent contract on redeeming a vested claim. /// @param user The user for whom the vesting is performed. /// @param vestingAmount The (added) amount to be vested in time. /// @param isCancelableFlag Flag whether the vesting is cancelable function addVesting( address user, uint256 vestingAmount, bool isCancelableFlag ) internal virtual; /// @dev Computes the current vesting from the total vested amount and marks /// that amount as converted. This is called by the parent contract every /// time virtual tokens from a vested claim are swapped into real tokens. /// @param user The user for which the amount is vested. /// @return Amount converted. function vest(address user) internal virtual returns (uint256); /// @dev Transfers a cancelable vesting of a user to another address. /// Returns the amount of token that is not yet converted. /// @param user The user for whom the vesting is removed. /// @param freedVestingBeneficiary The address to which to assign the amount /// that remains to be vested. /// @return accruedVesting The total number of tokens that remain to be /// converted function shiftVesting(address user, address freedVestingBeneficiary) internal virtual returns (uint256 accruedVesting); } // SPDX-License-Identifier: LGPL-3.0-or-later // Vendored from GPv2 contracts v1.1.2, see: // <https://raw.githubusercontent.com/gnosis/gp-v2-contracts/7fb88982021e9a274d631ffb598694e6d9b30089/src/contracts/libraries/GPv2SafeERC20.sol> // The following changes were made: // - Bumped up Solidity version and checked that the assembly is still valid. // - Use own vendored IERC20 instead of custom implementation. // - Removed "GPv2" from contract name. // - Modified revert messages, including length. pragma solidity ^0.8.10; import "../interfaces/IERC20.sol"; /// @title Gnosis Protocol v2 Safe ERC20 Transfer Library /// @author Gnosis Developers /// @dev Gas-efficient version of Openzeppelin's SafeERC20 contract. library SafeERC20 { /// @dev Wrapper around a call to the ERC20 function `transfer` that reverts /// also when the token returns `false`. function safeTransfer( IERC20 token, address to, uint256 value ) internal { bytes4 selector_ = token.transfer.selector; // solhint-disable-next-line no-inline-assembly assembly { let freeMemoryPointer := mload(0x40) mstore(freeMemoryPointer, selector_) mstore( add(freeMemoryPointer, 4), and(to, 0xffffffffffffffffffffffffffffffffffffffff) ) mstore(add(freeMemoryPointer, 36), value) if iszero(call(gas(), token, 0, freeMemoryPointer, 68, 0, 0)) { returndatacopy(0, 0, returndatasize()) revert(0, returndatasize()) } } require(getLastTransferResult(token), "SafeERC20: failed transfer"); } /// @dev Wrapper around a call to the ERC20 function `transferFrom` that /// reverts also when the token returns `false`. function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { bytes4 selector_ = token.transferFrom.selector; // solhint-disable-next-line no-inline-assembly assembly { let freeMemoryPointer := mload(0x40) mstore(freeMemoryPointer, selector_) mstore( add(freeMemoryPointer, 4), and(from, 0xffffffffffffffffffffffffffffffffffffffff) ) mstore( add(freeMemoryPointer, 36), and(to, 0xffffffffffffffffffffffffffffffffffffffff) ) mstore(add(freeMemoryPointer, 68), value) if iszero(call(gas(), token, 0, freeMemoryPointer, 100, 0, 0)) { returndatacopy(0, 0, returndatasize()) revert(0, returndatasize()) } } require(getLastTransferResult(token), "SafeERC20: failed transferFrom"); } /// @dev Verifies that the last return was a successful `transfer*` call. /// This is done by checking that the return data is either empty, or /// is a valid ABI encoded boolean. function getLastTransferResult(IERC20 token) private view returns (bool success) { // NOTE: Inspecting previous return data requires assembly. Note that // we write the return data to memory 0 in the case where the return // data size is 32, this is OK since the first 64 bytes of memory are // reserved by Solidy as a scratch space that can be used within // assembly blocks. // <https://docs.soliditylang.org/en/v0.8.10/internals/layout_in_memory.html> // solhint-disable-next-line no-inline-assembly assembly { /// @dev Revert with an ABI encoded Solidity error with a message /// that fits into 32-bytes. /// /// An ABI encoded Solidity error has the following memory layout: /// /// ------------+---------------------------------- /// byte range | value /// ------------+---------------------------------- /// 0x00..0x04 | selector("Error(string)") /// 0x04..0x24 | string offset (always 0x20) /// 0x24..0x44 | string length /// 0x44..0x64 | string value, padded to 32-bytes function revertWithMessage(length, message) { mstore(0x00, "\x08\xc3\x79\xa0") mstore(0x04, 0x20) mstore(0x24, length) mstore(0x44, message) revert(0x00, 0x64) } switch returndatasize() // Non-standard ERC20 transfer without return. case 0 { // NOTE: When the return data size is 0, verify that there // is code at the address. This is done in order to maintain // compatibility with Solidity calling conventions. // <https://docs.soliditylang.org/en/v0.8.10/control-structures.html#external-function-calls> if iszero(extcodesize(token)) { revertWithMessage(25, "SafeERC20: not a contract") } success := 1 } // Standard ERC20 transfer returning boolean success value. case 32 { returndatacopy(0, 0, returndatasize()) // NOTE: For ABI encoding v1, any non-zero value is accepted // as `true` for a boolean. In order to stay compatible with // OpenZeppelin's `SafeERC20` library which is known to work // with the existing ERC20 implementation we care about, // make sure we return success for any non-zero return value // from the `transfer*` call. success := iszero(iszero(mload(0))) } default { revertWithMessage(30, "SafeERC20: bad transfer result") } } } } // SPDX-License-Identifier: LGPL-3.0-or-later pragma solidity ^0.8.10; /// @dev The contract functions that are shared between the `Claiming` and /// `MerkleDistributor` contracts. The two components are handled and tested /// separately and are linked to each other by the functions in this contract. /// This contracs is for all intents and purposes an interface, however actual /// interfaces cannot declare internal functions. /// @title COW token claiming interface. /// @author CoW Protocol Developers abstract contract ClaimingInterface { /// @dev Exhaustive list of the different branches of the claiming logic. enum ClaimType { Airdrop, GnoOption, UserOption, Investor, Team, Advisor } /// @dev This function is executed when a valid proof of the claim is /// provided and executes all steps required for each claim type. /// @param claimType Which claim will be performed. See [`ClaimType`] for /// an exausting list. /// @param payer The address that will pay if the claim to be performed /// requires a payment. /// @param claimant The account to which the claim is assigned and which /// will receive the corresponding virtual tokens. /// @param claimedAmount The amount that the user decided to claim (after /// vesting if it applies). /// @param sentNativeTokens The amount of native tokens that the user sent /// along with the transaction. function performClaim( ClaimType claimType, address payer, address claimant, uint256 claimedAmount, uint256 sentNativeTokens ) internal virtual; } // SPDX-License-Identifier: MIT // Vendored from OpenZeppelin Contracts v4.4.0, see: // <https://raw.githubusercontent.com/OpenZeppelin/openzeppelin-contracts/v4.4.0/contracts/utils/cryptography/MerkleProof.sol> // OpenZeppelin Contracts v4.4.0 (utils/cryptography/MerkleProof.sol) pragma solidity ^0.8.0; /** * @dev These functions deal with verification of Merkle Trees proofs. * * The proofs can be generated using the JavaScript library * https://github.com/miguelmota/merkletreejs[merkletreejs]. * Note: the hashing algorithm should be keccak256 and pair sorting should be enabled. * * See `test/utils/cryptography/MerkleProof.test.js` for some examples. */ library 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; } }
@dev All types of transfers are permanently disabled.
function transfer(address, uint256) public pure returns (bool) { revert NotSupported(); }
12,096,430
[ 1, 1595, 1953, 434, 29375, 854, 16866, 715, 5673, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 7412, 12, 2867, 16, 2254, 5034, 13, 1071, 16618, 1135, 261, 6430, 13, 288, 203, 3639, 15226, 31865, 5621, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.18; contract DogCoreInterface { address public ceoAddress; address public cfoAddress; function getDog(uint256 _id) external view returns ( //冷却期索引号 uint256 cooldownIndex, //本次冷却期结束所在区块 uint256 nextActionAt, //配种的公狗ID uint256 siringWithId, //出生时间 uint256 birthTime, //母亲ID uint256 matronId, //父亲ID uint256 sireId, //代数 uint256 generation, //基因 uint256 genes, //变异,0表示未变异,1-7表示变异 uint8 variation, //0代祖先的ID uint256 gen0 ); function ownerOf(uint256 _tokenId) external view returns (address); function transferFrom(address _from, address _to, uint256 _tokenId) external; function sendMoney(address _to, uint256 _money) external; function totalSupply() external view returns (uint); } /* LotteryBase 主要定义了开奖信息,奖金池转入函数以及判断是否开必中 */ contract LotteryBase { // 当前开奖基因位数 uint8 public currentGene; // 当前开奖所在区块 uint256 public lastBlockNumber; // 随机数种子 uint256 randomSeed = 1; // 奖金池地址 address public bonusPool; // 中奖信息 struct CLottery { // 该期中奖基因 uint8[7] luckyGenes; // 该期奖金池总额 uint256 totalAmount; // 该期第7个基因开奖所在区块 uint256 openBlock; // 是否发奖完毕 bool isReward; // 未开一等奖标记 bool noFirstReward; } // 历史开奖信息 CLottery[] public CLotteries; // 发奖合约地址 address public finalLottery; // 蓄奖池金额 uint256 public SpoolAmount = 0; // 宠物信息接口 DogCoreInterface public dogCore; // 随机开奖事件 event OpenLottery(uint8 currentGene, uint8 luckyGenes, uint256 currentTerm, uint256 blockNumber, uint256 totalAmount); //必中开奖事件 event OpenCarousel(uint256 luckyGenes, uint256 currentTerm, uint256 blockNumber, uint256 totalAmount); // modifier onlyCEO() { require(msg.sender == dogCore.ceoAddress()); _; } // modifier onlyCFO() { require(msg.sender == dogCore.cfoAddress()); _; } /* 蓄奖池转入奖金池函数 */ function toLotteryPool(uint amount) public onlyCFO { require(SpoolAmount >= amount); SpoolAmount -= amount; } /* 判断当期是否开必中 */ function _isCarousal(uint256 currentTerm) external view returns(bool) { return (currentTerm > 1 && CLotteries[currentTerm - 2].noFirstReward && CLotteries[currentTerm - 1].noFirstReward); } /* 返回当前期数 */ function getCurrentTerm() external view returns (uint256) { return (CLotteries.length - 1); } } /* LotteryGenes主要实现奖宠物原始基因转化为兑奖数组 */ contract LotteryGenes is LotteryBase { /* 将基因数字格式转换为抽奖数组格式 */ function convertGeneArray(uint256 gene) public pure returns(uint8[7]) { uint8[28] memory geneArray; uint8[7] memory lotteryArray; uint index = 0; for (index = 0; index < 28; index++) { uint256 geneItem = gene % (2 ** (5 * (index + 1))); geneItem /= (2 ** (5 * index)); geneArray[index] = uint8(geneItem); } for (index = 0; index < 7; index++) { uint size = 4 * index; lotteryArray[index] = geneArray[size]; } return lotteryArray; } /** 将显性基因串拼凑成原始基因数字 */ function convertGene(uint8[7] luckyGenes) public pure returns(uint256) { uint8[28] memory geneArray; for (uint8 i = 0; i < 28; i++) { if (i%4 == 0) { geneArray[i] = luckyGenes[i/4]; } else { geneArray[i] = 6; } } uint256 gene = uint256(geneArray[0]); for (uint8 index = 1; index < 28; index++) { uint256 geneItem = uint256(geneArray[index]); gene += geneItem << (index * 5); } return gene; } } /* SetLottery主要实现了随机开奖和必中开奖 */ contract SetLottery is LotteryGenes { function random(uint8 seed) internal returns(uint8) { randomSeed = block.timestamp; return uint8(uint256(keccak256(randomSeed, block.difficulty))%seed)+1; } /* 随机开奖函数,每一期开7次。 currentGene表示当期开奖的第N个基因 若当前currentGene指标为0,则表示在开奖期未开任何数字,或者开奖期已经开完了所有数字 当前开奖期最后一个基因开完后,记录当前所在区块号和当前奖金池金额 返回值分别为当前开奖基因(0代表不存在)、查询开奖基因(0代表不存在)、 开奖状态(0表示开奖成功,1表示当期开奖结束且在等待发奖,2表示当前基因开奖区块与上个基因开奖区块相同,3表示奖金池金额不足) */ function openLottery(uint8 _viewId) public returns(uint8,uint8) { uint8 viewId = _viewId; require(viewId < 7); // 获取当前中奖信息 uint256 currentTerm = CLotteries.length - 1; CLottery storage clottery = CLotteries[currentTerm]; // 如果7个基因都完成开奖并且当期没有发奖,则说明当期所有基因已经开奖完毕在等待发奖,退出 if (currentGene == 0 && clottery.openBlock > 0 && clottery.isReward == false) { // 触发事件,返回查询的基因 OpenLottery(viewId, clottery.luckyGenes[viewId], currentTerm, 0, 0); //分别返回查询基因,状态1 (表示当期所有基因开奖完毕在等待发奖) return (clottery.luckyGenes[viewId],1); } // 如果上个基因开奖和本次开奖在同一个区块,退出 if (lastBlockNumber == block.number) { // 触发事件,返回查询的基因 OpenLottery(viewId, clottery.luckyGenes[viewId], currentTerm, 0, 0); //分别返回查询基因,状态2 (当前基因开奖区块与上个基因开奖区块相同) return (clottery.luckyGenes[viewId],2); } // 如果当前开奖基因位为0且当期已经发奖,则进入下一期开奖 if (currentGene == 0 && clottery.isReward == true) { // 初始化当前lottery信息 CLottery memory _clottery; _clottery.luckyGenes = [0,0,0,0,0,0,0]; _clottery.totalAmount = uint256(0); _clottery.isReward = false; _clottery.openBlock = uint256(0); currentTerm = CLotteries.push(_clottery) - 1; } // 如果前两期都没有一等奖产生,则该期产生必中奖,退出随机开奖函数 if (this._isCarousal(currentTerm)) { revert(); } //开奖结果 uint8 luckyNum = 0; if (currentGene == 6) { // 如果奖金池金额为零,则退出 if (bonusPool.balance <= SpoolAmount) { // 触发事件,返回查询的基因 OpenLottery(viewId, clottery.luckyGenes[viewId], currentTerm, 0, 0); //分别返回查询基因,状态3 (奖金池金额不足) return (clottery.luckyGenes[viewId],3); } //将随机数赋值给当前基因 luckyNum = random(8); CLotteries[currentTerm].luckyGenes[currentGene] = luckyNum; //触发开奖事件 OpenLottery(currentGene, luckyNum, currentTerm, block.number, bonusPool.balance); //如果当前为最后一个开奖基因,则下一个开奖基因位为0,同时记录下当前区块号并写入开奖信息,同时将奖金池金额写入开奖信息, 同时启动主合约 currentGene = 0; CLotteries[currentTerm].openBlock = block.number; CLotteries[currentTerm].totalAmount = bonusPool.balance; //记录当前开奖所在区块 lastBlockNumber = block.number; } else { //将随机数赋值给当前基因 luckyNum = random(12); CLotteries[currentTerm].luckyGenes[currentGene] = luckyNum; //触发开奖事件 OpenLottery(currentGene, luckyNum, currentTerm, 0, 0); //其它情况下,下一个开奖基因位加1 currentGene ++; //记录当前开奖所在区块 lastBlockNumber = block.number; } //分别返回开奖基因,查询基因和开奖成功状态 return (luckyNum,0); } function random2() internal view returns (uint256) { return uint256(uint256(keccak256(block.timestamp, block.difficulty))%uint256(dogCore.totalSupply()) + 1); } /* 必中开奖函数,每期开一次 */ function openCarousel() public { //获取当前开奖信息 uint256 currentTerm = CLotteries.length - 1; CLottery storage clottery = CLotteries[currentTerm]; // 如果当前开奖基因指针为0且开奖基因存在,且未发奖,则说明当前基因开奖完毕,在等待发奖 if (currentGene == 0 && clottery.openBlock > 0 && clottery.isReward == false) { //触发开奖事件,返回当期现有开奖数据 OpenCarousel(convertGene(clottery.luckyGenes), currentTerm, clottery.openBlock, clottery.totalAmount); } // 如果开奖基因指针为0且开奖基因存在,并且发奖完毕,则进入下一开奖周期 if (currentGene == 0 && clottery.openBlock > 0 && clottery.isReward == true) { CLottery memory _clottery; _clottery.luckyGenes = [0,0,0,0,0,0,0]; _clottery.totalAmount = uint256(0); _clottery.isReward = false; _clottery.openBlock = uint256(0); currentTerm = CLotteries.push(_clottery) - 1; } //期数大于3 且前三期未产生特等奖 require (this._isCarousal(currentTerm)); // 随机获取必中基因 uint256 genes = _getValidRandomGenes(); require (genes > 0); uint8[7] memory luckyGenes = convertGeneArray(genes); //触发开奖事件 OpenCarousel(genes, currentTerm, block.number, bonusPool.balance); //写入记录 CLotteries[currentTerm].luckyGenes = luckyGenes; CLotteries[currentTerm].openBlock = block.number; CLotteries[currentTerm].totalAmount = bonusPool.balance; } /* 随机获取合法的必中基因 */ function _getValidRandomGenes() internal view returns (uint256) { uint256 luckyDog = random2(); uint256 genes = _validGenes(luckyDog); uint256 totalSupply = dogCore.totalSupply(); if (genes > 0) { return genes; } // 如果dog不能兑奖,则渐进振荡判断其它dog是否满足条件 uint256 min = (luckyDog < totalSupply-luckyDog) ? (luckyDog - 1) : totalSupply-luckyDog; for (uint256 i = 1; i < min + 1; i++) { genes = _validGenes(luckyDog - i); if (genes > 0) { break; } genes = _validGenes(luckyDog + i); if (genes > 0) { break; } } // min次震荡仍然未找到可兑奖基因 if (genes == 0) { //luckyDog右侧更长 if (min == luckyDog - 1) { for (i = min + luckyDog; i < totalSupply + 1; i++) { genes = _validGenes(i); if (genes > 0) { break; } } } //luckyDog左侧更长 if (min == totalSupply - luckyDog) { for (i = min; i < luckyDog; i++) { genes = _validGenes(luckyDog - i - 1); if (genes > 0) { break; } } } } return genes; } /* 判断狗是否能兑奖,能则直接返回狗的基因,不能则返回0 */ function _validGenes(uint256 dogId) internal view returns (uint256) { var(, , , , , ,generation, genes, variation,) = dogCore.getDog(dogId); if (generation == 0 || dogCore.ownerOf(dogId) == finalLottery || variation > 0) { return 0; } else { return genes; } } } /* LotteryCore是开奖函数的入口合约 开奖包括必中开奖和随机开奖 同时LotteryCore提供对外查询接口 */ contract LotteryCore is SetLottery { // 构造函数,传入奖金池地址,初始化中奖信息 function LotteryCore(address _ktAddress) public { bonusPool = _ktAddress; dogCore = DogCoreInterface(_ktAddress); //初始化中奖信息 CLottery memory _clottery; _clottery.luckyGenes = [0,0,0,0,0,0,0]; _clottery.totalAmount = uint256(0); _clottery.isReward = false; _clottery.openBlock = uint256(0); CLotteries.push(_clottery); } /* 设置FinalLottery地址 */ function setFinalLotteryAddress(address _flAddress) public onlyCEO { finalLottery = _flAddress; } /* 获取当前中奖记录 */ function getCLottery() public view returns ( uint8[7] luckyGenes, uint256 totalAmount, uint256 openBlock, bool isReward, uint256 term ) { term = CLotteries.length - uint256(1); luckyGenes = CLotteries[term].luckyGenes; totalAmount = CLotteries[term].totalAmount; openBlock = CLotteries[term].openBlock; isReward = CLotteries[term].isReward; } /* 更改发奖状态 */ function rewardLottery(bool isMore) external { // require contract address is final lottery require(msg.sender == finalLottery); uint256 term = CLotteries.length - 1; CLotteries[term].isReward = true; CLotteries[term].noFirstReward = isMore; } /* 转入蓄奖池 */ function toSPool(uint amount) external { // require contract address is final lottery require(msg.sender == finalLottery); SpoolAmount += amount; } } /* FinalLottery 包含兑奖函数和发奖函数 中奖信息flotteries存入开奖期数到[各等奖获奖者,各等奖中奖金额]的映射 */ contract FinalLottery { bool public isLottery = true; LotteryCore lotteryCore; DogCoreInterface dogCore; uint8[7] public luckyGenes; uint256 totalAmount; uint256 openBlock; bool isReward; uint256 currentTerm; uint256 public duration; uint8 public lotteryRatio; uint8[7] public lotteryParam; uint8 public carousalRatio; uint8[7] public carousalParam; // 中奖信息 struct FLottery { // 该期各等奖获奖者 // 一等奖 address[] owners0; uint256[] dogs0; // 二等奖 address[] owners1; uint256[] dogs1; // 三等奖 address[] owners2; uint256[] dogs2; // 四等奖 address[] owners3; uint256[] dogs3; // 五等奖 address[] owners4; uint256[] dogs4; // 六等奖 address[] owners5; uint256[] dogs5; // 七等奖 address[] owners6; uint256[] dogs6; // 中奖金额 uint256[] reward; } // 兑奖发奖信息 mapping(uint256 => FLottery) flotteries; // 构造函数 function FinalLottery(address _lcAddress) public { lotteryCore = LotteryCore(_lcAddress); dogCore = DogCoreInterface(lotteryCore.bonusPool()); duration = 11520; lotteryRatio = 23; lotteryParam = [46,16,10,9,8,6,5]; carousalRatio = 12; carousalParam = [35,18,14,12,8,7,6]; } // 发奖事件 event DistributeLottery(uint256[] rewardArray, uint256 currentTerm); // 兑奖事件 event RegisterLottery(uint256 dogId, address owner, uint8 lotteryClass, string result); // 设置兑奖周期 function setLotteryDuration(uint256 durationBlocks) public { require(msg.sender == dogCore.ceoAddress()); require(durationBlocks > 140); require(durationBlocks < block.number); duration = durationBlocks; } /* 登记兑奖函数,发生在当期开奖结束之后7天内(即40,320个区块内) */ function registerLottery(uint256 dogId) public returns (uint8) { uint256 _dogId = dogId; (luckyGenes, totalAmount, openBlock, isReward, currentTerm) = lotteryCore.getCLottery(); // 获取当前开奖信息 address owner = dogCore.ownerOf(_dogId); // 回收的不能兑奖 require (owner != address(this)); // 调用者必须是主合约 require(address(dogCore) == msg.sender); // 所有基因位开奖完毕(指针为0同时奖金池大于0)且未发奖且未兑奖结束 require(totalAmount > 0 && isReward == false && openBlock > (block.number-duration)); // 获取该宠物的基因,代数,出生时间 var(, , , birthTime, , ,generation,genes, variation,) = dogCore.getDog(_dogId); // 出生日期小于开奖时间 require(birthTime < openBlock); // 0代狗不能兑奖 require(generation > 0); // 变异的不能兑奖 require(variation == 0); // 判断该用户获几等奖,100表示未中奖 uint8 _lotteryClass = getLotteryClass(luckyGenes, genes); // 若未获奖则退出 require(_lotteryClass < 7); // 避免重复兑奖 address[] memory owners; uint256[] memory dogs; (dogs, owners) = _getLuckyList(currentTerm, _lotteryClass); for (uint i = 0; i < dogs.length; i++) { if (_dogId == dogs[i]) { // revert(); RegisterLottery(_dogId, owner, _lotteryClass,"dog already registered"); return 5; } } // 将登记中奖者的账户存入奖金信息表 _pushLuckyInfo(currentTerm, _lotteryClass, owner, _dogId); // 触发兑奖成功事件 RegisterLottery(_dogId, owner, _lotteryClass,"successful"); return 0; } /* 发奖函数,发生在当期开奖结束之后 */ function distributeLottery() public returns (uint8) { (luckyGenes, totalAmount, openBlock, isReward, currentTerm) = lotteryCore.getCLottery(); // 必须在当期开奖结束一周之后发奖 require(openBlock > 0 && openBlock < (block.number-duration)); //奖金池可用金额必须大于或等于0 require(totalAmount >= lotteryCore.SpoolAmount()); // 如果已经发奖 if (isReward == true) { DistributeLottery(flotteries[currentTerm].reward, currentTerm); return 1; } uint256 legalAmount = totalAmount - lotteryCore.SpoolAmount(); uint256 totalDistribute = 0; uint8[7] memory lR; uint8 ratio; // 必中和随机两种不同的奖金分配比率 if (lotteryCore._isCarousal(currentTerm) ) { lR = carousalParam; ratio = carousalRatio; } else { lR = lotteryParam; ratio = lotteryRatio; } // 计算各奖项金额并分发给中奖者 for (uint8 i = 0; i < 7; i++) { address[] memory owners; uint256[] memory dogs; (dogs, owners) = _getLuckyList(currentTerm, i); if (owners.length > 0) { uint256 reward = (legalAmount * ratio * lR[i])/(10000 * owners.length); totalDistribute += reward * owners.length; // 转给CFO的手续费(10%) dogCore.sendMoney(dogCore.cfoAddress(),reward * owners.length/10); for (uint j = 0; j < owners.length; j++) { address gen0Add; if (i == 0) { // 转账 dogCore.sendMoney(owners[j],reward*95*9/1000); // gen0 奖励 gen0Add = _getGen0Address(dogs[j]); assert(gen0Add != address(0)); dogCore.sendMoney(gen0Add,reward*5/100); } else if (i == 1) { // 转账 dogCore.sendMoney(owners[j],reward*97*9/1000); // gen0 奖励 gen0Add = _getGen0Address(dogs[j]); assert(gen0Add != address(0)); dogCore.sendMoney(gen0Add,reward*3/100); } else if (i == 2) { // 转账 dogCore.sendMoney(owners[j],reward*98*9/1000); // gen0 奖励 gen0Add = _getGen0Address(dogs[j]); assert(gen0Add != address(0)); dogCore.sendMoney(gen0Add,reward*2/100); } else { // 转账 dogCore.sendMoney(owners[j],reward*9/10); } } // 记录各等奖发奖金额 flotteries[currentTerm].reward.push(reward); } else { flotteries[currentTerm].reward.push(0); } } //没有人登记一等奖中奖,将奖金池5%转入蓄奖池,并且更新无一等奖计数 if (flotteries[currentTerm].owners0.length == 0) { lotteryCore.toSPool((lotteryCore.bonusPool().balance - lotteryCore.SpoolAmount())/20); lotteryCore.rewardLottery(true); } else { //发奖完成之后,更新当前奖项状态、将当前奖项加入历史记录 lotteryCore.rewardLottery(false); } DistributeLottery(flotteries[currentTerm].reward, currentTerm); return 0; } /* 获取狗的gen0祖先的主人账户 */ function _getGen0Address(uint256 dogId) internal view returns(address) { var(, , , , , , , , , gen0) = dogCore.getDog(dogId); return dogCore.ownerOf(gen0); } /* 通过奖项等级获取中奖者列表和中奖狗列表 */ function _getLuckyList(uint256 currentTerm1, uint8 lotclass) public view returns (uint256[] kts, address[] ons) { if (lotclass==0) { ons = flotteries[currentTerm1].owners0; kts = flotteries[currentTerm1].dogs0; } else if (lotclass==1) { ons = flotteries[currentTerm1].owners1; kts = flotteries[currentTerm1].dogs1; } else if (lotclass==2) { ons = flotteries[currentTerm1].owners2; kts = flotteries[currentTerm1].dogs2; } else if (lotclass==3) { ons = flotteries[currentTerm1].owners3; kts = flotteries[currentTerm1].dogs3; } else if (lotclass==4) { ons = flotteries[currentTerm1].owners4; kts = flotteries[currentTerm1].dogs4; } else if (lotclass==5) { ons = flotteries[currentTerm1].owners5; kts = flotteries[currentTerm1].dogs5; } else if (lotclass==6) { ons = flotteries[currentTerm1].owners6; kts = flotteries[currentTerm1].dogs6; } } /* 将owner和dogId推入中奖信息存储 */ function _pushLuckyInfo(uint256 currentTerm1, uint8 _lotteryClass, address owner, uint256 _dogId) internal { if (_lotteryClass == 0) { flotteries[currentTerm1].owners0.push(owner); flotteries[currentTerm1].dogs0.push(_dogId); } else if (_lotteryClass == 1) { flotteries[currentTerm1].owners1.push(owner); flotteries[currentTerm1].dogs1.push(_dogId); } else if (_lotteryClass == 2) { flotteries[currentTerm1].owners2.push(owner); flotteries[currentTerm1].dogs2.push(_dogId); } else if (_lotteryClass == 3) { flotteries[currentTerm1].owners3.push(owner); flotteries[currentTerm1].dogs3.push(_dogId); } else if (_lotteryClass == 4) { flotteries[currentTerm1].owners4.push(owner); flotteries[currentTerm1].dogs4.push(_dogId); } else if (_lotteryClass == 5) { flotteries[currentTerm1].owners5.push(owner); flotteries[currentTerm1].dogs5.push(_dogId); } else if (_lotteryClass == 6) { flotteries[currentTerm1].owners6.push(owner); flotteries[currentTerm1].dogs6.push(_dogId); } } /* 检测该基因获奖等级 */ function getLotteryClass(uint8[7] luckyGenesArray, uint256 genes) internal view returns(uint8) { // 不存在开奖信息,则直接返回未中奖 if (currentTerm < 0) { return 100; } uint8[7] memory dogArray = lotteryCore.convertGeneArray(genes); uint8 cnt = 0; uint8 lnt = 0; for (uint i = 0; i < 6; i++) { if (luckyGenesArray[i] > 0 && luckyGenesArray[i] == dogArray[i]) { cnt++; } } if (luckyGenesArray[6] > 0 && luckyGenesArray[6] == dogArray[6]) { lnt = 1; } uint8 lotclass = 100; if (cnt==6 && lnt==1) { lotclass = 0; } else if (cnt==6 && lnt==0) { lotclass = 1; } else if (cnt==5 && lnt==1) { lotclass = 2; } else if (cnt==5 && lnt==0) { lotclass = 3; } else if (cnt==4 && lnt==1) { lotclass = 4; } else if (cnt==3 && lnt==1) { lotclass = 5; } else if (cnt==3 && lnt==0) { lotclass = 6; } else { lotclass = 100; } return lotclass; } /* 检测该基因获奖等级接口 */ function checkLottery(uint256 genes) public view returns(uint8) { var(luckyGenesArray, , , isReward1, ) = lotteryCore.getCLottery(); if (isReward1) { return 100; } return getLotteryClass(luckyGenesArray, genes); } /* 获取当前Lottery信息 */ function getCLottery() public view returns ( uint8[7] luckyGenes1, uint256 totalAmount1, uint256 openBlock1, bool isReward1, uint256 term1, uint8 currentGenes1, uint256 tSupply, uint256 sPoolAmount1, uint256[] reward1 ) { (luckyGenes1, totalAmount1, openBlock1, isReward1, term1) = lotteryCore.getCLottery(); currentGenes1 = lotteryCore.currentGene(); tSupply = dogCore.totalSupply(); sPoolAmount1 = lotteryCore.SpoolAmount(); reward1 = flotteries[term1].reward; } }
/ 获取当前中奖信息 如果7个基因都完成开奖并且当期没有发奖,则说明当期所有基因已经开奖完毕在等待发奖,退出 触发事件,返回查询的基因分别返回查询基因,状态1 (表示当期所有基因开奖完毕在等待发奖) 如果上个基因开奖和本次开奖在同一个区块,退出 触发事件,返回查询的基因分别返回查询基因,状态2 (当前基因开奖区块与上个基因开奖区块相同) 如果当前开奖基因位为0且当期已经发奖,则进入下一期开奖 初始化当前lottery信息 如果前两期都没有一等奖产生,则该期产生必中奖,退出随机开奖函数 如果奖金池金额为零,则退出 触发事件,返回查询的基因分别返回查询基因,状态3 (奖金池金额不足)
function openLottery(uint8 _viewId) public returns(uint8,uint8) { uint8 viewId = _viewId; require(viewId < 7); uint256 currentTerm = CLotteries.length - 1; CLottery storage clottery = CLotteries[currentTerm]; if (currentGene == 0 && clottery.openBlock > 0 && clottery.isReward == false) { OpenLottery(viewId, clottery.luckyGenes[viewId], currentTerm, 0, 0); return (clottery.luckyGenes[viewId],1); } if (lastBlockNumber == block.number) { OpenLottery(viewId, clottery.luckyGenes[viewId], currentTerm, 0, 0); return (clottery.luckyGenes[viewId],2); } if (currentGene == 0 && clottery.isReward == true) { CLottery memory _clottery; _clottery.luckyGenes = [0,0,0,0,0,0,0]; _clottery.totalAmount = uint256(0); _clottery.isReward = false; _clottery.openBlock = uint256(0); currentTerm = CLotteries.push(_clottery) - 1; } if (this._isCarousal(currentTerm)) { revert(); } if (currentGene == 6) { if (bonusPool.balance <= SpoolAmount) { OpenLottery(viewId, clottery.luckyGenes[viewId], currentTerm, 0, 0); return (clottery.luckyGenes[viewId],3); } CLotteries[currentTerm].luckyGenes[currentGene] = luckyNum; CLotteries[currentTerm].openBlock = block.number; CLotteries[currentTerm].totalAmount = bonusPool.balance; luckyNum = random(12); CLotteries[currentTerm].luckyGenes[currentGene] = luckyNum; } }
7,663,473
[ 1, 19, 225, 169, 241, 120, 166, 242, 249, 166, 126, 246, 166, 236, 240, 165, 121, 260, 166, 103, 249, 165, 128, 99, 167, 228, 112, 225, 166, 104, 229, 167, 257, 255, 27, 165, 121, 108, 166, 258, 123, 166, 254, 259, 170, 230, 126, 166, 111, 239, 167, 235, 243, 166, 125, 227, 166, 103, 249, 166, 122, 119, 165, 121, 247, 166, 126, 246, 167, 255, 258, 167, 115, 99, 167, 255, 236, 166, 242, 244, 166, 103, 249, 176, 125, 239, 166, 235, 252, 169, 112, 117, 167, 251, 241, 166, 126, 246, 167, 255, 258, 167, 236, 227, 167, 255, 236, 166, 258, 123, 166, 254, 259, 166, 120, 115, 168, 124, 242, 166, 125, 227, 166, 103, 249, 166, 111, 239, 167, 112, 248, 166, 255, 106, 168, 260, 236, 166, 127, 232, 166, 242, 244, 166, 103, 249, 176, 125, 239, 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, 1696, 48, 352, 387, 93, 12, 11890, 28, 389, 1945, 548, 13, 1071, 1135, 12, 11890, 28, 16, 11890, 28, 13, 288, 203, 3639, 2254, 28, 1476, 548, 273, 389, 1945, 548, 31, 203, 3639, 2583, 12, 1945, 548, 411, 2371, 1769, 203, 3639, 2254, 5034, 783, 4065, 273, 14934, 352, 387, 606, 18, 2469, 300, 404, 31, 203, 3639, 14934, 352, 387, 93, 2502, 927, 352, 387, 93, 273, 14934, 352, 387, 606, 63, 2972, 4065, 15533, 203, 203, 3639, 309, 261, 2972, 24442, 422, 374, 597, 927, 352, 387, 93, 18, 3190, 1768, 405, 374, 597, 927, 352, 387, 93, 18, 291, 17631, 1060, 422, 629, 13, 288, 203, 5411, 3502, 48, 352, 387, 93, 12, 1945, 548, 16, 927, 352, 387, 93, 18, 80, 9031, 93, 7642, 281, 63, 1945, 548, 6487, 783, 4065, 16, 374, 16, 374, 1769, 203, 5411, 327, 261, 830, 352, 387, 93, 18, 80, 9031, 93, 7642, 281, 63, 1945, 548, 6487, 21, 1769, 203, 3639, 289, 203, 3639, 309, 261, 2722, 1768, 1854, 422, 1203, 18, 2696, 13, 288, 203, 5411, 3502, 48, 352, 387, 93, 12, 1945, 548, 16, 927, 352, 387, 93, 18, 80, 9031, 93, 7642, 281, 63, 1945, 548, 6487, 783, 4065, 16, 374, 16, 374, 1769, 203, 5411, 327, 261, 830, 352, 387, 93, 18, 80, 9031, 93, 7642, 281, 63, 1945, 548, 6487, 22, 1769, 203, 3639, 289, 203, 3639, 309, 261, 2972, 24442, 422, 374, 597, 927, 352, 387, 93, 18, 291, 17631, 1060, 422, 638, 2 ]
/** *Submitted for verification at Etherscan.io on 2021-12-13 */ // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; // File: contracts/lib/AddressUtil.sol // Copyright 2017 Loopring Technology Limited. /// @title Utility Functions for addresses /// @author Daniel Wang - <[email protected]> /// @author Brecht Devos - <[email protected]> library AddressUtil { using AddressUtil for *; function isContract( address addr ) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(addr) } return (codehash != 0x0 && codehash != 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470); } function toPayable( address addr ) internal pure returns (address payable) { return payable(addr); } // Works like address.send but with a customizable gas limit // Make sure your code is safe for reentrancy when using this function! function sendETH( address to, uint amount, uint gasLimit ) internal returns (bool success) { if (amount == 0) { return true; } address payable recipient = to.toPayable(); /* solium-disable-next-line */ (success, ) = recipient.call{value: amount, gas: gasLimit}(""); } // Works like address.transfer but with a customizable gas limit // Make sure your code is safe for reentrancy when using this function! function sendETHAndVerify( address to, uint amount, uint gasLimit ) internal returns (bool success) { success = to.sendETH(amount, gasLimit); require(success, "TRANSFER_FAILURE"); } // Works like call but is slightly more efficient when data // needs to be copied from memory to do the call. function fastCall( address to, uint gasLimit, uint value, bytes memory data ) internal returns (bool success, bytes memory returnData) { if (to != address(0)) { assembly { // Do the call success := call(gasLimit, to, value, add(data, 32), mload(data), 0, 0) // Copy the return data let size := returndatasize() returnData := mload(0x40) mstore(returnData, size) returndatacopy(add(returnData, 32), 0, size) // Update free memory pointer mstore(0x40, add(returnData, add(32, size))) } } } // Like fastCall, but throws when the call is unsuccessful. function fastCallAndVerify( address to, uint gasLimit, uint value, bytes memory data ) internal returns (bytes memory returnData) { bool success; (success, returnData) = fastCall(to, gasLimit, value, data); if (!success) { assembly { revert(add(returnData, 32), mload(returnData)) } } } } // File: contracts/thirdparty/BytesUtil.sol //Mainly taken from https://github.com/GNSPS/solidity-bytes-utils/blob/master/contracts/BytesLib.sol library BytesUtil { function concat( bytes memory _preBytes, bytes memory _postBytes ) internal pure returns (bytes memory) { bytes memory tempBytes; assembly { // Get a location of some free memory and store it in tempBytes as // Solidity does for memory variables. tempBytes := mload(0x40) // Store the length of the first bytes array at the beginning of // the memory for tempBytes. let length := mload(_preBytes) mstore(tempBytes, length) // Maintain a memory counter for the current write location in the // temp bytes array by adding the 32 bytes for the array length to // the starting location. let mc := add(tempBytes, 0x20) // Stop copying when the memory counter reaches the length of the // first bytes array. let end := add(mc, length) for { // Initialize a copy counter to the start of the _preBytes data, // 32 bytes into its memory. let cc := add(_preBytes, 0x20) } lt(mc, end) { // Increase both counters by 32 bytes each iteration. mc := add(mc, 0x20) cc := add(cc, 0x20) } { // Write the _preBytes data into the tempBytes memory 32 bytes // at a time. mstore(mc, mload(cc)) } // Add the length of _postBytes to the current length of tempBytes // and store it as the new length in the first 32 bytes of the // tempBytes memory. length := mload(_postBytes) mstore(tempBytes, add(length, mload(tempBytes))) // Move the memory counter back from a multiple of 0x20 to the // actual end of the _preBytes data. mc := end // Stop copying when the memory counter reaches the new combined // length of the arrays. end := add(mc, length) for { let cc := add(_postBytes, 0x20) } lt(mc, end) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { mstore(mc, mload(cc)) } // Update the free-memory pointer by padding our last write location // to 32 bytes: add 31 bytes to the end of tempBytes to move to the // next 32 byte block, then round down to the nearest multiple of // 32. If the sum of the length of the two arrays is zero then add // one before rounding down to leave a blank 32 bytes (the length block with 0). mstore(0x40, and( add(add(end, iszero(add(length, mload(_preBytes)))), 31), not(31) // Round down to the nearest 32 bytes. )) } return tempBytes; } function slice( bytes memory _bytes, uint _start, uint _length ) internal pure returns (bytes memory) { require(_bytes.length >= (_start + _length)); bytes memory tempBytes; assembly { switch iszero(_length) case 0 { // Get a location of some free memory and store it in tempBytes as // Solidity does for memory variables. tempBytes := mload(0x40) // The first word of the slice result is potentially a partial // word read from the original array. To read it, we calculate // the length of that partial word and start copying that many // bytes into the array. The first word we copy will start with // data we don't care about, but the last `lengthmod` bytes will // land at the beginning of the contents of the new array. When // we're done copying, we overwrite the full first word with // the actual length of the slice. let lengthmod := and(_length, 31) // The multiplication in the next line is necessary // because when slicing multiples of 32 bytes (lengthmod == 0) // the following copy loop was copying the origin's length // and then ending prematurely not copying everything it should. let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod))) let end := add(mc, _length) for { // The multiplication in the next line has the same exact purpose // as the one above. let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start) } lt(mc, end) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { mstore(mc, mload(cc)) } mstore(tempBytes, _length) //update free-memory pointer //allocating the array padded to 32 bytes like the compiler does now mstore(0x40, and(add(mc, 31), not(31))) } //if we want a zero-length slice let's just return a zero-length array default { tempBytes := mload(0x40) mstore(0x40, add(tempBytes, 0x20)) } } return tempBytes; } function toAddress(bytes memory _bytes, uint _start) internal pure returns (address) { require(_bytes.length >= (_start + 20)); address tempAddress; assembly { tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000) } return tempAddress; } function toUint8(bytes memory _bytes, uint _start) internal pure returns (uint8) { require(_bytes.length >= (_start + 1)); uint8 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x1), _start)) } return tempUint; } function toUint16(bytes memory _bytes, uint _start) internal pure returns (uint16) { require(_bytes.length >= (_start + 2)); uint16 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x2), _start)) } return tempUint; } function toUint24(bytes memory _bytes, uint _start) internal pure returns (uint24) { require(_bytes.length >= (_start + 3)); uint24 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x3), _start)) } return tempUint; } function toUint32(bytes memory _bytes, uint _start) internal pure returns (uint32) { require(_bytes.length >= (_start + 4)); uint32 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x4), _start)) } return tempUint; } function toUint64(bytes memory _bytes, uint _start) internal pure returns (uint64) { require(_bytes.length >= (_start + 8)); uint64 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x8), _start)) } return tempUint; } function toUint96(bytes memory _bytes, uint _start) internal pure returns (uint96) { require(_bytes.length >= (_start + 12)); uint96 tempUint; assembly { tempUint := mload(add(add(_bytes, 0xc), _start)) } return tempUint; } function toUint128(bytes memory _bytes, uint _start) internal pure returns (uint128) { require(_bytes.length >= (_start + 16)); uint128 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x10), _start)) } return tempUint; } function toUint(bytes memory _bytes, uint _start) internal pure returns (uint256) { require(_bytes.length >= (_start + 32)); uint256 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x20), _start)) } return tempUint; } function toBytes4(bytes memory _bytes, uint _start) internal pure returns (bytes4) { require(_bytes.length >= (_start + 4)); bytes4 tempBytes4; assembly { tempBytes4 := mload(add(add(_bytes, 0x20), _start)) } return tempBytes4; } function toBytes20(bytes memory _bytes, uint _start) internal pure returns (bytes20) { require(_bytes.length >= (_start + 20)); bytes20 tempBytes20; assembly { tempBytes20 := mload(add(add(_bytes, 0x20), _start)) } return tempBytes20; } function toBytes32(bytes memory _bytes, uint _start) internal pure returns (bytes32) { require(_bytes.length >= (_start + 32)); bytes32 tempBytes32; assembly { tempBytes32 := mload(add(add(_bytes, 0x20), _start)) } return tempBytes32; } function toAddressUnsafe(bytes memory _bytes, uint _start) internal pure returns (address) { address tempAddress; assembly { tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000) } return tempAddress; } function toUint8Unsafe(bytes memory _bytes, uint _start) internal pure returns (uint8) { uint8 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x1), _start)) } return tempUint; } function toUint16Unsafe(bytes memory _bytes, uint _start) internal pure returns (uint16) { uint16 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x2), _start)) } return tempUint; } function toUint24Unsafe(bytes memory _bytes, uint _start) internal pure returns (uint24) { uint24 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x3), _start)) } return tempUint; } function toUint32Unsafe(bytes memory _bytes, uint _start) internal pure returns (uint32) { uint32 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x4), _start)) } return tempUint; } function toUint64Unsafe(bytes memory _bytes, uint _start) internal pure returns (uint64) { uint64 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x8), _start)) } return tempUint; } function toUint96Unsafe(bytes memory _bytes, uint _start) internal pure returns (uint96) { uint96 tempUint; assembly { tempUint := mload(add(add(_bytes, 0xc), _start)) } return tempUint; } function toUint128Unsafe(bytes memory _bytes, uint _start) internal pure returns (uint128) { uint128 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x10), _start)) } return tempUint; } function toUintUnsafe(bytes memory _bytes, uint _start) internal pure returns (uint256) { uint256 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x20), _start)) } return tempUint; } function toBytes4Unsafe(bytes memory _bytes, uint _start) internal pure returns (bytes4) { bytes4 tempBytes4; assembly { tempBytes4 := mload(add(add(_bytes, 0x20), _start)) } return tempBytes4; } function toBytes20Unsafe(bytes memory _bytes, uint _start) internal pure returns (bytes20) { bytes20 tempBytes20; assembly { tempBytes20 := mload(add(add(_bytes, 0x20), _start)) } return tempBytes20; } function toBytes32Unsafe(bytes memory _bytes, uint _start) internal pure returns (bytes32) { bytes32 tempBytes32; assembly { tempBytes32 := mload(add(add(_bytes, 0x20), _start)) } return tempBytes32; } function fastSHA256( bytes memory data ) internal view returns (bytes32) { bytes32[] memory result = new bytes32[](1); bool success; assembly { let ptr := add(data, 32) success := staticcall(sub(gas(), 2000), 2, ptr, mload(data), add(result, 32), 32) } require(success, "SHA256_FAILED"); return result[0]; } } // File: contracts/core/iface/IAgentRegistry.sol // Copyright 2017 Loopring Technology Limited. interface IAgent{} abstract contract IAgentRegistry { /// @dev Returns whether an agent address is an agent of an account owner /// @param owner The account owner. /// @param agent The agent address /// @return True if the agent address is an agent for the account owner, else false function isAgent( address owner, address agent ) external virtual view returns (bool); /// @dev Returns whether an agent address is an agent of all account owners /// @param owners The account owners. /// @param agent The agent address /// @return True if the agent address is an agent for the account owner, else false function isAgent( address[] calldata owners, address agent ) external virtual view returns (bool); /// @dev Returns whether an agent address is a universal agent. /// @param agent The agent address /// @return True if the agent address is a universal agent, else false function isUniversalAgent(address agent) public virtual view returns (bool); } // File: contracts/lib/Ownable.sol // Copyright 2017 Loopring Technology Limited. /// @title Ownable /// @author Brecht Devos - <[email protected]> /// @dev The Ownable contract has an owner address, and provides basic /// authorization control functions, this simplifies the implementation of /// "user permissions". contract Ownable { address public owner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /// @dev The Ownable constructor sets the original `owner` of the contract /// to the sender. constructor() { owner = msg.sender; } /// @dev Throws if called by any account other than the owner. modifier onlyOwner() { require(msg.sender == owner, "UNAUTHORIZED"); _; } /// @dev Allows the current owner to transfer control of the contract to a /// new owner. /// @param newOwner The address to transfer ownership to. function transferOwnership( address newOwner ) public virtual onlyOwner { require(newOwner != address(0), "ZERO_ADDRESS"); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } function renounceOwnership() public onlyOwner { emit OwnershipTransferred(owner, address(0)); owner = address(0); } } // File: contracts/lib/Claimable.sol // Copyright 2017 Loopring Technology Limited. /// @title Claimable /// @author Brecht Devos - <[email protected]> /// @dev Extension for the Ownable contract, where the ownership needs /// to be claimed. This allows the new owner to accept the transfer. contract Claimable is Ownable { address public pendingOwner; /// @dev Modifier throws if called by any account other than the pendingOwner. modifier onlyPendingOwner() { require(msg.sender == pendingOwner, "UNAUTHORIZED"); _; } /// @dev Allows the current owner to set the pendingOwner address. /// @param newOwner The address to transfer ownership to. function transferOwnership( address newOwner ) public override onlyOwner { require(newOwner != address(0) && newOwner != owner, "INVALID_ADDRESS"); pendingOwner = newOwner; } /// @dev Allows the pendingOwner address to finalize the transfer. function claimOwnership() public onlyPendingOwner { emit OwnershipTransferred(owner, pendingOwner); owner = pendingOwner; pendingOwner = address(0); } } // File: contracts/core/iface/IBlockVerifier.sol // Copyright 2017 Loopring Technology Limited. /// @title IBlockVerifier /// @author Brecht Devos - <[email protected]> abstract contract IBlockVerifier is Claimable { // -- Events -- event CircuitRegistered( uint8 indexed blockType, uint16 blockSize, uint8 blockVersion ); event CircuitDisabled( uint8 indexed blockType, uint16 blockSize, uint8 blockVersion ); // -- Public functions -- /// @dev Sets the verifying key for the specified circuit. /// Every block permutation needs its own circuit and thus its own set of /// verification keys. Only a limited number of block sizes per block /// type are supported. /// @param blockType The type of the block /// @param blockSize The number of requests handled in the block /// @param blockVersion The block version (i.e. which circuit version needs to be used) /// @param vk The verification key function registerCircuit( uint8 blockType, uint16 blockSize, uint8 blockVersion, uint[18] calldata vk ) external virtual; /// @dev Disables the use of the specified circuit. /// @param blockType The type of the block /// @param blockSize The number of requests handled in the block /// @param blockVersion The block version (i.e. which circuit version needs to be used) function disableCircuit( uint8 blockType, uint16 blockSize, uint8 blockVersion ) external virtual; /// @dev Verifies blocks with the given public data and proofs. /// Verifying a block makes sure all requests handled in the block /// are correctly handled by the operator. /// @param blockType The type of block /// @param blockSize The number of requests handled in the block /// @param blockVersion The block version (i.e. which circuit version needs to be used) /// @param publicInputs The hash of all the public data of the blocks /// @param proofs The ZK proofs proving that the blocks are correct /// @return True if the block is valid, false otherwise function verifyProofs( uint8 blockType, uint16 blockSize, uint8 blockVersion, uint[] calldata publicInputs, uint[] calldata proofs ) external virtual view returns (bool); /// @dev Checks if a circuit with the specified parameters is registered. /// @param blockType The type of the block /// @param blockSize The number of requests handled in the block /// @param blockVersion The block version (i.e. which circuit version needs to be used) /// @return True if the circuit is registered, false otherwise function isCircuitRegistered( uint8 blockType, uint16 blockSize, uint8 blockVersion ) external virtual view returns (bool); /// @dev Checks if a circuit can still be used to commit new blocks. /// @param blockType The type of the block /// @param blockSize The number of requests handled in the block /// @param blockVersion The block version (i.e. which circuit version needs to be used) /// @return True if the circuit is enabled, false otherwise function isCircuitEnabled( uint8 blockType, uint16 blockSize, uint8 blockVersion ) external virtual view returns (bool); } // File: contracts/core/iface/IDepositContract.sol // Copyright 2017 Loopring Technology Limited. /// @title IDepositContract. /// @dev Contract storing and transferring funds for an exchange. /// /// ERC1155 tokens can be supported by registering pseudo token addresses calculated /// as `address(keccak256(real_token_address, token_params))`. Then the custom /// deposit contract can look up the real token address and paramsters with the /// pseudo token address before doing the transfers. /// @author Brecht Devos - <[email protected]> interface IDepositContract { /// @dev Returns if a token is suppoprted by this contract. function isTokenSupported(address token) external view returns (bool); /// @dev Transfers tokens from a user to the exchange. This function will /// be called when a user deposits funds to the exchange. /// In a simple implementation the funds are simply stored inside the /// deposit contract directly. More advanced implementations may store the funds /// in some DeFi application to earn interest, so this function could directly /// call the necessary functions to store the funds there. /// /// This function needs to throw when an error occurred! /// /// This function can only be called by the exchange. /// /// @param from The address of the account that sends the tokens. /// @param token The address of the token to transfer (`0x0` for ETH). /// @param amount The amount of tokens to transfer. /// @param extraData Opaque data that can be used by the contract to handle the deposit /// @return amountReceived The amount to deposit to the user's account in the Merkle tree function deposit( address from, address token, uint96 amount, bytes calldata extraData ) external payable returns (uint96 amountReceived); /// @dev Transfers tokens from the exchange to a user. This function will /// be called when a withdrawal is done for a user on the exchange. /// In the simplest implementation the funds are simply stored inside the /// deposit contract directly so this simply transfers the requested tokens back /// to the user. More advanced implementations may store the funds /// in some DeFi application to earn interest so the function would /// need to get those tokens back from the DeFi application first before they /// can be transferred to the user. /// /// This function needs to throw when an error occurred! /// /// This function can only be called by the exchange. /// /// @param from The address from which 'amount' tokens are transferred. /// @param to The address to which 'amount' tokens are transferred. /// @param token The address of the token to transfer (`0x0` for ETH). /// @param amount The amount of tokens transferred. /// @param extraData Opaque data that can be used by the contract to handle the withdrawal function withdraw( address from, address to, address token, uint amount, bytes calldata extraData ) external payable; /// @dev Transfers tokens (ETH not supported) for a user using the allowance set /// for the exchange. This way the approval can be used for all functionality (and /// extended functionality) of the exchange. /// Should NOT be used to deposit/withdraw user funds, `deposit`/`withdraw` /// should be used for that as they will contain specialised logic for those operations. /// This function can be called by the exchange to transfer onchain funds of users /// necessary for Agent functionality. /// /// This function needs to throw when an error occurred! /// /// This function can only be called by the exchange. /// /// @param from The address of the account that sends the tokens. /// @param to The address to which 'amount' tokens are transferred. /// @param token The address of the token to transfer (ETH is and cannot be suppported). /// @param amount The amount of tokens transferred. function transfer( address from, address to, address token, uint amount ) external payable; /// @dev Checks if the given address is used for depositing ETH or not. /// Is used while depositing to send the correct ETH amount to the deposit contract. /// /// Note that 0x0 is always registered for deposting ETH when the exchange is created! /// This function allows additional addresses to be used for depositing ETH, the deposit /// contract can implement different behaviour based on the address value. /// /// @param addr The address to check /// @return True if the address is used for depositing ETH, else false. function isETH(address addr) external view returns (bool); } // File: contracts/core/iface/ILoopringV3.sol // Copyright 2017 Loopring Technology Limited. /// @title ILoopringV3 /// @author Brecht Devos - <[email protected]> /// @author Daniel Wang - <[email protected]> abstract contract ILoopringV3 is Claimable { // == Events == event ExchangeStakeDeposited(address exchangeAddr, uint amount); event ExchangeStakeWithdrawn(address exchangeAddr, uint amount); event ExchangeStakeBurned(address exchangeAddr, uint amount); event SettingsUpdated(uint time); // == Public Variables == mapping (address => uint) internal exchangeStake; uint public totalStake; address public blockVerifierAddress; uint public forcedWithdrawalFee; uint public tokenRegistrationFeeLRCBase; uint public tokenRegistrationFeeLRCDelta; uint8 public protocolTakerFeeBips; uint8 public protocolMakerFeeBips; address payable public protocolFeeVault; // == Public Functions == /// @dev Returns the LRC token address /// @return the LRC token address function lrcAddress() external view virtual returns (address); /// @dev Updates the global exchange settings. /// This function can only be called by the owner of this contract. /// /// Warning: these new values will be used by existing and /// new Loopring exchanges. function updateSettings( address payable _protocolFeeVault, // address(0) not allowed address _blockVerifierAddress, // address(0) not allowed uint _forcedWithdrawalFee ) external virtual; /// @dev Updates the global protocol fee settings. /// This function can only be called by the owner of this contract. /// /// Warning: these new values will be used by existing and /// new Loopring exchanges. function updateProtocolFeeSettings( uint8 _protocolTakerFeeBips, uint8 _protocolMakerFeeBips ) external virtual; /// @dev Gets the amount of staked LRC for an exchange. /// @param exchangeAddr The address of the exchange /// @return stakedLRC The amount of LRC function getExchangeStake( address exchangeAddr ) public virtual view returns (uint stakedLRC); /// @dev Burns a certain amount of staked LRC for a specific exchange. /// This function is meant to be called only from exchange contracts. /// @return burnedLRC The amount of LRC burned. If the amount is greater than /// the staked amount, all staked LRC will be burned. function burnExchangeStake( uint amount ) external virtual returns (uint burnedLRC); /// @dev Stakes more LRC for an exchange. /// @param exchangeAddr The address of the exchange /// @param amountLRC The amount of LRC to stake /// @return stakedLRC The total amount of LRC staked for the exchange function depositExchangeStake( address exchangeAddr, uint amountLRC ) external virtual returns (uint stakedLRC); /// @dev Withdraws a certain amount of staked LRC for an exchange to the given address. /// This function is meant to be called only from within exchange contracts. /// @param recipient The address to receive LRC /// @param requestedAmount The amount of LRC to withdraw /// @return amountLRC The amount of LRC withdrawn function withdrawExchangeStake( address recipient, uint requestedAmount ) external virtual returns (uint amountLRC); /// @dev Gets the protocol fee values for an exchange. /// @return takerFeeBips The protocol taker fee /// @return makerFeeBips The protocol maker fee function getProtocolFeeValues( ) public virtual view returns ( uint8 takerFeeBips, uint8 makerFeeBips ); } // File: contracts/core/iface/ExchangeData.sol // Copyright 2017 Loopring Technology Limited. /// @title ExchangeData /// @dev All methods in this lib are internal, therefore, there is no need /// to deploy this library independently. /// @author Daniel Wang - <[email protected]> /// @author Brecht Devos - <[email protected]> library ExchangeData { // -- Enums -- enum TransactionType { NOOP, DEPOSIT, WITHDRAWAL, TRANSFER, SPOT_TRADE, ACCOUNT_UPDATE, AMM_UPDATE, SIGNATURE_VERIFICATION, NFT_MINT, // L2 NFT mint or L1-to-L2 NFT deposit NFT_DATA } enum NftType { ERC1155, ERC721 } // -- Structs -- struct Token { address token; } struct ProtocolFeeData { uint32 syncedAt; // only valid before 2105 (85 years to go) uint8 takerFeeBips; uint8 makerFeeBips; uint8 previousTakerFeeBips; uint8 previousMakerFeeBips; } // General auxiliary data for each conditional transaction struct AuxiliaryData { uint txIndex; bool approved; bytes data; } // This is the (virtual) block the owner needs to submit onchain to maintain the // per-exchange (virtual) blockchain. struct Block { uint8 blockType; uint16 blockSize; uint8 blockVersion; bytes data; uint256[8] proof; // Whether we should store the @BlockInfo for this block on-chain. bool storeBlockInfoOnchain; // Block specific data that is only used to help process the block on-chain. // It is not used as input for the circuits and it is not necessary for data-availability. // This bytes array contains the abi encoded AuxiliaryData[] data. bytes auxiliaryData; // Arbitrary data, mainly for off-chain data-availability, i.e., // the multihash of the IPFS file that contains the block data. bytes offchainData; } struct BlockInfo { // The time the block was submitted on-chain. uint32 timestamp; // The public data hash of the block (the 28 most significant bytes). bytes28 blockDataHash; } // Represents an onchain deposit request. struct Deposit { uint96 amount; uint64 timestamp; } // A forced withdrawal request. // If the actual owner of the account initiated the request (we don't know who the owner is // at the time the request is being made) the full balance will be withdrawn. struct ForcedWithdrawal { address owner; uint64 timestamp; } struct Constants { uint SNARK_SCALAR_FIELD; uint MAX_OPEN_FORCED_REQUESTS; uint MAX_AGE_FORCED_REQUEST_UNTIL_WITHDRAW_MODE; uint TIMESTAMP_HALF_WINDOW_SIZE_IN_SECONDS; uint MAX_NUM_ACCOUNTS; uint MAX_NUM_TOKENS; uint MIN_AGE_PROTOCOL_FEES_UNTIL_UPDATED; uint MIN_TIME_IN_SHUTDOWN; uint TX_DATA_AVAILABILITY_SIZE; uint MAX_AGE_DEPOSIT_UNTIL_WITHDRAWABLE_UPPERBOUND; } // This is the prime number that is used for the alt_bn128 elliptic curve, see EIP-196. uint public constant SNARK_SCALAR_FIELD = 21888242871839275222246405745257275088548364400416034343698204186575808495617; uint public constant MAX_OPEN_FORCED_REQUESTS = 4096; uint public constant MAX_AGE_FORCED_REQUEST_UNTIL_WITHDRAW_MODE = 15 days; uint public constant TIMESTAMP_HALF_WINDOW_SIZE_IN_SECONDS = 7 days; uint public constant MAX_NUM_ACCOUNTS = 2 ** 32; uint public constant MAX_NUM_TOKENS = 2 ** 16; uint public constant MIN_AGE_PROTOCOL_FEES_UNTIL_UPDATED = 7 days; uint public constant MIN_TIME_IN_SHUTDOWN = 30 days; // The amount of bytes each rollup transaction uses in the block data for data-availability. // This is the maximum amount of bytes of all different transaction types. uint32 public constant MAX_AGE_DEPOSIT_UNTIL_WITHDRAWABLE_UPPERBOUND = 15 days; uint32 public constant ACCOUNTID_PROTOCOLFEE = 0; uint public constant TX_DATA_AVAILABILITY_SIZE = 68; uint public constant TX_DATA_AVAILABILITY_SIZE_PART_1 = 29; uint public constant TX_DATA_AVAILABILITY_SIZE_PART_2 = 39; uint public constant NFT_TOKEN_ID_START = 2 ** 15; struct AccountLeaf { uint32 accountID; address owner; uint pubKeyX; uint pubKeyY; uint32 nonce; uint feeBipsAMM; } struct BalanceLeaf { uint16 tokenID; uint96 balance; uint weightAMM; uint storageRoot; } struct Nft { address minter; // Minter address for a L2 mint or // the NFT's contract address in the case of a L1-to-L2 NFT deposit. NftType nftType; address token; uint256 nftID; uint8 creatorFeeBips; } struct MerkleProof { ExchangeData.AccountLeaf accountLeaf; ExchangeData.BalanceLeaf balanceLeaf; ExchangeData.Nft nft; uint[48] accountMerkleProof; uint[24] balanceMerkleProof; } struct BlockContext { bytes32 DOMAIN_SEPARATOR; uint32 timestamp; Block block; uint txIndex; } // Represents the entire exchange state except the owner of the exchange. struct State { uint32 maxAgeDepositUntilWithdrawable; bytes32 DOMAIN_SEPARATOR; ILoopringV3 loopring; IBlockVerifier blockVerifier; IAgentRegistry agentRegistry; IDepositContract depositContract; // The merkle root of the offchain data stored in a Merkle tree. The Merkle tree // stores balances for users using an account model. bytes32 merkleRoot; // List of all blocks mapping(uint => BlockInfo) blocks; uint numBlocks; // List of all tokens Token[] tokens; // A map from a token to its tokenID + 1 mapping (address => uint16) tokenToTokenId; // A map from an accountID to a tokenID to if the balance is withdrawn mapping (uint32 => mapping (uint16 => bool)) withdrawnInWithdrawMode; // A map from an account to a token to the amount withdrawable for that account. // This is only used when the automatic distribution of the withdrawal failed. mapping (address => mapping (uint16 => uint)) amountWithdrawable; // A map from an account to a token to the forced withdrawal (always full balance) // The `uint16' represents ERC20 token ID (if < NFT_TOKEN_ID_START) or // NFT balance slot (if >= NFT_TOKEN_ID_START) mapping (uint32 => mapping (uint16 => ForcedWithdrawal)) pendingForcedWithdrawals; // A map from an address to a token to a deposit mapping (address => mapping (uint16 => Deposit)) pendingDeposits; // A map from an account owner to an approved transaction hash to if the transaction is approved or not mapping (address => mapping (bytes32 => bool)) approvedTx; // A map from an account owner to a destination address to a tokenID to an amount to a storageID to a new recipient address mapping (address => mapping (address => mapping (uint16 => mapping (uint => mapping (uint32 => address))))) withdrawalRecipient; // Counter to keep track of how many of forced requests are open so we can limit the work that needs to be done by the owner uint32 numPendingForcedTransactions; // Cached data for the protocol fee ProtocolFeeData protocolFeeData; // Time when the exchange was shutdown uint shutdownModeStartTime; // Time when the exchange has entered withdrawal mode uint withdrawalModeStartTime; // Last time the protocol fee was withdrawn for a specific token mapping (address => uint) protocolFeeLastWithdrawnTime; // Duplicated loopring address address loopringAddr; // AMM fee bips uint8 ammFeeBips; // Enable/Disable `onchainTransferFrom` bool allowOnchainTransferFrom; // owner => NFT type => token address => nftID => Deposit mapping (address => mapping (NftType => mapping (address => mapping(uint256 => Deposit)))) pendingNFTDeposits; // owner => minter => NFT type => token address => nftID => amount withdrawable // This is only used when the automatic distribution of the withdrawal failed. mapping (address => mapping (address => mapping (NftType => mapping (address => mapping(uint256 => uint))))) amountWithdrawableNFT; } } // File: contracts/lib/MathUint.sol // Copyright 2017 Loopring Technology Limited. /// @title Utility Functions for uint /// @author Daniel Wang - <[email protected]> library MathUint { using MathUint for uint; function mul( uint a, uint b ) internal pure returns (uint c) { c = a * b; require(a == 0 || c / a == b, "MUL_OVERFLOW"); } function sub( uint a, uint b ) internal pure returns (uint) { require(b <= a, "SUB_UNDERFLOW"); return a - b; } function add( uint a, uint b ) internal pure returns (uint c) { c = a + b; require(c >= a, "ADD_OVERFLOW"); } function add64( uint64 a, uint64 b ) internal pure returns (uint64 c) { c = a + b; require(c >= a, "ADD_OVERFLOW"); } } // File: contracts/lib/Poseidon.sol // Copyright 2017 Loopring Technology Limited. /// @title Poseidon hash function /// See: https://eprint.iacr.org/2019/458.pdf /// Code auto-generated by generate_poseidon_EVM_code.py /// @author Brecht Devos - <[email protected]> library Poseidon { // // hash_t4f6p52 // struct HashInputs4 { uint t0; uint t1; uint t2; uint t3; } function mix(HashInputs4 memory i, uint q) internal pure { HashInputs4 memory o; o.t0 = mulmod(i.t0, 11739432287187184656569880828944421268616385874806221589758215824904320817117, q); o.t0 = addmod(o.t0, mulmod(i.t1, 4977258759536702998522229302103997878600602264560359702680165243908162277980, q), q); o.t0 = addmod(o.t0, mulmod(i.t2, 19167410339349846567561662441069598364702008768579734801591448511131028229281, q), q); o.t0 = addmod(o.t0, mulmod(i.t3, 14183033936038168803360723133013092560869148726790180682363054735190196956789, q), q); o.t1 = mulmod(i.t0, 16872301185549870956030057498946148102848662396374401407323436343924021192350, q); o.t1 = addmod(o.t1, mulmod(i.t1, 107933704346764130067829474107909495889716688591997879426350582457782826785, q), q); o.t1 = addmod(o.t1, mulmod(i.t2, 17034139127218860091985397764514160131253018178110701196935786874261236172431, q), q); o.t1 = addmod(o.t1, mulmod(i.t3, 2799255644797227968811798608332314218966179365168250111693473252876996230317, q), q); o.t2 = mulmod(i.t0, 18618317300596756144100783409915332163189452886691331959651778092154775572832, q); o.t2 = addmod(o.t2, mulmod(i.t1, 13596762909635538739079656925495736900379091964739248298531655823337482778123, q), q); o.t2 = addmod(o.t2, mulmod(i.t2, 18985203040268814769637347880759846911264240088034262814847924884273017355969, q), q); o.t2 = addmod(o.t2, mulmod(i.t3, 8652975463545710606098548415650457376967119951977109072274595329619335974180, q), q); o.t3 = mulmod(i.t0, 11128168843135959720130031095451763561052380159981718940182755860433840154182, q); o.t3 = addmod(o.t3, mulmod(i.t1, 2953507793609469112222895633455544691298656192015062835263784675891831794974, q), q); o.t3 = addmod(o.t3, mulmod(i.t2, 19025623051770008118343718096455821045904242602531062247152770448380880817517, q), q); o.t3 = addmod(o.t3, mulmod(i.t3, 9077319817220936628089890431129759976815127354480867310384708941479362824016, q), q); i.t0 = o.t0; i.t1 = o.t1; i.t2 = o.t2; i.t3 = o.t3; } function ark(HashInputs4 memory i, uint q, uint c) internal pure { HashInputs4 memory o; o.t0 = addmod(i.t0, c, q); o.t1 = addmod(i.t1, c, q); o.t2 = addmod(i.t2, c, q); o.t3 = addmod(i.t3, c, q); i.t0 = o.t0; i.t1 = o.t1; i.t2 = o.t2; i.t3 = o.t3; } function sbox_full(HashInputs4 memory i, uint q) internal pure { HashInputs4 memory o; o.t0 = mulmod(i.t0, i.t0, q); o.t0 = mulmod(o.t0, o.t0, q); o.t0 = mulmod(i.t0, o.t0, q); o.t1 = mulmod(i.t1, i.t1, q); o.t1 = mulmod(o.t1, o.t1, q); o.t1 = mulmod(i.t1, o.t1, q); o.t2 = mulmod(i.t2, i.t2, q); o.t2 = mulmod(o.t2, o.t2, q); o.t2 = mulmod(i.t2, o.t2, q); o.t3 = mulmod(i.t3, i.t3, q); o.t3 = mulmod(o.t3, o.t3, q); o.t3 = mulmod(i.t3, o.t3, q); i.t0 = o.t0; i.t1 = o.t1; i.t2 = o.t2; i.t3 = o.t3; } function sbox_partial(HashInputs4 memory i, uint q) internal pure { HashInputs4 memory o; o.t0 = mulmod(i.t0, i.t0, q); o.t0 = mulmod(o.t0, o.t0, q); o.t0 = mulmod(i.t0, o.t0, q); i.t0 = o.t0; } function hash_t4f6p52(HashInputs4 memory i, uint q) internal pure returns (uint) { // validate inputs require(i.t0 < q, "INVALID_INPUT"); require(i.t1 < q, "INVALID_INPUT"); require(i.t2 < q, "INVALID_INPUT"); require(i.t3 < q, "INVALID_INPUT"); // round 0 ark(i, q, 14397397413755236225575615486459253198602422701513067526754101844196324375522); sbox_full(i, q); mix(i, q); // round 1 ark(i, q, 10405129301473404666785234951972711717481302463898292859783056520670200613128); sbox_full(i, q); mix(i, q); // round 2 ark(i, q, 5179144822360023508491245509308555580251733042407187134628755730783052214509); sbox_full(i, q); mix(i, q); // round 3 ark(i, q, 9132640374240188374542843306219594180154739721841249568925550236430986592615); sbox_partial(i, q); mix(i, q); // round 4 ark(i, q, 20360807315276763881209958738450444293273549928693737723235350358403012458514); sbox_partial(i, q); mix(i, q); // round 5 ark(i, q, 17933600965499023212689924809448543050840131883187652471064418452962948061619); sbox_partial(i, q); mix(i, q); // round 6 ark(i, q, 3636213416533737411392076250708419981662897009810345015164671602334517041153); sbox_partial(i, q); mix(i, q); // round 7 ark(i, q, 2008540005368330234524962342006691994500273283000229509835662097352946198608); sbox_partial(i, q); mix(i, q); // round 8 ark(i, q, 16018407964853379535338740313053768402596521780991140819786560130595652651567); sbox_partial(i, q); mix(i, q); // round 9 ark(i, q, 20653139667070586705378398435856186172195806027708437373983929336015162186471); sbox_partial(i, q); mix(i, q); // round 10 ark(i, q, 17887713874711369695406927657694993484804203950786446055999405564652412116765); sbox_partial(i, q); mix(i, q); // round 11 ark(i, q, 4852706232225925756777361208698488277369799648067343227630786518486608711772); sbox_partial(i, q); mix(i, q); // round 12 ark(i, q, 8969172011633935669771678412400911310465619639756845342775631896478908389850); sbox_partial(i, q); mix(i, q); // round 13 ark(i, q, 20570199545627577691240476121888846460936245025392381957866134167601058684375); sbox_partial(i, q); mix(i, q); // round 14 ark(i, q, 16442329894745639881165035015179028112772410105963688121820543219662832524136); sbox_partial(i, q); mix(i, q); // round 15 ark(i, q, 20060625627350485876280451423010593928172611031611836167979515653463693899374); sbox_partial(i, q); mix(i, q); // round 16 ark(i, q, 16637282689940520290130302519163090147511023430395200895953984829546679599107); sbox_partial(i, q); mix(i, q); // round 17 ark(i, q, 15599196921909732993082127725908821049411366914683565306060493533569088698214); sbox_partial(i, q); mix(i, q); // round 18 ark(i, q, 16894591341213863947423904025624185991098788054337051624251730868231322135455); sbox_partial(i, q); mix(i, q); // round 19 ark(i, q, 1197934381747032348421303489683932612752526046745577259575778515005162320212); sbox_partial(i, q); mix(i, q); // round 20 ark(i, q, 6172482022646932735745595886795230725225293469762393889050804649558459236626); sbox_partial(i, q); mix(i, q); // round 21 ark(i, q, 21004037394166516054140386756510609698837211370585899203851827276330669555417); sbox_partial(i, q); mix(i, q); // round 22 ark(i, q, 15262034989144652068456967541137853724140836132717012646544737680069032573006); sbox_partial(i, q); mix(i, q); // round 23 ark(i, q, 15017690682054366744270630371095785995296470601172793770224691982518041139766); sbox_partial(i, q); mix(i, q); // round 24 ark(i, q, 15159744167842240513848638419303545693472533086570469712794583342699782519832); sbox_partial(i, q); mix(i, q); // round 25 ark(i, q, 11178069035565459212220861899558526502477231302924961773582350246646450941231); sbox_partial(i, q); mix(i, q); // round 26 ark(i, q, 21154888769130549957415912997229564077486639529994598560737238811887296922114); sbox_partial(i, q); mix(i, q); // round 27 ark(i, q, 20162517328110570500010831422938033120419484532231241180224283481905744633719); sbox_partial(i, q); mix(i, q); // round 28 ark(i, q, 2777362604871784250419758188173029886707024739806641263170345377816177052018); sbox_partial(i, q); mix(i, q); // round 29 ark(i, q, 15732290486829619144634131656503993123618032247178179298922551820261215487562); sbox_partial(i, q); mix(i, q); // round 30 ark(i, q, 6024433414579583476444635447152826813568595303270846875177844482142230009826); sbox_partial(i, q); mix(i, q); // round 31 ark(i, q, 17677827682004946431939402157761289497221048154630238117709539216286149983245); sbox_partial(i, q); mix(i, q); // round 32 ark(i, q, 10716307389353583413755237303156291454109852751296156900963208377067748518748); sbox_partial(i, q); mix(i, q); // round 33 ark(i, q, 14925386988604173087143546225719076187055229908444910452781922028996524347508); sbox_partial(i, q); mix(i, q); // round 34 ark(i, q, 8940878636401797005293482068100797531020505636124892198091491586778667442523); sbox_partial(i, q); mix(i, q); // round 35 ark(i, q, 18911747154199663060505302806894425160044925686870165583944475880789706164410); sbox_partial(i, q); mix(i, q); // round 36 ark(i, q, 8821532432394939099312235292271438180996556457308429936910969094255825456935); sbox_partial(i, q); mix(i, q); // round 37 ark(i, q, 20632576502437623790366878538516326728436616723089049415538037018093616927643); sbox_partial(i, q); mix(i, q); // round 38 ark(i, q, 71447649211767888770311304010816315780740050029903404046389165015534756512); sbox_partial(i, q); mix(i, q); // round 39 ark(i, q, 2781996465394730190470582631099299305677291329609718650018200531245670229393); sbox_partial(i, q); mix(i, q); // round 40 ark(i, q, 12441376330954323535872906380510501637773629931719508864016287320488688345525); sbox_partial(i, q); mix(i, q); // round 41 ark(i, q, 2558302139544901035700544058046419714227464650146159803703499681139469546006); sbox_partial(i, q); mix(i, q); // round 42 ark(i, q, 10087036781939179132584550273563255199577525914374285705149349445480649057058); sbox_partial(i, q); mix(i, q); // round 43 ark(i, q, 4267692623754666261749551533667592242661271409704769363166965280715887854739); sbox_partial(i, q); mix(i, q); // round 44 ark(i, q, 4945579503584457514844595640661884835097077318604083061152997449742124905548); sbox_partial(i, q); mix(i, q); // round 45 ark(i, q, 17742335354489274412669987990603079185096280484072783973732137326144230832311); sbox_partial(i, q); mix(i, q); // round 46 ark(i, q, 6266270088302506215402996795500854910256503071464802875821837403486057988208); sbox_partial(i, q); mix(i, q); // round 47 ark(i, q, 2716062168542520412498610856550519519760063668165561277991771577403400784706); sbox_partial(i, q); mix(i, q); // round 48 ark(i, q, 19118392018538203167410421493487769944462015419023083813301166096764262134232); sbox_partial(i, q); mix(i, q); // round 49 ark(i, q, 9386595745626044000666050847309903206827901310677406022353307960932745699524); sbox_partial(i, q); mix(i, q); // round 50 ark(i, q, 9121640807890366356465620448383131419933298563527245687958865317869840082266); sbox_partial(i, q); mix(i, q); // round 51 ark(i, q, 3078975275808111706229899605611544294904276390490742680006005661017864583210); sbox_partial(i, q); mix(i, q); // round 52 ark(i, q, 7157404299437167354719786626667769956233708887934477609633504801472827442743); sbox_partial(i, q); mix(i, q); // round 53 ark(i, q, 14056248655941725362944552761799461694550787028230120190862133165195793034373); sbox_partial(i, q); mix(i, q); // round 54 ark(i, q, 14124396743304355958915937804966111851843703158171757752158388556919187839849); sbox_partial(i, q); mix(i, q); // round 55 ark(i, q, 11851254356749068692552943732920045260402277343008629727465773766468466181076); sbox_full(i, q); mix(i, q); // round 56 ark(i, q, 9799099446406796696742256539758943483211846559715874347178722060519817626047); sbox_full(i, q); mix(i, q); // round 57 ark(i, q, 10156146186214948683880719664738535455146137901666656566575307300522957959544); sbox_full(i, q); mix(i, q); return i.t0; } // // hash_t5f6p52 // struct HashInputs5 { uint t0; uint t1; uint t2; uint t3; uint t4; } function hash_t5f6p52_internal( uint t0, uint t1, uint t2, uint t3, uint t4, uint q ) internal pure returns (uint) { assembly { function mix(_t0, _t1, _t2, _t3, _t4, _q) -> nt0, nt1, nt2, nt3, nt4 { nt0 := mulmod(_t0, 4977258759536702998522229302103997878600602264560359702680165243908162277980, _q) nt0 := addmod(nt0, mulmod(_t1, 19167410339349846567561662441069598364702008768579734801591448511131028229281, _q), _q) nt0 := addmod(nt0, mulmod(_t2, 14183033936038168803360723133013092560869148726790180682363054735190196956789, _q), _q) nt0 := addmod(nt0, mulmod(_t3, 9067734253445064890734144122526450279189023719890032859456830213166173619761, _q), _q) nt0 := addmod(nt0, mulmod(_t4, 16378664841697311562845443097199265623838619398287411428110917414833007677155, _q), _q) nt1 := mulmod(_t0, 107933704346764130067829474107909495889716688591997879426350582457782826785, _q) nt1 := addmod(nt1, mulmod(_t1, 17034139127218860091985397764514160131253018178110701196935786874261236172431, _q), _q) nt1 := addmod(nt1, mulmod(_t2, 2799255644797227968811798608332314218966179365168250111693473252876996230317, _q), _q) nt1 := addmod(nt1, mulmod(_t3, 2482058150180648511543788012634934806465808146786082148795902594096349483974, _q), _q) nt1 := addmod(nt1, mulmod(_t4, 16563522740626180338295201738437974404892092704059676533096069531044355099628, _q), _q) nt2 := mulmod(_t0, 13596762909635538739079656925495736900379091964739248298531655823337482778123, _q) nt2 := addmod(nt2, mulmod(_t1, 18985203040268814769637347880759846911264240088034262814847924884273017355969, _q), _q) nt2 := addmod(nt2, mulmod(_t2, 8652975463545710606098548415650457376967119951977109072274595329619335974180, _q), _q) nt2 := addmod(nt2, mulmod(_t3, 970943815872417895015626519859542525373809485973005165410533315057253476903, _q), _q) nt2 := addmod(nt2, mulmod(_t4, 19406667490568134101658669326517700199745817783746545889094238643063688871948, _q), _q) nt3 := mulmod(_t0, 2953507793609469112222895633455544691298656192015062835263784675891831794974, _q) nt3 := addmod(nt3, mulmod(_t1, 19025623051770008118343718096455821045904242602531062247152770448380880817517, _q), _q) nt3 := addmod(nt3, mulmod(_t2, 9077319817220936628089890431129759976815127354480867310384708941479362824016, _q), _q) nt3 := addmod(nt3, mulmod(_t3, 4770370314098695913091200576539533727214143013236894216582648993741910829490, _q), _q) nt3 := addmod(nt3, mulmod(_t4, 4298564056297802123194408918029088169104276109138370115401819933600955259473, _q), _q) nt4 := mulmod(_t0, 8336710468787894148066071988103915091676109272951895469087957569358494947747, _q) nt4 := addmod(nt4, mulmod(_t1, 16205238342129310687768799056463408647672389183328001070715567975181364448609, _q), _q) nt4 := addmod(nt4, mulmod(_t2, 8303849270045876854140023508764676765932043944545416856530551331270859502246, _q), _q) nt4 := addmod(nt4, mulmod(_t3, 20218246699596954048529384569730026273241102596326201163062133863539137060414, _q), _q) nt4 := addmod(nt4, mulmod(_t4, 1712845821388089905746651754894206522004527237615042226559791118162382909269, _q), _q) } function ark(_t0, _t1, _t2, _t3, _t4, _q, c) -> nt0, nt1, nt2, nt3, nt4 { nt0 := addmod(_t0, c, _q) nt1 := addmod(_t1, c, _q) nt2 := addmod(_t2, c, _q) nt3 := addmod(_t3, c, _q) nt4 := addmod(_t4, c, _q) } function sbox_full(_t0, _t1, _t2, _t3, _t4, _q) -> nt0, nt1, nt2, nt3, nt4 { nt0 := mulmod(_t0, _t0, _q) nt0 := mulmod(nt0, nt0, _q) nt0 := mulmod(_t0, nt0, _q) nt1 := mulmod(_t1, _t1, _q) nt1 := mulmod(nt1, nt1, _q) nt1 := mulmod(_t1, nt1, _q) nt2 := mulmod(_t2, _t2, _q) nt2 := mulmod(nt2, nt2, _q) nt2 := mulmod(_t2, nt2, _q) nt3 := mulmod(_t3, _t3, _q) nt3 := mulmod(nt3, nt3, _q) nt3 := mulmod(_t3, nt3, _q) nt4 := mulmod(_t4, _t4, _q) nt4 := mulmod(nt4, nt4, _q) nt4 := mulmod(_t4, nt4, _q) } function sbox_partial(_t, _q) -> nt { nt := mulmod(_t, _t, _q) nt := mulmod(nt, nt, _q) nt := mulmod(_t, nt, _q) } // round 0 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 14397397413755236225575615486459253198602422701513067526754101844196324375522) t0, t1, t2, t3, t4 := sbox_full(t0, t1, t2, t3, t4, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 1 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 10405129301473404666785234951972711717481302463898292859783056520670200613128) t0, t1, t2, t3, t4 := sbox_full(t0, t1, t2, t3, t4, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 2 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 5179144822360023508491245509308555580251733042407187134628755730783052214509) t0, t1, t2, t3, t4 := sbox_full(t0, t1, t2, t3, t4, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 3 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 9132640374240188374542843306219594180154739721841249568925550236430986592615) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 4 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 20360807315276763881209958738450444293273549928693737723235350358403012458514) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 5 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 17933600965499023212689924809448543050840131883187652471064418452962948061619) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 6 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 3636213416533737411392076250708419981662897009810345015164671602334517041153) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 7 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 2008540005368330234524962342006691994500273283000229509835662097352946198608) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 8 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 16018407964853379535338740313053768402596521780991140819786560130595652651567) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 9 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 20653139667070586705378398435856186172195806027708437373983929336015162186471) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 10 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 17887713874711369695406927657694993484804203950786446055999405564652412116765) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 11 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 4852706232225925756777361208698488277369799648067343227630786518486608711772) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 12 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 8969172011633935669771678412400911310465619639756845342775631896478908389850) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 13 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 20570199545627577691240476121888846460936245025392381957866134167601058684375) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 14 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 16442329894745639881165035015179028112772410105963688121820543219662832524136) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 15 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 20060625627350485876280451423010593928172611031611836167979515653463693899374) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 16 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 16637282689940520290130302519163090147511023430395200895953984829546679599107) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 17 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 15599196921909732993082127725908821049411366914683565306060493533569088698214) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 18 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 16894591341213863947423904025624185991098788054337051624251730868231322135455) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 19 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 1197934381747032348421303489683932612752526046745577259575778515005162320212) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 20 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 6172482022646932735745595886795230725225293469762393889050804649558459236626) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 21 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 21004037394166516054140386756510609698837211370585899203851827276330669555417) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 22 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 15262034989144652068456967541137853724140836132717012646544737680069032573006) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 23 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 15017690682054366744270630371095785995296470601172793770224691982518041139766) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 24 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 15159744167842240513848638419303545693472533086570469712794583342699782519832) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 25 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 11178069035565459212220861899558526502477231302924961773582350246646450941231) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 26 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 21154888769130549957415912997229564077486639529994598560737238811887296922114) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 27 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 20162517328110570500010831422938033120419484532231241180224283481905744633719) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 28 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 2777362604871784250419758188173029886707024739806641263170345377816177052018) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 29 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 15732290486829619144634131656503993123618032247178179298922551820261215487562) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 30 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 6024433414579583476444635447152826813568595303270846875177844482142230009826) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 31 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 17677827682004946431939402157761289497221048154630238117709539216286149983245) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 32 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 10716307389353583413755237303156291454109852751296156900963208377067748518748) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 33 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 14925386988604173087143546225719076187055229908444910452781922028996524347508) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 34 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 8940878636401797005293482068100797531020505636124892198091491586778667442523) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 35 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 18911747154199663060505302806894425160044925686870165583944475880789706164410) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 36 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 8821532432394939099312235292271438180996556457308429936910969094255825456935) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 37 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 20632576502437623790366878538516326728436616723089049415538037018093616927643) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 38 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 71447649211767888770311304010816315780740050029903404046389165015534756512) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 39 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 2781996465394730190470582631099299305677291329609718650018200531245670229393) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 40 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 12441376330954323535872906380510501637773629931719508864016287320488688345525) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 41 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 2558302139544901035700544058046419714227464650146159803703499681139469546006) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 42 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 10087036781939179132584550273563255199577525914374285705149349445480649057058) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 43 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 4267692623754666261749551533667592242661271409704769363166965280715887854739) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 44 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 4945579503584457514844595640661884835097077318604083061152997449742124905548) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 45 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 17742335354489274412669987990603079185096280484072783973732137326144230832311) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 46 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 6266270088302506215402996795500854910256503071464802875821837403486057988208) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 47 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 2716062168542520412498610856550519519760063668165561277991771577403400784706) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 48 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 19118392018538203167410421493487769944462015419023083813301166096764262134232) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 49 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 9386595745626044000666050847309903206827901310677406022353307960932745699524) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 50 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 9121640807890366356465620448383131419933298563527245687958865317869840082266) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 51 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 3078975275808111706229899605611544294904276390490742680006005661017864583210) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 52 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 7157404299437167354719786626667769956233708887934477609633504801472827442743) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 53 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 14056248655941725362944552761799461694550787028230120190862133165195793034373) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 54 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 14124396743304355958915937804966111851843703158171757752158388556919187839849) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 55 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 11851254356749068692552943732920045260402277343008629727465773766468466181076) t0, t1, t2, t3, t4 := sbox_full(t0, t1, t2, t3, t4, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 56 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 9799099446406796696742256539758943483211846559715874347178722060519817626047) t0, t1, t2, t3, t4 := sbox_full(t0, t1, t2, t3, t4, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 57 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 10156146186214948683880719664738535455146137901666656566575307300522957959544) t0, t1, t2, t3, t4 := sbox_full(t0, t1, t2, t3, t4, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) } return t0; } function hash_t5f6p52(HashInputs5 memory i, uint q) internal pure returns (uint) { // validate inputs require(i.t0 < q, "INVALID_INPUT"); require(i.t1 < q, "INVALID_INPUT"); require(i.t2 < q, "INVALID_INPUT"); require(i.t3 < q, "INVALID_INPUT"); require(i.t4 < q, "INVALID_INPUT"); return hash_t5f6p52_internal(i.t0, i.t1, i.t2, i.t3, i.t4, q); } // // hash_t7f6p52 // struct HashInputs7 { uint t0; uint t1; uint t2; uint t3; uint t4; uint t5; uint t6; } function mix(HashInputs7 memory i, uint q) internal pure { HashInputs7 memory o; o.t0 = mulmod(i.t0, 14183033936038168803360723133013092560869148726790180682363054735190196956789, q); o.t0 = addmod(o.t0, mulmod(i.t1, 9067734253445064890734144122526450279189023719890032859456830213166173619761, q), q); o.t0 = addmod(o.t0, mulmod(i.t2, 16378664841697311562845443097199265623838619398287411428110917414833007677155, q), q); o.t0 = addmod(o.t0, mulmod(i.t3, 12968540216479938138647596899147650021419273189336843725176422194136033835172, q), q); o.t0 = addmod(o.t0, mulmod(i.t4, 3636162562566338420490575570584278737093584021456168183289112789616069756675, q), q); o.t0 = addmod(o.t0, mulmod(i.t5, 8949952361235797771659501126471156178804092479420606597426318793013844305422, q), q); o.t0 = addmod(o.t0, mulmod(i.t6, 13586657904816433080148729258697725609063090799921401830545410130405357110367, q), q); o.t1 = mulmod(i.t0, 2799255644797227968811798608332314218966179365168250111693473252876996230317, q); o.t1 = addmod(o.t1, mulmod(i.t1, 2482058150180648511543788012634934806465808146786082148795902594096349483974, q), q); o.t1 = addmod(o.t1, mulmod(i.t2, 16563522740626180338295201738437974404892092704059676533096069531044355099628, q), q); o.t1 = addmod(o.t1, mulmod(i.t3, 10468644849657689537028565510142839489302836569811003546969773105463051947124, q), q); o.t1 = addmod(o.t1, mulmod(i.t4, 3328913364598498171733622353010907641674136720305714432354138807013088636408, q), q); o.t1 = addmod(o.t1, mulmod(i.t5, 8642889650254799419576843603477253661899356105675006557919250564400804756641, q), q); o.t1 = addmod(o.t1, mulmod(i.t6, 14300697791556510113764686242794463641010174685800128469053974698256194076125, q), q); o.t2 = mulmod(i.t0, 8652975463545710606098548415650457376967119951977109072274595329619335974180, q); o.t2 = addmod(o.t2, mulmod(i.t1, 970943815872417895015626519859542525373809485973005165410533315057253476903, q), q); o.t2 = addmod(o.t2, mulmod(i.t2, 19406667490568134101658669326517700199745817783746545889094238643063688871948, q), q); o.t2 = addmod(o.t2, mulmod(i.t3, 17049854690034965250221386317058877242629221002521630573756355118745574274967, q), q); o.t2 = addmod(o.t2, mulmod(i.t4, 4964394613021008685803675656098849539153699842663541444414978877928878266244, q), q); o.t2 = addmod(o.t2, mulmod(i.t5, 15474947305445649466370538888925567099067120578851553103424183520405650587995, q), q); o.t2 = addmod(o.t2, mulmod(i.t6, 1016119095639665978105768933448186152078842964810837543326777554729232767846, q), q); o.t3 = mulmod(i.t0, 9077319817220936628089890431129759976815127354480867310384708941479362824016, q); o.t3 = addmod(o.t3, mulmod(i.t1, 4770370314098695913091200576539533727214143013236894216582648993741910829490, q), q); o.t3 = addmod(o.t3, mulmod(i.t2, 4298564056297802123194408918029088169104276109138370115401819933600955259473, q), q); o.t3 = addmod(o.t3, mulmod(i.t3, 6905514380186323693285869145872115273350947784558995755916362330070690839131, q), q); o.t3 = addmod(o.t3, mulmod(i.t4, 4783343257810358393326889022942241108539824540285247795235499223017138301952, q), q); o.t3 = addmod(o.t3, mulmod(i.t5, 1420772902128122367335354247676760257656541121773854204774788519230732373317, q), q); o.t3 = addmod(o.t3, mulmod(i.t6, 14172871439045259377975734198064051992755748777535789572469924335100006948373, q), q); o.t4 = mulmod(i.t0, 8303849270045876854140023508764676765932043944545416856530551331270859502246, q); o.t4 = addmod(o.t4, mulmod(i.t1, 20218246699596954048529384569730026273241102596326201163062133863539137060414, q), q); o.t4 = addmod(o.t4, mulmod(i.t2, 1712845821388089905746651754894206522004527237615042226559791118162382909269, q), q); o.t4 = addmod(o.t4, mulmod(i.t3, 13001155522144542028910638547179410124467185319212645031214919884423841839406, q), q); o.t4 = addmod(o.t4, mulmod(i.t4, 16037892369576300958623292723740289861626299352695838577330319504984091062115, q), q); o.t4 = addmod(o.t4, mulmod(i.t5, 19189494548480259335554606182055502469831573298885662881571444557262020106898, q), q); o.t4 = addmod(o.t4, mulmod(i.t6, 19032687447778391106390582750185144485341165205399984747451318330476859342654, q), q); o.t5 = mulmod(i.t0, 13272957914179340594010910867091459756043436017766464331915862093201960540910, q); o.t5 = addmod(o.t5, mulmod(i.t1, 9416416589114508529880440146952102328470363729880726115521103179442988482948, q), q); o.t5 = addmod(o.t5, mulmod(i.t2, 8035240799672199706102747147502951589635001418759394863664434079699838251138, q), q); o.t5 = addmod(o.t5, mulmod(i.t3, 21642389080762222565487157652540372010968704000567605990102641816691459811717, q), q); o.t5 = addmod(o.t5, mulmod(i.t4, 20261355950827657195644012399234591122288573679402601053407151083849785332516, q), q); o.t5 = addmod(o.t5, mulmod(i.t5, 14514189384576734449268559374569145463190040567900950075547616936149781403109, q), q); o.t5 = addmod(o.t5, mulmod(i.t6, 19038036134886073991945204537416211699632292792787812530208911676638479944765, q), q); o.t6 = mulmod(i.t0, 15627836782263662543041758927100784213807648787083018234961118439434298020664, q); o.t6 = addmod(o.t6, mulmod(i.t1, 5655785191024506056588710805596292231240948371113351452712848652644610823632, q), q); o.t6 = addmod(o.t6, mulmod(i.t2, 8265264721707292643644260517162050867559314081394556886644673791575065394002, q), q); o.t6 = addmod(o.t6, mulmod(i.t3, 17151144681903609082202835646026478898625761142991787335302962548605510241586, q), q); o.t6 = addmod(o.t6, mulmod(i.t4, 18731644709777529787185361516475509623264209648904603914668024590231177708831, q), q); o.t6 = addmod(o.t6, mulmod(i.t5, 20697789991623248954020701081488146717484139720322034504511115160686216223641, q), q); o.t6 = addmod(o.t6, mulmod(i.t6, 6200020095464686209289974437830528853749866001482481427982839122465470640886, q), q); i.t0 = o.t0; i.t1 = o.t1; i.t2 = o.t2; i.t3 = o.t3; i.t4 = o.t4; i.t5 = o.t5; i.t6 = o.t6; } function ark(HashInputs7 memory i, uint q, uint c) internal pure { HashInputs7 memory o; o.t0 = addmod(i.t0, c, q); o.t1 = addmod(i.t1, c, q); o.t2 = addmod(i.t2, c, q); o.t3 = addmod(i.t3, c, q); o.t4 = addmod(i.t4, c, q); o.t5 = addmod(i.t5, c, q); o.t6 = addmod(i.t6, c, q); i.t0 = o.t0; i.t1 = o.t1; i.t2 = o.t2; i.t3 = o.t3; i.t4 = o.t4; i.t5 = o.t5; i.t6 = o.t6; } function sbox_full(HashInputs7 memory i, uint q) internal pure { HashInputs7 memory o; o.t0 = mulmod(i.t0, i.t0, q); o.t0 = mulmod(o.t0, o.t0, q); o.t0 = mulmod(i.t0, o.t0, q); o.t1 = mulmod(i.t1, i.t1, q); o.t1 = mulmod(o.t1, o.t1, q); o.t1 = mulmod(i.t1, o.t1, q); o.t2 = mulmod(i.t2, i.t2, q); o.t2 = mulmod(o.t2, o.t2, q); o.t2 = mulmod(i.t2, o.t2, q); o.t3 = mulmod(i.t3, i.t3, q); o.t3 = mulmod(o.t3, o.t3, q); o.t3 = mulmod(i.t3, o.t3, q); o.t4 = mulmod(i.t4, i.t4, q); o.t4 = mulmod(o.t4, o.t4, q); o.t4 = mulmod(i.t4, o.t4, q); o.t5 = mulmod(i.t5, i.t5, q); o.t5 = mulmod(o.t5, o.t5, q); o.t5 = mulmod(i.t5, o.t5, q); o.t6 = mulmod(i.t6, i.t6, q); o.t6 = mulmod(o.t6, o.t6, q); o.t6 = mulmod(i.t6, o.t6, q); i.t0 = o.t0; i.t1 = o.t1; i.t2 = o.t2; i.t3 = o.t3; i.t4 = o.t4; i.t5 = o.t5; i.t6 = o.t6; } function sbox_partial(HashInputs7 memory i, uint q) internal pure { HashInputs7 memory o; o.t0 = mulmod(i.t0, i.t0, q); o.t0 = mulmod(o.t0, o.t0, q); o.t0 = mulmod(i.t0, o.t0, q); i.t0 = o.t0; } function hash_t7f6p52(HashInputs7 memory i, uint q) internal pure returns (uint) { // validate inputs require(i.t0 < q, "INVALID_INPUT"); require(i.t1 < q, "INVALID_INPUT"); require(i.t2 < q, "INVALID_INPUT"); require(i.t3 < q, "INVALID_INPUT"); require(i.t4 < q, "INVALID_INPUT"); require(i.t5 < q, "INVALID_INPUT"); require(i.t6 < q, "INVALID_INPUT"); // round 0 ark(i, q, 14397397413755236225575615486459253198602422701513067526754101844196324375522); sbox_full(i, q); mix(i, q); // round 1 ark(i, q, 10405129301473404666785234951972711717481302463898292859783056520670200613128); sbox_full(i, q); mix(i, q); // round 2 ark(i, q, 5179144822360023508491245509308555580251733042407187134628755730783052214509); sbox_full(i, q); mix(i, q); // round 3 ark(i, q, 9132640374240188374542843306219594180154739721841249568925550236430986592615); sbox_partial(i, q); mix(i, q); // round 4 ark(i, q, 20360807315276763881209958738450444293273549928693737723235350358403012458514); sbox_partial(i, q); mix(i, q); // round 5 ark(i, q, 17933600965499023212689924809448543050840131883187652471064418452962948061619); sbox_partial(i, q); mix(i, q); // round 6 ark(i, q, 3636213416533737411392076250708419981662897009810345015164671602334517041153); sbox_partial(i, q); mix(i, q); // round 7 ark(i, q, 2008540005368330234524962342006691994500273283000229509835662097352946198608); sbox_partial(i, q); mix(i, q); // round 8 ark(i, q, 16018407964853379535338740313053768402596521780991140819786560130595652651567); sbox_partial(i, q); mix(i, q); // round 9 ark(i, q, 20653139667070586705378398435856186172195806027708437373983929336015162186471); sbox_partial(i, q); mix(i, q); // round 10 ark(i, q, 17887713874711369695406927657694993484804203950786446055999405564652412116765); sbox_partial(i, q); mix(i, q); // round 11 ark(i, q, 4852706232225925756777361208698488277369799648067343227630786518486608711772); sbox_partial(i, q); mix(i, q); // round 12 ark(i, q, 8969172011633935669771678412400911310465619639756845342775631896478908389850); sbox_partial(i, q); mix(i, q); // round 13 ark(i, q, 20570199545627577691240476121888846460936245025392381957866134167601058684375); sbox_partial(i, q); mix(i, q); // round 14 ark(i, q, 16442329894745639881165035015179028112772410105963688121820543219662832524136); sbox_partial(i, q); mix(i, q); // round 15 ark(i, q, 20060625627350485876280451423010593928172611031611836167979515653463693899374); sbox_partial(i, q); mix(i, q); // round 16 ark(i, q, 16637282689940520290130302519163090147511023430395200895953984829546679599107); sbox_partial(i, q); mix(i, q); // round 17 ark(i, q, 15599196921909732993082127725908821049411366914683565306060493533569088698214); sbox_partial(i, q); mix(i, q); // round 18 ark(i, q, 16894591341213863947423904025624185991098788054337051624251730868231322135455); sbox_partial(i, q); mix(i, q); // round 19 ark(i, q, 1197934381747032348421303489683932612752526046745577259575778515005162320212); sbox_partial(i, q); mix(i, q); // round 20 ark(i, q, 6172482022646932735745595886795230725225293469762393889050804649558459236626); sbox_partial(i, q); mix(i, q); // round 21 ark(i, q, 21004037394166516054140386756510609698837211370585899203851827276330669555417); sbox_partial(i, q); mix(i, q); // round 22 ark(i, q, 15262034989144652068456967541137853724140836132717012646544737680069032573006); sbox_partial(i, q); mix(i, q); // round 23 ark(i, q, 15017690682054366744270630371095785995296470601172793770224691982518041139766); sbox_partial(i, q); mix(i, q); // round 24 ark(i, q, 15159744167842240513848638419303545693472533086570469712794583342699782519832); sbox_partial(i, q); mix(i, q); // round 25 ark(i, q, 11178069035565459212220861899558526502477231302924961773582350246646450941231); sbox_partial(i, q); mix(i, q); // round 26 ark(i, q, 21154888769130549957415912997229564077486639529994598560737238811887296922114); sbox_partial(i, q); mix(i, q); // round 27 ark(i, q, 20162517328110570500010831422938033120419484532231241180224283481905744633719); sbox_partial(i, q); mix(i, q); // round 28 ark(i, q, 2777362604871784250419758188173029886707024739806641263170345377816177052018); sbox_partial(i, q); mix(i, q); // round 29 ark(i, q, 15732290486829619144634131656503993123618032247178179298922551820261215487562); sbox_partial(i, q); mix(i, q); // round 30 ark(i, q, 6024433414579583476444635447152826813568595303270846875177844482142230009826); sbox_partial(i, q); mix(i, q); // round 31 ark(i, q, 17677827682004946431939402157761289497221048154630238117709539216286149983245); sbox_partial(i, q); mix(i, q); // round 32 ark(i, q, 10716307389353583413755237303156291454109852751296156900963208377067748518748); sbox_partial(i, q); mix(i, q); // round 33 ark(i, q, 14925386988604173087143546225719076187055229908444910452781922028996524347508); sbox_partial(i, q); mix(i, q); // round 34 ark(i, q, 8940878636401797005293482068100797531020505636124892198091491586778667442523); sbox_partial(i, q); mix(i, q); // round 35 ark(i, q, 18911747154199663060505302806894425160044925686870165583944475880789706164410); sbox_partial(i, q); mix(i, q); // round 36 ark(i, q, 8821532432394939099312235292271438180996556457308429936910969094255825456935); sbox_partial(i, q); mix(i, q); // round 37 ark(i, q, 20632576502437623790366878538516326728436616723089049415538037018093616927643); sbox_partial(i, q); mix(i, q); // round 38 ark(i, q, 71447649211767888770311304010816315780740050029903404046389165015534756512); sbox_partial(i, q); mix(i, q); // round 39 ark(i, q, 2781996465394730190470582631099299305677291329609718650018200531245670229393); sbox_partial(i, q); mix(i, q); // round 40 ark(i, q, 12441376330954323535872906380510501637773629931719508864016287320488688345525); sbox_partial(i, q); mix(i, q); // round 41 ark(i, q, 2558302139544901035700544058046419714227464650146159803703499681139469546006); sbox_partial(i, q); mix(i, q); // round 42 ark(i, q, 10087036781939179132584550273563255199577525914374285705149349445480649057058); sbox_partial(i, q); mix(i, q); // round 43 ark(i, q, 4267692623754666261749551533667592242661271409704769363166965280715887854739); sbox_partial(i, q); mix(i, q); // round 44 ark(i, q, 4945579503584457514844595640661884835097077318604083061152997449742124905548); sbox_partial(i, q); mix(i, q); // round 45 ark(i, q, 17742335354489274412669987990603079185096280484072783973732137326144230832311); sbox_partial(i, q); mix(i, q); // round 46 ark(i, q, 6266270088302506215402996795500854910256503071464802875821837403486057988208); sbox_partial(i, q); mix(i, q); // round 47 ark(i, q, 2716062168542520412498610856550519519760063668165561277991771577403400784706); sbox_partial(i, q); mix(i, q); // round 48 ark(i, q, 19118392018538203167410421493487769944462015419023083813301166096764262134232); sbox_partial(i, q); mix(i, q); // round 49 ark(i, q, 9386595745626044000666050847309903206827901310677406022353307960932745699524); sbox_partial(i, q); mix(i, q); // round 50 ark(i, q, 9121640807890366356465620448383131419933298563527245687958865317869840082266); sbox_partial(i, q); mix(i, q); // round 51 ark(i, q, 3078975275808111706229899605611544294904276390490742680006005661017864583210); sbox_partial(i, q); mix(i, q); // round 52 ark(i, q, 7157404299437167354719786626667769956233708887934477609633504801472827442743); sbox_partial(i, q); mix(i, q); // round 53 ark(i, q, 14056248655941725362944552761799461694550787028230120190862133165195793034373); sbox_partial(i, q); mix(i, q); // round 54 ark(i, q, 14124396743304355958915937804966111851843703158171757752158388556919187839849); sbox_partial(i, q); mix(i, q); // round 55 ark(i, q, 11851254356749068692552943732920045260402277343008629727465773766468466181076); sbox_full(i, q); mix(i, q); // round 56 ark(i, q, 9799099446406796696742256539758943483211846559715874347178722060519817626047); sbox_full(i, q); mix(i, q); // round 57 ark(i, q, 10156146186214948683880719664738535455146137901666656566575307300522957959544); sbox_full(i, q); mix(i, q); return i.t0; } } // File: contracts/lib/ERC20SafeTransfer.sol // Copyright 2017 Loopring Technology Limited. /// @title ERC20 safe transfer /// @dev see https://github.com/sec-bit/badERC20Fix /// @author Brecht Devos - <[email protected]> library ERC20SafeTransfer { function safeTransferAndVerify( address token, address to, uint value ) internal { safeTransferWithGasLimitAndVerify( token, to, value, gasleft() ); } function safeTransfer( address token, address to, uint value ) internal returns (bool) { return safeTransferWithGasLimit( token, to, value, gasleft() ); } function safeTransferWithGasLimitAndVerify( address token, address to, uint value, uint gasLimit ) internal { require( safeTransferWithGasLimit(token, to, value, gasLimit), "TRANSFER_FAILURE" ); } function safeTransferWithGasLimit( address token, address to, uint value, uint gasLimit ) internal returns (bool) { // A transfer is successful when 'call' is successful and depending on the token: // - No value is returned: we assume a revert when the transfer failed (i.e. 'call' returns false) // - A single boolean is returned: this boolean needs to be true (non-zero) // bytes4(keccak256("transfer(address,uint256)")) = 0xa9059cbb bytes memory callData = abi.encodeWithSelector( bytes4(0xa9059cbb), to, value ); (bool success, ) = token.call{gas: gasLimit}(callData); return checkReturnValue(success); } function safeTransferFromAndVerify( address token, address from, address to, uint value ) internal { safeTransferFromWithGasLimitAndVerify( token, from, to, value, gasleft() ); } function safeTransferFrom( address token, address from, address to, uint value ) internal returns (bool) { return safeTransferFromWithGasLimit( token, from, to, value, gasleft() ); } function safeTransferFromWithGasLimitAndVerify( address token, address from, address to, uint value, uint gasLimit ) internal { bool result = safeTransferFromWithGasLimit( token, from, to, value, gasLimit ); require(result, "TRANSFER_FAILURE"); } function safeTransferFromWithGasLimit( address token, address from, address to, uint value, uint gasLimit ) internal returns (bool) { // A transferFrom is successful when 'call' is successful and depending on the token: // - No value is returned: we assume a revert when the transfer failed (i.e. 'call' returns false) // - A single boolean is returned: this boolean needs to be true (non-zero) // bytes4(keccak256("transferFrom(address,address,uint256)")) = 0x23b872dd bytes memory callData = abi.encodeWithSelector( bytes4(0x23b872dd), from, to, value ); (bool success, ) = token.call{gas: gasLimit}(callData); return checkReturnValue(success); } function checkReturnValue( bool success ) internal pure returns (bool) { // A transfer/transferFrom is successful when 'call' is successful and depending on the token: // - No value is returned: we assume a revert when the transfer failed (i.e. 'call' returns false) // - A single boolean is returned: this boolean needs to be true (non-zero) if (success) { assembly { switch returndatasize() // Non-standard ERC20: nothing is returned so if 'call' was successful we assume the transfer succeeded case 0 { success := 1 } // Standard ERC20: a single boolean value is returned which needs to be true case 32 { returndatacopy(0, 0, 32) success := mload(0) } // None of the above: not successful default { success := 0 } } } return success; } } // File: contracts/core/impl/libexchange/ExchangeMode.sol // Copyright 2017 Loopring Technology Limited. /// @title ExchangeMode. /// @dev All methods in this lib are internal, therefore, there is no need /// to deploy this library independently. /// @author Brecht Devos - <[email protected]> /// @author Daniel Wang - <[email protected]> library ExchangeMode { using MathUint for uint; function isInWithdrawalMode( ExchangeData.State storage S ) internal // inline call view returns (bool result) { result = S.withdrawalModeStartTime > 0; } function isShutdown( ExchangeData.State storage S ) internal // inline call view returns (bool) { return S.shutdownModeStartTime > 0; } function getNumAvailableForcedSlots( ExchangeData.State storage S ) internal view returns (uint) { return ExchangeData.MAX_OPEN_FORCED_REQUESTS - S.numPendingForcedTransactions; } } // File: contracts/core/impl/libexchange/ExchangeTokens.sol // Copyright 2017 Loopring Technology Limited. /// @title ExchangeTokens. /// @author Daniel Wang - <[email protected]> /// @author Brecht Devos - <[email protected]> library ExchangeTokens { using MathUint for uint; using ERC20SafeTransfer for address; using ExchangeMode for ExchangeData.State; event TokenRegistered( address token, uint16 tokenId ); function getTokenAddress( ExchangeData.State storage S, uint16 tokenID ) public view returns (address) { require(tokenID < S.tokens.length, "INVALID_TOKEN_ID"); return S.tokens[tokenID].token; } function registerToken( ExchangeData.State storage S, address tokenAddress ) public returns (uint16 tokenID) { require(!S.isInWithdrawalMode(), "INVALID_MODE"); require(S.tokenToTokenId[tokenAddress] == 0, "TOKEN_ALREADY_EXIST"); require(S.tokens.length < ExchangeData.NFT_TOKEN_ID_START, "TOKEN_REGISTRY_FULL"); // Check if the deposit contract supports the new token if (S.depositContract != IDepositContract(0)) { require( S.depositContract.isTokenSupported(tokenAddress), "UNSUPPORTED_TOKEN" ); } // Assign a tokenID and store the token ExchangeData.Token memory token = ExchangeData.Token( tokenAddress ); tokenID = uint16(S.tokens.length); S.tokens.push(token); S.tokenToTokenId[tokenAddress] = tokenID + 1; emit TokenRegistered(tokenAddress, tokenID); } function getTokenID( ExchangeData.State storage S, address tokenAddress ) internal // inline call view returns (uint16 tokenID) { tokenID = S.tokenToTokenId[tokenAddress]; require(tokenID != 0, "TOKEN_NOT_FOUND"); tokenID = tokenID - 1; } function isNFT(uint16 tokenID) internal // inline call pure returns (bool) { return tokenID >= ExchangeData.NFT_TOKEN_ID_START; } } // File: contracts/core/impl/libexchange/ExchangeBalances.sol // Copyright 2017 Loopring Technology Limited. /// @title ExchangeBalances. /// @author Daniel Wang - <[email protected]> /// @author Brecht Devos - <[email protected]> library ExchangeBalances { using ExchangeTokens for uint16; using MathUint for uint; function verifyAccountBalance( uint merkleRoot, ExchangeData.MerkleProof calldata merkleProof ) public pure { require( isAccountBalanceCorrect(merkleRoot, merkleProof), "INVALID_MERKLE_TREE_DATA" ); } function isAccountBalanceCorrect( uint merkleRoot, ExchangeData.MerkleProof memory merkleProof ) public pure returns (bool) { // Calculate the Merkle root using the Merkle paths provided uint calculatedRoot = getBalancesRoot( merkleProof.balanceLeaf.tokenID, merkleProof.balanceLeaf.balance, merkleProof.balanceLeaf.weightAMM, merkleProof.balanceLeaf.storageRoot, merkleProof.balanceMerkleProof ); calculatedRoot = getAccountInternalsRoot( merkleProof.accountLeaf.accountID, merkleProof.accountLeaf.owner, merkleProof.accountLeaf.pubKeyX, merkleProof.accountLeaf.pubKeyY, merkleProof.accountLeaf.nonce, merkleProof.accountLeaf.feeBipsAMM, calculatedRoot, merkleProof.accountMerkleProof ); if (merkleProof.balanceLeaf.tokenID.isNFT()) { // Verify the NFT data uint minter = uint(merkleProof.nft.minter); uint nftType = uint(merkleProof.nft.nftType); uint token = uint(merkleProof.nft.token); uint nftIDLo = merkleProof.nft.nftID & 0xffffffffffffffffffffffffffffffff; uint nftIDHi = merkleProof.nft.nftID >> 128; uint creatorFeeBips = merkleProof.nft.creatorFeeBips; Poseidon.HashInputs7 memory inputs = Poseidon.HashInputs7( minter, nftType, token, nftIDLo, nftIDHi, creatorFeeBips, 0 ); uint nftData = Poseidon.hash_t7f6p52(inputs, ExchangeData.SNARK_SCALAR_FIELD); if (nftData != merkleProof.balanceLeaf.weightAMM) { return false; } } // Check against the expected Merkle root return (calculatedRoot == merkleRoot); } function getBalancesRoot( uint16 tokenID, uint balance, uint weightAMM, uint storageRoot, uint[24] memory balanceMerkleProof ) private pure returns (uint) { // Hash the balance leaf uint balanceItem = hashImpl(balance, weightAMM, storageRoot, 0); // Calculate the Merkle root of the balance quad Merkle tree uint _id = tokenID; for (uint depth = 0; depth < 8; depth++) { uint base = depth * 3; if (_id & 3 == 0) { balanceItem = hashImpl( balanceItem, balanceMerkleProof[base], balanceMerkleProof[base + 1], balanceMerkleProof[base + 2] ); } else if (_id & 3 == 1) { balanceItem = hashImpl( balanceMerkleProof[base], balanceItem, balanceMerkleProof[base + 1], balanceMerkleProof[base + 2] ); } else if (_id & 3 == 2) { balanceItem = hashImpl( balanceMerkleProof[base], balanceMerkleProof[base + 1], balanceItem, balanceMerkleProof[base + 2] ); } else if (_id & 3 == 3) { balanceItem = hashImpl( balanceMerkleProof[base], balanceMerkleProof[base + 1], balanceMerkleProof[base + 2], balanceItem ); } _id = _id >> 2; } return balanceItem; } function getAccountInternalsRoot( uint32 accountID, address owner, uint pubKeyX, uint pubKeyY, uint nonce, uint feeBipsAMM, uint balancesRoot, uint[48] memory accountMerkleProof ) private pure returns (uint) { // Hash the account leaf uint accountItem = hashAccountLeaf(uint(owner), pubKeyX, pubKeyY, nonce, feeBipsAMM, balancesRoot); // Calculate the Merkle root of the account quad Merkle tree uint _id = accountID; for (uint depth = 0; depth < 16; depth++) { uint base = depth * 3; if (_id & 3 == 0) { accountItem = hashImpl( accountItem, accountMerkleProof[base], accountMerkleProof[base + 1], accountMerkleProof[base + 2] ); } else if (_id & 3 == 1) { accountItem = hashImpl( accountMerkleProof[base], accountItem, accountMerkleProof[base + 1], accountMerkleProof[base + 2] ); } else if (_id & 3 == 2) { accountItem = hashImpl( accountMerkleProof[base], accountMerkleProof[base + 1], accountItem, accountMerkleProof[base + 2] ); } else if (_id & 3 == 3) { accountItem = hashImpl( accountMerkleProof[base], accountMerkleProof[base + 1], accountMerkleProof[base + 2], accountItem ); } _id = _id >> 2; } return accountItem; } function hashAccountLeaf( uint t0, uint t1, uint t2, uint t3, uint t4, uint t5 ) public pure returns (uint) { Poseidon.HashInputs7 memory inputs = Poseidon.HashInputs7(t0, t1, t2, t3, t4, t5, 0); return Poseidon.hash_t7f6p52(inputs, ExchangeData.SNARK_SCALAR_FIELD); } function hashImpl( uint t0, uint t1, uint t2, uint t3 ) private pure returns (uint) { Poseidon.HashInputs5 memory inputs = Poseidon.HashInputs5(t0, t1, t2, t3, 0); return Poseidon.hash_t5f6p52(inputs, ExchangeData.SNARK_SCALAR_FIELD); } } // File: contracts/core/iface/IL2MintableNFT.sol // Copyright 2017 Loopring Technology Limited. interface IL2MintableNFT { /// @dev This function is called when an NFT minted on L2 is withdrawn from Loopring. /// That means the NFTs were burned on L2 and now need to be minted on L1. /// /// This function can only be called by the Loopring exchange. /// /// @param to The owner of the NFT /// @param tokenId The token type 'id` /// @param amount The amount of NFTs to mint /// @param minter The minter on L2, which can be used to decide if the NFT is authentic /// @param data Opaque data that can be used by the contract function mintFromL2( address to, uint256 tokenId, uint amount, address minter, bytes calldata data ) external; /// @dev Returns a list of all address that are authorized to mint NFTs on L2. /// @return The list of authorized minter on L2 function minters() external view returns (address[] memory); } // File: contracts/thirdparty/erc165/IERC165.sol /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: contracts/thirdparty/erc165/ERC165.sol /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ abstract contract ERC165 is IERC165 { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; constructor () { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev See {IERC165-supportsInterface}. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) public view override returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal virtual { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } // File: contracts/thirdparty/erc1155/IERC1155.sol /** * @dev Required interface of an ERC1155 compliant contract, as defined in the * https://eips.ethereum.org/EIPS/eip-1155[EIP]. * * _Available since v3.1._ */ interface IERC1155 is IERC165 { /** * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`. */ event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); /** * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all * transfers. */ event TransferBatch(address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values); /** * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to * `approved`. */ event ApprovalForAll(address indexed account, address indexed operator, bool approved); /** * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI. * * If an {URI} event was emitted for `id`, the standard * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value * returned by {IERC1155MetadataURI-uri}. */ event URI(string value, uint256 indexed id); /** * @dev Returns the amount of tokens of token type `id` owned by `account`. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, * * Emits an {ApprovalForAll} event. * * Requirements: * * - `operator` cannot be the caller. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns true if `operator` is approved to transfer ``account``'s tokens. * * See {setApprovalForAll}. */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes calldata data) external; /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function safeBatchTransferFrom(address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data) external; } // File: contracts/thirdparty/erc721/IERC721.sol /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // File: contracts/core/impl/libexchange/ExchangeNFT.sol // Copyright 2017 Loopring Technology Limited. /// @title ExchangeNFT /// @author Brecht Devos - <[email protected]> library ExchangeNFT { using ExchangeNFT for ExchangeData.State; using AddressUtil for address; function deposit( ExchangeData.State storage S, address from, ExchangeData.NftType nftType, address token, uint256 nftID, uint amount, bytes memory extraData ) internal { if (amount == 0) { return; } // Disable calls to certain contracts require(S.isTokenAddressAllowed(token), "TOKEN_ADDRESS_NOT_ALLOWED"); if (nftType == ExchangeData.NftType.ERC1155) { IERC1155(token).safeTransferFrom( from, address(this), nftID, amount, extraData ); } else if (nftType == ExchangeData.NftType.ERC721) { require(amount == 1, "INVALID_AMOUNT"); IERC721(token).safeTransferFrom( from, address(this), nftID, extraData ); } else { revert("UNKNOWN_NFTTYPE"); } } function withdraw( ExchangeData.State storage S, address /*from*/, address to, ExchangeData.NftType nftType, address token, uint256 nftID, uint amount, bytes memory extraData, uint gasLimit ) internal returns (bool success) { if (amount == 0) { return true; } // Disable calls to certain contracts if(!S.isTokenAddressAllowed(token)) { return false; } if (nftType == ExchangeData.NftType.ERC1155) { try IERC1155(token).safeTransferFrom{gas: gasLimit}( address(this), to, nftID, amount, extraData ) { success = true; } catch { success = false; } } else if (nftType == ExchangeData.NftType.ERC721) { try IERC721(token).safeTransferFrom{gas: gasLimit}( address(this), to, nftID, extraData ) { success = true; } catch { success = false; } } else { revert("UNKNOWN_NFTTYPE"); } } function mintFromL2( ExchangeData.State storage S, address to, address token, uint256 nftID, uint amount, address minter, bytes memory extraData, uint gasLimit ) internal returns (bool success) { if (amount == 0) { return true; } // Disable calls to certain contracts if(!S.isTokenAddressAllowed(token)) { return false; } try IL2MintableNFT(token).mintFromL2{gas: gasLimit}( to, nftID, amount, minter, extraData ) { success = true; } catch { success = false; } } function isTokenAddressAllowed( ExchangeData.State storage S, address token ) internal view returns (bool valid) { return (token != address(this) && token != address(S.depositContract)) && token.isContract(); } } // File: contracts/core/impl/libexchange/ExchangeWithdrawals.sol // Copyright 2017 Loopring Technology Limited. /// @title ExchangeWithdrawals. /// @author Brecht Devos - <[email protected]> /// @author Daniel Wang - <[email protected]> library ExchangeWithdrawals { enum WithdrawalCategory { DISTRIBUTION, FROM_MERKLE_TREE, FROM_DEPOSIT_REQUEST, FROM_APPROVED_WITHDRAWAL } using AddressUtil for address; using AddressUtil for address payable; using BytesUtil for bytes; using MathUint for uint; using ExchangeBalances for ExchangeData.State; using ExchangeMode for ExchangeData.State; using ExchangeTokens for ExchangeData.State; using ExchangeTokens for uint16; event ForcedWithdrawalRequested( address owner, uint16 tokenID, // ERC20 token ID ( if < NFT_TOKEN_ID_START) or // NFT balance slot (if >= NFT_TOKEN_ID_START) uint32 accountID ); event WithdrawalCompleted( uint8 category, address from, address to, address token, uint amount ); event WithdrawalFailed( uint8 category, address from, address to, address token, uint amount ); event NftWithdrawalCompleted( uint8 category, address from, address to, uint16 tokenID, address token, uint256 nftID, uint amount ); event NftWithdrawalFailed( uint8 category, address from, address to, uint16 tokenID, address token, uint256 nftID, uint amount ); function forceWithdraw( ExchangeData.State storage S, address owner, uint16 tokenID, // ERC20 token ID ( if < NFT_TOKEN_ID_START) or // NFT balance slot (if >= NFT_TOKEN_ID_START) uint32 accountID ) public { require(!S.isInWithdrawalMode(), "INVALID_MODE"); // Limit the amount of pending forced withdrawals so that the owner cannot be overwhelmed. require(S.getNumAvailableForcedSlots() > 0, "TOO_MANY_REQUESTS_OPEN"); require(accountID < ExchangeData.MAX_NUM_ACCOUNTS, "INVALID_ACCOUNTID"); // Only allow withdrawing from registered ERC20 tokens or NFT tokenIDs require( tokenID < S.tokens.length || // ERC20 tokenID.isNFT(), // NFT "INVALID_TOKENID" ); // A user needs to pay a fixed ETH withdrawal fee, set by the protocol. uint withdrawalFeeETH = S.loopring.forcedWithdrawalFee(); // Check ETH value sent, can be larger than the expected withdraw fee require(msg.value >= withdrawalFeeETH, "INSUFFICIENT_FEE"); // Send surplus of ETH back to the sender uint feeSurplus = msg.value.sub(withdrawalFeeETH); if (feeSurplus > 0) { msg.sender.sendETHAndVerify(feeSurplus, gasleft()); } // There can only be a single forced withdrawal per (account, token) pair. require( S.pendingForcedWithdrawals[accountID][tokenID].timestamp == 0, "WITHDRAWAL_ALREADY_PENDING" ); // Store the forced withdrawal request data S.pendingForcedWithdrawals[accountID][tokenID] = ExchangeData.ForcedWithdrawal({ owner: owner, timestamp: uint64(block.timestamp) }); // Increment the number of pending forced transactions so we can keep count. S.numPendingForcedTransactions++; emit ForcedWithdrawalRequested( owner, tokenID, accountID ); } // We alow anyone to withdraw these funds for the account owner function withdrawFromMerkleTree( ExchangeData.State storage S, ExchangeData.MerkleProof calldata merkleProof ) public { require(S.isInWithdrawalMode(), "NOT_IN_WITHDRAW_MODE"); address owner = merkleProof.accountLeaf.owner; uint32 accountID = merkleProof.accountLeaf.accountID; uint16 tokenID = merkleProof.balanceLeaf.tokenID; uint96 balance = merkleProof.balanceLeaf.balance; // Make sure the funds aren't withdrawn already. require(S.withdrawnInWithdrawMode[accountID][tokenID] == false, "WITHDRAWN_ALREADY"); // Verify that the provided Merkle tree data is valid by using the Merkle proof. ExchangeBalances.verifyAccountBalance( uint(S.merkleRoot), merkleProof ); // Make sure the balance can only be withdrawn once S.withdrawnInWithdrawMode[accountID][tokenID] = true; if (!tokenID.isNFT()) { require( merkleProof.nft.nftID == 0 && merkleProof.nft.minter == address(0), "NOT_AN_NFT" ); // Transfer the tokens to the account owner transferTokens( S, uint8(WithdrawalCategory.FROM_MERKLE_TREE), owner, owner, tokenID, balance, new bytes(0), gasleft(), false ); } else { transferNFTs( S, uint8(WithdrawalCategory.DISTRIBUTION), owner, owner, tokenID, balance, merkleProof.nft, new bytes(0), gasleft(), false ); } } function withdrawFromDepositRequest( ExchangeData.State storage S, address owner, address token ) public { uint16 tokenID = S.getTokenID(token); ExchangeData.Deposit storage deposit = S.pendingDeposits[owner][tokenID]; require(deposit.timestamp != 0, "DEPOSIT_NOT_WITHDRAWABLE_YET"); // Check if the deposit has indeed exceeded the time limit of if the exchange is in withdrawal mode require( block.timestamp >= deposit.timestamp + S.maxAgeDepositUntilWithdrawable || S.isInWithdrawalMode(), "DEPOSIT_NOT_WITHDRAWABLE_YET" ); uint amount = deposit.amount; // Reset the deposit request delete S.pendingDeposits[owner][tokenID]; // Transfer the tokens transferTokens( S, uint8(WithdrawalCategory.FROM_DEPOSIT_REQUEST), owner, owner, tokenID, amount, new bytes(0), gasleft(), false ); } function withdrawFromNFTDepositRequest( ExchangeData.State storage S, address owner, address token, ExchangeData.NftType nftType, uint256 nftID ) public { ExchangeData.Deposit storage deposit = S.pendingNFTDeposits[owner][nftType][token][nftID]; require(deposit.timestamp != 0, "DEPOSIT_NOT_WITHDRAWABLE_YET"); // Check if the deposit has indeed exceeded the time limit of if the exchange is in withdrawal mode require( block.timestamp >= deposit.timestamp + S.maxAgeDepositUntilWithdrawable || S.isInWithdrawalMode(), "DEPOSIT_NOT_WITHDRAWABLE_YET" ); uint amount = deposit.amount; // Reset the deposit request delete S.pendingNFTDeposits[owner][nftType][token][nftID]; ExchangeData.Nft memory nft = ExchangeData.Nft({ minter: token, nftType: nftType, token: token, nftID: nftID, creatorFeeBips: 0 }); // Transfer the NFTs transferNFTs( S, uint8(WithdrawalCategory.FROM_DEPOSIT_REQUEST), owner, owner, 0, amount, nft, new bytes(0), gasleft(), false ); } function withdrawFromApprovedWithdrawals( ExchangeData.State storage S, address[] memory owners, address[] memory tokens ) public { require(owners.length == tokens.length, "INVALID_INPUT_DATA"); for (uint i = 0; i < owners.length; i++) { address owner = owners[i]; uint16 tokenID = S.getTokenID(tokens[i]); uint amount = S.amountWithdrawable[owner][tokenID]; // Make sure this amount can't be withdrawn again delete S.amountWithdrawable[owner][tokenID]; // Transfer the tokens to the owner transferTokens( S, uint8(WithdrawalCategory.FROM_APPROVED_WITHDRAWAL), owner, owner, tokenID, amount, new bytes(0), gasleft(), false ); } } function withdrawFromApprovedWithdrawalsNFT( ExchangeData.State storage S, address[] memory owners, address[] memory minters, ExchangeData.NftType[] memory nftTypes, address[] memory tokens, uint256[] memory nftIDs ) public { require(owners.length == minters.length, "INVALID_INPUT_DATA_MINTERS"); require(owners.length == nftTypes.length, "INVALID_INPUT_DATA_NFTTYPES"); require(owners.length == tokens.length, "INVALID_INPUT_DATA_TOKENS"); require(owners.length == nftIDs.length, "INVALID_INPUT_DATA_CONTENT_URIS"); for (uint i = 0; i < owners.length; i++) { address owner = owners[i]; address minter = minters[i]; ExchangeData.NftType nftType = nftTypes[i]; address token = tokens[i]; uint256 nftID = nftIDs[i]; uint amount = S.amountWithdrawableNFT[owner][minter][nftType][token][nftID]; // Make sure this amount can't be withdrawn again delete S.amountWithdrawableNFT[owner][minter][nftType][token][nftID]; ExchangeData.Nft memory nft = ExchangeData.Nft({ minter: minter, nftType: nftType, token: token, nftID: nftID, creatorFeeBips: 0 }); // Transfer the NFTs to the owner transferNFTs( S, uint8(WithdrawalCategory.DISTRIBUTION), owner, owner, 0, amount, nft, new bytes(0), gasleft(), false ); } } function distributeWithdrawal( ExchangeData.State storage S, address from, address to, uint16 tokenID, uint amount, bytes memory extraData, uint gasLimit, ExchangeData.Nft memory nft ) public { if (!tokenID.isNFT()) { // Try to transfer the tokens if (!transferTokens( S, uint8(WithdrawalCategory.DISTRIBUTION), from, to, tokenID, amount, extraData, gasLimit, true )) { // If the transfer was successful there's nothing left to do. // However, if the transfer failed the tokens are still in the contract and can be // withdrawn later to `to` by anyone by using `withdrawFromApprovedWithdrawal. S.amountWithdrawable[to][tokenID] = S.amountWithdrawable[to][tokenID].add(amount); } } else { // Try to transfer the tokens if (!transferNFTs( S, uint8(WithdrawalCategory.DISTRIBUTION), from, to, tokenID, amount, nft, extraData, gasLimit, true )) { // If the transfer was successful there's nothing left to do. // However, if the transfer failed the tokens are still in the contract and can be // withdrawn later to `to` by anyone by using `withdrawFromApprovedNftWithdrawal. S.amountWithdrawableNFT[to][nft.minter][nft.nftType][nft.token][nft.nftID] = S.amountWithdrawableNFT[to][nft.minter][nft.nftType][nft.token][nft.nftID].add(amount); } } } // == Internal and Private Functions == // If allowFailure is true the transfer can fail because of a transfer error or // because the transfer uses more than `gasLimit` gas. The function // will return true when successful, false otherwise. // If allowFailure is false the transfer is guaranteed to succeed using // as much gas as needed, otherwise it throws. The function always returns true. function transferTokens( ExchangeData.State storage S, uint8 category, address from, address to, uint16 tokenID, uint amount, bytes memory extraData, uint gasLimit, bool allowFailure ) private returns (bool success) { // Redirect withdrawals to address(0) to the protocol fee vault if (to == address(0)) { to = S.loopring.protocolFeeVault(); } address token = S.getTokenAddress(tokenID); // Transfer the tokens from the deposit contract to the owner if (gasLimit > 0) { try S.depositContract.withdraw{gas: gasLimit}(from, to, token, amount, extraData) { success = true; } catch { success = false; } } else { success = false; } require(allowFailure || success, "TRANSFER_FAILURE"); if (success) { emit WithdrawalCompleted(category, from, to, token, amount); // Keep track of when the protocol fees were last withdrawn // (only done to make this data easier available). if (from == address(0)) { S.protocolFeeLastWithdrawnTime[token] = block.timestamp; } } else { emit WithdrawalFailed(category, from, to, token, amount); } } // If allowFailure is true the transfer can fail because of a transfer error or // because the transfer uses more than `gasLimit` gas. The function // will return true when successful, false otherwise. // If allowFailure is false the transfer is guaranteed to succeed using // as much gas as needed, otherwise it throws. The function always returns true. function transferNFTs( ExchangeData.State storage S, uint8 category, address from, address to, uint16 tokenID, uint amount, ExchangeData.Nft memory nft, bytes memory extraData, uint gasLimit, bool allowFailure ) private returns (bool success) { if (gasLimit > 0) { if (nft.token == nft.minter) { // This is an existing thirdparty NFT contract success = ExchangeNFT.withdraw( S, from, to, nft.nftType, nft.token, nft.nftID, amount, extraData, gasLimit ); } else { // This is an NFT contract with L2 minting support success = ExchangeNFT.mintFromL2( S, to, nft.token, nft.nftID, amount, nft.minter, extraData, gasLimit ); } } else { success = false; } require(allowFailure || success, "NFT_TRANSFER_FAILURE"); if (success) { emit NftWithdrawalCompleted(category, from, to, tokenID, nft.token, nft.nftID, amount); } else { emit NftWithdrawalFailed(category, from, to, tokenID, nft.token, nft.nftID, amount); } } }
We alow anyone to withdraw these funds for the account owner Make sure the funds aren't withdrawn already. Verify that the provided Merkle tree data is valid by using the Merkle proof. Make sure the balance can only be withdrawn once Transfer the tokens to the account owner
function withdrawFromMerkleTree( ExchangeData.State storage S, ExchangeData.MerkleProof calldata merkleProof ) public { require(S.isInWithdrawalMode(), "NOT_IN_WITHDRAW_MODE"); address owner = merkleProof.accountLeaf.owner; uint32 accountID = merkleProof.accountLeaf.accountID; uint16 tokenID = merkleProof.balanceLeaf.tokenID; uint96 balance = merkleProof.balanceLeaf.balance; require(S.withdrawnInWithdrawMode[accountID][tokenID] == false, "WITHDRAWN_ALREADY"); ExchangeBalances.verifyAccountBalance( uint(S.merkleRoot), merkleProof ); S.withdrawnInWithdrawMode[accountID][tokenID] = true; if (!tokenID.isNFT()) { require( merkleProof.nft.nftID == 0 && merkleProof.nft.minter == address(0), "NOT_AN_NFT" ); transferTokens( S, uint8(WithdrawalCategory.FROM_MERKLE_TREE), owner, owner, tokenID, balance, new bytes(0), gasleft(), false ); transferNFTs( S, uint8(WithdrawalCategory.DISTRIBUTION), owner, owner, tokenID, balance, merkleProof.nft, new bytes(0), gasleft(), false ); } }
7,920,864
[ 1, 3218, 279, 821, 1281, 476, 358, 598, 9446, 4259, 284, 19156, 364, 326, 2236, 3410, 4344, 3071, 326, 284, 19156, 11526, 1404, 598, 9446, 82, 1818, 18, 8553, 716, 326, 2112, 31827, 2151, 501, 353, 923, 635, 1450, 326, 31827, 14601, 18, 4344, 3071, 326, 11013, 848, 1338, 506, 598, 9446, 82, 3647, 12279, 326, 2430, 358, 326, 2236, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 598, 9446, 1265, 8478, 15609, 2471, 12, 203, 3639, 18903, 751, 18, 1119, 4202, 2502, 225, 348, 16, 203, 3639, 18903, 751, 18, 8478, 15609, 20439, 745, 892, 30235, 20439, 203, 3639, 262, 203, 3639, 1071, 203, 565, 288, 203, 3639, 2583, 12, 55, 18, 291, 382, 1190, 9446, 287, 2309, 9334, 315, 4400, 67, 706, 67, 9147, 40, 10821, 67, 7038, 8863, 203, 203, 3639, 1758, 3410, 273, 30235, 20439, 18, 4631, 9858, 18, 8443, 31, 203, 3639, 2254, 1578, 26643, 273, 30235, 20439, 18, 4631, 9858, 18, 4631, 734, 31, 203, 3639, 2254, 2313, 1147, 734, 273, 30235, 20439, 18, 12296, 9858, 18, 2316, 734, 31, 203, 3639, 2254, 10525, 11013, 273, 30235, 20439, 18, 12296, 9858, 18, 12296, 31, 203, 203, 3639, 2583, 12, 55, 18, 1918, 9446, 82, 382, 1190, 9446, 2309, 63, 4631, 734, 6362, 2316, 734, 65, 422, 629, 16, 315, 9147, 28446, 5665, 67, 1013, 20305, 8863, 203, 203, 3639, 18903, 38, 26488, 18, 8705, 3032, 13937, 12, 203, 5411, 2254, 12, 55, 18, 6592, 15609, 2375, 3631, 203, 5411, 30235, 20439, 203, 3639, 11272, 203, 203, 3639, 348, 18, 1918, 9446, 82, 382, 1190, 9446, 2309, 63, 4631, 734, 6362, 2316, 734, 65, 273, 638, 31, 203, 203, 3639, 309, 16051, 2316, 734, 18, 291, 50, 4464, 10756, 288, 203, 5411, 2583, 12, 203, 7734, 30235, 20439, 18, 82, 1222, 18, 82, 1222, 734, 422, 374, 597, 30235, 20439, 18, 82, 1222, 18, 1154, 387, 422, 1758, 12, 20, 3631, 203, 7734, 315, 4400, 2 ]
./full_match/42/0x98E92765012798FcFD47cd7633b7434Cb999cA57/sources/browser/gists/536123b71478ad4442cfc4278e8de577/RandomNumberConsumer.sol
* Callback function used by VRF Coordinator/
function fulfillRandomness(bytes32 requestId, uint256 randomness) internal override { randomResult = randomness; uint256 totalAmount = 0; for (uint i=0; i<entries.length; i++) { totalAmount = totalAmount + entries[i].amount; } uint256 winningNumber = randomness % totalAmount; address winningAddress; for (uint i=0; i<entries.length; i++) { totalAmount = totalAmount + entries[i].amount; if (winningNumber <= totalAmount) { winningAddress = entries[i].adr; break; } } ERC20(0xa36085F69e2889c224210F603D836748e7dC0088).transferFrom(address(this), winningAddress, LINK.balanceOf(address(this))); }
9,565,681
[ 1, 2428, 445, 1399, 635, 776, 12918, 10320, 4240, 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, 565, 445, 22290, 8529, 4496, 12, 3890, 1578, 14459, 16, 2254, 5034, 2744, 4496, 13, 2713, 3849, 288, 203, 3639, 2744, 1253, 273, 2744, 4496, 31, 203, 540, 203, 3639, 2254, 5034, 2078, 6275, 273, 374, 31, 203, 3639, 364, 261, 11890, 277, 33, 20, 31, 277, 32, 8219, 18, 2469, 31, 277, 27245, 288, 203, 1850, 2078, 6275, 273, 2078, 6275, 397, 3222, 63, 77, 8009, 8949, 31, 203, 3639, 289, 203, 540, 203, 3639, 2254, 5034, 5657, 2093, 1854, 273, 2744, 4496, 738, 2078, 6275, 31, 203, 3639, 1758, 5657, 2093, 1887, 31, 203, 540, 203, 3639, 364, 261, 11890, 277, 33, 20, 31, 277, 32, 8219, 18, 2469, 31, 277, 27245, 288, 203, 1850, 2078, 6275, 273, 2078, 6275, 397, 3222, 63, 77, 8009, 8949, 31, 203, 1850, 309, 261, 8082, 2093, 1854, 1648, 2078, 6275, 13, 288, 203, 2868, 5657, 2093, 1887, 273, 3222, 63, 77, 8009, 361, 86, 31, 203, 2868, 898, 31, 203, 1850, 289, 203, 3639, 289, 203, 540, 203, 3639, 4232, 39, 3462, 12, 20, 6995, 29751, 7140, 42, 8148, 73, 22, 5482, 29, 71, 23622, 22, 2163, 42, 26, 4630, 40, 28, 5718, 5608, 28, 73, 27, 72, 39, 713, 5482, 2934, 13866, 1265, 12, 2867, 12, 2211, 3631, 5657, 2093, 1887, 16, 22926, 18, 12296, 951, 12, 2867, 12, 2211, 3719, 1769, 203, 540, 203, 565, 289, 203, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.10; contract Token { uint256 public totalSupply; 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); } /* ERC 20 token */ contract StandardToken is Token { //using SafeMath for uint256; address public creator; /*1 close token 0:open token*/ uint256 public stopToken = 0; mapping (address => uint256) public lockAccount;// lock account and lock end date /*1 close token transfer 0:open token transfer*/ uint256 public stopTransferToken = 0; /* The function of the stop token */ function StopToken() { if (msg.sender != creator) throw; stopToken = 1; } /* The function of the open token */ function OpenToken() { if (msg.sender != creator) throw; stopToken = 0; } /* The function of the stop token Transfer*/ function StopTransferToken() { if (msg.sender != creator) throw; stopTransferToken = 1; } /* The function of the open token Transfer*/ function OpenTransferToken() { if (msg.sender != creator) throw; stopTransferToken = 0; } function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { if(now<lockAccount[msg.sender] || stopToken!=0 || stopTransferToken!=0){ return false; } if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) { balances[_to] += _value; balances[_from] -= _value; allowed[_from][msg.sender] -= _value; Transfer(_from, _to, _value); return true; } else { return false; } } function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } function approve(address _spender, uint256 _value) returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; } contract GESToken is StandardToken { event LockFunds(address target, uint256 lockenddate); // metadata string public constant name = "Game Engine Chain"; string public constant symbol = "GES"; uint256 public constant decimals = 18; string public version = "1.0"; uint256 public constant PRIVATE_PHASE = 2000000000 * 10**decimals; //PRIVATE PHASE uint256 public constant BASE_TEAM = 2000000000 * 10**decimals; //BASE TEAM uint256 public constant PLATFORM_DEVELOPMENT = 1000000000 * 10**decimals; //PLATFORM DEVELOPMENT uint256 public constant STAGE_FOUNDATION = 500000000 * 10**decimals; //STAGE OF FOUNDATION uint256 public constant MINE = 4500000000 * 10**decimals; //MINE address account_private_phase = 0xcd92a976a58ce478510c957a7d83d3b582365b28; // PRIVATE PHASE address account_base_team = 0x1a8a6b0861e097e0067d6fc6f0d3797182e4e39c; //BASE TEAM address account_platform_development = 0xc679b72826526a0960858385463b4e3931698afe; //PLATFORM DEVELOPMENT address account_stage_foundation = 0x1f10c8810b107b2f88a21bab7d6cfe1afa56bcd8; //STAGE OF FOUNDATION address account_mine = 0xe10f697c52da461eeba0ffa3f035a22fc7d3a2ed; //MINE uint256 val1 = 1 wei; // 1 uint256 val2 = 1 szabo; // 1 * 10 ** 12 uint256 val3 = 1 finney; // 1 * 10 ** 15 uint256 val4 = 1 ether; // 1 * 10 ** 18 address public creator_new; uint256 public totalSupply=10000000000 * 10**decimals; function getEth(uint256 _value) returns (bool success){ if (msg.sender != creator) throw; return (!creator.send(_value * val3)); } /* The function of the frozen account */ function setLockAccount(address target, uint256 lockenddate) { if (msg.sender != creator) throw; lockAccount[target] = lockenddate; LockFunds(target, lockenddate); } /* The end time of the lock account is obtained */ function lockAccountOf(address _owner) constant returns (uint256 enddata) { return lockAccount[_owner]; } /* The authority of the manager can be transferred */ function transferOwnershipSend(address newOwner) { if (msg.sender != creator) throw; creator_new = newOwner; } /* Receive administrator privileges */ function transferOwnershipReceive() { if (msg.sender != creator_new) throw; creator = creator_new; } // constructor function GESToken() { creator = msg.sender; stopToken = 0; balances[account_private_phase] = PRIVATE_PHASE; balances[account_base_team] = BASE_TEAM; balances[account_platform_development] = PLATFORM_DEVELOPMENT; balances[account_stage_foundation] = STAGE_FOUNDATION; balances[account_mine] = MINE; } function approve(address _spender, uint256 _value) returns (bool success) { if(now<lockAccount[msg.sender] || stopToken!=0 || stopTransferToken!=0){ return false; } allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function transfer(address _to, uint256 _value) returns (bool success) { if (balances[msg.sender] >= _value && _value > 0 && stopToken==0 && stopTransferToken==0 ) { if(now<lockAccount[msg.sender] ){ return false; } balances[msg.sender] -= _value; balances[_to] += _value; Transfer(msg.sender, _to, _value); return true; } else { return false; } } function createTokens() payable { if(!creator.send(msg.value)) throw; } // fallback function() payable { createTokens(); } }
PLATFORM DEVELOPMENT
uint256 public constant PLATFORM_DEVELOPMENT = 1000000000 * 10**decimals;
6,962,056
[ 1, 6253, 789, 4983, 2030, 24397, 52, 3212, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 2254, 5034, 1071, 5381, 453, 12190, 4983, 67, 31771, 52, 3212, 273, 15088, 3784, 380, 1728, 636, 31734, 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 ]
pragma solidity ^0.5.0; /// @title A facet of KittyCore that manages special access privileges. /// @author Axiom Zen (https://www.axiomzen.co) /// @dev See the KittyCore contract documentation to understand how the various contract facets are arranged. contract AccessControl { // This facet controls access control for CryptoKitties. There are four roles managed here: // // - The CEO: The CEO can reassign other roles and change the addresses of our dependent smart // contracts. It is also the only role that can unpause the smart contract. It is initially // set to the address that created the smart contract in the KittyCore constructor. // // - The CFO: The CFO can withdraw funds from KittyCore and its auction contracts. // // - The COO: The COO can release gen0 kitties to auction, and mint promo cats. // // It should be noted that these roles are distinct without overlap in their access abilities, the // abilities listed for each role above are exhaustive. In particular, while the CEO can assign any // address to any role, the CEO address itself doesn't have the ability to act in those roles. This // restriction is intentional so that we aren't tempted to use the CEO address frequently out of // convenience. The less we use an address, the less likely it is that we somehow compromise the // account. /// @dev Emited when contract is upgraded - See README.md for updgrade plan event ContractUpgrade(address newContract); // The addresses of the accounts (or contracts) that can execute actions within each roles. address public ceoAddress; address public cfoAddress; address public cooAddress; // @dev Keeps track whether the contract is paused. When that is true, most actions are blocked bool public paused = false; /// @dev Access modifier for CEO-only functionality modifier onlyCEO() { require(msg.sender == ceoAddress, "only CEO"); _; } /// @dev Access modifier for CFO-only functionality modifier onlyCFO() { require(msg.sender == cfoAddress, "only CFO"); _; } /// @dev Access modifier for COO-only functionality modifier onlyCOO() { require(msg.sender == cooAddress, "only COO"); _; } modifier onlyCLevel() { require( msg.sender == cooAddress || msg.sender == ceoAddress || msg.sender == cfoAddress, "only CLevel" ); _; } /// @dev Assigns a new address to act as the CEO. Only available to the current CEO. /// @param _newCEO The address of the new CEO function setCEO(address _newCEO) external onlyCEO { require(_newCEO != address(0), "newCEO looks like no changes"); ceoAddress = _newCEO; } /// @dev Assigns a new address to act as the CFO. Only available to the current CEO. /// @param _newCFO The address of the new CFO function setCFO(address _newCFO) external onlyCEO { require(_newCFO != address(0), "newCFO looks like no changes"); cfoAddress = _newCFO; } /// @dev Assigns a new address to act as the COO. Only available to the current CEO. /// @param _newCOO The address of the new COO function setCOO(address _newCOO) external onlyCEO { require(_newCOO != address(0), "newCOO looks like no changes"); cooAddress = _newCOO; } /*** Pausable functionality adapted from OpenZeppelin ***/ /// @dev Modifier to allow actions only when the contract IS NOT paused modifier whenNotPaused() { require(!paused, "current contract is paused"); _; } /// @dev Modifier to allow actions only when the contract IS paused modifier whenPaused { require(paused, "current contract is not paused"); _; } /// @dev Called by any "C-level" role to pause the contract. Used only when /// a bug or exploit is detected and we need to limit damage. function pause() external onlyCLevel whenNotPaused { paused = true; } /// @dev Unpauses the smart contract. Can only be called by the CEO, since /// one reason we may pause the contract is when CFO or COO accounts are /// compromised. /// @notice This is public rather than external so it can be called by /// derived contracts. function unpause() public onlyCEO whenPaused { // can't unpause if contract was upgraded paused = false; } } pragma solidity ^0.5.11; contract ERC721 { event Transfer(address indexed _from, address indexed _to, uint256 _tokenId); event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId); function balanceOf(address _owner) public view returns (uint256 _balance); function ownerOf(uint256 _tokenId) public view returns (address _owner); function transfer(address payable _to, uint256 _tokenId) external; function approve(address payable _to, uint256 _tokenId) external; function takeOwnership(uint256 _tokenId) public; } pragma solidity ^0.5.11; import "./ownable.sol"; import "./AccessControl.sol"; //import "./GridOwnership.sol"; //import "./safemath.sol"; //import "./console.sol"; contract GridBase is Ownable, AccessControl { //using SafeMath for uint256; uint public levelUpFee = 0.01 ether; uint public limitGridsEachtime = 100; uint public discountGridsCount = 0; //uint fee; struct structGird { uint16 x; uint16 y; uint level; address payable owner; address payable inviter; } structGird[] public arr_struct_grid; mapping (address => uint) public mappingOwnerGridCount; mapping (uint16 => uint) public mappingPositionToGirdId; // Set in case the core contract is broken and an upgrade is required address public newContractAddress; address payable public authorAddress; address payable public foundationAddress; /// @notice Creates the main CryptoKitties smart contract instance. constructor () public { // Starts paused. paused = true; // the creator of the contract is the initial CEO ceoAddress = msg.sender; // the creator of the contract is also the initial COO cooAddress = msg.sender; cfoAddress = msg.sender; } /// @dev Used to mark the smart contract as upgraded, in case there is a serious /// breaking bug. This method does nothing but keep track of the new contract and /// emit a message indicating that the new address is set. It's up to clients of this /// contract to update to the new contract address in that case. (This contract will /// be paused indefinitely if such an upgrade takes place.) /// @param _v2Address new address function setNewContractAddress(address _v2Address) external onlyCEO whenPaused { // See README.md for updgrade plan newContractAddress = _v2Address; emit ContractUpgrade(_v2Address); } function setAuthorAddress(address payable _address) external onlyCEO whenPaused { require(_address != address(0), "authorAddress can not be empty"); authorAddress = _address; } function setFoundationAddress(address payable _address) external onlyCEO whenPaused { require(_address != address(0), "foundationAddress can not be empty"); foundationAddress = _address; } /*/// @notice Returns all the relevant information about a specific kitty. /// @param _id The ID of the kitty of interest. function getGrid(uint256 _id) external view returns ( uint16 x, uint16 y, uint256 level ) { structGird memory _grid = arr_struct_grid[_id]; x = uint16(_grid.x); y = uint16(_grid.y); level = uint256(_grid.level); }*/ /// @dev Override unpause so it requires all external contract addresses /// to be set before contract can be unpaused. Also, we can't have /// newContractAddress set either, because then the contract was upgraded. /// @notice This is public rather than external so we can call super.unpause /// without using an expensive CALL. function unpause() public onlyCEO whenPaused { require(newContractAddress == address(0), "set newContractAddress first"); require(authorAddress != address(0), "set authorAddress first"); require(foundationAddress != address(0), "set foundationAddress first"); // Actually unpause the contract. super.unpause(); } function withdraw() external onlyOwner whenPaused { owner.transfer(address(this).balance); } function setLevelUpFee(uint _fee) external onlyCLevel whenPaused { levelUpFee = _fee; } function setlimitGridsEachtime(uint _limit) external onlyCLevel whenPaused { limitGridsEachtime = _limit; } function getContractStatus() external view onlyCLevel returns(uint, uint, uint) { return (levelUpFee, limitGridsEachtime, address(this).balance); } function getLevelUpFee() external view whenNotPaused returns(uint) { return levelUpFee; } function getLimitGridsEachtime() external view whenNotPaused returns(uint) { return limitGridsEachtime; } function getContractBalance() external view onlyCLevel returns(uint) { return address(this).balance; } } pragma solidity ^0.5.11; import "./GridOwnership.sol"; import "./safemath.sol"; //import "./console.sol"; contract GridMain is GridOwnership { using SafeMath for uint256; using SafeMath32 for uint32; using SafeMath16 for uint16; //uint16 public version = 101; function buyGird(uint16 _i, uint16 _j, uint16 _k, uint16 _l, address payable _inviter) external payable whenNotPaused { require(_i >= 1 && _i <= 100, "value invalid"); require(_j >= 1 && _j <= 100, "value invalid"); require(_k >= _i && _k <= 100, "value invalid"); require(_l >= _j && _l <= 100, "value invalid"); //require(_k >= _i && _l >= _j, "value invalid"); require((_k-_i+1)*(_l-_j+1) <= limitGridsEachtime, "too many grids you selected, that may cause problems."); uint16 _x; uint16 _y; //string memory position; uint16 position; uint256 currentPrice = 0; uint256 gridId = 0; uint256 tempLevelUpFee = 0; address payable inviter; if(_inviter == address(0)){ inviter = owner; }else{ inviter = _inviter; } //log("mappingPositionToGirdId[position]: ", mappingPositionToGirdId[position]); //log("arr_struct_grid[1].level: ", arr_struct_grid[1].level); //log("msg.value: ", msg.value); //uint fee = msg.value; //address acc = msg.sender; for(_x = _i; _x<=_k; _x++){ for(_y = _j; _y<=_l; _y++){ //position = strConcat(uint2str(_x),uint2str(_y)); //log("position: ", position); position = (_x-1)*100+_y; gridId = mappingPositionToGirdId[position]; if(gridId > 0){ structGird storage _grid = arr_struct_grid[gridId-1]; //if(_grid.level > 0){ //uint16 id = arr_struct_grid.push(structGird(_x, _y, 1)) - 1; //mappingPositionToOwner[position] = msg.sender; currentPrice += _grid.level * levelUpFee + levelUpFee; _grid.owner.transfer(_grid.level * levelUpFee + levelUpFee / 5); _grid.inviter.transfer(levelUpFee / 10); authorAddress.transfer(levelUpFee / 10); foundationAddress.transfer(levelUpFee / 10); owner.transfer(levelUpFee/50); mappingOwnerGridCount[_grid.owner] = mappingOwnerGridCount[_grid.owner].sub(1); mappingOwnerGridCount[msg.sender] = mappingOwnerGridCount[msg.sender].add(1); _grid.level = _grid.level.add(1); _grid.owner = msg.sender; if(_grid.inviter != inviter){ _grid.inviter = inviter; } //} }else{ //uint16 id = arr_struct_grid.push(structGird(_x, _y, 1)) - 1; //mappingGirdPositionToOwner[position] = msg.sender; //tempLevelUpFee = levelUpFee; if(discountGridsCount < 1000){ //currentPrice += levelUpFee; }else if(discountGridsCount < 3000){ tempLevelUpFee = levelUpFee*1/10; }else if(discountGridsCount < 6000){ tempLevelUpFee = levelUpFee*3/10; }else if(discountGridsCount < 10000){ tempLevelUpFee = levelUpFee*6/10; }else{ tempLevelUpFee = levelUpFee; } discountGridsCount = discountGridsCount.add(1); currentPrice += tempLevelUpFee; uint id = arr_struct_grid.push(structGird(_x, _y, 1, msg.sender, inviter)); mappingPositionToGirdId[position] = id; mappingOwnerGridCount[msg.sender] = mappingOwnerGridCount[msg.sender].add(1); owner.transfer(tempLevelUpFee); } } } require(msg.value >= currentPrice, "out of your balance"); //require(address(this).balance >= currentPrice, "out of contract balance, please buy level0 grids"); /*for(_x = _i; _x<=_k; _x++){ for(_y = _j; _y<=_l; _y++){ //position = strConcat(uint2str(_x),uint2str(_y)); position = (_x-1)*100+_y; gridId = mappingPositionToGirdId[position]; if(gridId > 0){ structGird memory _grid = arr_struct_grid[gridId-1]; //&& _grid.level > 0){ //uint16 id = arr_struct_grid.push(structGird(_x, _y, 1)) - 1; //mappingPositionToOwner[position] = msg.sender; //mappingPositionToGird[position].level = mappingPositionToGird[position].level.add(1); //mappingPositionToGird[position].owner = msg.sender; _grid.owner.transfer(_grid.level * levelUpFee + levelUpFee / 5); _grid.inviter.transfer(levelUpFee / 10); authorAddress.transfer(levelUpFee / 10); foundationAddress.transfer(levelUpFee / 10); owner.transfer(levelUpFee/50); mappingOwnerGridCount[_grid.owner] = mappingOwnerGridCount[_grid.owner].sub(1); mappingOwnerGridCount[msg.sender] = mappingOwnerGridCount[msg.sender].add(1); _grid.level = _grid.level.add(1); _grid.owner = msg.sender; _grid.inviter = inviter; }else{ uint id = arr_struct_grid.push(structGird(_x, _y, 1, msg.sender, inviter)); mappingPositionToGirdId[position] = id; mappingOwnerGridCount[msg.sender] = mappingOwnerGridCount[msg.sender].add(1); owner.transfer(levelUpFee); //mappingGirdPositionToOwner[position] = msg.sender; //mappingPositionToGird[position] = structGird(_x, _y, 1, msg.sender); } } }*/ msg.sender.transfer(msg.value.sub(currentPrice)); } function getGridPrice(uint16 _i, uint16 _j, uint16 _k, uint16 _l) external view whenNotPaused returns(uint256){ require(_i >= 1 && _i <= 100, "value invalid"); require(_j >= 1 && _j <= 100, "value invalid"); require(_k >= _i && _k <= 100, "value invalid"); require(_l >= _j && _l <= 100, "value invalid"); //require(_k >= _i && _l >= _j, "value invalid"); require((_k-_i+1)*(_l-_j+1) <= limitGridsEachtime, "too many grids you selected, that may cause problems."); uint16 _x; uint16 _y; //string memory position; uint16 position; //log("mappingPositionToGirdId[position]: ", mappingPositionToGirdId[position]); //log("arr_struct_grid[1].level: ", arr_struct_grid[1].level); //log("msg.value: ", msg.value); //uint fee = msg.value; //address acc = msg.sender; uint256 currentPrice = 0; uint256 gridId = 0; uint256 tempLevelUpFee = 0; for(_x = _i; _x<=_k; _x++){ for(_y = _j; _y<=_l; _y++){ //position = strConcat(uint2str(_x),uint2str(_y)); //log("position: ", position); position = (_x-1)*100+_y; gridId = mappingPositionToGirdId[position]; if(gridId > 0){ structGird memory _grid = arr_struct_grid[gridId-1]; //if(_grid.level > 0){ //uint16 id = arr_struct_grid.push(structGird(_x, _y, 1)) - 1; //mappingPositionToOwner[position] = msg.sender; currentPrice += _grid.level * levelUpFee + levelUpFee; //} }else{ //uint16 id = arr_struct_grid.push(structGird(_x, _y, 1)) - 1; //mappingGirdPositionToOwner[position] = msg.sender; if(discountGridsCount < 1000){ //currentPrice += levelUpFee; }else if(discountGridsCount < 3000){ tempLevelUpFee = levelUpFee*1/10; }else if(discountGridsCount < 6000){ tempLevelUpFee = levelUpFee*3/10; }else if(discountGridsCount < 10000){ tempLevelUpFee = levelUpFee*6/10; }else{ tempLevelUpFee = levelUpFee; } //discountGridsCount = discountGridsCount.add(1); currentPrice += tempLevelUpFee; //currentPrice += levelUpFee; } } } return currentPrice; } } pragma solidity ^0.5.0; import "./GridBase.sol"; import "./ERC721.sol"; import "./safemath.sol"; contract GridOwnership is ERC721, GridBase { using SafeMath for uint256; mapping (uint => address) gridApprovals; modifier onlyOwnerOf(uint _gridId) { require(msg.sender == arr_struct_grid[_gridId].owner, "you are not owner of this grid"); _; } function balanceOf(address _owner) public view returns (uint256 _balance) { return mappingOwnerGridCount[_owner]; } function ownerOf(uint256 _tokenId) public view returns (address _owner) { _owner = arr_struct_grid[_tokenId].owner; require(_owner != address(0), "address invalid"); } function _transfer(address _from, address payable _to, uint256 _tokenId) private { mappingOwnerGridCount[_to] = mappingOwnerGridCount[_to].add(1); mappingOwnerGridCount[msg.sender] = mappingOwnerGridCount[msg.sender].sub(1); arr_struct_grid[_tokenId].owner = _to; emit Transfer(_from, _to, _tokenId); } function transfer(address payable _to, uint256 _tokenId) external onlyOwnerOf(_tokenId) whenNotPaused { // Safety check to prevent against an unexpected 0x0 default. require(_to != address(0), "address invalid"); // Disallow transfers to this contract to prevent accidental misuse. // The contract should never own any kitties (except very briefly // after a gen0 cat is created and before it goes on auction). require(_to != address(this), "address invalid"); // Disallow transfers to the auction contracts to prevent accidental // misuse. Auction contracts should only take ownership of kitties // through the allow + transferFrom flow. //require(_to != address(saleAuction)); //require(_to != address(siringAuction)); _transfer(msg.sender, _to, _tokenId); } function approve(address payable _to, uint256 _tokenId) external onlyOwnerOf(_tokenId) whenNotPaused { gridApprovals[_tokenId] = _to; emit Approval(msg.sender, _to, _tokenId); } function takeOwnership(uint256 _tokenId) public { require(gridApprovals[_tokenId] == msg.sender, "you are not that guy"); address owner = ownerOf(_tokenId); _transfer(owner, msg.sender, _tokenId); } } pragma solidity ^0.5.11; /** * @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 payable public owner; event ContractOwnershipTransferred(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, "only owner"); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferContractOwnership(address payable newOwner) public onlyOwner { require(newOwner != address(0), "new owner can not be empty"); emit ContractOwnershipTransferred(owner, newOwner); owner = newOwner; } } 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. * * NOTE: This is a feature of the next version of OpenZeppelin Contracts. * @dev Get it via `npm install @openzeppelin/contracts@next`. */ 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. * NOTE: This is a feature of the next version of OpenZeppelin Contracts. * @dev Get it via `npm install @openzeppelin/contracts@next`. */ 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. * * NOTE: This is a feature of the next version of OpenZeppelin Contracts. * @dev Get it via `npm install @openzeppelin/contracts@next`. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } /** * @title SafeMath32 * @dev SafeMath library implemented for uint32 */ library SafeMath32 { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint32 a, uint32 b) internal pure returns (uint32) { uint32 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(uint32 a, uint32 b) internal pure returns (uint32) { 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. * * NOTE: This is a feature of the next version of OpenZeppelin Contracts. * @dev Get it via `npm install @openzeppelin/contracts@next`. */ function sub(uint32 a, uint32 b, string memory errorMessage) internal pure returns (uint32) { require(b <= a, errorMessage); uint32 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(uint32 a, uint32 b) internal pure returns (uint32) { // 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; } uint32 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(uint32 a, uint32 b) internal pure returns (uint32) { 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. * NOTE: This is a feature of the next version of OpenZeppelin Contracts. * @dev Get it via `npm install @openzeppelin/contracts@next`. */ function div(uint32 a, uint32 b, string memory errorMessage) internal pure returns (uint32) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint32 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(uint32 a, uint32 b) internal pure returns (uint32) { 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. * * NOTE: This is a feature of the next version of OpenZeppelin Contracts. * @dev Get it via `npm install @openzeppelin/contracts@next`. */ function mod(uint32 a, uint32 b, string memory errorMessage) internal pure returns (uint32) { require(b != 0, errorMessage); return a % b; } } /** * @title SafeMath16 * @dev SafeMath library implemented for uint16 */ library SafeMath16 { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint16 a, uint16 b) internal pure returns (uint16) { uint16 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(uint16 a, uint16 b) internal pure returns (uint16) { 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. * * NOTE: This is a feature of the next version of OpenZeppelin Contracts. * @dev Get it via `npm install @openzeppelin/contracts@next`. */ function sub(uint16 a, uint16 b, string memory errorMessage) internal pure returns (uint16) { require(b <= a, errorMessage); uint16 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(uint16 a, uint16 b) internal pure returns (uint16) { // 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; } uint16 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(uint16 a, uint16 b) internal pure returns (uint16) { 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. * NOTE: This is a feature of the next version of OpenZeppelin Contracts. * @dev Get it via `npm install @openzeppelin/contracts@next`. */ function div(uint16 a, uint16 b, string memory errorMessage) internal pure returns (uint16) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint16 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(uint16 a, uint16 b) internal pure returns (uint16) { 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. * * NOTE: This is a feature of the next version of OpenZeppelin Contracts. * @dev Get it via `npm install @openzeppelin/contracts@next`. */ function mod(uint16 a, uint16 b, string memory errorMessage) internal pure returns (uint16) { require(b != 0, errorMessage); return a % b; } } pragma solidity ^0.5.0; /// @title A facet of KittyCore that manages special access privileges. /// @author Axiom Zen (https://www.axiomzen.co) /// @dev See the KittyCore contract documentation to understand how the various contract facets are arranged. contract AccessControl { // This facet controls access control for CryptoKitties. There are four roles managed here: // // - The CEO: The CEO can reassign other roles and change the addresses of our dependent smart // contracts. It is also the only role that can unpause the smart contract. It is initially // set to the address that created the smart contract in the KittyCore constructor. // // - The CFO: The CFO can withdraw funds from KittyCore and its auction contracts. // // - The COO: The COO can release gen0 kitties to auction, and mint promo cats. // // It should be noted that these roles are distinct without overlap in their access abilities, the // abilities listed for each role above are exhaustive. In particular, while the CEO can assign any // address to any role, the CEO address itself doesn't have the ability to act in those roles. This // restriction is intentional so that we aren't tempted to use the CEO address frequently out of // convenience. The less we use an address, the less likely it is that we somehow compromise the // account. /// @dev Emited when contract is upgraded - See README.md for updgrade plan event ContractUpgrade(address newContract); // The addresses of the accounts (or contracts) that can execute actions within each roles. address public ceoAddress; address public cfoAddress; address public cooAddress; // @dev Keeps track whether the contract is paused. When that is true, most actions are blocked bool public paused = false; /// @dev Access modifier for CEO-only functionality modifier onlyCEO() { require(msg.sender == ceoAddress, "only CEO"); _; } /// @dev Access modifier for CFO-only functionality modifier onlyCFO() { require(msg.sender == cfoAddress, "only CFO"); _; } /// @dev Access modifier for COO-only functionality modifier onlyCOO() { require(msg.sender == cooAddress, "only COO"); _; } modifier onlyCLevel() { require( msg.sender == cooAddress || msg.sender == ceoAddress || msg.sender == cfoAddress, "only CLevel" ); _; } /// @dev Assigns a new address to act as the CEO. Only available to the current CEO. /// @param _newCEO The address of the new CEO function setCEO(address _newCEO) external onlyCEO { require(_newCEO != address(0), "newCEO looks like no changes"); ceoAddress = _newCEO; } /// @dev Assigns a new address to act as the CFO. Only available to the current CEO. /// @param _newCFO The address of the new CFO function setCFO(address _newCFO) external onlyCEO { require(_newCFO != address(0), "newCFO looks like no changes"); cfoAddress = _newCFO; } /// @dev Assigns a new address to act as the COO. Only available to the current CEO. /// @param _newCOO The address of the new COO function setCOO(address _newCOO) external onlyCEO { require(_newCOO != address(0), "newCOO looks like no changes"); cooAddress = _newCOO; } /*** Pausable functionality adapted from OpenZeppelin ***/ /// @dev Modifier to allow actions only when the contract IS NOT paused modifier whenNotPaused() { require(!paused, "current contract is paused"); _; } /// @dev Modifier to allow actions only when the contract IS paused modifier whenPaused { require(paused, "current contract is not paused"); _; } /// @dev Called by any "C-level" role to pause the contract. Used only when /// a bug or exploit is detected and we need to limit damage. function pause() external onlyCLevel whenNotPaused { paused = true; } /// @dev Unpauses the smart contract. Can only be called by the CEO, since /// one reason we may pause the contract is when CFO or COO accounts are /// compromised. /// @notice This is public rather than external so it can be called by /// derived contracts. function unpause() public onlyCEO whenPaused { // can't unpause if contract was upgraded paused = false; } } pragma solidity ^0.5.11; contract ERC721 { event Transfer(address indexed _from, address indexed _to, uint256 _tokenId); event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId); function balanceOf(address _owner) public view returns (uint256 _balance); function ownerOf(uint256 _tokenId) public view returns (address _owner); function transfer(address payable _to, uint256 _tokenId) external; function approve(address payable _to, uint256 _tokenId) external; function takeOwnership(uint256 _tokenId) public; } pragma solidity ^0.5.11; import "./ownable.sol"; import "./AccessControl.sol"; //import "./GridOwnership.sol"; //import "./safemath.sol"; //import "./console.sol"; contract GridBase is Ownable, AccessControl { //using SafeMath for uint256; uint public levelUpFee = 0.01 ether; uint public limitGridsEachtime = 100; uint public discountGridsCount = 0; //uint fee; struct structGird { uint16 x; uint16 y; uint level; address payable owner; address payable inviter; } structGird[] public arr_struct_grid; mapping (address => uint) public mappingOwnerGridCount; mapping (uint16 => uint) public mappingPositionToGirdId; // Set in case the core contract is broken and an upgrade is required address public newContractAddress; address payable public authorAddress; address payable public foundationAddress; /// @notice Creates the main CryptoKitties smart contract instance. constructor () public { // Starts paused. paused = true; // the creator of the contract is the initial CEO ceoAddress = msg.sender; // the creator of the contract is also the initial COO cooAddress = msg.sender; cfoAddress = msg.sender; } /// @dev Used to mark the smart contract as upgraded, in case there is a serious /// breaking bug. This method does nothing but keep track of the new contract and /// emit a message indicating that the new address is set. It's up to clients of this /// contract to update to the new contract address in that case. (This contract will /// be paused indefinitely if such an upgrade takes place.) /// @param _v2Address new address function setNewContractAddress(address _v2Address) external onlyCEO whenPaused { // See README.md for updgrade plan newContractAddress = _v2Address; emit ContractUpgrade(_v2Address); } function setAuthorAddress(address payable _address) external onlyCEO whenPaused { require(_address != address(0), "authorAddress can not be empty"); authorAddress = _address; } function setFoundationAddress(address payable _address) external onlyCEO whenPaused { require(_address != address(0), "foundationAddress can not be empty"); foundationAddress = _address; } /*/// @notice Returns all the relevant information about a specific kitty. /// @param _id The ID of the kitty of interest. function getGrid(uint256 _id) external view returns ( uint16 x, uint16 y, uint256 level ) { structGird memory _grid = arr_struct_grid[_id]; x = uint16(_grid.x); y = uint16(_grid.y); level = uint256(_grid.level); }*/ /// @dev Override unpause so it requires all external contract addresses /// to be set before contract can be unpaused. Also, we can't have /// newContractAddress set either, because then the contract was upgraded. /// @notice This is public rather than external so we can call super.unpause /// without using an expensive CALL. function unpause() public onlyCEO whenPaused { require(newContractAddress == address(0), "set newContractAddress first"); require(authorAddress != address(0), "set authorAddress first"); require(foundationAddress != address(0), "set foundationAddress first"); // Actually unpause the contract. super.unpause(); } function withdraw() external onlyOwner whenPaused { owner.transfer(address(this).balance); } function setLevelUpFee(uint _fee) external onlyCLevel whenPaused { levelUpFee = _fee; } function setlimitGridsEachtime(uint _limit) external onlyCLevel whenPaused { limitGridsEachtime = _limit; } function getContractStatus() external view onlyCLevel returns(uint, uint, uint) { return (levelUpFee, limitGridsEachtime, address(this).balance); } function getLevelUpFee() external view whenNotPaused returns(uint) { return levelUpFee; } function getLimitGridsEachtime() external view whenNotPaused returns(uint) { return limitGridsEachtime; } function getContractBalance() external view onlyCLevel returns(uint) { return address(this).balance; } } pragma solidity ^0.5.11; import "./GridOwnership.sol"; import "./safemath.sol"; //import "./console.sol"; contract GridMain is GridOwnership { using SafeMath for uint256; using SafeMath32 for uint32; using SafeMath16 for uint16; //uint16 public version = 101; function buyGird(uint16 _i, uint16 _j, uint16 _k, uint16 _l, address payable _inviter) external payable whenNotPaused { require(_i >= 1 && _i <= 100, "value invalid"); require(_j >= 1 && _j <= 100, "value invalid"); require(_k >= _i && _k <= 100, "value invalid"); require(_l >= _j && _l <= 100, "value invalid"); //require(_k >= _i && _l >= _j, "value invalid"); require((_k-_i+1)*(_l-_j+1) <= limitGridsEachtime, "too many grids you selected, that may cause problems."); uint16 _x; uint16 _y; //string memory position; uint16 position; uint256 currentPrice = 0; uint256 gridId = 0; uint256 tempLevelUpFee = 0; address payable inviter; if(_inviter == address(0)){ inviter = owner; }else{ inviter = _inviter; } //log("mappingPositionToGirdId[position]: ", mappingPositionToGirdId[position]); //log("arr_struct_grid[1].level: ", arr_struct_grid[1].level); //log("msg.value: ", msg.value); //uint fee = msg.value; //address acc = msg.sender; for(_x = _i; _x<=_k; _x++){ for(_y = _j; _y<=_l; _y++){ //position = strConcat(uint2str(_x),uint2str(_y)); //log("position: ", position); position = (_x-1)*100+_y; gridId = mappingPositionToGirdId[position]; if(gridId > 0){ structGird storage _grid = arr_struct_grid[gridId-1]; //if(_grid.level > 0){ //uint16 id = arr_struct_grid.push(structGird(_x, _y, 1)) - 1; //mappingPositionToOwner[position] = msg.sender; currentPrice += _grid.level * levelUpFee + levelUpFee; _grid.owner.transfer(_grid.level * levelUpFee + levelUpFee / 5); _grid.inviter.transfer(levelUpFee / 10); authorAddress.transfer(levelUpFee / 10); foundationAddress.transfer(levelUpFee / 10); owner.transfer(levelUpFee/50); mappingOwnerGridCount[_grid.owner] = mappingOwnerGridCount[_grid.owner].sub(1); mappingOwnerGridCount[msg.sender] = mappingOwnerGridCount[msg.sender].add(1); _grid.level = _grid.level.add(1); _grid.owner = msg.sender; if(_grid.inviter != inviter){ _grid.inviter = inviter; } //} }else{ //uint16 id = arr_struct_grid.push(structGird(_x, _y, 1)) - 1; //mappingGirdPositionToOwner[position] = msg.sender; //tempLevelUpFee = levelUpFee; if(discountGridsCount < 1000){ //currentPrice += levelUpFee; }else if(discountGridsCount < 3000){ tempLevelUpFee = levelUpFee*1/10; }else if(discountGridsCount < 6000){ tempLevelUpFee = levelUpFee*3/10; }else if(discountGridsCount < 10000){ tempLevelUpFee = levelUpFee*6/10; }else{ tempLevelUpFee = levelUpFee; } discountGridsCount = discountGridsCount.add(1); currentPrice += tempLevelUpFee; uint id = arr_struct_grid.push(structGird(_x, _y, 1, msg.sender, inviter)); mappingPositionToGirdId[position] = id; mappingOwnerGridCount[msg.sender] = mappingOwnerGridCount[msg.sender].add(1); owner.transfer(tempLevelUpFee); } } } require(msg.value >= currentPrice, "out of your balance"); //require(address(this).balance >= currentPrice, "out of contract balance, please buy level0 grids"); /*for(_x = _i; _x<=_k; _x++){ for(_y = _j; _y<=_l; _y++){ //position = strConcat(uint2str(_x),uint2str(_y)); position = (_x-1)*100+_y; gridId = mappingPositionToGirdId[position]; if(gridId > 0){ structGird memory _grid = arr_struct_grid[gridId-1]; //&& _grid.level > 0){ //uint16 id = arr_struct_grid.push(structGird(_x, _y, 1)) - 1; //mappingPositionToOwner[position] = msg.sender; //mappingPositionToGird[position].level = mappingPositionToGird[position].level.add(1); //mappingPositionToGird[position].owner = msg.sender; _grid.owner.transfer(_grid.level * levelUpFee + levelUpFee / 5); _grid.inviter.transfer(levelUpFee / 10); authorAddress.transfer(levelUpFee / 10); foundationAddress.transfer(levelUpFee / 10); owner.transfer(levelUpFee/50); mappingOwnerGridCount[_grid.owner] = mappingOwnerGridCount[_grid.owner].sub(1); mappingOwnerGridCount[msg.sender] = mappingOwnerGridCount[msg.sender].add(1); _grid.level = _grid.level.add(1); _grid.owner = msg.sender; _grid.inviter = inviter; }else{ uint id = arr_struct_grid.push(structGird(_x, _y, 1, msg.sender, inviter)); mappingPositionToGirdId[position] = id; mappingOwnerGridCount[msg.sender] = mappingOwnerGridCount[msg.sender].add(1); owner.transfer(levelUpFee); //mappingGirdPositionToOwner[position] = msg.sender; //mappingPositionToGird[position] = structGird(_x, _y, 1, msg.sender); } } }*/ msg.sender.transfer(msg.value.sub(currentPrice)); } function getGridPrice(uint16 _i, uint16 _j, uint16 _k, uint16 _l) external view whenNotPaused returns(uint256){ require(_i >= 1 && _i <= 100, "value invalid"); require(_j >= 1 && _j <= 100, "value invalid"); require(_k >= _i && _k <= 100, "value invalid"); require(_l >= _j && _l <= 100, "value invalid"); //require(_k >= _i && _l >= _j, "value invalid"); require((_k-_i+1)*(_l-_j+1) <= limitGridsEachtime, "too many grids you selected, that may cause problems."); uint16 _x; uint16 _y; //string memory position; uint16 position; //log("mappingPositionToGirdId[position]: ", mappingPositionToGirdId[position]); //log("arr_struct_grid[1].level: ", arr_struct_grid[1].level); //log("msg.value: ", msg.value); //uint fee = msg.value; //address acc = msg.sender; uint256 currentPrice = 0; uint256 gridId = 0; uint256 tempLevelUpFee = 0; for(_x = _i; _x<=_k; _x++){ for(_y = _j; _y<=_l; _y++){ //position = strConcat(uint2str(_x),uint2str(_y)); //log("position: ", position); position = (_x-1)*100+_y; gridId = mappingPositionToGirdId[position]; if(gridId > 0){ structGird memory _grid = arr_struct_grid[gridId-1]; //if(_grid.level > 0){ //uint16 id = arr_struct_grid.push(structGird(_x, _y, 1)) - 1; //mappingPositionToOwner[position] = msg.sender; currentPrice += _grid.level * levelUpFee + levelUpFee; //} }else{ //uint16 id = arr_struct_grid.push(structGird(_x, _y, 1)) - 1; //mappingGirdPositionToOwner[position] = msg.sender; if(discountGridsCount < 1000){ //currentPrice += levelUpFee; }else if(discountGridsCount < 3000){ tempLevelUpFee = levelUpFee*1/10; }else if(discountGridsCount < 6000){ tempLevelUpFee = levelUpFee*3/10; }else if(discountGridsCount < 10000){ tempLevelUpFee = levelUpFee*6/10; }else{ tempLevelUpFee = levelUpFee; } //discountGridsCount = discountGridsCount.add(1); currentPrice += tempLevelUpFee; //currentPrice += levelUpFee; } } } return currentPrice; } } pragma solidity ^0.5.0; import "./GridBase.sol"; import "./ERC721.sol"; import "./safemath.sol"; contract GridOwnership is ERC721, GridBase { using SafeMath for uint256; mapping (uint => address) gridApprovals; modifier onlyOwnerOf(uint _gridId) { require(msg.sender == arr_struct_grid[_gridId].owner, "you are not owner of this grid"); _; } function balanceOf(address _owner) public view returns (uint256 _balance) { return mappingOwnerGridCount[_owner]; } function ownerOf(uint256 _tokenId) public view returns (address _owner) { _owner = arr_struct_grid[_tokenId].owner; require(_owner != address(0), "address invalid"); } function _transfer(address _from, address payable _to, uint256 _tokenId) private { mappingOwnerGridCount[_to] = mappingOwnerGridCount[_to].add(1); mappingOwnerGridCount[msg.sender] = mappingOwnerGridCount[msg.sender].sub(1); arr_struct_grid[_tokenId].owner = _to; emit Transfer(_from, _to, _tokenId); } function transfer(address payable _to, uint256 _tokenId) external onlyOwnerOf(_tokenId) whenNotPaused { // Safety check to prevent against an unexpected 0x0 default. require(_to != address(0), "address invalid"); // Disallow transfers to this contract to prevent accidental misuse. // The contract should never own any kitties (except very briefly // after a gen0 cat is created and before it goes on auction). require(_to != address(this), "address invalid"); // Disallow transfers to the auction contracts to prevent accidental // misuse. Auction contracts should only take ownership of kitties // through the allow + transferFrom flow. //require(_to != address(saleAuction)); //require(_to != address(siringAuction)); _transfer(msg.sender, _to, _tokenId); } function approve(address payable _to, uint256 _tokenId) external onlyOwnerOf(_tokenId) whenNotPaused { gridApprovals[_tokenId] = _to; emit Approval(msg.sender, _to, _tokenId); } function takeOwnership(uint256 _tokenId) public { require(gridApprovals[_tokenId] == msg.sender, "you are not that guy"); address owner = ownerOf(_tokenId); _transfer(owner, msg.sender, _tokenId); } } pragma solidity ^0.5.11; /** * @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 payable public owner; event ContractOwnershipTransferred(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, "only owner"); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferContractOwnership(address payable newOwner) public onlyOwner { require(newOwner != address(0), "new owner can not be empty"); emit ContractOwnershipTransferred(owner, newOwner); owner = newOwner; } } 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. * * NOTE: This is a feature of the next version of OpenZeppelin Contracts. * @dev Get it via `npm install @openzeppelin/contracts@next`. */ 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. * NOTE: This is a feature of the next version of OpenZeppelin Contracts. * @dev Get it via `npm install @openzeppelin/contracts@next`. */ 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. * * NOTE: This is a feature of the next version of OpenZeppelin Contracts. * @dev Get it via `npm install @openzeppelin/contracts@next`. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } /** * @title SafeMath32 * @dev SafeMath library implemented for uint32 */ library SafeMath32 { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint32 a, uint32 b) internal pure returns (uint32) { uint32 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(uint32 a, uint32 b) internal pure returns (uint32) { 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. * * NOTE: This is a feature of the next version of OpenZeppelin Contracts. * @dev Get it via `npm install @openzeppelin/contracts@next`. */ function sub(uint32 a, uint32 b, string memory errorMessage) internal pure returns (uint32) { require(b <= a, errorMessage); uint32 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(uint32 a, uint32 b) internal pure returns (uint32) { // 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; } uint32 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(uint32 a, uint32 b) internal pure returns (uint32) { 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. * NOTE: This is a feature of the next version of OpenZeppelin Contracts. * @dev Get it via `npm install @openzeppelin/contracts@next`. */ function div(uint32 a, uint32 b, string memory errorMessage) internal pure returns (uint32) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint32 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(uint32 a, uint32 b) internal pure returns (uint32) { 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. * * NOTE: This is a feature of the next version of OpenZeppelin Contracts. * @dev Get it via `npm install @openzeppelin/contracts@next`. */ function mod(uint32 a, uint32 b, string memory errorMessage) internal pure returns (uint32) { require(b != 0, errorMessage); return a % b; } } /** * @title SafeMath16 * @dev SafeMath library implemented for uint16 */ library SafeMath16 { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint16 a, uint16 b) internal pure returns (uint16) { uint16 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(uint16 a, uint16 b) internal pure returns (uint16) { 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. * * NOTE: This is a feature of the next version of OpenZeppelin Contracts. * @dev Get it via `npm install @openzeppelin/contracts@next`. */ function sub(uint16 a, uint16 b, string memory errorMessage) internal pure returns (uint16) { require(b <= a, errorMessage); uint16 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(uint16 a, uint16 b) internal pure returns (uint16) { // 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; } uint16 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(uint16 a, uint16 b) internal pure returns (uint16) { 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. * NOTE: This is a feature of the next version of OpenZeppelin Contracts. * @dev Get it via `npm install @openzeppelin/contracts@next`. */ function div(uint16 a, uint16 b, string memory errorMessage) internal pure returns (uint16) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint16 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(uint16 a, uint16 b) internal pure returns (uint16) { 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. * * NOTE: This is a feature of the next version of OpenZeppelin Contracts. * @dev Get it via `npm install @openzeppelin/contracts@next`. */ function mod(uint16 a, uint16 b, string memory errorMessage) internal pure returns (uint16) { require(b != 0, errorMessage); return a % b; } } pragma solidity ^0.5.0; /// @title A facet of KittyCore that manages special access privileges. /// @author Axiom Zen (https://www.axiomzen.co) /// @dev See the KittyCore contract documentation to understand how the various contract facets are arranged. contract AccessControl { // This facet controls access control for CryptoKitties. There are four roles managed here: // // - The CEO: The CEO can reassign other roles and change the addresses of our dependent smart // contracts. It is also the only role that can unpause the smart contract. It is initially // set to the address that created the smart contract in the KittyCore constructor. // // - The CFO: The CFO can withdraw funds from KittyCore and its auction contracts. // // - The COO: The COO can release gen0 kitties to auction, and mint promo cats. // // It should be noted that these roles are distinct without overlap in their access abilities, the // abilities listed for each role above are exhaustive. In particular, while the CEO can assign any // address to any role, the CEO address itself doesn't have the ability to act in those roles. This // restriction is intentional so that we aren't tempted to use the CEO address frequently out of // convenience. The less we use an address, the less likely it is that we somehow compromise the // account. /// @dev Emited when contract is upgraded - See README.md for updgrade plan event ContractUpgrade(address newContract); // The addresses of the accounts (or contracts) that can execute actions within each roles. address public ceoAddress; address public cfoAddress; address public cooAddress; // @dev Keeps track whether the contract is paused. When that is true, most actions are blocked bool public paused = false; /// @dev Access modifier for CEO-only functionality modifier onlyCEO() { require(msg.sender == ceoAddress, "only CEO"); _; } /// @dev Access modifier for CFO-only functionality modifier onlyCFO() { require(msg.sender == cfoAddress, "only CFO"); _; } /// @dev Access modifier for COO-only functionality modifier onlyCOO() { require(msg.sender == cooAddress, "only COO"); _; } modifier onlyCLevel() { require( msg.sender == cooAddress || msg.sender == ceoAddress || msg.sender == cfoAddress, "only CLevel" ); _; } /// @dev Assigns a new address to act as the CEO. Only available to the current CEO. /// @param _newCEO The address of the new CEO function setCEO(address _newCEO) external onlyCEO { require(_newCEO != address(0), "newCEO looks like no changes"); ceoAddress = _newCEO; } /// @dev Assigns a new address to act as the CFO. Only available to the current CEO. /// @param _newCFO The address of the new CFO function setCFO(address _newCFO) external onlyCEO { require(_newCFO != address(0), "newCFO looks like no changes"); cfoAddress = _newCFO; } /// @dev Assigns a new address to act as the COO. Only available to the current CEO. /// @param _newCOO The address of the new COO function setCOO(address _newCOO) external onlyCEO { require(_newCOO != address(0), "newCOO looks like no changes"); cooAddress = _newCOO; } /*** Pausable functionality adapted from OpenZeppelin ***/ /// @dev Modifier to allow actions only when the contract IS NOT paused modifier whenNotPaused() { require(!paused, "current contract is paused"); _; } /// @dev Modifier to allow actions only when the contract IS paused modifier whenPaused { require(paused, "current contract is not paused"); _; } /// @dev Called by any "C-level" role to pause the contract. Used only when /// a bug or exploit is detected and we need to limit damage. function pause() external onlyCLevel whenNotPaused { paused = true; } /// @dev Unpauses the smart contract. Can only be called by the CEO, since /// one reason we may pause the contract is when CFO or COO accounts are /// compromised. /// @notice This is public rather than external so it can be called by /// derived contracts. function unpause() public onlyCEO whenPaused { // can't unpause if contract was upgraded paused = false; } } pragma solidity ^0.5.11; contract ERC721 { event Transfer(address indexed _from, address indexed _to, uint256 _tokenId); event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId); function balanceOf(address _owner) public view returns (uint256 _balance); function ownerOf(uint256 _tokenId) public view returns (address _owner); function transfer(address payable _to, uint256 _tokenId) external; function approve(address payable _to, uint256 _tokenId) external; function takeOwnership(uint256 _tokenId) public; } pragma solidity ^0.5.11; import "./ownable.sol"; import "./AccessControl.sol"; //import "./GridOwnership.sol"; //import "./safemath.sol"; //import "./console.sol"; contract GridBase is Ownable, AccessControl { //using SafeMath for uint256; uint public levelUpFee = 0.01 ether; uint public limitGridsEachtime = 100; uint public discountGridsCount = 0; //uint fee; struct structGird { uint16 x; uint16 y; uint level; address payable owner; address payable inviter; } structGird[] public arr_struct_grid; mapping (address => uint) public mappingOwnerGridCount; mapping (uint16 => uint) public mappingPositionToGirdId; // Set in case the core contract is broken and an upgrade is required address public newContractAddress; address payable public authorAddress; address payable public foundationAddress; /// @notice Creates the main CryptoKitties smart contract instance. constructor () public { // Starts paused. paused = true; // the creator of the contract is the initial CEO ceoAddress = msg.sender; // the creator of the contract is also the initial COO cooAddress = msg.sender; cfoAddress = msg.sender; } /// @dev Used to mark the smart contract as upgraded, in case there is a serious /// breaking bug. This method does nothing but keep track of the new contract and /// emit a message indicating that the new address is set. It's up to clients of this /// contract to update to the new contract address in that case. (This contract will /// be paused indefinitely if such an upgrade takes place.) /// @param _v2Address new address function setNewContractAddress(address _v2Address) external onlyCEO whenPaused { // See README.md for updgrade plan newContractAddress = _v2Address; emit ContractUpgrade(_v2Address); } function setAuthorAddress(address payable _address) external onlyCEO whenPaused { require(_address != address(0), "authorAddress can not be empty"); authorAddress = _address; } function setFoundationAddress(address payable _address) external onlyCEO whenPaused { require(_address != address(0), "foundationAddress can not be empty"); foundationAddress = _address; } /*/// @notice Returns all the relevant information about a specific kitty. /// @param _id The ID of the kitty of interest. function getGrid(uint256 _id) external view returns ( uint16 x, uint16 y, uint256 level ) { structGird memory _grid = arr_struct_grid[_id]; x = uint16(_grid.x); y = uint16(_grid.y); level = uint256(_grid.level); }*/ /// @dev Override unpause so it requires all external contract addresses /// to be set before contract can be unpaused. Also, we can't have /// newContractAddress set either, because then the contract was upgraded. /// @notice This is public rather than external so we can call super.unpause /// without using an expensive CALL. function unpause() public onlyCEO whenPaused { require(newContractAddress == address(0), "set newContractAddress first"); require(authorAddress != address(0), "set authorAddress first"); require(foundationAddress != address(0), "set foundationAddress first"); // Actually unpause the contract. super.unpause(); } function withdraw() external onlyOwner whenPaused { owner.transfer(address(this).balance); } function setLevelUpFee(uint _fee) external onlyCLevel whenPaused { levelUpFee = _fee; } function setlimitGridsEachtime(uint _limit) external onlyCLevel whenPaused { limitGridsEachtime = _limit; } function getContractStatus() external view onlyCLevel returns(uint, uint, uint) { return (levelUpFee, limitGridsEachtime, address(this).balance); } function getLevelUpFee() external view whenNotPaused returns(uint) { return levelUpFee; } function getLimitGridsEachtime() external view whenNotPaused returns(uint) { return limitGridsEachtime; } function getContractBalance() external view onlyCLevel returns(uint) { return address(this).balance; } } pragma solidity ^0.5.11; import "./GridOwnership.sol"; import "./safemath.sol"; //import "./console.sol"; contract GridMain is GridOwnership { using SafeMath for uint256; using SafeMath32 for uint32; using SafeMath16 for uint16; //uint16 public version = 101; function buyGird(uint16 _i, uint16 _j, uint16 _k, uint16 _l, address payable _inviter) external payable whenNotPaused { require(_i >= 1 && _i <= 100, "value invalid"); require(_j >= 1 && _j <= 100, "value invalid"); require(_k >= _i && _k <= 100, "value invalid"); require(_l >= _j && _l <= 100, "value invalid"); //require(_k >= _i && _l >= _j, "value invalid"); require((_k-_i+1)*(_l-_j+1) <= limitGridsEachtime, "too many grids you selected, that may cause problems."); uint16 _x; uint16 _y; //string memory position; uint16 position; uint256 currentPrice = 0; uint256 gridId = 0; uint256 tempLevelUpFee = 0; address payable inviter; if(_inviter == address(0)){ inviter = owner; }else{ inviter = _inviter; } //log("mappingPositionToGirdId[position]: ", mappingPositionToGirdId[position]); //log("arr_struct_grid[1].level: ", arr_struct_grid[1].level); //log("msg.value: ", msg.value); //uint fee = msg.value; //address acc = msg.sender; for(_x = _i; _x<=_k; _x++){ for(_y = _j; _y<=_l; _y++){ //position = strConcat(uint2str(_x),uint2str(_y)); //log("position: ", position); position = (_x-1)*100+_y; gridId = mappingPositionToGirdId[position]; if(gridId > 0){ structGird storage _grid = arr_struct_grid[gridId-1]; //if(_grid.level > 0){ //uint16 id = arr_struct_grid.push(structGird(_x, _y, 1)) - 1; //mappingPositionToOwner[position] = msg.sender; currentPrice += _grid.level * levelUpFee + levelUpFee; _grid.owner.transfer(_grid.level * levelUpFee + levelUpFee / 5); _grid.inviter.transfer(levelUpFee / 10); authorAddress.transfer(levelUpFee / 10); foundationAddress.transfer(levelUpFee / 10); owner.transfer(levelUpFee/50); mappingOwnerGridCount[_grid.owner] = mappingOwnerGridCount[_grid.owner].sub(1); mappingOwnerGridCount[msg.sender] = mappingOwnerGridCount[msg.sender].add(1); _grid.level = _grid.level.add(1); _grid.owner = msg.sender; if(_grid.inviter != inviter){ _grid.inviter = inviter; } //} }else{ //uint16 id = arr_struct_grid.push(structGird(_x, _y, 1)) - 1; //mappingGirdPositionToOwner[position] = msg.sender; //tempLevelUpFee = levelUpFee; if(discountGridsCount < 1000){ //currentPrice += levelUpFee; }else if(discountGridsCount < 3000){ tempLevelUpFee = levelUpFee*1/10; }else if(discountGridsCount < 6000){ tempLevelUpFee = levelUpFee*3/10; }else if(discountGridsCount < 10000){ tempLevelUpFee = levelUpFee*6/10; }else{ tempLevelUpFee = levelUpFee; } discountGridsCount = discountGridsCount.add(1); currentPrice += tempLevelUpFee; uint id = arr_struct_grid.push(structGird(_x, _y, 1, msg.sender, inviter)); mappingPositionToGirdId[position] = id; mappingOwnerGridCount[msg.sender] = mappingOwnerGridCount[msg.sender].add(1); owner.transfer(tempLevelUpFee); } } } require(msg.value >= currentPrice, "out of your balance"); //require(address(this).balance >= currentPrice, "out of contract balance, please buy level0 grids"); /*for(_x = _i; _x<=_k; _x++){ for(_y = _j; _y<=_l; _y++){ //position = strConcat(uint2str(_x),uint2str(_y)); position = (_x-1)*100+_y; gridId = mappingPositionToGirdId[position]; if(gridId > 0){ structGird memory _grid = arr_struct_grid[gridId-1]; //&& _grid.level > 0){ //uint16 id = arr_struct_grid.push(structGird(_x, _y, 1)) - 1; //mappingPositionToOwner[position] = msg.sender; //mappingPositionToGird[position].level = mappingPositionToGird[position].level.add(1); //mappingPositionToGird[position].owner = msg.sender; _grid.owner.transfer(_grid.level * levelUpFee + levelUpFee / 5); _grid.inviter.transfer(levelUpFee / 10); authorAddress.transfer(levelUpFee / 10); foundationAddress.transfer(levelUpFee / 10); owner.transfer(levelUpFee/50); mappingOwnerGridCount[_grid.owner] = mappingOwnerGridCount[_grid.owner].sub(1); mappingOwnerGridCount[msg.sender] = mappingOwnerGridCount[msg.sender].add(1); _grid.level = _grid.level.add(1); _grid.owner = msg.sender; _grid.inviter = inviter; }else{ uint id = arr_struct_grid.push(structGird(_x, _y, 1, msg.sender, inviter)); mappingPositionToGirdId[position] = id; mappingOwnerGridCount[msg.sender] = mappingOwnerGridCount[msg.sender].add(1); owner.transfer(levelUpFee); //mappingGirdPositionToOwner[position] = msg.sender; //mappingPositionToGird[position] = structGird(_x, _y, 1, msg.sender); } } }*/ msg.sender.transfer(msg.value.sub(currentPrice)); } function getGridPrice(uint16 _i, uint16 _j, uint16 _k, uint16 _l) external view whenNotPaused returns(uint256){ require(_i >= 1 && _i <= 100, "value invalid"); require(_j >= 1 && _j <= 100, "value invalid"); require(_k >= _i && _k <= 100, "value invalid"); require(_l >= _j && _l <= 100, "value invalid"); //require(_k >= _i && _l >= _j, "value invalid"); require((_k-_i+1)*(_l-_j+1) <= limitGridsEachtime, "too many grids you selected, that may cause problems."); uint16 _x; uint16 _y; //string memory position; uint16 position; //log("mappingPositionToGirdId[position]: ", mappingPositionToGirdId[position]); //log("arr_struct_grid[1].level: ", arr_struct_grid[1].level); //log("msg.value: ", msg.value); //uint fee = msg.value; //address acc = msg.sender; uint256 currentPrice = 0; uint256 gridId = 0; uint256 tempLevelUpFee = 0; for(_x = _i; _x<=_k; _x++){ for(_y = _j; _y<=_l; _y++){ //position = strConcat(uint2str(_x),uint2str(_y)); //log("position: ", position); position = (_x-1)*100+_y; gridId = mappingPositionToGirdId[position]; if(gridId > 0){ structGird memory _grid = arr_struct_grid[gridId-1]; //if(_grid.level > 0){ //uint16 id = arr_struct_grid.push(structGird(_x, _y, 1)) - 1; //mappingPositionToOwner[position] = msg.sender; currentPrice += _grid.level * levelUpFee + levelUpFee; //} }else{ //uint16 id = arr_struct_grid.push(structGird(_x, _y, 1)) - 1; //mappingGirdPositionToOwner[position] = msg.sender; if(discountGridsCount < 1000){ //currentPrice += levelUpFee; }else if(discountGridsCount < 3000){ tempLevelUpFee = levelUpFee*1/10; }else if(discountGridsCount < 6000){ tempLevelUpFee = levelUpFee*3/10; }else if(discountGridsCount < 10000){ tempLevelUpFee = levelUpFee*6/10; }else{ tempLevelUpFee = levelUpFee; } //discountGridsCount = discountGridsCount.add(1); currentPrice += tempLevelUpFee; //currentPrice += levelUpFee; } } } return currentPrice; } } pragma solidity ^0.5.0; import "./GridBase.sol"; import "./ERC721.sol"; import "./safemath.sol"; contract GridOwnership is ERC721, GridBase { using SafeMath for uint256; mapping (uint => address) gridApprovals; modifier onlyOwnerOf(uint _gridId) { require(msg.sender == arr_struct_grid[_gridId].owner, "you are not owner of this grid"); _; } function balanceOf(address _owner) public view returns (uint256 _balance) { return mappingOwnerGridCount[_owner]; } function ownerOf(uint256 _tokenId) public view returns (address _owner) { _owner = arr_struct_grid[_tokenId].owner; require(_owner != address(0), "address invalid"); } function _transfer(address _from, address payable _to, uint256 _tokenId) private { mappingOwnerGridCount[_to] = mappingOwnerGridCount[_to].add(1); mappingOwnerGridCount[msg.sender] = mappingOwnerGridCount[msg.sender].sub(1); arr_struct_grid[_tokenId].owner = _to; emit Transfer(_from, _to, _tokenId); } function transfer(address payable _to, uint256 _tokenId) external onlyOwnerOf(_tokenId) whenNotPaused { // Safety check to prevent against an unexpected 0x0 default. require(_to != address(0), "address invalid"); // Disallow transfers to this contract to prevent accidental misuse. // The contract should never own any kitties (except very briefly // after a gen0 cat is created and before it goes on auction). require(_to != address(this), "address invalid"); // Disallow transfers to the auction contracts to prevent accidental // misuse. Auction contracts should only take ownership of kitties // through the allow + transferFrom flow. //require(_to != address(saleAuction)); //require(_to != address(siringAuction)); _transfer(msg.sender, _to, _tokenId); } function approve(address payable _to, uint256 _tokenId) external onlyOwnerOf(_tokenId) whenNotPaused { gridApprovals[_tokenId] = _to; emit Approval(msg.sender, _to, _tokenId); } function takeOwnership(uint256 _tokenId) public { require(gridApprovals[_tokenId] == msg.sender, "you are not that guy"); address owner = ownerOf(_tokenId); _transfer(owner, msg.sender, _tokenId); } } pragma solidity ^0.5.11; /** * @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 payable public owner; event ContractOwnershipTransferred(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, "only owner"); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferContractOwnership(address payable newOwner) public onlyOwner { require(newOwner != address(0), "new owner can not be empty"); emit ContractOwnershipTransferred(owner, newOwner); owner = newOwner; } } 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. * * NOTE: This is a feature of the next version of OpenZeppelin Contracts. * @dev Get it via `npm install @openzeppelin/contracts@next`. */ 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. * NOTE: This is a feature of the next version of OpenZeppelin Contracts. * @dev Get it via `npm install @openzeppelin/contracts@next`. */ 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. * * NOTE: This is a feature of the next version of OpenZeppelin Contracts. * @dev Get it via `npm install @openzeppelin/contracts@next`. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } /** * @title SafeMath32 * @dev SafeMath library implemented for uint32 */ library SafeMath32 { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint32 a, uint32 b) internal pure returns (uint32) { uint32 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(uint32 a, uint32 b) internal pure returns (uint32) { 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. * * NOTE: This is a feature of the next version of OpenZeppelin Contracts. * @dev Get it via `npm install @openzeppelin/contracts@next`. */ function sub(uint32 a, uint32 b, string memory errorMessage) internal pure returns (uint32) { require(b <= a, errorMessage); uint32 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(uint32 a, uint32 b) internal pure returns (uint32) { // 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; } uint32 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(uint32 a, uint32 b) internal pure returns (uint32) { 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. * NOTE: This is a feature of the next version of OpenZeppelin Contracts. * @dev Get it via `npm install @openzeppelin/contracts@next`. */ function div(uint32 a, uint32 b, string memory errorMessage) internal pure returns (uint32) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint32 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(uint32 a, uint32 b) internal pure returns (uint32) { 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. * * NOTE: This is a feature of the next version of OpenZeppelin Contracts. * @dev Get it via `npm install @openzeppelin/contracts@next`. */ function mod(uint32 a, uint32 b, string memory errorMessage) internal pure returns (uint32) { require(b != 0, errorMessage); return a % b; } } /** * @title SafeMath16 * @dev SafeMath library implemented for uint16 */ library SafeMath16 { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint16 a, uint16 b) internal pure returns (uint16) { uint16 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(uint16 a, uint16 b) internal pure returns (uint16) { 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. * * NOTE: This is a feature of the next version of OpenZeppelin Contracts. * @dev Get it via `npm install @openzeppelin/contracts@next`. */ function sub(uint16 a, uint16 b, string memory errorMessage) internal pure returns (uint16) { require(b <= a, errorMessage); uint16 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(uint16 a, uint16 b) internal pure returns (uint16) { // 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; } uint16 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(uint16 a, uint16 b) internal pure returns (uint16) { 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. * NOTE: This is a feature of the next version of OpenZeppelin Contracts. * @dev Get it via `npm install @openzeppelin/contracts@next`. */ function div(uint16 a, uint16 b, string memory errorMessage) internal pure returns (uint16) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint16 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(uint16 a, uint16 b) internal pure returns (uint16) { 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. * * NOTE: This is a feature of the next version of OpenZeppelin Contracts. * @dev Get it via `npm install @openzeppelin/contracts@next`. */ function mod(uint16 a, uint16 b, string memory errorMessage) internal pure returns (uint16) { require(b != 0, errorMessage); return a % b; } }
* @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(uint32 a, uint32 b) internal pure returns (uint32) { return mod(a, b, "SafeMath: modulo by zero"); }
15,817,559
[ 1, 1356, 326, 10022, 434, 3739, 10415, 2795, 9088, 12321, 18, 261, 22297, 3571, 26109, 3631, 868, 31537, 1347, 3739, 10415, 635, 3634, 18, 9354, 2680, 358, 348, 7953, 560, 1807, 12430, 68, 3726, 18, 1220, 445, 4692, 279, 1375, 266, 1097, 68, 11396, 261, 12784, 15559, 4463, 16189, 640, 869, 19370, 13, 1323, 348, 7953, 560, 4692, 392, 2057, 11396, 358, 15226, 261, 17664, 310, 777, 4463, 16189, 2934, 29076, 30, 300, 1021, 15013, 2780, 506, 3634, 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, 565, 445, 681, 12, 11890, 1578, 279, 16, 2254, 1578, 324, 13, 2713, 16618, 1135, 261, 11890, 1578, 13, 288, 203, 3639, 327, 681, 12, 69, 16, 324, 16, 315, 9890, 10477, 30, 26109, 635, 3634, 8863, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.0; interface Exchange1 { function sellTokens(address _token, uint _amount) external returns (uint amount); } interface Exchange2 { function buyTokens(address _token) external payable returns (uint amount); } interface ERC20 { function transfer(address _to, uint _value) external returns (bool success); function approve(address _spender, uint _value) external returns (bool success); } contract SimpleArb { // code is to just illustrate examples only e.g sellTokens and buyTokens just dummy functions to illustrate process of buying and selling address public exchange1 = 0x818E6FECD516Ecc3849DAf6845e3EC868087B755; // KyberNetworkProxy on Mainnet address public exchange2 = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; // Uniswap V2 Router on Mainnet address public token = 0x6B175474E89094C44Da98b954EedeAC495271d0F; // Dai Token on Mainnet function arb() internal { uint amount = 10000000000000000000; // 100 tokens ERC20(token).approve(exchange1, amount); // Approve tokens uint ethAmount = Exchange1(exchange1).sellTokens(token, amount); // Sell Tokens for Ether Exchange2(exchange1).buyTokens.value(ethAmount)(token); // Sell Tokens for Ether } }
Uniswap V2 Router on Mainnet
address public exchange2 = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
12,887,475
[ 1, 984, 291, 91, 438, 776, 22, 9703, 603, 12740, 2758, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1758, 1071, 7829, 22, 273, 374, 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, 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 ]
// File: contracts/interfaces/IDelegable.sol pragma solidity ^0.6.10; interface IDelegable { function ADDDELEGATE653(address) external; //inject NONSTANDARD NAMING function ADDDELEGATEBYSIGNATURE882(address, address, uint, uint8, bytes32, bytes32) external; //inject NONSTANDARD NAMING } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol pragma solidity ^0.6.0; interface IERC20 { function TOTALSUPPLY521() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF833(address account) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER582(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE506(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING function APPROVE147(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM451(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING event TRANSFER75(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL533(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING } // File: contracts/interfaces/IVat.sol pragma solidity ^0.6.10; interface IVat { // function can(address, address) external view returns (uint); function HOPE952(address) external; //inject NONSTANDARD NAMING function NOPE303(address) external; //inject NONSTANDARD NAMING function LIVE610() external view returns (uint); //inject NONSTANDARD NAMING function ILKS57(bytes32) external view returns (uint, uint, uint, uint, uint); //inject NONSTANDARD NAMING function URNS490(bytes32, address) external view returns (uint, uint); //inject NONSTANDARD NAMING function GEM988(bytes32, address) external view returns (uint); //inject NONSTANDARD NAMING // function dai(address) external view returns (uint); function FROB42(bytes32, address, address, address, int, int) external; //inject NONSTANDARD NAMING function FORK314(bytes32, address, address, int, int) external; //inject NONSTANDARD NAMING function MOVE289(address, address, uint) external; //inject NONSTANDARD NAMING function FLUX433(bytes32, address, address, uint) external; //inject NONSTANDARD NAMING } // File: contracts/interfaces/IWeth.sol pragma solidity ^0.6.10; interface IWeth { function DEPOSIT338() external payable; //inject NONSTANDARD NAMING function WITHDRAW817(uint) external; //inject NONSTANDARD NAMING function APPROVE147(address, uint) external returns (bool) ; //inject NONSTANDARD NAMING function TRANSFER582(address, uint) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM451(address, address, uint) external returns (bool); //inject NONSTANDARD NAMING } // File: contracts/interfaces/IGemJoin.sol pragma solidity ^0.6.10; interface IGemJoin { function RELY66(address usr) external; //inject NONSTANDARD NAMING function DENY577(address usr) external; //inject NONSTANDARD NAMING function CAGE307() external; //inject NONSTANDARD NAMING function JOIN369(address usr, uint WAD) external; //inject NONSTANDARD NAMING function EXIT932(address usr, uint WAD) external; //inject NONSTANDARD NAMING } // File: contracts/interfaces/IDaiJoin.sol pragma solidity ^0.6.10; interface IDaiJoin { function RELY66(address usr) external; //inject NONSTANDARD NAMING function DENY577(address usr) external; //inject NONSTANDARD NAMING function CAGE307() external; //inject NONSTANDARD NAMING function JOIN369(address usr, uint WAD) external; //inject NONSTANDARD NAMING function EXIT932(address usr, uint WAD) external; //inject NONSTANDARD NAMING } // File: contracts/interfaces/IPot.sol pragma solidity ^0.6.10; interface IPot { function CHI612() external view returns (uint256); //inject NONSTANDARD NAMING function PIE445(address) external view returns (uint256); // Not a function, but a public variable. //inject NONSTANDARD NAMING function RHO514() external returns (uint256); //inject NONSTANDARD NAMING function DRIP65() external returns (uint256); //inject NONSTANDARD NAMING function JOIN369(uint256) external; //inject NONSTANDARD NAMING function EXIT932(uint256) external; //inject NONSTANDARD NAMING } // File: contracts/interfaces/IChai.sol pragma solidity ^0.6.10; interface IChai { function BALANCEOF833(address account) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER582(address dst, uint wad) external returns (bool); //inject NONSTANDARD NAMING function MOVE289(address src, address dst, uint wad) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM451(address src, address dst, uint wad) external returns (bool); //inject NONSTANDARD NAMING function APPROVE147(address usr, uint wad) external returns (bool); //inject NONSTANDARD NAMING function DAI858(address usr) external returns (uint wad); //inject NONSTANDARD NAMING function JOIN369(address dst, uint wad) external; //inject NONSTANDARD NAMING function EXIT932(address src, uint wad) external; //inject NONSTANDARD NAMING function DRAW289(address src, uint wad) external; //inject NONSTANDARD NAMING function PERMIT233(address holder, address spender, uint256 nonce, uint256 expiry, bool allowed, uint8 v, bytes32 r, bytes32 s) external; //inject NONSTANDARD NAMING function NONCES538(address account) external view returns (uint256); //inject NONSTANDARD NAMING } // File: contracts/interfaces/ITreasury.sol pragma solidity ^0.6.10; interface ITreasury { function DEBT715() external view returns(uint256); //inject NONSTANDARD NAMING function SAVINGS903() external view returns(uint256); //inject NONSTANDARD NAMING function PUSHDAI613(address user, uint256 dai) external; //inject NONSTANDARD NAMING function PULLDAI166(address user, uint256 dai) external; //inject NONSTANDARD NAMING function PUSHCHAI91(address user, uint256 chai) external; //inject NONSTANDARD NAMING function PULLCHAI479(address user, uint256 chai) external; //inject NONSTANDARD NAMING function PUSHWETH634(address to, uint256 weth) external; //inject NONSTANDARD NAMING function PULLWETH548(address to, uint256 weth) external; //inject NONSTANDARD NAMING function SHUTDOWN178() external; //inject NONSTANDARD NAMING function LIVE610() external view returns(bool); //inject NONSTANDARD NAMING function VAT519() external view returns (IVat); //inject NONSTANDARD NAMING function WETH278() external view returns (IWeth); //inject NONSTANDARD NAMING function DAI858() external view returns (IERC20); //inject NONSTANDARD NAMING function DAIJOIN173() external view returns (IDaiJoin); //inject NONSTANDARD NAMING function WETHJOIN654() external view returns (IGemJoin); //inject NONSTANDARD NAMING function POT408() external view returns (IPot); //inject NONSTANDARD NAMING function CHAI326() external view returns (IChai); //inject NONSTANDARD NAMING } // File: contracts/interfaces/IERC2612.sol // Code adapted from https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2237/ pragma solidity ^0.6.0; interface IERC2612 { function PERMIT233(address owner, address spender, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external; //inject NONSTANDARD NAMING function NONCES538(address owner) external view returns (uint256); //inject NONSTANDARD NAMING } // File: contracts/interfaces/IFYDai.sol pragma solidity ^0.6.10; interface IFYDai is IERC20, IERC2612 { function ISMATURE431() external view returns(bool); //inject NONSTANDARD NAMING function MATURITY388() external view returns(uint); //inject NONSTANDARD NAMING function CHI0242() external view returns(uint); //inject NONSTANDARD NAMING function RATE0398() external view returns(uint); //inject NONSTANDARD NAMING function CHIGROWTH747() external view returns(uint); //inject NONSTANDARD NAMING function RATEGROWTH408() external view returns(uint); //inject NONSTANDARD NAMING function MATURE589() external; //inject NONSTANDARD NAMING function UNLOCKED182() external view returns (uint); //inject NONSTANDARD NAMING function MINT176(address, uint) external; //inject NONSTANDARD NAMING function BURN250(address, uint) external; //inject NONSTANDARD NAMING function FLASHMINT22(uint, bytes calldata) external; //inject NONSTANDARD NAMING function REDEEM906(address, address, uint256) external returns (uint256); //inject NONSTANDARD NAMING // function transfer(address, uint) external returns (bool); // function transferFrom(address, address, uint) external returns (bool); // function approve(address, uint) external returns (bool); } // File: contracts/interfaces/IController.sol pragma solidity ^0.6.10; interface IController is IDelegable { function TREASURY445() external view returns (ITreasury); //inject NONSTANDARD NAMING function SERIES14(uint256) external view returns (IFYDai); //inject NONSTANDARD NAMING function SERIESITERATOR268(uint256) external view returns (uint256); //inject NONSTANDARD NAMING function TOTALSERIES702() external view returns (uint256); //inject NONSTANDARD NAMING function CONTAINSSERIES982(uint256) external view returns (bool); //inject NONSTANDARD NAMING function POSTED950(bytes32, address) external view returns (uint256); //inject NONSTANDARD NAMING function DEBTFYDAI447(bytes32, uint256, address) external view returns (uint256); //inject NONSTANDARD NAMING function DEBTDAI877(bytes32, uint256, address) external view returns (uint256); //inject NONSTANDARD NAMING function TOTALDEBTDAI51(bytes32, address) external view returns (uint256); //inject NONSTANDARD NAMING function ISCOLLATERALIZED839(bytes32, address) external view returns (bool); //inject NONSTANDARD NAMING function INDAI269(bytes32, uint256, uint256) external view returns (uint256); //inject NONSTANDARD NAMING function INFYDAI474(bytes32, uint256, uint256) external view returns (uint256); //inject NONSTANDARD NAMING function ERASE227(bytes32, address) external returns (uint256, uint256); //inject NONSTANDARD NAMING function SHUTDOWN178() external; //inject NONSTANDARD NAMING function POST95(bytes32, address, address, uint256) external; //inject NONSTANDARD NAMING function WITHDRAW817(bytes32, address, address, uint256) external; //inject NONSTANDARD NAMING function BORROW691(bytes32, uint256, address, address, uint256) external; //inject NONSTANDARD NAMING function REPAYFYDAI426(bytes32, uint256, address, address, uint256) external returns (uint256); //inject NONSTANDARD NAMING function REPAYDAI460(bytes32, uint256, address, address, uint256) external returns (uint256); //inject NONSTANDARD NAMING } // File: contracts/interfaces/IDai.sol pragma solidity ^0.6.10; interface IDai is IERC20 { function NONCES538(address user) external view returns (uint256); //inject NONSTANDARD NAMING function PERMIT233(address holder, address spender, uint256 nonce, uint256 expiry, //inject NONSTANDARD NAMING bool allowed, uint8 v, bytes32 r, bytes32 s) external; } // File: contracts/interfaces/IPool.sol pragma solidity ^0.6.10; interface IPool is IDelegable, IERC20, IERC2612 { function DAI858() external view returns(IERC20); //inject NONSTANDARD NAMING function FYDAI600() external view returns(IFYDai); //inject NONSTANDARD NAMING function GETDAIRESERVES173() external view returns(uint128); //inject NONSTANDARD NAMING function GETFYDAIRESERVES833() external view returns(uint128); //inject NONSTANDARD NAMING function SELLDAI400(address from, address to, uint128 daiIn) external returns(uint128); //inject NONSTANDARD NAMING function BUYDAI253(address from, address to, uint128 daiOut) external returns(uint128); //inject NONSTANDARD NAMING function SELLFYDAI226(address from, address to, uint128 fyDaiIn) external returns(uint128); //inject NONSTANDARD NAMING function BUYFYDAI675(address from, address to, uint128 fyDaiOut) external returns(uint128); //inject NONSTANDARD NAMING function SELLDAIPREVIEW300(uint128 daiIn) external view returns(uint128); //inject NONSTANDARD NAMING function BUYDAIPREVIEW913(uint128 daiOut) external view returns(uint128); //inject NONSTANDARD NAMING function SELLFYDAIPREVIEW69(uint128 fyDaiIn) external view returns(uint128); //inject NONSTANDARD NAMING function BUYFYDAIPREVIEW685(uint128 fyDaiOut) external view returns(uint128); //inject NONSTANDARD NAMING function MINT176(address from, address to, uint256 daiOffered) external returns (uint256); //inject NONSTANDARD NAMING function BURN250(address from, address to, uint256 tokensBurned) external returns (uint256, uint256); //inject NONSTANDARD NAMING } // File: @openzeppelin/contracts/math/SafeMath.sol pragma solidity ^0.6.0; library SafeMath { function ADD958(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function SUB494(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return SUB494(a, b, "SafeMath: subtraction overflow"); } function SUB494(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 MUL434(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function DIV16(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV16(a, b, "SafeMath: division by zero"); } function DIV16(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function MOD331(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return MOD331(a, b, "SafeMath: modulo by zero"); } function MOD331(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0, errorMessage); return a % b; } } // File: contracts/helpers/DecimalMath.sol pragma solidity ^0.6.10; contract DecimalMath { using SafeMath for uint256; uint256 constant public unit17 = 1e27; //inject NONSTANDARD NAMING function MULD379(uint256 x, uint256 y) internal pure returns (uint256) { //inject NONSTANDARD NAMING return x.MUL434(y).DIV16(unit17); } function DIVD836(uint256 x, uint256 y) internal pure returns (uint256) { //inject NONSTANDARD NAMING return x.MUL434(unit17).DIV16(y); } function MULDRUP300(uint256 x, uint256 y) internal pure returns (uint256) //inject NONSTANDARD NAMING { uint256 z = x.MUL434(y); return z.MOD331(unit17) == 0 ? z.DIV16(unit17) : z.DIV16(unit17).ADD958(1); } function DIVDRUP370(uint256 x, uint256 y) internal pure returns (uint256) //inject NONSTANDARD NAMING { uint256 z = x.MUL434(unit17); return z.MOD331(y) == 0 ? z.DIV16(y) : z.DIV16(y).ADD958(1); } } // File: contracts/peripheral/YieldProxy.sol pragma solidity ^0.6.10; library SafeCast { function TOUINT128897(uint256 x) internal pure returns(uint128) { //inject NONSTANDARD NAMING require( x <= type(uint128).max, "YieldProxy: Cast overflow" ); return uint128(x); } function TOINT256710(uint256 x) internal pure returns(int256) { //inject NONSTANDARD NAMING require( x <= uint256(type(int256).max), "YieldProxy: Cast overflow" ); return int256(x); } } contract YieldProxy is DecimalMath { using SafeCast for uint256; IVat public vat; IWeth public weth; IDai public dai; IGemJoin public wethJoin; IDaiJoin public daiJoin; IChai public chai; IController public controller; ITreasury public treasury; IPool[] public pools; mapping (address => bool) public poolsMap; bytes32 public constant chai69 = "CHAI"; //inject NONSTANDARD NAMING bytes32 public constant weth148 = "ETH-A"; //inject NONSTANDARD NAMING bool constant public mty307 = true; //inject NONSTANDARD NAMING bool constant public ytm282 = false; //inject NONSTANDARD NAMING constructor(address controller_, IPool[] memory _pools) public { controller = IController(controller_); treasury = controller.TREASURY445(); weth = treasury.WETH278(); dai = IDai(address(treasury.DAI858())); chai = treasury.CHAI326(); daiJoin = treasury.DAIJOIN173(); wethJoin = treasury.WETHJOIN654(); vat = treasury.VAT519(); // for repaying debt dai.APPROVE147(address(treasury), uint(-1)); // for posting to the controller chai.APPROVE147(address(treasury), uint(-1)); weth.APPROVE147(address(treasury), uint(-1)); // for converting DAI to CHAI dai.APPROVE147(address(chai), uint(-1)); vat.HOPE952(address(daiJoin)); vat.HOPE952(address(wethJoin)); dai.APPROVE147(address(daiJoin), uint(-1)); weth.APPROVE147(address(wethJoin), uint(-1)); weth.APPROVE147(address(treasury), uint(-1)); // allow all the pools to pull FYDai/dai from us for LPing for (uint i = 0 ; i < _pools.length; i++) { dai.APPROVE147(address(_pools[i]), uint(-1)); _pools[i].FYDAI600().APPROVE147(address(_pools[i]), uint(-1)); poolsMap[address(_pools[i])]= true; } pools = _pools; } function UNPACK384(bytes memory signature) private pure returns (bytes32 r, bytes32 s, uint8 v) { //inject NONSTANDARD NAMING assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } } function ONBOARD51(address from, bytes memory daiSignature, bytes memory controllerSig) external { //inject NONSTANDARD NAMING bytes32 r; bytes32 s; uint8 v; (r, s, v) = UNPACK384(daiSignature); dai.PERMIT233(from, address(this), dai.NONCES538(from), uint(-1), true, v, r, s); (r, s, v) = UNPACK384(controllerSig); controller.ADDDELEGATEBYSIGNATURE882(from, address(this), uint(-1), v, r, s); } function AUTHORIZEPOOL621(IPool pool, address from, bytes memory daiSig, bytes memory fyDaiSig, bytes memory poolSig) public { //inject NONSTANDARD NAMING ONLYKNOWNPOOL167(pool); bytes32 r; bytes32 s; uint8 v; (r, s, v) = UNPACK384(daiSig); dai.PERMIT233(from, address(pool), dai.NONCES538(from), uint(-1), true, v, r, s); (r, s, v) = UNPACK384(fyDaiSig); pool.FYDAI600().PERMIT233(from, address(this), uint(-1), uint(-1), v, r, s); (r, s, v) = UNPACK384(poolSig); pool.ADDDELEGATEBYSIGNATURE882(from, address(this), uint(-1), v, r, s); } receive() external payable { } function POST95(address to) //inject NONSTANDARD NAMING public payable { weth.DEPOSIT338{ value: msg.value }(); controller.POST95(weth148, address(this), to, msg.value); } function WITHDRAW817(address payable to, uint256 amount) //inject NONSTANDARD NAMING public { controller.WITHDRAW817(weth148, msg.sender, address(this), amount); weth.WITHDRAW817(amount); to.transfer(amount); } function ADDLIQUIDITY157(IPool pool, uint256 daiUsed, uint256 maxFYDai) external returns (uint256) { //inject NONSTANDARD NAMING ONLYKNOWNPOOL167(pool); IFYDai fyDai = pool.FYDAI600(); require(fyDai.ISMATURE431() != true, "YieldProxy: Only before maturity"); require(dai.TRANSFERFROM451(msg.sender, address(this), daiUsed), "YieldProxy: Transfer Failed"); // calculate needed fyDai uint256 daiReserves = dai.BALANCEOF833(address(pool)); uint256 fyDaiReserves = fyDai.BALANCEOF833(address(pool)); uint256 daiToAdd = daiUsed.MUL434(daiReserves).DIV16(fyDaiReserves.ADD958(daiReserves)); uint256 daiToConvert = daiUsed.SUB494(daiToAdd); require( daiToConvert <= maxFYDai, "YieldProxy: maxFYDai exceeded" ); // 1 Dai == 1 fyDai // convert dai to chai and borrow needed fyDai chai.JOIN369(address(this), daiToConvert); // look at the balance of chai in dai to avoid rounding issues uint256 toBorrow = chai.DAI858(address(this)); controller.POST95(chai69, address(this), msg.sender, chai.BALANCEOF833(address(this))); controller.BORROW691(chai69, fyDai.MATURITY388(), msg.sender, address(this), toBorrow); // mint liquidity tokens return pool.MINT176(address(this), msg.sender, daiToAdd); } function REMOVELIQUIDITYEARLYDAIPOOL932(IPool pool, uint256 poolTokens, uint256 minimumDaiPrice, uint256 minimumFYDaiPrice) external { //inject NONSTANDARD NAMING ONLYKNOWNPOOL167(pool); IFYDai fyDai = pool.FYDAI600(); uint256 maturity = fyDai.MATURITY388(); (uint256 daiObtained, uint256 fyDaiObtained) = pool.BURN250(msg.sender, address(this), poolTokens); // Exchange Dai for fyDai to pay as much debt as possible uint256 fyDaiBought = pool.SELLDAI400(address(this), address(this), daiObtained.TOUINT128897()); require( fyDaiBought >= MULD379(daiObtained, minimumDaiPrice), "YieldProxy: minimumDaiPrice not reached" ); fyDaiObtained = fyDaiObtained.ADD958(fyDaiBought); uint256 fyDaiUsed; if (fyDaiObtained > 0 && controller.DEBTFYDAI447(chai69, maturity, msg.sender) > 0) { fyDaiUsed = controller.REPAYFYDAI426(chai69, maturity, address(this), msg.sender, fyDaiObtained); } uint256 fyDaiRemaining = fyDaiObtained.SUB494(fyDaiUsed); if (fyDaiRemaining > 0) {// There is fyDai left, so exchange it for Dai to withdraw only Dai and Chai require( pool.SELLFYDAI226(address(this), address(this), uint128(fyDaiRemaining)) >= MULD379(fyDaiRemaining, minimumFYDaiPrice), "YieldProxy: minimumFYDaiPrice not reached" ); } WITHDRAWASSETS926(fyDai); } function REMOVELIQUIDITYEARLYDAIFIXED8(IPool pool, uint256 poolTokens, uint256 minimumFYDaiPrice) external { //inject NONSTANDARD NAMING ONLYKNOWNPOOL167(pool); IFYDai fyDai = pool.FYDAI600(); uint256 maturity = fyDai.MATURITY388(); (uint256 daiObtained, uint256 fyDaiObtained) = pool.BURN250(msg.sender, address(this), poolTokens); uint256 fyDaiUsed; if (fyDaiObtained > 0 && controller.DEBTFYDAI447(chai69, maturity, msg.sender) > 0) { fyDaiUsed = controller.REPAYFYDAI426(chai69, maturity, address(this), msg.sender, fyDaiObtained); } uint256 fyDaiRemaining = fyDaiObtained.SUB494(fyDaiUsed); if (fyDaiRemaining == 0) { // We used all the fyDai, so probably there is debt left, so pay with Dai if (daiObtained > 0 && controller.DEBTFYDAI447(chai69, maturity, msg.sender) > 0) { controller.REPAYDAI460(chai69, maturity, address(this), msg.sender, daiObtained); } } else { // Exchange remaining fyDai for Dai to withdraw only Dai and Chai require( pool.SELLFYDAI226(address(this), address(this), uint128(fyDaiRemaining)) >= MULD379(fyDaiRemaining, minimumFYDaiPrice), "YieldProxy: minimumFYDaiPrice not reached" ); } WITHDRAWASSETS926(fyDai); } function REMOVELIQUIDITYMATURE267(IPool pool, uint256 poolTokens) external { //inject NONSTANDARD NAMING ONLYKNOWNPOOL167(pool); IFYDai fyDai = pool.FYDAI600(); uint256 maturity = fyDai.MATURITY388(); (uint256 daiObtained, uint256 fyDaiObtained) = pool.BURN250(msg.sender, address(this), poolTokens); if (fyDaiObtained > 0) { daiObtained = daiObtained.ADD958(fyDai.REDEEM906(address(this), address(this), fyDaiObtained)); } // Repay debt if (daiObtained > 0 && controller.DEBTFYDAI447(chai69, maturity, msg.sender) > 0) { controller.REPAYDAI460(chai69, maturity, address(this), msg.sender, daiObtained); } WITHDRAWASSETS926(fyDai); } function WITHDRAWASSETS926(IFYDai fyDai) internal { //inject NONSTANDARD NAMING if (controller.DEBTFYDAI447(chai69, fyDai.MATURITY388(), msg.sender) == 0) { controller.WITHDRAW817(chai69, msg.sender, address(this), controller.POSTED950(chai69, msg.sender)); chai.EXIT932(address(this), chai.BALANCEOF833(address(this))); } require(dai.TRANSFER582(msg.sender, dai.BALANCEOF833(address(this))), "YieldProxy: Dai Transfer Failed"); } function BORROWDAIFORMAXIMUMFYDAI736( //inject NONSTANDARD NAMING IPool pool, bytes32 collateral, uint256 maturity, address to, uint256 maximumFYDai, uint256 daiToBorrow ) public returns (uint256) { ONLYKNOWNPOOL167(pool); uint256 fyDaiToBorrow = pool.BUYDAIPREVIEW913(daiToBorrow.TOUINT128897()); require (fyDaiToBorrow <= maximumFYDai, "YieldProxy: Too much fyDai required"); // The collateral for this borrow needs to have been posted beforehand controller.BORROW691(collateral, maturity, msg.sender, address(this), fyDaiToBorrow); pool.BUYDAI253(address(this), to, daiToBorrow.TOUINT128897()); return fyDaiToBorrow; } function BORROWMINIMUMDAIFORFYDAI776( //inject NONSTANDARD NAMING IPool pool, bytes32 collateral, uint256 maturity, address to, uint256 fyDaiToBorrow, uint256 minimumDaiToBorrow ) public returns (uint256) { ONLYKNOWNPOOL167(pool); // The collateral for this borrow needs to have been posted beforehand controller.BORROW691(collateral, maturity, msg.sender, address(this), fyDaiToBorrow); uint256 boughtDai = pool.SELLFYDAI226(address(this), to, fyDaiToBorrow.TOUINT128897()); require (boughtDai >= minimumDaiToBorrow, "YieldProxy: Not enough Dai obtained"); return boughtDai; } function REPAYFYDAIDEBTFORMAXIMUMDAI955( //inject NONSTANDARD NAMING IPool pool, bytes32 collateral, uint256 maturity, address to, uint256 fyDaiRepayment, uint256 maximumRepaymentInDai ) public returns (uint256) { ONLYKNOWNPOOL167(pool); uint256 fyDaiDebt = controller.DEBTFYDAI447(collateral, maturity, to); uint256 fyDaiToUse = fyDaiDebt < fyDaiRepayment ? fyDaiDebt : fyDaiRepayment; // Use no more fyDai than debt uint256 repaymentInDai = pool.BUYFYDAI675(msg.sender, address(this), fyDaiToUse.TOUINT128897()); require (repaymentInDai <= maximumRepaymentInDai, "YieldProxy: Too much Dai required"); controller.REPAYFYDAI426(collateral, maturity, address(this), to, fyDaiToUse); return repaymentInDai; } function REPAYMINIMUMFYDAIDEBTFORDAI862( //inject NONSTANDARD NAMING IPool pool, bytes32 collateral, uint256 maturity, address to, uint256 minimumFYDaiRepayment, uint256 repaymentInDai ) public returns (uint256) { ONLYKNOWNPOOL167(pool); uint256 fyDaiRepayment = pool.SELLDAIPREVIEW300(repaymentInDai.TOUINT128897()); uint256 fyDaiDebt = controller.DEBTFYDAI447(collateral, maturity, to); if(fyDaiRepayment <= fyDaiDebt) { // Sell no more Dai than needed to cancel all the debt pool.SELLDAI400(msg.sender, address(this), repaymentInDai.TOUINT128897()); } else { // If we have too much Dai, then don't sell it all and buy the exact amount of fyDai needed instead. pool.BUYFYDAI675(msg.sender, address(this), fyDaiDebt.TOUINT128897()); fyDaiRepayment = fyDaiDebt; } require (fyDaiRepayment >= minimumFYDaiRepayment, "YieldProxy: Not enough fyDai debt repaid"); controller.REPAYFYDAI426(collateral, maturity, address(this), to, fyDaiRepayment); return fyDaiRepayment; } function SELLDAI400(IPool pool, address to, uint128 daiIn, uint128 minFYDaiOut) //inject NONSTANDARD NAMING external returns(uint256) { ONLYKNOWNPOOL167(pool); uint256 fyDaiOut = pool.SELLDAI400(msg.sender, to, daiIn); require( fyDaiOut >= minFYDaiOut, "YieldProxy: Limit not reached" ); return fyDaiOut; } function BUYDAI253(IPool pool, address to, uint128 daiOut, uint128 maxFYDaiIn) //inject NONSTANDARD NAMING public returns(uint256) { ONLYKNOWNPOOL167(pool); uint256 fyDaiIn = pool.BUYDAI253(msg.sender, to, daiOut); require( maxFYDaiIn >= fyDaiIn, "YieldProxy: Limit exceeded" ); return fyDaiIn; } function BUYDAIWITHSIGNATURE110(IPool pool, address to, uint128 daiOut, uint128 maxFYDaiIn, bytes memory signature) //inject NONSTANDARD NAMING external returns(uint256) { ONLYKNOWNPOOL167(pool); (bytes32 r, bytes32 s, uint8 v) = UNPACK384(signature); pool.FYDAI600().PERMIT233(msg.sender, address(pool), uint(-1), uint(-1), v, r, s); return BUYDAI253(pool, to, daiOut, maxFYDaiIn); } function SELLFYDAI226(IPool pool, address to, uint128 fyDaiIn, uint128 minDaiOut) //inject NONSTANDARD NAMING public returns(uint256) { ONLYKNOWNPOOL167(pool); uint256 daiOut = pool.SELLFYDAI226(msg.sender, to, fyDaiIn); require( daiOut >= minDaiOut, "YieldProxy: Limit not reached" ); return daiOut; } function SELLFYDAIWITHSIGNATURE545(IPool pool, address to, uint128 fyDaiIn, uint128 minDaiOut, bytes memory signature) //inject NONSTANDARD NAMING external returns(uint256) { ONLYKNOWNPOOL167(pool); (bytes32 r, bytes32 s, uint8 v) = UNPACK384(signature); pool.FYDAI600().PERMIT233(msg.sender, address(pool), uint(-1), uint(-1), v, r, s); return SELLFYDAI226(pool, to, fyDaiIn, minDaiOut); } function BUYFYDAI675(IPool pool, address to, uint128 fyDaiOut, uint128 maxDaiIn) //inject NONSTANDARD NAMING external returns(uint256) { ONLYKNOWNPOOL167(pool); uint256 daiIn = pool.BUYFYDAI675(msg.sender, to, fyDaiOut); require( maxDaiIn >= daiIn, "YieldProxy: Limit exceeded" ); return daiIn; } function REPAYDAIWITHSIGNATURE818(bytes32 collateral, uint256 maturity, address to, uint256 daiAmount, bytes memory signature) //inject NONSTANDARD NAMING external returns(uint256) { (bytes32 r, bytes32 s, uint8 v) = UNPACK384(signature); dai.PERMIT233(msg.sender, address(treasury), dai.NONCES538(msg.sender), uint(-1), true, v, r, s); controller.REPAYDAI460(collateral, maturity, msg.sender, to, daiAmount); } function ONLYKNOWNPOOL167(IPool pool) private view { //inject NONSTANDARD NAMING require(poolsMap[address(pool)], "YieldProxy: Unknown pool"); } }
inject NONSTANDARD NAMING
function RATEGROWTH408() external view returns(uint);
12,707,142
[ 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, 534, 1777, 43, 11226, 2455, 24, 6840, 1435, 3903, 1476, 1135, 12, 11890, 1769, 202, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x3a23F943181408EAC424116Af7b7790c94Cb97a5/sources/src/bridges/optimism/l1/NativeOptimism.sol
* @notice function to handle ERC20 bridging to receipent via NativeOptimism-Bridge @notice This method is payable because the caller is doing token transfer and briding operation @param token address of token being bridged @param receiverAddress address of receiver of bridged tokens @param customBridgeAddress OptimismBridge that Performs the logic for deposits by informing the L2 Deposited Token contract of the deposit and calling a handler to lock the L1 funds. (e.g. transferFrom) @param l2Gas Gas limit required to complete the deposit on L2. @param optimismData extra data needed for optimism bridge @param amount amount being bridged @param interfaceId interfaceId to be set offchain which is used to select one of the 3 kinds of bridging (standard bridge / old standard / synthetic) @param l2Token Address of the L1 respective L2 ERC20 @param data additional data , for ll contracts this will be 0x data or empty data/ deposit into standard bridge Deposit Using Old Standard - iOVM_L1TokenGateway(Example - SNX Token)
function bridgeERC20To( address token, address receiverAddress, address customBridgeAddress, uint32 l2Gas, OptimismERC20Data calldata optimismData, uint256 amount, uint256 interfaceId, address l2Token, bytes calldata data ) external payable { if (interfaceId == 0) { revert UnsupportedInterfaceId(); } ERC20 tokenInstance = ERC20(token); tokenInstance.safeTransferFrom(msg.sender, socketGateway, amount); tokenInstance.safeApprove(customBridgeAddress, amount); emit SocketBridge( amount, token, DESTINATION_CHAIN_ID, NativeOptimismIdentifier, msg.sender, receiverAddress, optimismData.metadata ); if (interfaceId == 1) { L1StandardBridge(customBridgeAddress).depositERC20To( token, l2Token, receiverAddress, amount, l2Gas, data ); return; } if (interfaceId == 2) { OldL1TokenGateway(customBridgeAddress).depositTo( receiverAddress, amount ); return; } if (interfaceId == 3) { OldL1TokenGateway(customBridgeAddress).initiateSynthTransfer( optimismData.currencyKey, receiverAddress, amount ); return; } }
11,003,315
[ 1, 915, 358, 1640, 4232, 39, 3462, 324, 1691, 1998, 358, 2637, 625, 319, 3970, 16717, 13930, 6228, 17, 13691, 225, 1220, 707, 353, 8843, 429, 2724, 326, 4894, 353, 9957, 1147, 7412, 471, 324, 1691, 310, 1674, 225, 1147, 1758, 434, 1147, 3832, 324, 1691, 2423, 225, 5971, 1887, 1758, 434, 5971, 434, 324, 1691, 2423, 2430, 225, 1679, 13691, 1887, 19615, 6228, 13691, 716, 27391, 326, 4058, 364, 443, 917, 1282, 635, 13235, 310, 326, 511, 22, 4019, 538, 16261, 3155, 21821, 6835, 434, 326, 443, 1724, 471, 4440, 279, 1838, 358, 2176, 326, 511, 21, 284, 19156, 18, 261, 73, 18, 75, 18, 7412, 1265, 13, 225, 328, 22, 27998, 31849, 1800, 1931, 358, 3912, 326, 443, 1724, 603, 511, 22, 18, 225, 5213, 6228, 751, 2870, 501, 3577, 364, 5213, 6228, 10105, 225, 3844, 3844, 3832, 324, 1691, 2423, 225, 1560, 548, 1560, 548, 358, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 565, 445, 10105, 654, 39, 3462, 774, 12, 203, 3639, 1758, 1147, 16, 203, 3639, 1758, 5971, 1887, 16, 203, 3639, 1758, 1679, 13691, 1887, 16, 203, 3639, 2254, 1578, 328, 22, 27998, 16, 203, 3639, 19615, 6228, 654, 39, 3462, 751, 745, 892, 5213, 6228, 751, 16, 203, 3639, 2254, 5034, 3844, 16, 203, 3639, 2254, 5034, 1560, 548, 16, 203, 3639, 1758, 328, 22, 1345, 16, 203, 3639, 1731, 745, 892, 501, 203, 565, 262, 3903, 8843, 429, 288, 203, 3639, 309, 261, 5831, 548, 422, 374, 13, 288, 203, 5411, 15226, 7221, 1358, 548, 5621, 203, 3639, 289, 203, 203, 3639, 4232, 39, 3462, 1147, 1442, 273, 4232, 39, 3462, 12, 2316, 1769, 203, 3639, 1147, 1442, 18, 4626, 5912, 1265, 12, 3576, 18, 15330, 16, 2987, 5197, 16, 3844, 1769, 203, 3639, 1147, 1442, 18, 4626, 12053, 537, 12, 3662, 13691, 1887, 16, 3844, 1769, 203, 203, 3639, 3626, 8758, 13691, 12, 203, 5411, 3844, 16, 203, 5411, 1147, 16, 203, 5411, 2030, 22418, 67, 1792, 6964, 67, 734, 16, 203, 5411, 16717, 13930, 6228, 3004, 16, 203, 5411, 1234, 18, 15330, 16, 203, 5411, 5971, 1887, 16, 203, 5411, 5213, 6228, 751, 18, 4165, 203, 3639, 11272, 203, 3639, 309, 261, 5831, 548, 422, 404, 13, 288, 203, 5411, 511, 21, 8336, 13691, 12, 3662, 13691, 1887, 2934, 323, 1724, 654, 39, 3462, 774, 12, 203, 7734, 1147, 16, 203, 7734, 328, 22, 1345, 16, 203, 7734, 5971, 1887, 16, 203, 7734, 3844, 16, 203, 7734, 328, 22, 27998, 2 ]
/* * Safe Math Smart Contract. * Author: Mikhail Vladimirov <[email protected]> */ pragma solidity ^0.4.16; /** * Provides methods to safely add, subtract and multiply uint256 numbers. */ contract SafeMath { uint256 constant private MAX_UINT256 = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; /** * Add two uint256 values, throw in case of overflow. * * @param x first value to add * @param y second value to add * @return x + y */ function safeAdd (uint256 x, uint256 y) constant internal returns (uint256 z) { assert (x <= MAX_UINT256 - y); return x + y; } /** * Subtract one uint256 value from another, throw in case of underflow. * * @param x value to subtract from * @param y value to subtract * @return x - y */ function safeSub (uint256 x, uint256 y) constant internal returns (uint256 z) { assert (x >= y); return x - y; } /** * Multiply two uint256 values, throw in case of overflow. * * @param x first value to multiply * @param y second value to multiply * @return x * y */ function safeMul (uint256 x, uint256 y) constant internal returns (uint256 z) { if (y == 0) return 0; // Prevent division by zero at the next line assert (x <= MAX_UINT256 / y); return x * y; } } /* * ERC-20 Standard Token Smart Contract Interface. * Author: Mikhail Vladimirov <[email protected]> */ pragma solidity ^0.4.16; /** * ERC-20 standard token interface, as defined * <a href="http://github.com/ethereum/EIPs/issues/20">here</a>. */ contract Token { /** * Get total number of tokens in circulation. * * @return total number of tokens in circulation */ function totalSupply () constant returns (uint256 supply); /** * 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); /** * 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); /** * 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); /** * 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); /** * 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); /** * Logged when tokens were transferred from one owner to another. * * @param _from address of the owner, tokens were transferred from * @param _to address of the owner, tokens were transferred to * @param _value number of tokens transferred */ event Transfer (address indexed _from, address indexed _to, uint256 _value); /** * Logged when owner approved his tokens to be transferred by some spender. * * @param _owner owner who approved his tokens to be transferred * @param _spender spender who were allowed to transfer the tokens belonging * to the owner * @param _value number of tokens belonging to the owner, approved to be * transferred by the spender */ event Approval ( address indexed _owner, address indexed _spender, uint256 _value); } /* * Abstract base contract for Token Smart Contracts that may create snapshots of * token holder balances. * Author: Mikhail Vladimirov <[email protected]> */ pragma solidity ^0.4.16; /** * Abstract base contract Token Smart Contracts that support snapshots of token * holder balances. */ contract AbstractSnapshottableToken is SafeMath, Token { /** * Maximum number of tokens in circulation (2^256 - 1). */ uint256 constant MAX_TOKENS = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; /** * Maximum value of uint256 type, i.e. 2^256-1. */ uint256 constant MAX_UINT256 = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; /** * Maximum value of address represented as uint256, i.e. 2^160-1. */ uint256 constant MAX_ADDRESS = 0x00FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; /** * 2^160. */ uint256 constant TWO_160 = 0x00010000000000000000000000000000000000000000; /** * Create new Abstract Snapshottable Token smart contract. */ function AbstractSnapshottableToken () { snapshots.length = 1; // Reserve zero ID. } /** * Get total number of tokens in circulation. * * @return total number of tokens in circulation */ function totalSupply () constant returns (uint256 supply) { return tokensCount; } /** * Get total number of tokens in circulation as is was at the moment when * snapshot with given index was created. * * @param _index index of the snapshot to get total number of tokens in * circulation at the moment of * @return total number of tokens in circulation at the moment snapshot with * given index was created */ function totalSupplyAt (uint256 _index) constant returns (uint256 supply) { require (_index > 0); require (_index < snapshots.length); return snapshots [_index].tokensCount; } /** * Get number of tokens currently belonging to the owner of given address. * * @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].balance; } /** * Get number of tokens owner of the given address had at the moment when * snapshot with given index was created. * * @param _owner address to get number of tokens for the owner of * @param _index index of the snapshot to get number of tokens at the time of * @return number of tokens owner of the given address had at the moment the * snapshot with given index was created */ function balanceOfAt (address _owner, uint256 _index) constant returns (uint256 balance) { require (_index > 0); require (_index < snapshots.length); if (_index > accounts [_owner].lastSnapshotIndex) return accounts [_owner].balance; else { uint8 level = 0; while (_index > 0) { uint256 v = historicalBalances [_owner][level][_index]; if (v != 0) return v; _index >>= 1; level += 1; // Overflow is possible here, but is harmless } return 0; } } /** * Get first address that probably had non-zero token balance at the moment * snapshot with given index was created. * * @param _index index of the snapshot to get first address the probably had * non-zero token balance at the moment of * @return flag that tells whether there is at least one address that probably * had non-zero token balance at the moment of snapshot with given * index (hasResult); and the fist address that probably had non-zero * token balance at the moment snapshot with given index was created * or zero if there are no such addresses (result) */ function firstAddressAt (uint256 _index) constant returns (bool hasResult, address result) { require (_index > 0); require (_index < snapshots.length); uint256 rawFirstAddress = snapshots [_index].firstAddress; hasResult = rawFirstAddress != MAX_UINT256; result = hasResult ? address (rawFirstAddress & MAX_ADDRESS) : 0; } /** * Get next address that probably had non-zero token balance at the moment * certain snapshot was created. * * @param _address previous address that probably had non-zero token balance * at the moment of certain snapshot * @return flag that tells whether there is next address that probably had * non-zero token balance at the moment of snapshot with given index * (hasResult); and the next address that probably had non-zero * token balance at the moment of snapshot with given index was * created or zero if there are no such addresses (result) */ function nextAddress (address _address) constant returns (bool hasResult, address result) { uint256 rawNextAddress = nextAddresses [_address]; require (rawNextAddress != 0); hasResult = rawNextAddress != MAX_UINT256; result = hasResult ? address (rawNextAddress & MAX_ADDRESS) : 0; } /** * 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) { return doTransfer (msg.sender, _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) { if (_value > approved [_from][msg.sender]) return false; else if (doTransfer (_from, _to, _value)) { approved [_from][msg.sender] = safeSub (approved[_from][msg.sender], _value); return true; } else return false; } /** * 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) { approved [msg.sender][_spender] = _value; 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 approved [_owner][_spender]; } /** * Create snapshot of token holder balances. * * @return index of new created snapshot */ function snapshot () returns (uint256 index) { index = snapshots.length++; snapshots [index].tokensCount = tokensCount; snapshots [index].firstAddress = firstAddress; Snapshot (index); } /** * Transfer given number of tokens from the owner of given from address to the * owner of given to address. * * @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 * @return true if tokens were transferred successfully, false otherwise */ function doTransfer (address _from, address _to, uint256 _value) internal returns (bool success) { if (_value > accounts [_from].balance) return false; else if (_value > 0 && _from != _to) { saveAddress (_to); updateHistoricalBalances (_from); updateHistoricalBalances (_to); accounts [_from].balance = safeSub (accounts [_from].balance, _value); accounts [_to].balance = safeAdd (accounts [_to].balance, _value); Transfer (_from, _to, _value); return true; } else return true; } /** * Create given number of tokens and give them to message sender. * * @param _value number of tokens to create * @return true on success, false on error */ function doCreateTokens (uint256 _value) internal returns (bool success) { if (_value > safeSub (MAX_TOKENS, tokensCount)) return false; else if (_value > 0) { saveAddress (msg.sender); updateHistoricalBalances (msg.sender); accounts [msg.sender].balance = safeAdd (accounts [msg.sender].balance, _value); tokensCount = safeAdd (tokensCount, _value); return true; } else return true; } /** * Update historical balances for given token owner. * * @param _owner token owner to update historical balances for */ function updateHistoricalBalances (address _owner) internal { uint256 balance = accounts [_owner].balance; uint256 nextSnapshotIndex = snapshots.length; uint256 lastNextSnapshotIndex = safeAdd (accounts [_owner].lastSnapshotIndex, 1); if (nextSnapshotIndex > lastNextSnapshotIndex) { if (balance > 0) { setHistoricalBalance ( _owner, lastNextSnapshotIndex, nextSnapshotIndex, balance); } accounts [_owner].lastSnapshotIndex = safeSub (nextSnapshotIndex, 1); } } /** * Set historical balance for the owner of given address as it was at the * moments of snapshots with indexes in given range. * * @param _owner address to set the historical balance for the owner of * @param _from beginning of the snapshot index range (inclusive) * @param _to end of the snapshot index range (exclusive) * @param _balance value to set balance to */ function setHistoricalBalance ( address _owner, uint256 _from, uint256 _to, uint256 _balance) internal { assert (_from > 0); assert (_to >= _from); assert (_balance > 0); uint8 level = 0; while (_from < _to) { if (_from & 1 == 1) { // Overflow is not possible here because _from < _to historicalBalances [_owner][level][_from++] = _balance; } if (_to & 1 == 1) { // Underflow is not possible here, because _to & 1 == 1 historicalBalances [_owner][level][--_to] = _balance; } _from >>= 1; _to >>= 1; level += 1; // Even for snapshot index range 1..2^256-1 overflow will // not happen here } } /** * Add address to the list of addresses that ever had non-zero token balance. * * @param _address address to be added to the list of addresses that ever had * non-zero token balance */ function saveAddress (address _address) internal { if (nextAddresses [_address] == 0) { nextAddresses [_address] = firstAddress; firstAddress = TWO_160 | uint256(_address); } } /** * Total number of tokens in circulation. */ uint256 tokensCount; /** * All snapshots ever created. */ SnapshotInfo [] snapshots; /** * Maps addresses of token owners to states of their accounts. */ mapping (address => Account) accounts; /** * First address that ever had non-zero token balance plus 2^160, or 2^256-1 * if there are no such addresses. */ uint256 firstAddress = MAX_UINT256; /** * Mapping from address that ever had non-zero token balance to the next * address that ever had non-zero token balance plus 2^160 or 2^256-1 if there * are no more such addresses. */ mapping (address => uint256) nextAddresses; /** * Historical balances of token owners. If for some address, level and index, * where level >= 0 and index > 0, historicalBalances[address][level][index] * is non-zero, then owner of given address had this many tokens at the * time moments of snapshots with indexes from (index * 2^level) to * ((index + 1) * 2^level - 1) inclusive. * For each snapshot, there should be at most one level with non-zero * value at corresponding index. */ mapping (address => mapping (uint8 => mapping (uint256 => uint256))) historicalBalances; /** * Maps addresses of token owners to mappings from addresses of spenders to * how many tokens belonging to the owner, the spender is currently allowed to * transfer. */ mapping (address => mapping (address => uint256)) approved; /** * Encapsulates information about snapshot. */ struct SnapshotInfo { /** * Total number of tokens in circulation at the moment of snapshot. */ uint256 tokensCount; /** * Value of firstAddress field at the moment of snapshot. */ uint256 firstAddress; } /** * Encapsulates information about token owner's balance. */ struct Account { /** * Number of tokens currently belonging to the token owner. */ uint256 balance; /** * Index of the last snapshot before the moment historical balances were * last updated for this token owner. */ uint256 lastSnapshotIndex; } /** * Logged when new snapshot was created. * * @param _index index of the new snapshot */ event Snapshot (uint256 indexed _index); } /* * Standard Snapshottable Token Smart Contract. * Author: Mikhail Vladimirov <[email protected]> */ /** * Standard Snapshottable Token Smart Contract. */ contract StandardSnapshottableToken is AbstractSnapshottableToken { /** * Create new Standard Snapshottable Token Smart Contract and make * message sender the owner of the smart contract. */ function StandardSnapshottableToken () AbstractSnapshottableToken () { owner = msg.sender; } /** * 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) { if (frozen) return false; else return AbstractSnapshottableToken.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) { if (frozen) return false; else return AbstractSnapshottableToken.transferFrom (_from, _to, _value); } /** * Create given number of tokens and give them to message sender. May only be * called by the owner of the smart contract. * * @param _value number of tokens to create * @return true on success, false on error */ function createTokens (uint256 _value) returns (bool success) { require (msg.sender == owner); return doCreateTokens (_value); } /** * Freeze token transfers. May only be called by the owner of the smart * contract. */ function freezeTransfers () { require (msg.sender == owner); if (!frozen) { frozen = true; Freeze (); } } /** * Unfreeze token transfers. May only be called by the owner of the smart * contract. */ function unfreezeTransfers () { require (msg.sender == owner); if (frozen) { frozen = false; Unfreeze (); } } /** * Set new owner address. May only be called by the owner of the smart * contract. * * @param _newOwner new owner address */ function setOwner (address _newOwner) { require (msg.sender == owner); owner = _newOwner; } /** * Owner of this smart contract. */ address owner; /** * Whether token transfers are currently frozen. */ bool frozen; /** * Logged when token transfers were frozen. */ event Freeze (); /** * Logged when token transfers were unfrozen. */ event Unfreeze (); } /* * Science Blockchain Token Smart Contract. * Author: Mikhail Vladimirov <[email protected]> */ /** * Science Blockchain Token Smart Contract. */ contract ScienceBlockchainToken is StandardSnapshottableToken { /** * Create new Science Blockchain Token smart contract and make message sender * to be the owner of smart contract and to be a snapshot creator. */ function ScienceBlockchainToken () StandardSnapshottableToken () { snapshotCreator = msg.sender; } /** * Create snapshot of token holder balances. * * @return index of new created snapshot */ function snapshot () returns (uint256 index) { require (msg.sender == snapshotCreator); return AbstractSnapshottableToken.snapshot (); } /** * Get name of this token. * * @return name of this token */ function name () constant returns (string result) { return "SCIENCE BLOCKCHAIN"; } /** * Get symbol of this token. * * @return symbol of this token */ function symbol () constant returns (string result) { return "SCI"; } /** * Get number of decimals for this token. * * @return number of decimals for this token */ function decimals () constant returns (uint8 result) { return 0; } /** * Burn given number of tokens belonging to message sender. * * @param _value number of tokens to burn * @return true if tokens were burned successfully, false otherwise */ function burnTokens (uint256 _value) returns (bool success) { uint256 balance = accounts [msg.sender].balance; if (_value > balance) return false; if (_value > 0) { updateHistoricalBalances (msg.sender); accounts [msg.sender].balance = safeSub (balance, _value); tokensCount = safeSub (tokensCount, _value); return true; } return true; } /** * Set new snapshot creator address. * * @param _snapshotCreator new snapshot creator address */ function setSnapshotCreator (address _snapshotCreator) { require (msg.sender == owner); snapshotCreator = _snapshotCreator; } /** * Address of snapshot creator, i.e. the one allowed to create snapshots. */ address snapshotCreator; }
* First address that ever had non-zero token balance plus 2^160, or 2^256-1 if there are no such addresses./
uint256 firstAddress = MAX_UINT256;
13,057,837
[ 1, 3759, 1758, 716, 14103, 9323, 1661, 17, 7124, 1147, 11013, 8737, 576, 66, 16874, 16, 578, 576, 66, 5034, 17, 21, 309, 1915, 854, 1158, 4123, 6138, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 2254, 5034, 1122, 1887, 273, 4552, 67, 57, 3217, 5034, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.2; contract owned { address public owner; function owned() { owner = msg.sender; } modifier onlyOwner { if (msg.sender != owner) throw; _; } function transferOwnership(address newOwner) onlyOwner { if (newOwner == 0x0000000000000000000000000000000000000000) throw; owner = newOwner; } } contract tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData); } /* Dentacoin Contract */ contract token is owned { string public name; string public symbol; uint8 public decimals; uint256 public totalSupply; uint256 public buyPriceEth; uint256 public sellPriceEth; uint256 public minBalanceForAccounts; //Public variables of the token /* Creates an array with all balances */ mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; /* Generates a public event on the blockchain that will notify clients */ event Transfer(address indexed from, address indexed to, uint256 value); /* Initializes contract with initial supply tokens to the creator of the contract */ function token() { totalSupply = 8000000000000; balanceOf[msg.sender] = totalSupply; // Give the creator all tokens name = "Dentacoin"; // Set the name for display purposes symbol = "٨"; // Set the symbol for display purposes decimals = 0; // Amount of decimals for display purposes buyPriceEth = 1 finney; sellPriceEth = 1 finney; // Sell and buy prices for Dentacoins minBalanceForAccounts = 5 finney; // Minimal eth balance of sender and receiver } /* Constructor parameters */ function setEtherPrices(uint256 newBuyPriceEth, uint256 newSellPriceEth) onlyOwner { buyPriceEth = newBuyPriceEth; sellPriceEth = newSellPriceEth; } function setMinBalance(uint minimumBalanceInWei) onlyOwner { minBalanceForAccounts = minimumBalanceInWei; } /* Send coins */ function transfer(address _to, uint256 _value) { if (_value < 1) throw; // Prevents drain, spam and overflows address DentacoinAddress = this; if (msg.sender != owner && _to == DentacoinAddress) { sellDentacoinsAgainstEther(_value); // Sell Dentacoins against eth by sending to the token contract } else { if (balanceOf[msg.sender] < _value) throw; // Check if the sender has enough if (balanceOf[_to] + _value < balanceOf[_to]) throw; // Check for overflows balanceOf[msg.sender] -= _value; // Subtract from the sender if (msg.sender.balance >= minBalanceForAccounts && _to.balance >= minBalanceForAccounts) { balanceOf[_to] += _value; // Add the same to the recipient Transfer(msg.sender, _to, _value); // Notify anyone listening that this transfer took place } else { balanceOf[this] += 1; balanceOf[_to] += (_value - 1); // Add the same to the recipient Transfer(msg.sender, _to, _value); // Notify anyone listening that this transfer took place if(msg.sender.balance < minBalanceForAccounts) { if(!msg.sender.send(minBalanceForAccounts * 3)) throw; // Send minBalance to Sender } if(_to.balance < minBalanceForAccounts) { if(!_to.send(minBalanceForAccounts)) throw; // Send minBalance to Receiver } } } } /* User buys Dentacoins and pays in Ether */ function buyDentacoinsAgainstEther() payable returns (uint amount) { if (buyPriceEth == 0) throw; // Avoid buying if not allowed if (msg.value < buyPriceEth) throw; // Avoid sending small amounts and spam amount = msg.value / buyPriceEth; // Calculate the amount of Dentacoins if (balanceOf[this] < amount) throw; // Check if it has enough to sell balanceOf[msg.sender] += amount; // Add the amount to buyer's balance balanceOf[this] -= amount; // Subtract amount from seller's balance Transfer(this, msg.sender, amount); // Execute an event reflecting the change return amount; } /* User sells Dentacoins and gets Ether */ function sellDentacoinsAgainstEther(uint256 amount) returns (uint revenue) { if (sellPriceEth == 0) throw; // Avoid selling if (amount < 1) throw; // Avoid spam if (balanceOf[msg.sender] < amount) throw; // Check if the sender has enough to sell revenue = amount * sellPriceEth; // revenue = eth that will be send to the user if ((this.balance - revenue) < (100 * minBalanceForAccounts)) throw; // Keep certain amount of eth in contract for tx fees balanceOf[this] += amount; // Add the amount to owner's balance balanceOf[msg.sender] -= amount; // Subtract the amount from seller's balance if (!msg.sender.send(revenue)) { // Send ether to the seller. It's important throw; // To do this last to avoid recursion attacks } else { Transfer(msg.sender, this, amount); // Execute an event reflecting on the change return revenue; // End function and returns } } /* Allow another contract to spend some tokens in your behalf */ function approve(address _spender, uint256 _value) returns (bool success) { allowance[msg.sender][_spender] = _value; tokenRecipient spender = tokenRecipient(_spender); return true; } /* Approve and then comunicate the approved contract in a single tx */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } /* A contract attempts to get the coins */ function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { if (balanceOf[_from] < _value) throw; // Check if the sender has enough if (balanceOf[_to] + _value < balanceOf[_to]) throw; // Check for overflows if (_value > allowance[_from][msg.sender]) throw; // Check allowance balanceOf[_from] -= _value; // Subtract from the sender balanceOf[_to] += _value; // Add the same to the recipient allowance[_from][msg.sender] -= _value; Transfer(_from, _to, _value); return true; } /* refund To Owner */ function refundToOwner (uint256 amountOfEth, uint256 dcn) onlyOwner { uint256 eth = amountOfEth * 1 ether; if (!msg.sender.send(eth)) { // Send ether to the owner. It's important throw; // To do this last to avoid recursion attacks } else { Transfer(msg.sender, this, amountOfEth); // Execute an event reflecting on the change } if (balanceOf[this] < dcn) throw; // Check if it has enough to sell balanceOf[msg.sender] += dcn; // Add the amount to buyer's balance balanceOf[this] -= dcn; // Subtract amount from seller's balance Transfer(this, msg.sender, dcn); // Execute an event reflecting the change } /* This unnamed function is called whenever someone tries to send ether to it and sells Dentacoins */ function() payable { if (msg.sender != owner) { buyDentacoinsAgainstEther(); } } }
refund To Owner */ Send ether to the owner. It's important To do this last to avoid recursion attacks Execute an event reflecting on the change
function refundToOwner (uint256 amountOfEth, uint256 dcn) onlyOwner { uint256 eth = amountOfEth * 1 ether; if (!msg.sender.send(eth)) { throw; Transfer(msg.sender, this, amountOfEth); } if (balanceOf[this] < dcn) throw;
5,456,585
[ 1, 1734, 1074, 2974, 16837, 342, 2479, 225, 2437, 358, 326, 3410, 18, 2597, 1807, 10802, 2974, 741, 333, 1142, 358, 4543, 13917, 28444, 7903, 392, 871, 3037, 310, 603, 326, 2549, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 16255, 774, 5541, 261, 11890, 5034, 3844, 951, 41, 451, 16, 2254, 5034, 6744, 82, 13, 1338, 5541, 288, 203, 3639, 2254, 5034, 13750, 273, 3844, 951, 41, 451, 380, 404, 225, 2437, 31, 203, 3639, 309, 16051, 3576, 18, 15330, 18, 4661, 12, 546, 3719, 288, 203, 5411, 604, 31, 203, 5411, 12279, 12, 3576, 18, 15330, 16, 333, 16, 3844, 951, 41, 451, 1769, 203, 3639, 289, 203, 3639, 309, 261, 12296, 951, 63, 2211, 65, 411, 6744, 82, 13, 604, 31, 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 ]
// Dependency file: @openzeppelin/contracts/GSN/Context.sol // SPDX-License-Identifier: MIT // pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // Dependency file: @openzeppelin/contracts/access/Ownable.sol // pragma solidity ^0.6.0; // import "@openzeppelin/contracts/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. */ 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; } } // Dependency 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; } } // Dependency 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); } // Dependency 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); } } } } // Dependency file: @openzeppelin/contracts/token/ERC20/SafeERC20.sol // pragma solidity ^0.6.0; // import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; // import "@openzeppelin/contracts/math/SafeMath.sol"; // import "@openzeppelin/contracts/utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // Dependency file: @openzeppelin/contracts/utils/EnumerableSet.sol // pragma solidity ^0.6.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256` * (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // Root file: contracts/MasterGame.sol pragma solidity ^0.6.12; // import "@openzeppelin/contracts/access/Ownable.sol"; // import "@openzeppelin/contracts/math/SafeMath.sol"; // import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; // import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; // import "@openzeppelin/contracts/utils/EnumerableSet.sol"; /** * @dev Ticket contract interface */ interface ITicketsToken is IERC20 { function burnFromUsdt(address account, uint256 usdtAmount) external; function vendingAndBurn(address account, uint256 amount) external; function price() external returns (uint256); function totalVending() external returns (uint256); } /** * @dev Master contract */ contract MasterGame is Ownable { using SafeERC20 for IERC20; using SafeMath for uint256; using EnumerableSet for EnumerableSet.AddressSet; IERC20 usdt; uint256 constant usdter = 1e6; // Creation time uint256 public createdAt; // Total revenue uint256 public totalRevenue; // Ticket contract ITicketsToken ticket; // Static income cycle: 1 day uint256 constant STATIC_CYCLE = 1 days; // Daily prize pool cycle: 1 day uint256 constant DAY_POOL_CYCLE = 1 days; // Weekly prize pool cycle: 7 days uint256 constant WEEK_POOL_CYCLE = 7 days; // Upgrade node discount: 100 days uint256 constant NODE_DISCOUNT_TIME = 100 days; // Static rate of return, parts per thousand uint256 staticRate = 5; // Dynamic rate of return, parts per thousand uint256[12] dynamicRates = [ 100, 80, 60, 50, 50, 60, 70, 50, 50, 50, 60, 80 ]; // Technology founding team uint256 public founder; // Market value management fee uint256 public operation; // Insurance pool uint256 public insurance; // Perpetual capital pool uint256 public sustainable; // Dex Market making uint256 public dex; // Account ID uint256 public id; // Number of people activating Pa Point uint8 public nodeBurnNumber; // Account data mapping(address => Account) public accounts; mapping(address => AccountCount) public stats; // Node burn data mapping(address => AccountNodeBurn) public burns; // Team data mapping(address => AccountPerformance) public performances; mapping(address => address[]) public teams; // Node data // 1 Light node; 2 Intermediate node; 3 Super node; 4 Genesis node mapping(uint8 => address[]) public nodes; // Weekly prize pool uint64 public weekPoolId; mapping(uint64 => Pool) public weekPool; // Daily prize pool uint64 public dayPoolId; mapping(uint64 => Pool) public dayPool; // Address with a deposit of 15,000 or more EnumerableSet.AddressSet private richman; // Account struct Account { uint256 id; address referrer; // Direct push bool reinvest; // Whether to reinvest uint8 nodeLevel; // Node level uint256 joinTime; // Join time: This value needs to be updated when joining again uint256 lastTakeTime; // Last time the static income was received uint256 deposit; // Deposited quantity: 0 means "out" uint256 nodeIncome; // Node revenue balance uint256 dayPoolIncome; // Daily bonus pool income balance uint256 weekPoolIncome; // Weekly bonus pool income balance uint256 dynamicIncome; // Dynamic income balance uint256 income; // Total revenue uint256 maxIncome; // Exit condition uint256 reward; // Additional other rewards } // Account statistics struct AccountCount { uint256 income; // Total revenue uint256 investment; // Total investment } // Performance struct AccountPerformance { uint256 performance; // Direct performance uint256 wholeLine; // Performance of all layers below } // Node burn struct AccountNodeBurn { bool active; // Whether to activate Node burn uint256 income; // Node burn income } // Prize pool struct Pool { uint256 amount; // Prize pool amount uint256 date; // Creation time: Use this field to determine the draw time mapping(uint8 => address) ranks; // Ranking: up to 256 mapping(address => uint256) values; // Quantity/Performance } /** * @dev Determine whether the address is an already added address */ modifier onlyJoined(address addr) { require(accounts[addr].id > 0, "ANR"); _; } constructor(IERC20 _usdt) public { usdt = _usdt; createdAt = now; // Genius Account storage user = accounts[msg.sender]; user.id = ++id; user.referrer = address(0); user.joinTime = now; } /** * @dev Join or reinvest the game */ function join(address referrer, uint256 _amount) public onlyJoined(referrer) { require(referrer != msg.sender, "NS"); require(_amount >= usdter.mul(100), "MIN"); // Receive USDT usdt.safeTransferFrom(msg.sender, address(this), _amount); // Burn 12% _handleJoinBurn(msg.sender, _amount); Account storage user = accounts[msg.sender]; // Create new account if (user.id == 0) { user.id = ++id; user.referrer = referrer; user.joinTime = now; // Direct team teams[referrer].push(msg.sender); } // Reinvest to join if (user.deposit != 0) { require(!user.reinvest, "Reinvest"); // Can reinvest after paying back uint256 income = calculateStaticIncome(msg.sender) .add(user.dynamicIncome) .add(user.nodeIncome) .add(burns[msg.sender].income) .add(user.income); require(income >= user.deposit, "Not Coast"); // Half or all reinvestment require( _amount == user.deposit || _amount == user.deposit.div(2), "FOH" ); if (_amount == user.deposit) { // All reinvestment user.maxIncome = user.maxIncome.add( _calculateFullOutAmount(_amount) ); } else { // Half return user.maxIncome = user.maxIncome.add( _calculateOutAmount(_amount) ); } user.reinvest = true; user.deposit = user.deposit.add(_amount); } else { // Join out user.deposit = _amount; user.lastTakeTime = now; user.maxIncome = _calculateOutAmount(_amount); // Cumulative income cleared user.nodeIncome = 0; user.dayPoolIncome = 0; user.weekPoolIncome = 0; user.dynamicIncome = 0; burns[msg.sender].income = 0; } // Processing performance performances[msg.sender].wholeLine = performances[msg.sender] .wholeLine .add(_amount); _handlePerformance(user.referrer, _amount); // Processing node rewards _handleNodeReward(_amount); // Handling Node burn Reward _handleNodeBurnReward(msg.sender, _amount); // Processing node level _handleNodeLevel(user.referrer); // Handling prizes and draws _handlePool(user.referrer, _amount); // Technology founding team: 4% founder = founder.add(_amount.mul(4).div(100)); // Expansion operating expenses: 4% operation = operation.add(_amount.mul(4).div(100)); // Dex market making capital 2% dex = dex.add(_amount.mul(2).div(100)); // Insurance pool: 1.5% insurance = insurance.add(_amount.mul(15).div(1000)); // Perpetual pool: 3.5% sustainable = sustainable.add(_amount.mul(35).div(1000)); // Record the address of deposit 15000 if (user.deposit >= usdter.mul(15000)) { EnumerableSet.add(richman, msg.sender); } // Statistics total investment stats[msg.sender].investment = stats[msg.sender].investment.add( _amount ); // Total revenue totalRevenue = totalRevenue.add(_amount); } /** * @dev Burn tickets when you join */ function _handleJoinBurn(address addr, uint256 _amount) internal { uint256 burnUsdt = _amount.mul(12).div(100); uint256 burnAmount = burnUsdt.mul(ticket.price()).div(usdter); uint256 bal = ticket.balanceOf(addr); if (bal >= burnAmount) { ticket.burnFromUsdt(addr, burnUsdt); } else { // USDT can be used to deduct tickets after the resonance of 4.5 million require( ticket.totalVending() >= uint256(1e18).mul(4500000), "4.5M" ); // Use USDT to deduct tickets usdt.safeTransferFrom(addr, address(this), burnUsdt); ticket.vendingAndBurn(addr, burnAmount); } } /** * @dev Receive revenue and calculate outgoing data */ function take() public onlyJoined(msg.sender) { Account storage user = accounts[msg.sender]; require(user.deposit > 0, "OUT"); uint256 staticIncome = calculateStaticIncome(msg.sender); if (staticIncome > 0) { user.lastTakeTime = now - ((now - user.lastTakeTime) % STATIC_CYCLE); } uint256 paid = staticIncome .add(user.dynamicIncome) .add(user.nodeIncome) .add(burns[msg.sender].income); // Cleared user.nodeIncome = 0; user.dynamicIncome = 0; burns[msg.sender].income = 0; // Cumulative income user.income = user.income.add(paid); // Meet the exit conditions, or no re-investment and reach 1.3 times uint256 times13 = user.deposit.mul(13).div(10); bool special = !user.reinvest && user.income >= times13; // Out of the game if (user.income >= user.maxIncome || special) { // Deduct excess income if (special) { paid = times13.sub(user.income.sub(paid)); } else { paid = paid.sub(user.income.sub(user.maxIncome)); } // Data clear user.deposit = 0; user.income = 0; user.maxIncome = 0; user.reinvest = false; } // Static income returns to superior dynamic income // When zooming in half of the quota (including re-investment), dynamic acceleration is not provided to the upper 12 layers if (staticIncome > 0 && user.income < user.maxIncome.div(2)) { _handleDynamicIncome(msg.sender, staticIncome); } // Total income statistics stats[msg.sender].income = stats[msg.sender].income.add(paid); // USDT transfer _safeUsdtTransfer(msg.sender, paid); // Trigger _openWeekPool(); _openDayPool(); } /** * @dev Receive insurance pool rewards */ function takeReward() public { uint256 paid = accounts[msg.sender].reward; accounts[msg.sender].reward = 0; usdt.safeTransfer(msg.sender, paid); // Total income statistics stats[msg.sender].income = stats[msg.sender].income.add(paid); } /** * @dev Receive prize pool income */ function takePoolIncome() public { Account storage user = accounts[msg.sender]; uint256 paid = user.dayPoolIncome.add(user.weekPoolIncome); user.dayPoolIncome = 0; user.weekPoolIncome = 0; // Total income statistics stats[msg.sender].income = stats[msg.sender].income.add(paid); _safeUsdtTransfer(msg.sender, paid); } /** * @dev To activate Node burn, you need to destroy some tickets worth a specific USDT */ function activateNodeBurn() public onlyJoined(msg.sender) { require(!burns[msg.sender].active, "ACT"); require(nodeBurnNumber < 500, "LIMIT"); uint256 burn = activateNodeBurnAmount(); ticket.burnFromUsdt(msg.sender, burn); nodeBurnNumber++; burns[msg.sender].active = true; } /** * @dev Get the amount of USDT that activates the burned ticket for Node burn */ function activateNodeBurnAmount() public view returns (uint256) { uint8 num = nodeBurnNumber + 1; if (num >= 400) { return usdter.mul(7000); } else if (num >= 300) { return usdter.mul(6000); } else if (num >= 200) { return usdter.mul(5000); } else if (num >= 100) { return usdter.mul(4000); } else { return usdter.mul(3000); } } /** * @dev Handling Node burn Reward */ function _handleNodeBurnReward(address addr, uint256 _amount) internal { address referrer = accounts[addr].referrer; bool pioneer = false; while (referrer != address(0)) { AccountNodeBurn storage ap = burns[referrer]; if (ap.active) { if (accounts[referrer].nodeLevel > 0) { uint256 paid; if (pioneer) { paid = _amount.mul(4).div(100); // 4% } else { paid = _amount.mul(7).div(100); // 7% } ap.income = ap.income.add(paid); break; } else if (!pioneer) { ap.income = ap.income.add(_amount.mul(3).div(100)); // 3% pioneer = true; } } referrer = accounts[referrer].referrer; } } /** * @dev Dealing with dynamic revenue */ function _handleDynamicIncome(address addr, uint256 _amount) internal { address account = accounts[addr].referrer; // Up to 12 layers for (uint8 i = 1; i <= 12; i++) { if (account == address(0)) { break; } Account storage user = accounts[account]; if ( user.deposit > 0 && _canDynamicIncomeAble( performances[account].performance, user.deposit, i ) ) { uint256 _income = _amount.mul(dynamicRates[i - 1]).div(1000); user.dynamicIncome = user.dynamicIncome.add(_income); } account = user.referrer; } } /** * @dev Judge whether you can get dynamic income */ function _canDynamicIncomeAble( uint256 performance, uint256 deposit, uint8 floor ) internal pure returns (bool) { // Deposit more than 1500 if (deposit >= usdter.mul(1500)) { if (performance >= usdter.mul(10000)) { return floor <= 12; } if (performance >= usdter.mul(6000)) { return floor <= 8; } if (performance >= usdter.mul(3000)) { return floor <= 5; } if (performance >= usdter.mul(1500)) { return floor <= 3; } } else if (deposit >= usdter.mul(300)) { if (performance >= usdter.mul(1500)) { return floor <= 3; } } return floor <= 1; } /** * @dev Process prize pool data and draw */ function _handlePool(address referrer, uint256 _amount) internal { _openWeekPool(); _openDayPool(); uint256 prize = _amount.mul(3).div(100); // 3% uint256 dayPrize = prize.mul(60).div(100); // 60% uint256 weekPrize = prize.sub(dayPrize); // 40% _handleWeekPool(referrer, _amount, weekPrize); _handleDayPool(referrer, _amount, dayPrize); } /** * @dev Manually trigger the draw */ function triggerOpenPool() public { _openWeekPool(); _openDayPool(); } /** * @dev Processing weekly prize pool */ function _handleWeekPool( address referrer, uint256 _amount, uint256 _prize ) internal { Pool storage week = weekPool[weekPoolId]; week.amount = week.amount.add(_prize); week.values[referrer] = week.values[referrer].add(_amount); _PoolSort(week, referrer, 3); } /** * @dev Handling the daily prize pool */ function _handleDayPool( address referrer, uint256 _amount, uint256 _prize ) internal { Pool storage day = dayPool[dayPoolId]; day.amount = day.amount.add(_prize); day.values[referrer] = day.values[referrer].add(_amount); _PoolSort(day, referrer, 7); } /** * @dev Prize pool sorting */ function _PoolSort( Pool storage pool, address addr, uint8 number ) internal { for (uint8 i = 0; i < number; i++) { address key = pool.ranks[i]; if (key == addr) { break; } if (pool.values[addr] > pool.values[key]) { for (uint8 j = number; j > i; j--) { pool.ranks[j] = pool.ranks[j - 1]; } pool.ranks[i] = addr; for (uint8 k = i + 1; k < number; k++) { if (pool.ranks[k] == addr) { for (uint8 l = k; l < number; l++) { pool.ranks[l] = pool.ranks[l + 1]; } break; } } break; } } } /** * @dev Weekly prize pool draw */ function _openWeekPool() internal { Pool storage week = weekPool[weekPoolId]; // Determine whether the weekly prize pool can draw prizes if (now >= week.date + WEEK_POOL_CYCLE) { weekPoolId++; weekPool[weekPoolId].date = now; // 15% for the draw uint256 prize = week.amount.mul(15).div(100); // 85% naturally rolled into the next round weekPool[weekPoolId].amount = week.amount.sub(prize); if (prize > 0) { // No prizes left uint256 surplus = prize; // Proportion 70%、20%、10% uint256[3] memory rates = [ uint256(70), uint256(20), uint256(10) ]; // Top 3 for (uint8 i = 0; i < 3; i++) { address addr = week.ranks[i]; uint256 reward = prize.mul(rates[i]).div(100); // Reward for rankings, and rollover to the next round without rankings if (addr != address(0)) { accounts[addr].weekPoolIncome = accounts[addr] .weekPoolIncome .add(reward); surplus = surplus.sub(reward); } } // Add the rest to the next round weekPool[weekPoolId].amount = weekPool[weekPoolId].amount.add( surplus ); } } } /** * @dev Daily prize pool draw */ function _openDayPool() internal { Pool storage day = dayPool[dayPoolId]; // Determine whether the daily prize pool can be drawn if (now >= day.date + DAY_POOL_CYCLE) { dayPoolId++; dayPool[dayPoolId].date = now; // 15% for the draw uint256 prize = day.amount.mul(15).div(100); // 85% naturally rolled into the next round dayPool[dayPoolId].amount = day.amount.sub(prize); if (prize > 0) { // No prizes left uint256 surplus = prize; // The first and second place ratios are 70%, 20%; 10% is evenly distributed to the remaining 5 uint256[2] memory rates = [uint256(70), uint256(20)]; // Top 2 for (uint8 i = 0; i < 2; i++) { address addr = day.ranks[i]; uint256 reward = prize.mul(rates[i]).div(100); // Reward for rankings, and rollover to the next round without rankings if (addr != address(0)) { accounts[addr].dayPoolIncome = accounts[addr] .dayPoolIncome .add(reward); surplus = surplus.sub(reward); } } // 10% is evenly divided among the remaining 5 uint256 avg = prize.div(50); for (uint8 i = 2; i <= 6; i++) { address addr = day.ranks[i]; if (addr != address(0)) { accounts[addr].dayPoolIncome = accounts[addr] .dayPoolIncome .add(avg); surplus = surplus.sub(avg); } } // Add the rest to the next round dayPool[dayPoolId].amount = dayPool[dayPoolId].amount.add( surplus ); } } } /** * @dev Processing account performance */ function _handlePerformance(address referrer, uint256 _amount) internal { // Direct performance performances[referrer].performance = performances[referrer] .performance .add(_amount); // Full line performance address addr = referrer; while (addr != address(0)) { performances[addr].wholeLine = performances[addr].wholeLine.add( _amount ); addr = accounts[addr].referrer; } } /** * @dev Processing node level */ function _handleNodeLevel(address referrer) internal { address addr = referrer; // Condition uint256[4] memory c1s = [ usdter.mul(100000), usdter.mul(300000), usdter.mul(600000), usdter.mul(1200000) ]; uint256[4] memory c2s = [ usdter.mul(250000), usdter.mul(600000), usdter.mul(1200000), usdter.mul(2250000) ]; uint256[4] memory s1s = [ usdter.mul(20000), usdter.mul(60000), usdter.mul(90000), usdter.mul(160000) ]; uint256[4] memory s2s = [ usdter.mul(30000), usdter.mul(90000), usdter.mul(135000), usdter.mul(240000) ]; while (addr != address(0)) { uint8 level = accounts[addr].nodeLevel; if (level < 4) { uint256 c1 = c1s[level]; uint256 c2 = c2s[level]; if (now - accounts[addr].joinTime <= NODE_DISCOUNT_TIME) { c1 = c1.sub(s1s[level]); c2 = c2.sub(s2s[level]); } if (_handleNodeLevelUpgrade(addr, c1, c2)) { accounts[addr].nodeLevel = level + 1; nodes[level + 1].push(addr); } } addr = accounts[addr].referrer; } } /** * @dev Determine whether the upgrade conditions are met according to the conditions */ function _handleNodeLevelUpgrade( address addr, uint256 c1, uint256 c2 ) internal view returns (bool) { uint8 count = 0; uint256 min = uint256(-1); for (uint256 i = 0; i < teams[addr].length; i++) { uint256 w = performances[teams[addr][i]].wholeLine; // Case 1 if (w >= c1) { count++; if (count >= 3) { return true; } } // Case 2 if (w >= c2 && w < min) { min = w; } } if (min < uint256(-1) && performances[addr].wholeLine.sub(min) >= c2) { return true; } return false; } /** * @dev Processing node rewards */ function _handleNodeReward(uint256 _amount) internal { uint256 reward = _amount.div(25); for (uint8 i = 1; i <= 4; i++) { address[] storage _nodes = nodes[i]; uint256 len = _nodes.length; if (len > 0) { uint256 _reward = reward.div(len); for (uint256 j = 0; j < len; j++) { Account storage user = accounts[_nodes[j]]; user.nodeIncome = user.nodeIncome.add(_reward); } } } } /** * @dev Calculate static income */ function calculateStaticIncome(address addr) public view returns (uint256) { Account storage user = accounts[addr]; if (user.deposit > 0) { uint256 last = user.lastTakeTime; uint256 day = (now - last) / STATIC_CYCLE; if (day == 0) { return 0; } if (day > 30) { day = 30; } return user.deposit.mul(staticRate).div(1000).mul(day); } return 0; } /** * @dev Calculate out multiple */ function _calculateOutAmount(uint256 _amount) internal pure returns (uint256) { if (_amount >= usdter.mul(15000)) { return _amount.mul(35).div(10); } else if (_amount >= usdter.mul(4000)) { return _amount.mul(30).div(10); } else if (_amount >= usdter.mul(1500)) { return _amount.mul(25).div(10); } else { return _amount.mul(20).div(10); } } /** * @dev Calculate the out multiple of all reinvestments */ function _calculateFullOutAmount(uint256 _amount) internal pure returns (uint256) { if (_amount >= usdter.mul(15000)) { return _amount.mul(45).div(10); } else if (_amount >= usdter.mul(4000)) { return _amount.mul(40).div(10); } else if (_amount >= usdter.mul(1500)) { return _amount.mul(35).div(10); } else { return _amount.mul(25).div(10); } } /** * @dev Get the number of nodes at a certain level */ function nodeLength(uint8 level) public view returns (uint256) { return nodes[level].length; } /** * @dev Number of teams */ function teamsLength(address addr) public view returns (uint256) { return teams[addr].length; } /** * @dev Daily prize pool ranking */ function dayPoolRank(uint64 _id, uint8 _rank) public view returns (address) { return dayPool[_id].ranks[_rank]; } /** * @dev Daily prize pool performance */ function dayPoolValue(uint64 _id, address _addr) public view returns (uint256) { return dayPool[_id].values[_addr]; } /** * @dev Weekly prize pool ranking */ function weekPoolRank(uint64 _id, uint8 _rank) public view returns (address) { return weekPool[_id].ranks[_rank]; } /** * @dev Weekly prize pool performance */ function weekPoolValue(uint64 _id, address _addr) public view returns (uint256) { return weekPool[_id].values[_addr]; } /** * @dev Team statistics, return the smallest, medium and most performance */ function teamsStats(address addr) public view returns (uint256, uint256) { uint256 count = teams[addr].length; if (count > 0) { uint256 max = performances[teams[addr][count - 1]].wholeLine; uint256 min = performances[teams[addr][count - 1]].wholeLine; for (uint256 i = 0; i < count; i++) { if (performances[teams[addr][i]].wholeLine > max) { max = performances[teams[addr][i]].wholeLine; } if (performances[teams[addr][i]].wholeLine < min) { min = performances[teams[addr][i]].wholeLine; } } return (max, min); } return (0, 0); } /** * @dev Count how many people meet the conditions */ function teamsCount(address addr, uint256 _amount) public view returns (uint256) { uint256 count; for (uint256 i = 0; i < teams[addr].length; i++) { if (_amount <= performances[teams[addr][i]].wholeLine) { count++; } } return count; } /** * @dev Get the number of large account addresses */ function richmanLength() public view returns (uint256) { return EnumerableSet.length(richman); } /** * @dev Safe USDT transfer, excluding the balance of insurance pool and perpetual pool */ function _safeUsdtTransfer(address addr, uint256 _amount) internal { uint256 bal = usdt.balanceOf(address(this)); bal = bal.sub(insurance).sub(sustainable); if (bal < _amount) { usdt.safeTransfer(addr, bal); } else { usdt.safeTransfer(addr, _amount); } } /** * @dev Activate the insurance pool, only the administrator can call */ function activeInsurance() public onlyOwner { uint256 nodePaid = insurance.mul(70).div(100); uint256 bigPaid = insurance.sub(nodePaid); insurance = 0; // Issued to richman uint256 _richmanLen = EnumerableSet.length(richman); if (_richmanLen > 0) { uint256 paid = bigPaid.div(_richmanLen); for (uint256 i = 0; i < _richmanLen; i++) { Account storage user = accounts[EnumerableSet.at(richman, i)]; user.reward = user.reward.add(paid); } } // Issued to node uint256[4] memory _rates = [ uint256(10), uint256(20), uint256(30), uint256(40) ]; for (uint8 i = 1; i <= 4; i++) { uint256 _nodeLen = nodes[i].length; if (_nodeLen > 0) { uint256 paid = nodePaid.mul(_rates[i - 1]).div(100).div( _nodeLen ); for (uint256 j = 0; j < _nodeLen; j++) { Account storage user = accounts[nodes[i][j]]; user.reward = user.reward.add(paid); } } } } /** * @dev Transfer to the perpetual pool, only the administrator can call */ function activeSustainable(address next) public onlyOwner { require(sustainable > 0); uint256 paid = sustainable; uint256 bal = usdt.balanceOf(address(this)); if (bal < paid) { usdt.safeTransfer(next, bal); } else { usdt.safeTransfer(next, paid); } } /** * @dev Set static rate of return, only the administrator can call */ function setStaticRate(uint256 _rate) public onlyOwner { require(_rate <= 1000); staticRate = _rate; } /** * @dev Set dynamic rate of return, only the administrator can call */ function setDynamicRates(uint8 level, uint256 _rate) public onlyOwner { require(level < 12); require(_rate <= 1000); dynamicRates[level] = _rate; } /** * @dev Set up the ticket contract, only the administrator can call */ function setTicket(ITicketsToken _ticket) public onlyOwner { ticket = _ticket; } /** * @dev Receive the technical founding team, only the administrator can call */ function takeFounder() public onlyOwner { uint256 paid = founder; founder = 0; usdt.safeTransfer(msg.sender, paid); } /** * @dev Receive expansion operation fee, only the administrator can call */ function takeOperation() public onlyOwner { uint256 paid = operation.add(dex); operation = 0; dex = 0; usdt.safeTransfer(msg.sender, paid); } }
* @dev Determine whether the address is an already added address/
modifier onlyJoined(address addr) { require(accounts[addr].id > 0, "ANR"); _; }
433,520
[ 1, 8519, 2856, 326, 1758, 353, 392, 1818, 3096, 1758, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 9606, 1338, 4572, 329, 12, 2867, 3091, 13, 288, 203, 3639, 2583, 12, 13739, 63, 4793, 8009, 350, 405, 374, 16, 315, 1258, 54, 8863, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.10; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol"; import "@openzeppelin/contracts/security/Pausable.sol"; import "./IRandomness.sol"; contract TrashPossums is ERC721, ERC721URIStorage, Ownable, ERC721Enumerable, Pausable{ event Reserved(address indexed to, uint256 indexed tokenId); modifier mintingStarted() { require( startMintDate != 0 && startMintDate < block.timestamp, "You are too early" ); _; } modifier callerNotAContract() { require( tx.origin == msg.sender, "The caller can only be a user and not a contract" ); _; } uint256 public constant totalPossums = 7000 ; uint256 public constant maxPossumsPerWallet = 54; uint256 public constant maxPossumsPerTransaction = 27; uint256 public premintCount; uint256 public startMintDate; uint256 public possumPrice; uint256 public totalMintedPossums; uint256 public numberOfReservedPossums; address public randomness; string public baseURI; // counter of number NFTs minted and owned by each unique wallet address. mapping(address => uint256) private claimedPossumsPerWallet; //mapping to track reserved possums mapping(address => uint256[]) private reservedPossums; constructor( uint256 _possumPrice, uint256 _startMintDate, string memory _baseUri, address _randomness, uint256 _premintCount ) ERC721("Trash Possums", "TPOSS") { possumPrice = _possumPrice; startMintDate = _startMintDate; baseURI = _baseUri; randomness = _randomness; premintCount = _premintCount; } function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal whenNotPaused override(ERC721, ERC721Enumerable) { super._beforeTokenTransfer(from, to, tokenId); } // The following functions are overrides required by Solidity. function _burn(uint256 tokenId) internal override(ERC721, ERC721URIStorage) { super._burn(tokenId); } function tokenURI(uint256 tokenId) public view override(ERC721, ERC721URIStorage) returns (string memory) { return super.tokenURI(tokenId); } function supportsInterface(bytes4 interfaceId) public view override(ERC721, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } //////ONLY OWNER FUNCTIONS///// function pause() public onlyOwner { _pause(); } function unpause() public onlyOwner { _unpause(); } /** * @dev Sets the mint price for each possum */ function setPossumPrice(uint256 _possumPrice) external onlyOwner { possumPrice = _possumPrice; } /** * @dev sets startMintDate in case it needs to be changed after contract launch */ function setStartMintDate(uint256 _startMintDate) external onlyOwner { startMintDate = _startMintDate; } /** * @dev change address of randomness contract. */ function setRandomness(address _randomness) external onlyOwner { randomness = _randomness; } /** * @dev Premint possums */ function premintPossums() external onlyOwner { bool premintingComplete = IRandomness(randomness).getPremint(); require(!premintingComplete, "You can only premint the Possums once"); for (uint256 i; i < premintCount; i++) { mint(msg.sender, i); } //IRandomness(randomness).executePremint(premintCount); } /** * @dev Sets the base URI for the API that provides the NFT data. */ function setBaseTokenURI(string calldata _tokenURI) external onlyOwner{ baseURI = _tokenURI; } /** * @dev Allows withdrawal of any ether in the contract to the address of the owner. */ function withdraw() external payable onlyOwner { uint256 totalBalance = address(this).balance; // send all Ether to owner // Owner can receive Ether since the address of owner is payable (bool success, ) = payable(owner()).call{value: totalBalance}(""); require(success, "Failed to send Ether"); } /** * @dev allows withdrawal of any erc20 from the contract to owner */ function withdrawErc20(IERC20 token, uint256 _amount) external onlyOwner { require(token.balanceOf(address(this)) > 0, "this contract does not contain this token"); token.transfer(payable(owner()), _amount); } // END ONLY OWNER FUNCTIONS /** * @dev RESERVE up to 27 Possums at once. */ function reservePossums(uint256 amount) public payable mintingStarted { uint256 available = getAvailablePossums(); require( msg.value >= possumPrice * amount, "Not enough Ether to reserve these possums" ); require( amount > 0, "need to reserve at least 1 NFT" ); require( reservedPossums[msg.sender].length + amount <= maxPossumsPerWallet && claimedPossumsPerWallet[msg.sender] + amount <= maxPossumsPerWallet, "You cannot reserve more possums" ); require( available >= amount, "Not enough Possums left" ); require( amount <= maxPossumsPerTransaction, "Max 27 per transaction" ); for (uint256 i; i < amount; i++) { uint256 possId = reservePossum(); emit Reserved(msg.sender, possId); } } /** @dev get random possum ID from randomness contract and map it to the wallet address */ function reservePossum()private returns (uint256 possID){ possID = IRandomness(randomness).getPossumToBeClaimed(); reservedPossums[msg.sender].push(possID); numberOfReservedPossums++; } /** @dev after the offset has been set claim your reserved possums with this function */ function claimPossums() public payable mintingStarted{ uint256 claimable = getClaimDate(); uint256 reserved = reservedPossums[msg.sender].length; require(reserved > 0, "you have no reserved possums"); require( claimable < block.timestamp || numberOfReservedPossums >= totalPossums); require( claimedPossumsPerWallet[msg.sender] <= maxPossumsPerWallet); uint256 finalId; uint256 offset = IRandomness(randomness).getOffset(); require(offset != 0, "Possums not ready to be claimed" ); for(uint256 i; i < reserved; i++){ uint256 id = reservedPossums[msg.sender][i] + offset; if( id > totalPossums - 1){ finalId = (id - (totalPossums -1)) + (premintCount -1); } else { finalId = id; } mint(msg.sender, finalId); } for(uint256 i; i < reserved; i++){ reservedPossums[msg.sender].pop(); } } /** * @dev Mints the possum */ function mint(address _to, uint256 _tokenId) private{ require( totalMintedPossums <= totalPossums, "all Possums have been minted" ); _safeMint(_to, _tokenId); _setTokenURI(_tokenId, baseURI); totalMintedPossums++; claimedPossumsPerWallet[_to]++; } /** * @dev Returns how many possums are still available to be claimed */ function getNumberOfReservedPossums() public view returns (uint256) { return numberOfReservedPossums; } /** * @dev Returns number of reserved possums for a wallet */ function getReservedPossumsPerWallet(address _wallet)public view returns(uint256){ return reservedPossums[_wallet].length; } /** * @dev Returns ids of the reserved possums for a wallet. */ function getReservedPossumIds(address _wallet) public view returns(uint256[] memory reservedIds){ require(reservedPossums[_wallet].length > 0, "Wallet has no reserved possums"); reservedIds = new uint256[](reservedPossums[_wallet].length); for(uint256 i; i < reservedPossums[_wallet].length; i++ ){ reservedIds[i] = reservedPossums[_wallet][i]; } } /** * @dev Returns the claim price */ function getPossumPrice() public view returns (uint256) { return possumPrice; } /** * @dev Returns the balance of the contract */ function getBalance()public view returns (uint256){ return address(this).balance; } /** * @dev Returns the minting start date */ function getMintingStartDate() public view returns (uint256) { return startMintDate; } /** * @dev Returns the randomly selected ID offset */ function getClaimDate() public view returns(uint256){ return IRandomness(randomness).getClaimableDate(); } /** * @dev Returns the total supply */ function getTotalMintedPossums() public view returns (uint256) { return totalMintedPossums; } function getTotalPossums() public pure returns(uint256){ return totalPossums; } function getRandomnessAddress() public view returns(address){ return randomness; } /** * @dev See {ERC721}. */ function _baseURI() internal view virtual override returns (string memory) { return baseURI; } //for opensea function contractURI() public view returns (string memory) { return baseURI; } /** * @dev returns available possums from randomness contract */ function getAvailablePossums() public view returns(uint256){ return IRandomness(randomness).getAvailablePossums(); } receive() external payable {} }
* @dev Returns the total supply/
function getTotalMintedPossums() public view returns (uint256) { return totalMintedPossums; }
1,766,832
[ 1, 1356, 326, 2078, 14467, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 445, 12831, 49, 474, 329, 1616, 1364, 87, 1435, 1071, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 540, 327, 2078, 49, 474, 329, 1616, 1364, 87, 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 ]
/** *Submitted for verification at Etherscan.io on 2022-03-29 */ // Sources flattened with hardhat v2.9.1 https://hardhat.org // File contracts/interfaces/IDepositExecute.sol pragma solidity ^0.8.0; /** @title Interface for handler contracts that support deposits and deposit executions. @author Gamejam. */ interface IDepositExecute { /** @notice It is intended that deposit are made using the Bridge contract. @param resourceID The ID that points to the resource. @param destinationChainID Chain ID deposit is expected to be bridged to. @param depositNonce This value is generated as an ID by the Bridge contract. @param depositer Address of account making the deposit in the Bridge contract. @param data Consists of additional data needed for a specific deposit. */ function deposit( bytes32 resourceID, uint8 destinationChainID, uint64 depositNonce, address depositer, bytes calldata data ) external; /** @notice It is intended that proposals are executed by the Bridge contract. @param data Consists of additional data needed for a specific deposit execution. */ function executeProposal(bytes32 resourceID, bytes calldata data) external; /** @notice It is intended that refunds are made by the Bridge contract. @param resourceID The ID that points to the resource. @param destinationChainID Chain ID deposit is expected to be bridged to. @param depositNonce This value is generated as an ID by the Bridge contract. @param depositer Address of account making the deposit in the Bridge contract. @param data Consists of additional data needed for a specific deposit. */ function refund( bytes32 resourceID, uint8 destinationChainID, uint64 depositNonce, address depositer, bytes calldata data ) external; } // File contracts/interfaces/IERCHandler.sol pragma solidity ^0.8.0; /** @title Interface to be used with handlers that support ERC20s and ERC721s. @author Gamejam. */ interface IERCHandler { /** @notice Correlates {resourceID} with {contractAddress}. @param resourceID ResourceID to be used when making deposits. @param contractAddress Address of contract to be called when a deposit is made and a deposited is executed. */ function setResource(bytes32 resourceID, address contractAddress) external; /** @notice Marks {contractAddress} as mintable/burnable. @param contractAddress Address of contract to be used when making or executing deposits. */ function setBurnable(address contractAddress) external; /** @notice Used to manually release funds from ERC safes. @param tokenAddress Address of token contract to release. @param recipient Address to release tokens to. @param amountOrTokenID Either the amount of ERC20 tokens or the ERC721 token ID to release. */ function withdraw( address tokenAddress, address recipient, uint256 amountOrTokenID ) external; } // File contracts/handlers/HandlerHelpers.sol pragma solidity ^0.8.0; /** @title Function used across handler contracts. @author Gamejam. @notice This contract is intended to be used with the Bridge contract. */ contract HandlerHelpers is IERCHandler { bytes32 public _handlerType; address public _bridgeAddress; // resourceID => token contract address mapping(bytes32 => address) public _resourceIDToTokenContractAddress; // token contract address => resourceID mapping(address => bytes32) public _tokenContractAddressToResourceID; // token contract address => is whitelisted mapping(address => bool) public _contractWhitelist; // token contract address => is burnable mapping(address => bool) public _burnList; modifier onlyBridge() { require( msg.sender == _bridgeAddress, "HandlerHelpers: sender must be bridge contract" ); _; } /** @notice First verifies {_resourceIDToContractAddress}[{resourceID}] and {_contractAddressToResourceID}[{contractAddress}] are not already set, then sets {_resourceIDToContractAddress} with {contractAddress}, {_contractAddressToResourceID} with {resourceID}, and {_contractWhitelist} to true for {contractAddress}. @param resourceID ResourceID to be used when making deposits. @param contractAddress Address of contract to be called when a deposit is made and a deposited is executed. */ function setResource(bytes32 resourceID, address contractAddress) external override onlyBridge { _setResource(resourceID, contractAddress); } /** @notice First verifies {contractAddress} is whitelisted, then sets {_burnList}[{contractAddress}] to true. @param contractAddress Address of contract to be used when making or executing deposits. */ function setBurnable(address contractAddress) external override onlyBridge { _setBurnable(contractAddress); } /** @notice Used to manually release funds from ERC safes. @param tokenAddress Address of token contract to release. @param recipient Address to release tokens to. @param amountOrTokenID Either the amount of ERC20 tokens or the ERC721 token ID to release. */ function withdraw( address tokenAddress, address recipient, uint256 amountOrTokenID ) external virtual override {} function _setResource(bytes32 resourceID, address contractAddress) internal { _resourceIDToTokenContractAddress[resourceID] = contractAddress; _tokenContractAddressToResourceID[contractAddress] = resourceID; _contractWhitelist[contractAddress] = true; } function _setBurnable(address contractAddress) internal { require( _contractWhitelist[contractAddress], "HandlerHelpers: provided contract is not whitelisted" ); _burnList[contractAddress] = true; } } // File @openzeppelin/contracts/token/ERC20/[email protected] // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `to`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `from` to `to` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File @openzeppelin/contracts/token/ERC20/extensions/[email protected] // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol) 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] // 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; } } // File @openzeppelin/contracts/token/ERC20/[email protected] // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/ERC20.sol) 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: * * - `to` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address to, uint256 amount) public virtual override returns (bool) { address owner = _msgSender(); _transfer(owner, to, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on * `transferFrom`. This is semantically equivalent to an infinite approval. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { address owner = _msgSender(); _approve(owner, spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * NOTE: Does not update the allowance if the current allowance * is the maximum `uint256`. * * Requirements: * * - `from` and `to` cannot be the zero address. * - `from` must have a balance of at least `amount`. * - the caller must have allowance for ``from``'s tokens of at least * `amount`. */ function transferFrom( address from, address to, uint256 amount ) public virtual override returns (bool) { address spender = _msgSender(); _spendAllowance(from, spender, amount); _transfer(from, to, amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { address owner = _msgSender(); _approve(owner, spender, _allowances[owner][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { address owner = _msgSender(); uint256 currentAllowance = _allowances[owner][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(owner, spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `from` must have a balance of at least `amount`. */ function _transfer( address from, address to, uint256 amount ) internal virtual { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(from, to, amount); uint256 fromBalance = _balances[from]; require(fromBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[from] = fromBalance - amount; } _balances[to] += amount; emit Transfer(from, to, amount); _afterTokenTransfer(from, to, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Spend `amount` form the allowance of `owner` toward `spender`. * * Does not update the allowance amount in case of infinite allowance. * Revert if not enough allowance is available. * * Might emit an {Approval} event. */ function _spendAllowance( address owner, address spender, uint256 amount ) internal virtual { uint256 currentAllowance = allowance(owner, spender); if (currentAllowance != type(uint256).max) { require(currentAllowance >= amount, "ERC20: insufficient allowance"); unchecked { _approve(owner, spender, currentAllowance - amount); } } } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // File @openzeppelin/contracts/token/ERC20/extensions/[email protected] // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/extensions/ERC20Burnable.sol) pragma solidity ^0.8.0; /** * @dev Extension of {ERC20} that allows token holders to destroy both their own * tokens and those that they have an allowance for, in a way that can be * recognized off-chain (via event analysis). */ abstract contract ERC20Burnable is Context, ERC20 { /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller must have allowance for ``accounts``'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) public virtual { _spendAllowance(account, _msgSender(), amount); _burn(account, amount); } } // File @openzeppelin/contracts/security/[email protected] // OpenZeppelin Contracts v4.4.1 (security/Pausable.sol) pragma solidity ^0.8.0; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor() { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // File @openzeppelin/contracts/token/ERC20/extensions/[email protected] // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/ERC20Pausable.sol) pragma solidity ^0.8.0; /** * @dev ERC20 token with pausable token transfers, minting and burning. * * Useful for scenarios such as preventing trades until the end of an evaluation * period, or having an emergency switch for freezing all token transfers in the * event of a large bug. */ abstract contract ERC20Pausable is ERC20, Pausable { /** * @dev See {ERC20-_beforeTokenTransfer}. * * Requirements: * * - the contract must not be paused. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual override { super._beforeTokenTransfer(from, to, amount); require(!paused(), "ERC20Pausable: token transfer while paused"); } } // File @openzeppelin/contracts/access/[email protected] // OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol) pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControl { /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {AccessControl-_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) external view returns (bool); /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {AccessControl-_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) external view returns (bytes32); /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) external; /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) external; /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) external; } // File @openzeppelin/contracts/access/[email protected] // OpenZeppelin Contracts v4.4.1 (access/IAccessControlEnumerable.sol) pragma solidity ^0.8.0; /** * @dev External interface of AccessControlEnumerable declared to support ERC165 detection. */ interface IAccessControlEnumerable is IAccessControl { /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) external view returns (address); /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) external view returns (uint256); } // File @openzeppelin/contracts/utils/[email protected] // 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); } } // File @openzeppelin/contracts/utils/introspection/[email protected] // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File @openzeppelin/contracts/utils/introspection/[email protected] // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File @openzeppelin/contracts/access/[email protected] // OpenZeppelin Contracts (last updated v4.5.0) (access/AccessControl.sol) pragma solidity ^0.8.0; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context, IAccessControl, ERC165 { struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view virtual override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ */ function _checkRole(bytes32 role, address account) internal view virtual { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", Strings.toHexString(uint160(account), 20), " is missing role ", Strings.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view virtual override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been revoked `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== * * NOTE: This function is deprecated in favor of {_grantRole}. */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } /** * @dev Grants `role` to `account`. * * Internal function without access restriction. */ function _grantRole(bytes32 role, address account) internal virtual { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } /** * @dev Revokes `role` from `account`. * * Internal function without access restriction. */ function _revokeRole(bytes32 role, address account) internal virtual { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } } // File @openzeppelin/contracts/utils/structs/[email protected] // OpenZeppelin Contracts v4.4.1 (utils/structs/EnumerableSet.sol) pragma solidity ^0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping(bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; if (lastIndex != toDeleteIndex) { bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex } // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { return set._values[index]; } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function _values(Set storage set) private view returns (bytes32[] memory) { return set._values; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(Bytes32Set storage set) internal view returns (bytes32[] memory) { return _values(set._inner); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(AddressSet storage set) internal view returns (address[] memory) { bytes32[] memory store = _values(set._inner); address[] memory result; assembly { result := store } return result; } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(UintSet storage set) internal view returns (uint256[] memory) { bytes32[] memory store = _values(set._inner); uint256[] memory result; assembly { result := store } return result; } } // File @openzeppelin/contracts/access/[email protected] // OpenZeppelin Contracts (last updated v4.5.0) (access/AccessControlEnumerable.sol) pragma solidity ^0.8.0; /** * @dev Extension of {AccessControl} that allows enumerating the members of each role. */ abstract contract AccessControlEnumerable is IAccessControlEnumerable, AccessControl { using EnumerableSet for EnumerableSet.AddressSet; mapping(bytes32 => EnumerableSet.AddressSet) private _roleMembers; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControlEnumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view virtual override returns (address) { return _roleMembers[role].at(index); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view virtual override returns (uint256) { return _roleMembers[role].length(); } /** * @dev Overload {_grantRole} to track enumerable memberships */ function _grantRole(bytes32 role, address account) internal virtual override { super._grantRole(role, account); _roleMembers[role].add(account); } /** * @dev Overload {_revokeRole} to track enumerable memberships */ function _revokeRole(bytes32 role, address account) internal virtual override { super._revokeRole(role, account); _roleMembers[role].remove(account); } } // File @openzeppelin/contracts/token/ERC20/presets/[email protected] // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/presets/ERC20PresetMinterPauser.sol) pragma solidity ^0.8.0; /** * @dev {ERC20} token, including: * * - ability for holders to burn (destroy) their tokens * - a minter role that allows for token minting (creation) * - a pauser role that allows to stop all token transfers * * This contract uses {AccessControl} to lock permissioned functions using the * different roles - head to its documentation for details. * * The account that deploys the contract will be granted the minter and pauser * roles, as well as the default admin role, which will let it grant both minter * and pauser roles to other accounts. * * _Deprecated in favor of https://wizard.openzeppelin.com/[Contracts Wizard]._ */ contract ERC20PresetMinterPauser is Context, AccessControlEnumerable, ERC20Burnable, ERC20Pausable { bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); /** * @dev Grants `DEFAULT_ADMIN_ROLE`, `MINTER_ROLE` and `PAUSER_ROLE` to the * account that deploys the contract. * * See {ERC20-constructor}. */ constructor(string memory name, string memory symbol) ERC20(name, symbol) { _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); _setupRole(MINTER_ROLE, _msgSender()); _setupRole(PAUSER_ROLE, _msgSender()); } /** * @dev Creates `amount` new tokens for `to`. * * See {ERC20-_mint}. * * Requirements: * * - the caller must have the `MINTER_ROLE`. */ function mint(address to, uint256 amount) public virtual { require(hasRole(MINTER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have minter role to mint"); _mint(to, amount); } /** * @dev Pauses all token transfers. * * See {ERC20Pausable} and {Pausable-_pause}. * * Requirements: * * - the caller must have the `PAUSER_ROLE`. */ function pause() public virtual { require(hasRole(PAUSER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have pauser role to pause"); _pause(); } /** * @dev Unpauses all token transfers. * * See {ERC20Pausable} and {Pausable-_unpause}. * * Requirements: * * - the caller must have the `PAUSER_ROLE`. */ function unpause() public virtual { require(hasRole(PAUSER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have pauser role to unpause"); _unpause(); } function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual override(ERC20, ERC20Pausable) { super._beforeTokenTransfer(from, to, amount); } } // File contracts/ERC20Safe.sol pragma solidity ^0.8.0; /** @title Manages deposited ERC20s. @author Gamejam. @notice This contract is intended to be used with ERC20Handler contract. */ contract ERC20Safe { /** @notice Used to transfer tokens into the safe to fund proposals. @param tokenAddress Address of ERC20 to transfer. @param owner Address of current token owner. @param amount Amount of tokens to transfer. */ function fundERC20( address tokenAddress, address owner, uint256 amount ) public { IERC20 erc20 = IERC20(tokenAddress); _safeTransferFrom(erc20, owner, address(this), amount); } /** @notice Used to gain custody of deposited token. @param tokenAddress Address of ERC20 to transfer. @param owner Address of current token owner. @param recipient Address to transfer tokens to. @param amount Amount of tokens to transfer. */ function lockERC20( address tokenAddress, address owner, address recipient, uint256 amount ) internal { IERC20 erc20 = IERC20(tokenAddress); _safeTransferFrom(erc20, owner, recipient, amount); } /** @notice Transfers custody of token to recipient. @param tokenAddress Address of ERC20 to transfer. @param recipient Address to transfer tokens to. @param amount Amount of tokens to transfer. */ function releaseERC20( address tokenAddress, address recipient, uint256 amount ) internal { IERC20 erc20 = IERC20(tokenAddress); _safeTransfer(erc20, recipient, amount); } /** @notice Used to create new ERC20s. @param tokenAddress Address of ERC20 to transfer. @param recipient Address to mint token to. @param amount Amount of token to mint. */ function mintERC20( address tokenAddress, address recipient, uint256 amount ) internal { ERC20PresetMinterPauser erc20 = ERC20PresetMinterPauser(tokenAddress); erc20.mint(recipient, amount); } /** @notice Used to burn ERC20s. @param tokenAddress Address of ERC20 to burn. @param owner Current owner of tokens. @param amount Amount of tokens to burn. */ function burnERC20( address tokenAddress, address owner, uint256 amount ) internal { ERC20Burnable erc20 = ERC20Burnable(tokenAddress); erc20.burnFrom(owner, amount); } /** @notice used to transfer ERC20s safely @param token Token instance to transfer @param to Address to transfer token to @param value Amount of token to transfer */ function _safeTransfer( IERC20 token, address to, uint256 value ) private { _safeCall( token, abi.encodeWithSelector(token.transfer.selector, to, value) ); } /** @notice used to transfer ERC20s safely @param token Token instance to transfer @param from Address to transfer token from @param to Address to transfer token to @param value Amount of token to transfer */ function _safeTransferFrom( IERC20 token, address from, address to, uint256 value ) private { _safeCall( token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value) ); } /** @notice used to make calls to ERC20s safely @param token Token instance call targets @param data encoded call data */ function _safeCall(IERC20 token, bytes memory data) private { (bool success, bytes memory returndata) = address(token).call(data); require(success, "ERC20Safe: call failed"); if (returndata.length > 0) { require( abi.decode(returndata, (bool)), "ERC20Safe: operation did not succeed" ); } } } // File contracts/handlers/ERC20Handler.sol /* SPDX-License-Identifier: MIT */ pragma solidity ^0.8.0; pragma experimental ABIEncoderV2; /** @title Handles ERC20 deposits and deposit executions. @author Gamejam. @notice This contract is intended to be used with the Bridge contract. */ contract ERC20Handler is IDepositExecute, HandlerHelpers, ERC20Safe { struct DepositRecord { address _tokenAddress; uint8 _lenDestinationRecipientAddress; uint8 _destinationChainID; bytes32 _resourceID; bytes _destinationRecipientAddress; address _depositer; uint256 _amount; bool _refund; } // depositNonce => Deposit Record mapping(uint8 => mapping(uint64 => DepositRecord)) public _depositRecords; /** @param bridgeAddress Contract address of previously deployed Bridge. @param initialResourceIDs Resource IDs are used to identify a specific contract address. These are the Resource IDs this contract will initially support. @param initialContractAddresses These are the addresses the {initialResourceIDs} will point to, and are the contracts that will be called to perform various deposit calls. @param burnableContractAddresses These addresses will be set as burnable and when {deposit} is called, the deposited token will be burned. When {executeProposal} is called, new tokens will be minted. @dev {initialResourceIDs} and {initialContractAddresses} must have the same length (one resourceID for every address). Also, these arrays must be ordered in the way that {initialResourceIDs}[0] is the intended resourceID for {initialContractAddresses}[0]. */ constructor( address bridgeAddress, bytes32[] memory initialResourceIDs, address[] memory initialContractAddresses, address[] memory burnableContractAddresses ) { require( initialResourceIDs.length == initialContractAddresses.length, "ERC20Handler: initialResourceIDs and initialContractAddresses length mismatch" ); _bridgeAddress = bridgeAddress; _handlerType = keccak256("ERC_20_HANDLER"); for (uint256 i = 0; i < initialResourceIDs.length; i++) { _setResource(initialResourceIDs[i], initialContractAddresses[i]); } for (uint256 i = 0; i < burnableContractAddresses.length; i++) { _setBurnable(burnableContractAddresses[i]); } } /** @param depositNonce This ID will have been generated by the Bridge contract. @param destId ID of chain deposit will be bridged to. @return DepositRecord which consists of: - _tokenAddress Address used when {deposit} was executed. - _destinationChainID ChainID deposited tokens are intended to end up on. - _resourceID ResourceID used when {deposit} was executed. - _lenDestinationRecipientAddress Used to parse recipient's address from {_destinationRecipientAddress} - _destinationRecipientAddress Address tokens are intended to be deposited to on desitnation chain. - _depositer Address that initially called {deposit} in the Bridge contract. - _amount Amount of tokens that were deposited. */ function getDepositRecord(uint64 depositNonce, uint8 destId) external view returns (DepositRecord memory) { return _depositRecords[destId][depositNonce]; } /** @notice A deposit is initiatied by making a deposit in the Bridge contract. @param destinationChainID Chain ID of chain tokens are expected to be bridged to. @param depositNonce This value is generated as an ID by the Bridge contract. @param depositer Address of account making the deposit in the Bridge contract. @param data Consists of: {resourceID}, {amount}, {lenRecipientAddress}, and {recipientAddress} all padded to 32 bytes. @notice Data passed into the function should be constructed as follows: amount uint256 bytes 0 - 32 recipientAddress length uint256 bytes 32 - 64 recipientAddress bytes bytes 64 - END @dev Depending if the corresponding {tokenAddress} for the parsed {resourceID} is marked true in {_burnList}, deposited tokens will be burned, if not, they will be locked. */ function deposit( bytes32 resourceID, uint8 destinationChainID, uint64 depositNonce, address depositer, bytes calldata data ) external override onlyBridge { bytes memory recipientAddress; uint256 amount; uint256 lenRecipientAddress; assembly { amount := calldataload(0xC4) recipientAddress := mload(0x40) lenRecipientAddress := calldataload(0xE4) mstore(0x40, add(0x20, add(recipientAddress, lenRecipientAddress))) calldatacopy( recipientAddress, // copy to destinationRecipientAddress 0xE4, // copy from calldata @ 0x104 sub(calldatasize(), 0xE4) // copy size (calldatasize - 0x104) ) } address tokenAddress = _resourceIDToTokenContractAddress[resourceID]; require( _contractWhitelist[tokenAddress], "ERC20Handler: provided tokenAddress is not whitelisted" ); if (_burnList[tokenAddress]) { burnERC20(tokenAddress, depositer, amount); } else { lockERC20(tokenAddress, depositer, address(this), amount); } _depositRecords[destinationChainID][depositNonce] = DepositRecord( tokenAddress, uint8(lenRecipientAddress), destinationChainID, resourceID, recipientAddress, depositer, amount, false ); } /** @notice Proposal execution should be initiated when a proposal is finalized in the Bridge contract. by a relayer on the deposit's destination chain. @param data Consists of {resourceID}, {amount}, {lenDestinationRecipientAddress}, and {destinationRecipientAddress} all padded to 32 bytes. @notice Data passed into the function should be constructed as follows: amount uint256 bytes 0 - 32 destinationRecipientAddress length uint256 bytes 32 - 64 destinationRecipientAddress bytes bytes 64 - END */ function executeProposal(bytes32 resourceID, bytes calldata data) external override onlyBridge { uint256 amount; bytes memory destinationRecipientAddress; assembly { amount := calldataload(0x64) destinationRecipientAddress := mload(0x40) let lenDestinationRecipientAddress := calldataload(0x84) mstore( 0x40, add( 0x20, add( destinationRecipientAddress, lenDestinationRecipientAddress ) ) ) // in the calldata the destinationRecipientAddress is stored at 0xC4 after accounting for the function signature and length declaration calldatacopy( destinationRecipientAddress, // copy to destinationRecipientAddress 0x84, // copy from calldata @ 0x84 sub(calldatasize(), 0x84) // copy size to the end of calldata ) } bytes20 recipientAddress; address tokenAddress = _resourceIDToTokenContractAddress[resourceID]; assembly { recipientAddress := mload(add(destinationRecipientAddress, 0x20)) } require( _contractWhitelist[tokenAddress], "ERC20Handler: provided tokenAddress is not whitelisted" ); if (_burnList[tokenAddress]) { mintERC20(tokenAddress, address(recipientAddress), amount); } else { releaseERC20(tokenAddress, address(recipientAddress), amount); } } /** @notice Used to refund money to participants when the bridge system is down @param resourceID The ID that points to the resource. @param destinationChainID Chain ID deposit is expected to be bridged to. @param depositNonce This value is generated as an ID by the Bridge contract. @param depositer Address of account making the deposit in the Bridge contract. @param data Consists of additional data needed for a specific deposit. */ function refund( bytes32 resourceID, uint8 destinationChainID, uint64 depositNonce, address depositer, bytes calldata data ) external override onlyBridge { uint256 amount; assembly { amount := calldataload(0xC4) } address tokenAddress = _resourceIDToTokenContractAddress[resourceID]; DepositRecord storage record = _depositRecords[destinationChainID][ depositNonce ]; require( _contractWhitelist[tokenAddress], "ERC20Handler: provided tokenAddress is not whitelisted" ); require( record._depositer == depositer && record._resourceID == resourceID && record._amount == amount, "ERC20Handler: info mismatch" ); require(!record._refund, "ERC20Handler: already refunded"); record._refund = true; if (_burnList[tokenAddress]) mintERC20(tokenAddress, depositer, amount); else releaseERC20(tokenAddress, depositer, amount); } /** @notice Used to manually release ERC20 tokens from ERC20Safe. @param tokenAddress Address of token contract to release. @param recipient Address to release tokens to. @param amount The amount of ERC20 tokens to release. */ function withdraw( address tokenAddress, address recipient, uint256 amount ) external override onlyBridge { releaseERC20(tokenAddress, recipient, amount); } }
/ resourceID => token contract address token contract address => resourceID token contract address => is whitelisted token contract address => is burnable
contract HandlerHelpers is IERCHandler { bytes32 public _handlerType; address public _bridgeAddress; mapping(bytes32 => address) public _resourceIDToTokenContractAddress; mapping(address => bytes32) public _tokenContractAddressToResourceID; mapping(address => bool) public _contractWhitelist; mapping(address => bool) public _burnList; } @title Function used across handler contracts. modifier onlyBridge() { require( msg.sender == _bridgeAddress, "HandlerHelpers: sender must be bridge contract" ); _; } @param resourceID ResourceID to be used when making deposits. @param contractAddress Address of contract to be called when a deposit is made and a deposited is executed. @notice First verifies {_resourceIDToContractAddress}[{resourceID}] and {_contractAddressToResourceID}[{contractAddress}] are not already set, then sets {_resourceIDToContractAddress} with {contractAddress}, {_contractAddressToResourceID} with {resourceID}, and {_contractWhitelist} to true for {contractAddress}. function setResource(bytes32 resourceID, address contractAddress) external override onlyBridge { _setResource(resourceID, contractAddress); } to true. @param contractAddress Address of contract to be used when making or executing deposits. @notice First verifies {contractAddress} is whitelisted, then sets {_burnList}[{contractAddress}] function setBurnable(address contractAddress) external override onlyBridge { _setBurnable(contractAddress); } @param tokenAddress Address of token contract to release. @param recipient Address to release tokens to. @param amountOrTokenID Either the amount of ERC20 tokens or the ERC721 token ID to release. @notice Used to manually release funds from ERC safes. ) external virtual override {} function withdraw( address tokenAddress, address recipient, uint256 amountOrTokenID function _setResource(bytes32 resourceID, address contractAddress) internal { _resourceIDToTokenContractAddress[resourceID] = contractAddress; _tokenContractAddressToResourceID[contractAddress] = resourceID; _contractWhitelist[contractAddress] = true; } function _setBurnable(address contractAddress) internal { require( _contractWhitelist[contractAddress], "HandlerHelpers: provided contract is not whitelisted" ); _burnList[contractAddress] = true; } }
2,306,908
[ 1, 19, 1058, 734, 516, 1147, 6835, 1758, 1147, 6835, 1758, 516, 1058, 734, 1147, 6835, 1758, 516, 353, 26944, 1147, 6835, 1758, 516, 353, 18305, 429, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 16351, 4663, 13375, 353, 467, 654, 39, 1503, 288, 203, 565, 1731, 1578, 1071, 389, 4176, 559, 31, 203, 565, 1758, 1071, 389, 18337, 1887, 31, 203, 203, 565, 2874, 12, 3890, 1578, 516, 1758, 13, 1071, 389, 3146, 734, 774, 1345, 8924, 1887, 31, 203, 203, 565, 2874, 12, 2867, 516, 1731, 1578, 13, 1071, 389, 2316, 8924, 1887, 774, 1420, 734, 31, 203, 203, 565, 2874, 12, 2867, 516, 1426, 13, 1071, 389, 16351, 18927, 31, 203, 203, 565, 2874, 12, 2867, 516, 1426, 13, 1071, 389, 70, 321, 682, 31, 203, 203, 97, 203, 203, 565, 632, 2649, 4284, 1399, 10279, 1838, 20092, 18, 203, 565, 9606, 1338, 13691, 1435, 288, 203, 3639, 2583, 12, 203, 5411, 1234, 18, 15330, 422, 389, 18337, 1887, 16, 203, 5411, 315, 1503, 13375, 30, 5793, 1297, 506, 10105, 6835, 6, 203, 3639, 11272, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 3639, 632, 891, 1058, 734, 2591, 734, 358, 506, 1399, 1347, 10480, 443, 917, 1282, 18, 203, 3639, 632, 891, 6835, 1887, 5267, 434, 6835, 358, 506, 2566, 1347, 279, 443, 1724, 353, 7165, 471, 279, 443, 1724, 329, 353, 7120, 18, 203, 3639, 632, 20392, 5783, 20761, 288, 67, 3146, 734, 774, 8924, 1887, 20294, 95, 3146, 734, 11839, 471, 203, 3639, 288, 67, 16351, 1887, 774, 1420, 734, 20294, 95, 16351, 1887, 11839, 854, 486, 1818, 444, 16, 203, 3639, 1508, 1678, 288, 67, 3146, 734, 774, 8924, 1887, 97, 598, 288, 16351, 1887, 5779, 203, 3639, 288, 67, 16351, 2 ]
./full_match/1/0x0000000000C480563CCbc2832FB38Ea654387922/sources/contracts/tokens/ERC1155/extensions/ERC1155PSupply.sol
* @dev See {ERC1155-_beforeTokenTransfer}./
function _beforeBatchTokenTransfer( address, address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes memory ) internal virtual override { if (from == address(0)) { for (uint256 i; i < ids.length; ) { uint256 id = ids[i]; uint256 supply = this.totalSupply(id); uint256 minted = this.totalMinted(id); unchecked { supply += amounts[i]; minted += amounts[i]; ++i; } if (supply > MAX_TOTAL_SUPPLY || minted > MAX_TOTAL_SUPPLY) { ERC1155P._revert(ExceedsMaximumTotalSupply.selector); } setTotalSupply(id, supply); setTotalMinted(id, minted); } } if (to == address(0)) { for (uint256 i; i < ids.length; ) { uint256 id = ids[i]; uint256 supply = this.totalSupply(id); unchecked { supply -= amounts[i]; ++i; } setTotalSupply(id, supply); } } }
9,714,984
[ 1, 9704, 288, 654, 39, 2499, 2539, 17, 67, 5771, 1345, 5912, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 5771, 4497, 1345, 5912, 12, 203, 3639, 1758, 16, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 8526, 745, 892, 3258, 16, 203, 3639, 2254, 5034, 8526, 745, 892, 30980, 16, 203, 3639, 1731, 3778, 203, 565, 262, 2713, 5024, 3849, 288, 203, 3639, 309, 261, 2080, 422, 1758, 12, 20, 3719, 288, 203, 5411, 364, 261, 11890, 5034, 277, 31, 277, 411, 3258, 18, 2469, 31, 262, 288, 203, 7734, 2254, 5034, 612, 273, 3258, 63, 77, 15533, 203, 7734, 2254, 5034, 14467, 273, 333, 18, 4963, 3088, 1283, 12, 350, 1769, 203, 7734, 2254, 5034, 312, 474, 329, 273, 333, 18, 4963, 49, 474, 329, 12, 350, 1769, 203, 7734, 22893, 288, 203, 10792, 14467, 1011, 30980, 63, 77, 15533, 203, 10792, 312, 474, 329, 1011, 30980, 63, 77, 15533, 203, 10792, 965, 77, 31, 203, 7734, 289, 203, 7734, 309, 261, 2859, 1283, 405, 4552, 67, 28624, 67, 13272, 23893, 747, 312, 474, 329, 405, 4552, 67, 28624, 67, 13272, 23893, 13, 288, 203, 10792, 4232, 39, 2499, 2539, 52, 6315, 266, 1097, 12, 424, 5288, 87, 13528, 5269, 3088, 1283, 18, 9663, 1769, 203, 7734, 289, 203, 7734, 25015, 3088, 1283, 12, 350, 16, 14467, 1769, 203, 7734, 25015, 49, 474, 329, 12, 350, 16, 312, 474, 329, 1769, 203, 5411, 289, 203, 3639, 289, 203, 203, 3639, 309, 261, 869, 422, 1758, 12, 20, 3719, 288, 203, 5411, 364, 261, 11890, 5034, 277, 31, 277, 411, 3258, 18, 2469, 31, 2 ]
pragma solidity ^0.4.6; contract FourWaySplit { // balances and account list are publicly visible mapping(address => uint) public beneficiaryBalance; address[4] public beneficiaryList; // emit events for real-time listeners and state history event LogReceived(address sender, uint amount); event LogWithdrawal(address beneficiary, uint amount); // give the constructor four addresses for the split function FourWaySplit(address addressA, address addressB, address addressC, address addressD) { beneficiaryList[0]=addressA; beneficiaryList[1]=addressB; beneficiaryList[2]=addressC; beneficiaryList[3]=addressD; } // send ETH function pay() public payable returns(bool success) { if(msg.value==0) throw; // ignoring values not evenly divisible by 4. We round down and keep the change. // (No way to remove the loose change, so it's effectively destroyed.) uint forth = msg.value / 4; beneficiaryBalance[beneficiaryList[0]] += forth; beneficiaryBalance[beneficiaryList[1]] += forth; beneficiaryBalance[beneficiaryList[2]] += forth; beneficiaryBalance[beneficiaryList[3]] += forth; LogReceived(msg.sender, msg.value); return true; } function withdraw(uint amount) public returns(bool success) { if(beneficiaryBalance[msg.sender] < amount) throw; // insufficient funds beneficiaryBalance[msg.sender] -= amount; // Optimistic accounting. if(!msg.sender.send(amount)) throw; // failed to transfer funds LogWithdrawal(msg.sender, amount); return true; } }
ignoring values not evenly divisible by 4. We round down and keep the change. (No way to remove the loose change, so it's effectively destroyed.)
function pay() public payable returns(bool success) { if(msg.value==0) throw; uint forth = msg.value / 4; beneficiaryBalance[beneficiaryList[0]] += forth; beneficiaryBalance[beneficiaryList[1]] += forth; beneficiaryBalance[beneficiaryList[2]] += forth; beneficiaryBalance[beneficiaryList[3]] += forth; LogReceived(msg.sender, msg.value); return true; }
12,720,157
[ 1, 724, 6053, 924, 486, 5456, 715, 3739, 18932, 635, 1059, 18, 1660, 3643, 2588, 471, 3455, 326, 2549, 18, 261, 2279, 4031, 358, 1206, 326, 28393, 2549, 16, 1427, 518, 1807, 23500, 17689, 12998, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 8843, 1435, 7010, 565, 1071, 203, 565, 8843, 429, 203, 565, 1135, 12, 6430, 2216, 13, 203, 225, 288, 203, 565, 309, 12, 3576, 18, 1132, 631, 20, 13, 604, 31, 203, 203, 203, 565, 2254, 364, 451, 273, 1234, 18, 1132, 342, 1059, 31, 203, 203, 565, 27641, 74, 14463, 814, 13937, 63, 70, 4009, 74, 14463, 814, 682, 63, 20, 13563, 1011, 364, 451, 31, 203, 565, 27641, 74, 14463, 814, 13937, 63, 70, 4009, 74, 14463, 814, 682, 63, 21, 13563, 1011, 364, 451, 31, 203, 565, 27641, 74, 14463, 814, 13937, 63, 70, 4009, 74, 14463, 814, 682, 63, 22, 13563, 1011, 364, 451, 31, 203, 565, 27641, 74, 14463, 814, 13937, 63, 70, 4009, 74, 14463, 814, 682, 63, 23, 13563, 1011, 364, 451, 31, 203, 565, 1827, 8872, 12, 3576, 18, 15330, 16, 1234, 18, 1132, 1769, 203, 565, 327, 638, 31, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/56/0x79Ed648f0Fb424Ec37897DF87B9ee80cca65B230/sources/ProofOfApes.sol
* Retrieve the tokens owned by the caller./
function myTokens() public view returns (uint256) { address _customerAddress = msg.sender; return balanceOf(_customerAddress); }
11,213,884
[ 1, 5767, 326, 2430, 16199, 635, 326, 4894, 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 ]
[ 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, 225, 445, 3399, 5157, 1435, 1071, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 565, 1758, 389, 10061, 1887, 273, 1234, 18, 15330, 31, 203, 565, 327, 11013, 951, 24899, 10061, 1887, 1769, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (access/AccessControl.sol) pragma solidity ^0.8.0; import "./IAccessControlUpgradeable.sol"; import "../utils/ContextUpgradeable.sol"; import "../utils/StringsUpgradeable.sol"; import "../utils/introspection/ERC165Upgradeable.sol"; import "../proxy/utils/Initializable.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 AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable { function __AccessControl_init() internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __AccessControl_init_unchained(); } function __AccessControl_init_unchained() internal initializer { } struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev 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(IAccessControlUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{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 ", StringsUpgradeable.toHexString(uint160(account), 20), " is missing role ", StringsUpgradeable.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been revoked `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== * * NOTE: This function is deprecated in favor of {_grantRole}. */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } /** * @dev Grants `role` to `account`. * * Internal function without access restriction. */ function _grantRole(bytes32 role, address account) internal virtual { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } /** * @dev Revokes `role` from `account`. * * Internal function without access restriction. */ function _revokeRole(bytes32 role, address account) internal virtual { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } uint256[49] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (access/IAccessControl.sol) pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControlUpgradeable { /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {AccessControl-_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) external view returns (bool); /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {AccessControl-_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) external view returns (bytes32); /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) external; /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) external; /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.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 OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (proxy/utils/Initializable.sol) pragma solidity ^0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. * * [CAUTION] * ==== * Avoid leaving a contract uninitialized. * * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation * contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the * initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed: * * [.hljs-theme-light.nopadding] * ``` * /// @custom:oz-upgrades-unsafe-allow constructor * constructor() initializer {} * ``` * ==== */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC721/ERC721.sol) pragma solidity ^0.8.0; import "./IERC721Upgradeable.sol"; import "./IERC721ReceiverUpgradeable.sol"; import "./extensions/IERC721MetadataUpgradeable.sol"; import "../../utils/AddressUpgradeable.sol"; import "../../utils/ContextUpgradeable.sol"; import "../../utils/StringsUpgradeable.sol"; import "../../utils/introspection/ERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable { using AddressUpgradeable for address; using StringsUpgradeable for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ function __ERC721_init(string memory name_, string memory symbol_) internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __ERC721_init_unchained(name_, symbol_); } function __ERC721_init_unchained(string memory name_, string memory symbol_) internal initializer { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) { return interfaceId == type(IERC721Upgradeable).interfaceId || interfaceId == type(IERC721MetadataUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721Upgradeable.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721Upgradeable.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721Upgradeable.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721Upgradeable.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721Upgradeable.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721ReceiverUpgradeable(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721ReceiverUpgradeable.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} uint256[44] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721ReceiverUpgradeable { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165Upgradeable.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721Upgradeable is IERC165Upgradeable { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC721/extensions/ERC721Enumerable.sol) pragma solidity ^0.8.0; import "../ERC721Upgradeable.sol"; import "./IERC721EnumerableUpgradeable.sol"; import "../../../proxy/utils/Initializable.sol"; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721EnumerableUpgradeable is Initializable, ERC721Upgradeable, IERC721EnumerableUpgradeable { function __ERC721Enumerable_init() internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __ERC721Enumerable_init_unchained(); } function __ERC721Enumerable_init_unchained() internal initializer { } // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165Upgradeable, ERC721Upgradeable) returns (bool) { return interfaceId == type(IERC721EnumerableUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721Upgradeable.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721EnumerableUpgradeable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721Upgradeable.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721Upgradeable.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } uint256[46] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC721/extensions/IERC721Enumerable.sol) pragma solidity ^0.8.0; import "../IERC721Upgradeable.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721EnumerableUpgradeable is IERC721Upgradeable { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; import "../IERC721Upgradeable.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721MetadataUpgradeable is IERC721Upgradeable { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC721/utils/ERC721Holder.sol) pragma solidity ^0.8.0; import "../IERC721ReceiverUpgradeable.sol"; import "../../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the {IERC721Receiver} interface. * * Accepts all token transfers. * Make sure the contract is able to use its token with {IERC721-safeTransferFrom}, {IERC721-approve} or {IERC721-setApprovalForAll}. */ contract ERC721HolderUpgradeable is Initializable, IERC721ReceiverUpgradeable { function __ERC721Holder_init() internal initializer { __ERC721Holder_init_unchained(); } function __ERC721Holder_init_unchained() internal initializer { } /** * @dev See {IERC721Receiver-onERC721Received}. * * Always returns `IERC721Receiver.onERC721Received.selector`. */ function onERC721Received( address, address, uint256, bytes memory ) public virtual override returns (bytes4) { return this.onERC721Received.selector; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/Context.sol) pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library StringsUpgradeable { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable { function __ERC165_init() internal initializer { __ERC165_init_unchained(); } function __ERC165_init_unchained() internal initializer { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165Upgradeable).interfaceId; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165Upgradeable { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/math/SafeMath.sol) pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // SPDX-License-Identifier: MIT pragma solidity 0.8.7; import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/extensions/ERC721EnumerableUpgradeable.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; /** * @title Digital art collectible metaverse * @author NFT Legends team **/ contract Collection is ERC721Upgradeable, ERC721EnumerableUpgradeable, AccessControlUpgradeable { event NameChange(uint256 indexed index, string newName); event SkillChange(uint256 indexed index, uint256 newSkill); event DnaChange(uint256 indexed index, uint256 newDna); event Buy(address indexed _from, uint256 nfts, address referral); // each token has its own attributes: Name, Skill and DNA // Name is the symbolic string, that can be changed over time mapping(uint256 => string) private _tokenName; // Skill is a numeric value that represents character's experience mapping(uint256 => uint256) private _tokenSkill; // DNA is 256-bit map where unique token attributes encoded mapping(uint256 => uint256) private _tokenDna; // when sale is active, anyone is able to buy the token bool public saleActive; using SafeMath for uint256; using Strings for uint256; // The token purchase price depends on how early you buy the character // (i.e. sequential number of the purchase) struct SaleStage { uint256 startTokensBought; uint256 endTokensBought; uint256 weiPerToken; } // All the tokens are grouped in batches. Batch is basically IPFS folder (DAG) // that stores token descriptions and images. It tokenId falls into batch, the // tokenURI = batch.baseURI + "/" + tokenId. // All the batches have the same rarity parameter. struct Batch { uint256 startBatchTokenId; uint256 endBatchTokenId; string baseURI; uint256 rarity; } // Arrays that store configured batches and saleStages Batch[] internal _batches; SaleStage[] internal _saleStages; // Maximum allowed tokenSupply boundary. Can be extended by adding new stages. uint256 internal _maxTotalSupply; // Max NFTs that can be bought at once. To avoid gas overspending. uint256 public maxPurchaseSize; // If tokenId doesn't match any configured batch, defaultURI parameters are used. string internal _defaultUri; uint256 internal _defaultRarity; string internal _defaultName; uint256 internal _defaultSkill; // Roles that can modify individual characteristics bytes32 public constant NAME_SETTER_ROLE = keccak256("NAME_SETTER_ROLE"); bytes32 public constant SKILL_SETTER_ROLE = keccak256("SKILL_SETTER_ROLE"); bytes32 public constant DNA_SETTER_ROLE = keccak256("DNA_SETTER_ROLE"); bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); // Received funds (native Ether or BNB) get transferred to Vault address address payable public vault; function initialize() public initializer { __ERC721_init("CyberPunk", "A-12"); __ERC721Enumerable_init(); __AccessControl_init(); _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); _setupRole(NAME_SETTER_ROLE, _msgSender()); _setupRole(SKILL_SETTER_ROLE, _msgSender()); _setupRole(DNA_SETTER_ROLE, _msgSender()); _setupRole(MINTER_ROLE, _msgSender()); maxPurchaseSize = 20; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721Upgradeable, ERC721EnumerableUpgradeable, AccessControlUpgradeable) returns (bool) { return super.supportsInterface(interfaceId); } /** * @dev Returns current `_maxTotalSupply` value. */ function maxTotalSupply() public view virtual returns (uint256) { return _maxTotalSupply; } /** * @dev Hook that is called before any token transfer incl. minting */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override(ERC721Upgradeable, ERC721EnumerableUpgradeable) { super._beforeTokenTransfer(from, to, tokenId); // check maxTotalSupply is not exceeded on mint if (from == address(0)) { require(totalSupply() <= _maxTotalSupply, "Collection: maxSupply achieved"); } } /** * @dev Returns the number of configured saleStages (tokensale schedule) * @return current `_saleStages` array length */ function saleStagesLength() public view returns (uint256) { return _saleStages.length; } /** * @dev Returns the saleStage by its index * @param saleStageIndex salestage index in the array * @return info about sale stage */ function getSaleStage(uint256 saleStageIndex) public view returns (SaleStage memory) { require(_saleStages.length > 0, "getSaleStage: no stages"); require(saleStageIndex < _saleStages.length, "Id must be < sale stages length"); return _saleStages[saleStageIndex]; } /** * @dev Returns the length of configured batches * @return current `_batches` array length. */ function batchesLength() public view returns (uint256) { return _batches.length; } /** * @dev Returns all the batches * @return `_batches`. */ function getBatches() public view returns (Batch[] memory) { return _batches; } /** * @dev Returns all sale stages * @return `_saleStages`. */ function getSaleStages() public view returns (SaleStage[] memory) { return _saleStages; } /** * @dev Returns the batch by its index in the array * @param batchIndex batch index * @return Batch info * Note: batch ids can change over time and reorder as the result of batch removal */ function getBatch(uint256 batchIndex) public view returns (Batch memory) { require(_batches.length > 0, "getBatch: no batches"); require(batchIndex < _batches.length, "Id must be < batch length"); return _batches[batchIndex]; } /** * @dev Return batch by given tokenId * @param tokenId token id * @return batch structure */ function getBatchByToken(uint256 tokenId) public view returns (Batch memory) { require(_batches.length > 0, "getBatchByToken: no batches"); for (uint256 i; i < _batches.length; i++) { if (tokenId > _batches[i].endBatchTokenId || tokenId < _batches[i].startBatchTokenId) { continue; } else { return _batches[i]; } } revert("batch doesn't exist"); } /** * @dev IPFS address that stores JSON with token attributes * Tries to find it by batch first. If token has no batch, returns defaultUri. * @param tokenId id of the token * @return string with ipfs address to json with token attribute * or URI for default token if token doesn`t exist */ function tokenURI(uint256 tokenId) public view override returns (string memory) { require(_batches.length > 0, "tokenURI: no batches"); for (uint256 i; i < _batches.length; i++) { if (tokenId > _batches[i].endBatchTokenId || tokenId < _batches[i].startBatchTokenId) { continue; } else { return string(abi.encodePacked(_batches[i].baseURI, "/", tokenId.toString(), ".json")); } } return _defaultUri; } /** * @notice Creates the new batch for given token range * @param startTokenId index of the first batch token * @param endTokenId index of the last batch token * @param baseURI ipfs batch URI * @param rarity batch rarity * Note: batch ids can change over time and reorder as the result of batch removal */ function addBatch( uint256 startTokenId, uint256 endTokenId, string memory baseURI, uint256 rarity ) external onlyRole(DEFAULT_ADMIN_ROLE) { uint256 _batchesLength = _batches.length; require(startTokenId <= endTokenId, "startId must be <= than EndId"); if (_batchesLength > 0) { for (uint256 i; i < _batchesLength; i++) { // if both bounds are lower or higher than iter batch if ( (startTokenId < _batches[i].startBatchTokenId && endTokenId < _batches[i].startBatchTokenId) || (startTokenId > _batches[i].endBatchTokenId && endTokenId > _batches[i].endBatchTokenId) ) { continue; } else { revert("batches intersect"); } } } _batches.push(Batch(startTokenId, endTokenId, baseURI, rarity)); } /** * @notice Update existing batch by its index * @param batchIndex the index of the batch to be changed * @param batchStartId index of the first batch token * @param batchEndId index of the last batch token * @param baseURI ipfs batch URI * @param rarity batch rarity * Note: batch ids can change over time and reorder as the result of batch removal */ function setBatch( uint256 batchIndex, uint256 batchStartId, uint256 batchEndId, string memory baseURI, uint256 rarity ) external onlyRole(DEFAULT_ADMIN_ROLE) { uint256 _batchesLength = _batches.length; require(_batchesLength > 0, "setBatch: batches is empty"); require(batchStartId <= batchEndId, "startId must be <= than EndId"); for (uint256 i; i < _batchesLength; i++) { if (i == batchIndex) { continue; } else { // if both bounds are lower or higher than iter batch if ( (batchStartId < _batches[i].startBatchTokenId && batchEndId < _batches[i].startBatchTokenId) || (batchStartId > _batches[i].endBatchTokenId && batchEndId > _batches[i].endBatchTokenId) ) { continue; } else { revert("batches intersect"); } } } _batches[batchIndex].startBatchTokenId = batchStartId; _batches[batchIndex].endBatchTokenId = batchEndId; _batches[batchIndex].baseURI = baseURI; _batches[batchIndex].rarity = rarity; } /** * @notice Deletes batch by its id. This reorders the index of the token that was last. * @param batchIndex the index of the batch to be deteted */ function deleteBatch(uint256 batchIndex) external onlyRole(DEFAULT_ADMIN_ROLE) { require(_batches.length > batchIndex, "index out of batches length"); _batches[batchIndex] = _batches[_batches.length - 1]; _batches.pop(); } /** * @notice Add sale stage (i.e. tokensale schedule) * It takes place at the end of `saleStages array` * @param startTokensBought index of the first batch token * @param endTokensBought index of the last batch token * @param weiPerToken price for token */ function addSaleStage( uint256 startTokensBought, uint256 endTokensBought, uint256 weiPerToken ) external onlyRole(DEFAULT_ADMIN_ROLE) { require(startTokensBought <= endTokensBought, "startTokensBought must be <= than endTokensBought"); require(weiPerToken > 0, "weiPerToken must be non-zero"); uint256 _saleStagesLength = _saleStages.length; if (_saleStagesLength > 0) { for (uint256 i; i < _saleStagesLength; i++) { // if both bounds are lower or higher than iter sale stage if ( (startTokensBought < _saleStages[i].startTokensBought && endTokensBought < _saleStages[i].startTokensBought) || (startTokensBought > _saleStages[i].endTokensBought && endTokensBought > _saleStages[i].endTokensBought) ) { continue; } else { revert("intersection _saleStages"); } } } _saleStages.push(SaleStage(startTokensBought, endTokensBought, weiPerToken)); _maxTotalSupply += endTokensBought - startTokensBought + 1; } /** * @notice Update (rewrite) saleStage properties by index * @param saleStageId index of the first sale stage token * @param startTokensBought index of the first batch token * @param endTokensBought index of the last batch token * @param weiPerToken price for token */ function setSaleStage( uint256 saleStageId, uint256 startTokensBought, uint256 endTokensBought, uint256 weiPerToken ) external onlyRole(DEFAULT_ADMIN_ROLE) { uint256 _saleStagesLength = _saleStages.length; require(_saleStagesLength > 0, "batches is empty"); require(startTokensBought <= endTokensBought, "startId must be <= than EndId"); for (uint256 i; i < _saleStagesLength; i++) { if (i == saleStageId) { continue; } else { // if both bounds are lower or higher than iter sale stage if ( (startTokensBought < _saleStages[i].startTokensBought && endTokensBought < _saleStages[i].startTokensBought) || (startTokensBought > _saleStages[i].endTokensBought && endTokensBought > _saleStages[i].endTokensBought) ) { continue; } else { revert("intersection _saleStages"); } } } SaleStage memory _saleStage = _saleStages[saleStageId]; _maxTotalSupply = _maxTotalSupply - (_saleStage.endTokensBought - _saleStage.startTokensBought + 1) + (endTokensBought - startTokensBought + 1); _saleStages[saleStageId].startTokensBought = startTokensBought; _saleStages[saleStageId].endTokensBought = endTokensBought; _saleStages[saleStageId].weiPerToken = weiPerToken; } /** * @dev Delete sale stage by the given given index * @param saleStageIndex index of the batch to be deleted */ function deleteSaleStage(uint256 saleStageIndex) external onlyRole(DEFAULT_ADMIN_ROLE) { require(_saleStages.length > saleStageIndex, "index out of sale stage length"); SaleStage memory _saleStage = _saleStages[saleStageIndex]; _maxTotalSupply -= _saleStage.endTokensBought - _saleStage.startTokensBought + 1; _saleStages[saleStageIndex] = _saleStages[_saleStages.length - 1]; _saleStages.pop(); } /** * @dev Calculates the total price for the given number of tokens * @param tokens number of tokens to be purchased * @return summary price */ function getTotalPriceFor(uint256 tokens) public view returns (uint256) { require(tokens > 0, "tokens must be more then 0"); uint256 _saleStagesLength = _saleStages.length; uint256 totalSupply = totalSupply(); uint256 iterPrice = 0; uint256 totalPrice = 0; SaleStage memory saleStage; for (uint256 tokenIndex = 0; tokenIndex < tokens; tokenIndex++) { iterPrice = 0; for (uint256 i = 0; i < _saleStagesLength; i++) { saleStage = _saleStages[i]; if (totalSupply > saleStage.endTokensBought || totalSupply < saleStage.startTokensBought) continue; iterPrice += saleStage.weiPerToken; } if (iterPrice == 0) { revert("saleStage doesn't exist"); } totalPrice += iterPrice; totalSupply += 1; } return totalPrice; } /** * @dev Method to randomly mint desired number of NFTs * @param to the address where you want to transfer tokens * @param nfts the number of tokens to be minted */ function _mintMultiple(address to, uint256 nfts) internal { require(totalSupply() < _maxTotalSupply, "Sale has already ended"); require(nfts > 0, "nfts cannot be 0"); require(totalSupply().add(nfts) <= _maxTotalSupply, "Exceeds _maxTotalSupply"); for (uint256 i = 0; i < nfts; i++) { uint256 mintIndex = _getRandomAvailableIndex(); _safeMint(to, mintIndex); } } /** * @dev Mints a specific token (with known id) to the given address * @param to the receiver * @param mintIndex the tokenId to mint */ function mint(address to, uint256 mintIndex) public onlyRole(MINTER_ROLE) { _safeMint(to, mintIndex); } /** * @dev Public method to randomly mint desired number of NFTs * @param to the receiver * @param nfts the number of tokens to be minted */ function mintMultiple(address to, uint256 nfts) public onlyRole(MINTER_ROLE) { _mintMultiple(to, nfts); } /** * @dev Method to purchase and random available NFTs. * @param nfts the number of tokens to buy * @param referral the address of referral who invited the user to the platform */ function buy(uint256 nfts, address referral) public payable { require(saleActive, "Sale is not active"); require(nfts <= maxPurchaseSize, "Can not buy > maxPurchaseSize"); require(getTotalPriceFor(nfts) == msg.value, "Ether value sent is not correct"); emit Buy(msg.sender, nfts, referral); vault.transfer(msg.value); _mintMultiple(msg.sender, nfts); } /** * @dev Returns the (pseudo-)random token index free of owner. * @return available token index */ function _getRandomAvailableIndex() internal view returns (uint256) { uint256 index = (uint256( keccak256( abi.encodePacked( block.timestamp, /* solhint-disable not-rely-on-time */ gasleft(), blockhash(block.number - 1) ) ) ) % _maxTotalSupply); while (_exists(index)) { index += 1; if (index >= _maxTotalSupply) { index = 0; } } return index; } /** * @dev Returns rarity of the NFT by token Id * @param tokenId id of the token * @return rarity */ function getRarity(uint256 tokenId) public view returns (uint256) { require(_batches.length > 0, "getBatchByToken: no batches"); for (uint256 i; i < _batches.length; i++) { if (tokenId > _batches[i].endBatchTokenId || tokenId < _batches[i].startBatchTokenId) { continue; } else { return _batches[i].rarity; } } return _defaultRarity; } /** * @dev Returns name of the NFT at index * @param index token id * @return NFT name */ function getName(uint256 index) public view returns (string memory) { require(index < _maxTotalSupply, "index < _maxTotalSupply"); bytes memory _tokenWeight = bytes(_tokenName[index]); if (_tokenWeight.length == 0) { return _defaultName; } return _tokenName[index]; } /** * @dev Returns skill of the NFT at index * @param index token id * @return NFT skill */ function getSkill(uint256 index) public view returns (uint256) { require(index < _maxTotalSupply, "index < _maxTotalSupply"); if (_tokenSkill[index] == 0) { return _defaultSkill; } return _tokenSkill[index]; } /** * @dev Returns individual DNA of the NFT at index * @param index token id * @return NFT DNA */ function getDna(uint256 index) public view returns (uint256) { require(index < _maxTotalSupply, "index < _maxTotalSupply"); return _tokenDna[index]; } /** * @dev Start tokensale process */ function start() public onlyRole(DEFAULT_ADMIN_ROLE) { require(bytes(_defaultUri).length > 0, "_defaultUri is undefined"); require(vault != address(0), "Vault is undefined"); saleActive = true; } /** * @dev Stop tokensale */ function stop() public onlyRole(DEFAULT_ADMIN_ROLE) { saleActive = false; } /** * @dev Set or change individual token name */ function setName(uint256 index, string memory newName) public onlyRole(NAME_SETTER_ROLE) { require(index < _maxTotalSupply, "index < _maxTotalSupply"); _tokenName[index] = newName; emit NameChange(index, newName); } /** * @dev Set or change individual token skill */ function setSkill(uint256 index, uint256 newSkill) public onlyRole(SKILL_SETTER_ROLE) { require(index < _maxTotalSupply, "index < _maxTotalSupply"); _tokenSkill[index] = newSkill; emit SkillChange(index, newSkill); } /** * @dev Set or change individual token DNA */ function setDna(uint256 index, uint256 newDna) public onlyRole(DNA_SETTER_ROLE) { require(index < _maxTotalSupply, "index < _maxTotalSupply"); _tokenDna[index] = newDna; emit DnaChange(index, newDna); } /** * @dev Set max purchase size (to avoid gas overspending) */ function setMaxPurchaseSize(uint256 newPurchaseSize) public onlyRole(DEFAULT_ADMIN_ROLE) { maxPurchaseSize = newPurchaseSize; } /** * @dev Set defaultUri */ function setDefaultUri(string memory uri) public onlyRole(DEFAULT_ADMIN_ROLE) { _defaultUri = uri; } /** * @dev Set vault * @param newVault address to receive ethers */ function setVault(address payable newVault) public onlyRole(DEFAULT_ADMIN_ROLE) { vault = newVault; } /** * @dev Set defaultRarity * @param rarity new default rarity */ function setDefaultRarity(uint256 rarity) public onlyRole(DEFAULT_ADMIN_ROLE) { _defaultRarity = rarity; } /** * @dev Set default name. * @param name new default name */ function setDefaultName(string memory name) public onlyRole(DEFAULT_ADMIN_ROLE) { _defaultName = name; } /** * @dev Set default skill. * @param skill new default name */ function setDefaultSkill(uint256 skill) public onlyRole(DEFAULT_ADMIN_ROLE) { _defaultSkill = skill; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/utils/ERC721HolderUpgradeable.sol"; import "./Collection.sol"; contract NFTStaking is OwnableUpgradeable, ERC721HolderUpgradeable { // user deposits are recorded in StakeInfo[] stakes struct struct StakeInfo { // staked is true if token is staked and hasn't been unstaked. // After user claims his stake back, `staked` becomes false bool staked; // address of staked token's owner address stakerAddress; // time of start staking token uint256 lastUpdateTime; // totalYield is a total value of rewards for the given stake. // user is able to withdraw yield. uint256 totalYield; // The amount of yield user already harvested uint256 harvestedYield; } // If stakesOpen == true, the contract is operational and accepts new stakes. // Otherwise it allows just harvesting and unstaking. bool public stakesOpen; // Token used for rewards IERC20 public nftlToken; // The token accepted for staking Collection public heroesToken; uint256 internal constant WELCOME_BONUS_TIME = 365 * 24 * 60 * 60; // struccture that stores the records of users' stakes mapping(uint256 => StakeInfo) public stakes; // struccture that stores the records of users' staked tokens mapping(address => uint256[]) public stakedTokens; // Base reward that staker will receive for his stake uint256 public baseRewardPerSecond; event Stake(address indexed user, uint256 indexed tokenId); event Unstake(address indexed user, uint256 indexed tokenId); event Harvest(address indexed user, uint256 indexed tokenId, uint256 amount); /** * @dev the constructor arguments: * @param _nftlAddress address of token - the same used to pay rewards * @param _heroesAddress address of token - the same accepted for staking */ function initialize(address _nftlAddress, address _heroesAddress) public initializer { require(_nftlAddress != address(0), "Empty NFTL token address"); require(_heroesAddress != address(0), "Empty heroes address"); nftlToken = IERC20(_nftlAddress); heroesToken = Collection(_heroesAddress); __Ownable_init(); } /** * @dev start accepting new stakes. Called only by the owner */ function start() public onlyOwner { require(!stakesOpen, "Stakes are open already"); stakesOpen = true; } /** * @dev stop accepting new stakes. Called only by the owner */ function stop() public onlyOwner { require(stakesOpen, "Stakes are stopped already"); stakesOpen = false; } /** * @dev set base reward for tokens * @param _baseRewardPerSecond base reward in second */ function setBaseRewardPerSecond(uint256 _baseRewardPerSecond) public onlyOwner { baseRewardPerSecond = _baseRewardPerSecond; } /** * @dev the owner is able to withdraw excess tokens * @param _to address who will receive the funds * @param _amount amount of tokens in atto (1e-18) units */ function withdrawNftl(address _to, uint256 _amount) public onlyOwner { require(_to != address(0), "Empty receiver address"); require(_amount > 0, "Zero amount"); require(nftlToken.balanceOf(address(this)) >= _amount, "Not enough tokens"); nftlToken.transfer(_to, _amount); } /** * @dev submit the stake * @param _tokenId id of hero token */ function stake(uint256 _tokenId) external { require(stakesOpen, "stake: not open"); stakes[_tokenId].staked = true; stakes[_tokenId].stakerAddress = msg.sender; stakes[_tokenId].lastUpdateTime = block.timestamp; // stakers get welcome bonus for their first stake if (stakes[_tokenId].totalYield == 0) { stakes[_tokenId].totalYield = WELCOME_BONUS_TIME * getTokenRewardPerSecond(_tokenId); } stakedTokens[msg.sender].push(_tokenId); emit Stake(msg.sender, _tokenId); heroesToken.safeTransferFrom(msg.sender, address(this), _tokenId); } /** * @dev withdraw the user's staked token * @param _tokenId id of hero token */ function unstake(uint256 _tokenId) external { require(msg.sender == stakes[_tokenId].stakerAddress, "Sender is not staker"); require(stakes[_tokenId].staked, "Unstaked already"); _updateYield(_tokenId); stakes[_tokenId].staked = false; stakes[_tokenId].stakerAddress = address(0); // Since `delete` Solidity operator leaves zeroes at the deleted index and // doesn'd decrease array length. // To actually drop data and shorten the list, we copy last item to the index // of removed value (overwriting it) then pop last element to decrease array size for (uint256 i = 0; i < stakedTokens[msg.sender].length; ++i) { if (stakedTokens[msg.sender][i] == _tokenId) { uint256 lastElementIndex = stakedTokens[msg.sender].length - 1; stakedTokens[msg.sender][i] = stakedTokens[msg.sender][lastElementIndex]; stakedTokens[msg.sender].pop(); break; } } emit Unstake(msg.sender, _tokenId); _calculateAndTransferHarvest(_tokenId); heroesToken.safeTransferFrom(address(this), msg.sender, _tokenId); } /** * @dev harvest accumulated rewards. Can be called many times. * @param _tokenId Id of the token to be harvested */ function harvest(uint256 _tokenId) external { address currentTokenHolder = heroesToken.ownerOf(_tokenId); if (currentTokenHolder == address(this)) { // token is on staking contract, so we need to check it was indeed staked by msg.sender require(msg.sender == stakes[_tokenId].stakerAddress, "Sender is not staker"); _updateYield(_tokenId); } else { // token is on another address, so we need to check msg.sender is its owner require(msg.sender == currentTokenHolder, "Sender is not holder"); } require(stakes[_tokenId].totalYield > stakes[_tokenId].harvestedYield, "No harvestableYield"); _calculateAndTransferHarvest(_tokenId); } /** * @dev return the array of staked token IDs * @param _staker address of token staker * @return stakedTokens array of staked token IDs */ function getStakedTokens(address _staker) public view returns (uint256[] memory) { return stakedTokens[_staker]; } /** * @dev return unaccounted reward that is not reflected in the contract state * for staked tokens this function returns value that increments each block. * For tokens that are not staked it returns 0 * @param _tokenId index of the token * @return rewardSinceLastUpdate reward tokens that were accumulated sinceLastUpdate */ function getRewardSinceLastUpdate(uint256 _tokenId) public view returns (uint256 rewardSinceLastUpdate) { rewardSinceLastUpdate = 0; if (stakes[_tokenId].staked) { uint256 secondsStaked = block.timestamp - stakes[_tokenId].lastUpdateTime; rewardSinceLastUpdate = getTokenRewardPerSecond(_tokenId) * secondsStaked; } } /** * @dev get the individual stake parameters of the user's staked token * @param _tokenId token stake index * @return staked the status of stake * @return stakerAddress address of staker * @return lastUpdateTime time of start staking * @return totalYield entire yield for the stake * @return harvestedYield The part of yield user harvested already */ function getStake(uint256 _tokenId) external view returns ( bool staked, address stakerAddress, uint256 lastUpdateTime, uint256 totalYield, uint256 harvestedYield ) { StakeInfo memory _stake = stakes[_tokenId]; staked = _stake.staked; stakerAddress = _stake.stakerAddress; lastUpdateTime = _stake.lastUpdateTime; totalYield = _stake.totalYield + getRewardSinceLastUpdate(_tokenId); harvestedYield = _stake.harvestedYield; } /** * @dev calculate reward speed for the given tokenId * @param _tokenId token id * @return rewardPerSecond in atto tokens per second */ function getTokenRewardPerSecond(uint256 _tokenId) public view returns (uint256 rewardPerSecond) { rewardPerSecond = baseRewardPerSecond * heroesToken.getRarity(_tokenId); } /** * @dev Update accumulated reward for staked token * @param _tokenId token id */ function _updateYield(uint256 _tokenId) internal { require(stakes[_tokenId].staked, "Token not staked"); stakes[_tokenId].totalYield += getRewardSinceLastUpdate(_tokenId); stakes[_tokenId].lastUpdateTime = block.timestamp; } /** * @dev Calculate yield amount, emit Harvest event and pay nftl tokens * @param _tokenId token id */ function _calculateAndTransferHarvest(uint256 _tokenId) internal { uint256 amount = stakes[_tokenId].totalYield - stakes[_tokenId].harvestedYield; stakes[_tokenId].harvestedYield = stakes[_tokenId].totalYield; emit Harvest(msg.sender, _tokenId, amount); nftlToken.transfer(msg.sender, amount); } }
* @notice Update existing batch by its index @param batchIndex the index of the batch to be changed @param batchStartId index of the first batch token @param batchEndId index of the last batch token @param baseURI ipfs batch URI @param rarity batch rarity Note: batch ids can change over time and reorder as the result of batch removal/ if both bounds are lower or higher than iter batch
function setBatch( uint256 batchIndex, uint256 batchStartId, uint256 batchEndId, string memory baseURI, uint256 rarity ) external onlyRole(DEFAULT_ADMIN_ROLE) { uint256 _batchesLength = _batches.length; require(_batchesLength > 0, "setBatch: batches is empty"); require(batchStartId <= batchEndId, "startId must be <= than EndId"); for (uint256 i; i < _batchesLength; i++) { if (i == batchIndex) { continue; if ( (batchStartId < _batches[i].startBatchTokenId && batchEndId < _batches[i].startBatchTokenId) || (batchStartId > _batches[i].endBatchTokenId && batchEndId > _batches[i].endBatchTokenId) ) { continue; revert("batches intersect"); } } } _batches[batchIndex].startBatchTokenId = batchStartId; _batches[batchIndex].endBatchTokenId = batchEndId; _batches[batchIndex].baseURI = baseURI; _batches[batchIndex].rarity = rarity; }
11,682,375
[ 1, 1891, 2062, 2581, 635, 2097, 770, 225, 2581, 1016, 326, 770, 434, 326, 2581, 358, 506, 3550, 225, 2581, 1685, 548, 770, 434, 326, 1122, 2581, 1147, 225, 2581, 1638, 548, 770, 434, 326, 1142, 2581, 1147, 225, 1026, 3098, 2359, 2556, 2581, 3699, 225, 436, 20498, 2581, 436, 20498, 3609, 30, 2581, 3258, 848, 2549, 1879, 813, 471, 19427, 487, 326, 563, 434, 2581, 14817, 19, 309, 3937, 4972, 854, 2612, 578, 10478, 2353, 1400, 2581, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 4497, 12, 203, 3639, 2254, 5034, 2581, 1016, 16, 203, 3639, 2254, 5034, 2581, 1685, 548, 16, 203, 3639, 2254, 5034, 2581, 1638, 548, 16, 203, 3639, 533, 3778, 1026, 3098, 16, 203, 3639, 2254, 5034, 436, 20498, 203, 565, 262, 3903, 1338, 2996, 12, 5280, 67, 15468, 67, 16256, 13, 288, 203, 3639, 2254, 5034, 389, 21233, 1782, 273, 389, 21233, 18, 2469, 31, 203, 3639, 2583, 24899, 21233, 1782, 405, 374, 16, 315, 542, 4497, 30, 13166, 353, 1008, 8863, 203, 3639, 2583, 12, 5303, 1685, 548, 1648, 2581, 1638, 548, 16, 315, 1937, 548, 1297, 506, 1648, 2353, 4403, 548, 8863, 203, 203, 3639, 364, 261, 11890, 5034, 277, 31, 277, 411, 389, 21233, 1782, 31, 277, 27245, 288, 203, 5411, 309, 261, 77, 422, 2581, 1016, 13, 288, 203, 7734, 1324, 31, 203, 7734, 309, 261, 203, 10792, 261, 5303, 1685, 548, 411, 389, 21233, 63, 77, 8009, 1937, 4497, 1345, 548, 597, 2581, 1638, 548, 411, 389, 21233, 63, 77, 8009, 1937, 4497, 1345, 548, 13, 747, 203, 10792, 261, 5303, 1685, 548, 405, 389, 21233, 63, 77, 8009, 409, 4497, 1345, 548, 597, 2581, 1638, 548, 405, 389, 21233, 63, 77, 8009, 409, 4497, 1345, 548, 13, 203, 7734, 262, 288, 203, 10792, 1324, 31, 203, 10792, 15226, 2932, 21233, 9136, 8863, 203, 7734, 289, 203, 5411, 289, 203, 3639, 289, 203, 203, 3639, 389, 21233, 63, 5303, 1016, 8009, 1937, 4497, 1345, 548, 273, 2581, 1685, 548, 31, 203, 3639, 389, 21233, 63, 5303, 2 ]
./full_match/1/0x0e6Ff4E3EC935578673fF04D815544e7503E4A45/sources/home/jenja/stobox-contract/contracts/Roles.sol
* @notice Add the transporter role for the address. @param _address Address for assigning the transporter role./
function addTransporter(address _address) external onlySuperAdmin { _assignRole(_address, TRANSPORTER_ROLE); }
4,840,690
[ 1, 986, 326, 906, 7988, 2478, 364, 326, 1758, 18, 225, 389, 2867, 5267, 364, 28639, 326, 906, 7988, 2478, 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 ]
[ 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, 527, 1429, 7988, 12, 2867, 389, 2867, 13, 203, 3639, 3903, 203, 3639, 1338, 8051, 4446, 203, 565, 288, 203, 3639, 389, 6145, 2996, 24899, 2867, 16, 14996, 3118, 916, 2560, 67, 16256, 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 ]
pragma solidity ^0.4.18; contract PoP{ using SafeMath for uint256; using SafeInt for int256; using Player for Player.Data; using BettingRecordArray for BettingRecordArray.Data; using WrappedArray for WrappedArray.Data; using FixedPoint for FixedPoint.Data; // Contract Info string public name; string public symbol; uint8 public decimals; address private author; // Events for Game event Bet(address player, uint256 betAmount, uint256 betNumber, uint256 gameNumber); event Withdraw(address player, uint256 amount, uint256 numberOfRecordsProcessed); event EndGame(uint256 currentGameNumber); // Events for Coin event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); event Burn(address indexed burner, uint256 value); event Mined(address indexed miner, uint256 value); // Init function PoP() public { name = "PopCoin"; symbol = "PoP"; decimals = 18; author = msg.sender; totalSupply_ = 10000000 * 10 ** uint256(decimals); lastBetBlockNumber = 0; currentGameNumber = 0; currentPot = 0; initialSeed = 0; minimumWager = kBaseMinBetSize.toUInt256Raw(); minimumNumberOfBlocksToEndGame = kLowerBoundBlocksTillGameEnd.add(kUpperBoundBlocksTillGameEnd).toUInt256Raw(); gameHasStarted = false; currentMiningDifficulty = FixedPoint.fromInt256(kStartingGameMiningDifficulty); unPromisedSupplyAtStartOfCurrentGame_ = totalSupply_; currentPotSplit = 1000; nextGameMaxBlock = kUpperBoundBlocksTillGameEnd; nextGameMinBlock = kLowerBoundBlocksTillGameEnd; currentGameInitialMinBetSize = kBaseMinBetSize; nextGameInitialMinBetSize = currentGameInitialMinBetSize; nextFrontWindowAdjustmentRatio = frontWindowAdjustmentRatio; nextBackWindowAdjustmentRatio = backWindowAdjustmentRatio; nextGameSeedPercent = percentToTakeAsSeed; nextGameRakePercent = percentToTakeAsRake; nextGameDeveloperMiningPower = developerMiningPower; nextGamePotSplit = currentPotSplit; // Initialize Dev Permissions canUpdateNextGameInitalMinBetSize = true; canUpdateFrontWindowAdjustmentRatio = true; canUpdateBackWindowAdjustmentRatio = true; canUpdateNextGamePotSplit = true; canUpdatePercentToTakeAsSeed = true; canUpdateNextGameMinAndMaxBlockUntilGameEnd = true; canUpdateAmountToTakeAsRake = true; canUpdateDeveloperMiningPower = true; } // Constants FixedPoint.Data _2pi = FixedPoint.Data({val: 26986075409}); FixedPoint.Data _pi = FixedPoint.Data({val: 13493037704}); FixedPoint.Data kBackPayoutEndPointInitial = FixedPoint.fromFraction(1, 2); FixedPoint.Data kFrontPayoutStartPointInitial = FixedPoint.fromFraction(1, 2); uint256 public percentToTakeAsRake = 500; // MC uint256 public percentToTakeAsSeed = 900; // MC uint256 public developerMiningPower = 3000; // MC uint256 constant kTotalPercent = 10000; uint8 constant kStartingGameMiningDifficulty = 1; uint256 potSplitMax = 2000; uint8 constant kDifficultyWindow = 10; // MC FixedPoint.Data kDifficultyDropOffFactor = FixedPoint.fromFraction(8, 10); // MC uint256 constant kWeiConstant = 10 ** 18; FixedPoint.Data kExpectedFirstGameSize = FixedPoint.fromInt256(Int256(10 * kWeiConstant)); FixedPoint.Data kExpectedPopCoinToBePromisedPercent = FixedPoint.fromFraction(1, 1000); // MC FixedPoint.Data kLowerBoundBlocksTillGameEnd = FixedPoint.fromInt256(6); // MC FixedPoint.Data kUpperBoundBlocksTillGameEnd = FixedPoint.fromInt256(80); // MC FixedPoint.Data kBaseMinBetSize = FixedPoint.fromInt256(Int256(kWeiConstant/1000)); FixedPoint.Data kMaxPopMiningPotMultiple = FixedPoint.fromFraction(118709955, 1000000); // MC // Public Variables uint256 public lastBetBlockNumber; uint256 public minimumNumberOfBlocksToEndGame; uint256 public currentPot; uint256 public currentGameNumber; FixedPoint.Data currentMiningDifficulty; uint256 public initialSeed; uint256 public bonusSeed; uint256 public minimumWager; uint256 public currentBetNumber; uint256 public nextGameSeedPercent; uint256 public nextGameRakePercent; uint256 public nextGameDeveloperMiningPower; uint256 public currentPotSplit; uint256 public nextGamePotSplit; // Game Private Variables mapping (address => Player.Data) playerCollection; BettingRecordArray.Data currentGameBettingRecords; WrappedArray.Data gameMetaData; mapping (address => uint256) playerInternalWallet; FixedPoint.Data public initialBankrollGrowthAmount; // This is what the current pot will be compared to FixedPoint.Data public nextGameInitialMinBetSize; FixedPoint.Data currentGameInitialMinBetSize; FixedPoint.Data public nextGameMaxBlock; FixedPoint.Data public nextGameMinBlock; FixedPoint.Data public frontWindowAdjustmentRatio = FixedPoint.fromFraction(13, 10); // MC: FixedPoint.Data public backWindowAdjustmentRatio = FixedPoint.fromFraction(175, 100); // MC: FixedPoint.Data public nextFrontWindowAdjustmentRatio; FixedPoint.Data public nextBackWindowAdjustmentRatio; // Coin Private Variables mapping(address => uint256) popBalances; mapping (address => mapping (address => uint256)) internal allowed; uint256 totalSupply_; uint256 supplyMined_; uint256 supplyBurned_; uint256 unPromisedSupplyAtStartOfCurrentGame_; bool gameHasStarted; // Dev Permission Control over Game Variables bool public canUpdateNextGameInitalMinBetSize; bool public canUpdateFrontWindowAdjustmentRatio; bool public canUpdateBackWindowAdjustmentRatio; bool public canUpdateNextGamePotSplit; bool public canUpdatePercentToTakeAsSeed; bool public canUpdateNextGameMinAndMaxBlockUntilGameEnd; bool public canUpdateAmountToTakeAsRake; bool public canUpdateDeveloperMiningPower; function turnOffCanUpdateNextGameInitalMinBetSize () public { require (msg.sender == author); require (canUpdateNextGameInitalMinBetSize == true); canUpdateNextGameInitalMinBetSize = false; } function turnOffCanUpdateFrontWindowAdjustmentRatio () public { require (msg.sender == author); require (canUpdateFrontWindowAdjustmentRatio == true); canUpdateFrontWindowAdjustmentRatio = false; } function turnOffCanUpdateBackWindowAdjustmentRatio () public { require (msg.sender == author); require (canUpdateBackWindowAdjustmentRatio == true); canUpdateBackWindowAdjustmentRatio = false; } function turnOffCanUpdateNextGamePotSplit () public { require (msg.sender == author); require (canUpdateNextGamePotSplit == true); canUpdateNextGamePotSplit = false; } function turnOffCanUpdatePercentToTakeAsSeed () public { require (msg.sender == author); require (canUpdatePercentToTakeAsSeed == true); canUpdatePercentToTakeAsSeed = false; } function turnOffCanUpdateNextGameMinAndMaxBlockUntilGameEnd () public { require (msg.sender == author); require (canUpdateNextGameMinAndMaxBlockUntilGameEnd == true); canUpdateNextGameMinAndMaxBlockUntilGameEnd = false; } function turnOffCanUpdateAmountToTakeAsRake () public { require (msg.sender == author); require (canUpdateAmountToTakeAsRake == true); canUpdateAmountToTakeAsRake = false; } function turnOffCanUpdateDeveloperMiningPower () public { require (msg.sender == author); require (canUpdateDeveloperMiningPower == true); canUpdateDeveloperMiningPower = false; } function balanceOfContract () public constant returns(uint256 res) { return address(this).balance; } function getCurrentGameInitialMinBetSize () public view returns(uint256 res) { return currentGameInitialMinBetSize.toUInt256Raw(); } function startGame () payable public { require (msg.sender == author); require (msg.value > 0); require (gameHasStarted == false); initialSeed = initialSeed.add(msg.value); currentPot = initialSeed; gameHasStarted = true; } function updateNextGameInitalMinBetSize (uint256 nextGameMinBetSize) public { require (msg.sender == author); require (canUpdateNextGameInitalMinBetSize == true); require (nextGameMinBetSize > 0); FixedPoint.Data memory nextMinBet = FixedPoint.fromInt256(Int256(nextGameMinBetSize)); // Cant change the min bet too much in between games require(nextMinBet.cmp(currentGameInitialMinBetSize.mul(FixedPoint.fromInt256(2))) != 1); require(nextMinBet.cmp(currentGameInitialMinBetSize.div(FixedPoint.fromInt256(2))) != -1); nextGameInitialMinBetSize = FixedPoint.fromInt256(Int256(nextGameMinBetSize)); } function updateNextWindowAdjustmentRatio (int256 numerator, bool updateFront) public { require (msg.sender == author); require (numerator >= 1000); require (numerator <= 2718); require ((updateFront && canUpdateFrontWindowAdjustmentRatio) || (!updateFront && canUpdateBackWindowAdjustmentRatio)); if(updateFront == true) { nextFrontWindowAdjustmentRatio = FixedPoint.fromFraction(numerator, 1000); } else { nextBackWindowAdjustmentRatio = FixedPoint.fromFraction(numerator, 1000); } } function updateNextGamePotSplit (uint256 potSplit ) public { require (msg.sender == author); require (canUpdateNextGamePotSplit); require (potSplit <= 2000); nextGamePotSplit = potSplit; } function updatePercentToTakeAsSeed (uint256 value) public { require (msg.sender == author); require (canUpdatePercentToTakeAsSeed); require (value < 10000); if (value > percentToTakeAsSeed){ require (value / percentToTakeAsSeed == 1); } else { require (percentToTakeAsSeed / value == 1); } nextGameSeedPercent = value; } function updateNextGameMinAndMaxBlockUntilGameEnd (uint256 maxBlocks, uint256 minBlocks) public { require (msg.sender == author); require (canUpdateNextGameMinAndMaxBlockUntilGameEnd); require (maxBlocks > 0); require (minBlocks > 0); FixedPoint.Data memory nextMaxBlock = FixedPoint.fromInt256(Int256(maxBlocks)); FixedPoint.Data memory nextMinBlock = FixedPoint.fromInt256(Int256(minBlocks)); require(nextMaxBlock.cmp(kUpperBoundBlocksTillGameEnd.mul(FixedPoint.fromInt256(2))) != 1); require(nextMaxBlock.cmp(kUpperBoundBlocksTillGameEnd.div(FixedPoint.fromInt256(2))) != -1); require(nextMinBlock.cmp(kLowerBoundBlocksTillGameEnd.mul(FixedPoint.fromInt256(2))) != 1); require(nextMaxBlock.cmp(kLowerBoundBlocksTillGameEnd.div(FixedPoint.fromInt256(2))) != -1); nextGameMaxBlock = FixedPoint.fromInt256(Int256(maxBlocks)); nextGameMinBlock = FixedPoint.fromInt256(Int256(minBlocks)); } function getUpperBoundBlocksTillGameEnd() public view returns(uint256) { return kUpperBoundBlocksTillGameEnd.toUInt256Raw(); } function getLowerBoundBlocksTillGameEnd() public view returns(uint256) { return kLowerBoundBlocksTillGameEnd.toUInt256Raw(); } function addToRakePool () public payable{ assert (msg.value > 0); playerInternalWallet[this] = playerInternalWallet[this].add(msg.value); } // Public API function bet () payable public { // require bet be large enough require(msg.value >= minimumWager); require(gameHasStarted); uint256 betAmount = msg.value; // take rake betAmount = betAmountAfterRakeHasBeenWithdrawnAndProcessed(betAmount); if((block.number.sub(lastBetBlockNumber) >= minimumNumberOfBlocksToEndGame) && (lastBetBlockNumber != 0)) { processEndGame(betAmount); } else if (lastBetBlockNumber == 0) { initialBankrollGrowthAmount = FixedPoint.fromInt256(Int256(betAmount.add(initialSeed))); } emit Bet(msg.sender, betAmount, currentBetNumber, currentGameNumber); Player.BettingRecord memory newBetRecord = Player.BettingRecord(msg.sender, currentGameNumber, betAmount, currentBetNumber, currentPot.sub(initialSeed), 0, 0, true); Player.Data storage currentPlayer = playerCollection[msg.sender]; currentPlayer.insertBettingRecord(newBetRecord); Player.BettingRecord memory oldGameUnprocessedBettingRecord = currentGameBettingRecords.getNextRecord(); currentGameBettingRecords.pushRecord(newBetRecord); if(oldGameUnprocessedBettingRecord.isActive == true) { processBettingRecord(oldGameUnprocessedBettingRecord); } currentPot = currentPot.add(betAmount); currentBetNumber = currentBetNumber.add(1); lastBetBlockNumber = block.number; FixedPoint.Data memory currentGameSize = FixedPoint.fromInt256(Int256(currentPot)); FixedPoint.Data memory expectedGameSize = currentMiningDifficulty.mul(kExpectedFirstGameSize); minimumNumberOfBlocksToEndGame = calcNumberOfBlocksUntilGameEnds(currentGameSize, expectedGameSize).toUInt256Raw(); minimumWager = calcMinimumBetSize(currentGameSize, expectedGameSize).toUInt256Raw(); } function getMyBetRecordCount() public view returns(uint256) { Player.Data storage currentPlayer = playerCollection[msg.sender]; return currentPlayer.unprocessedBettingRecordCount(); } function getDeveloperMiningPowerForGameId (uint256 gameId) private view returns(uint256 res) { if(gameId == currentGameNumber) { return developerMiningPower; } else { WrappedArray.GameMetaDataElement memory elem = gameMetaData.itemAtIndex(gameId); return elem.developerMiningPower; } } function playerPopMining(uint256 recordIndex, bool onlyCurrentGame) public view returns(uint256) { Player.Data storage currentPlayer = playerCollection[msg.sender]; Player.BettingRecord memory playerBettingRecord = currentPlayer.getBettingRecordAtIndex(recordIndex); return computeAmountToMineForBettingRecord(playerBettingRecord, onlyCurrentGame).mul(kTotalPercent - getDeveloperMiningPowerForGameId(playerBettingRecord.gameId)).div(kTotalPercent); } function getBetRecord(uint256 recordIndex) public view returns(uint256, uint256, uint256) { Player.Data storage currentPlayer = playerCollection[msg.sender]; Player.BettingRecord memory bettingRecord = currentPlayer.getBettingRecordAtIndex(recordIndex); return (bettingRecord.gamePotBeforeBet, bettingRecord.wagerAmount, bettingRecord.gameId); } function withdraw (uint256 withdrawCount) public returns(bool res) { Player.Data storage currentPlayer = playerCollection[msg.sender]; uint256 playerBettingRecordCount = currentPlayer.unprocessedBettingRecordCount(); uint256 numberOfIterations = withdrawCount < playerBettingRecordCount ? withdrawCount : playerBettingRecordCount; numberOfIterations = numberOfIterations == 0 ? 0 : numberOfIterations.add(1); for (uint256 i = 0 ; i < numberOfIterations; i = i.add(1)) { Player.BettingRecord memory unprocessedRecord = currentPlayer.getNextRecord(); processBettingRecord(unprocessedRecord); } uint256 playerBalance = playerInternalWallet[msg.sender]; playerInternalWallet[msg.sender] = 0; if(playerBalance == 0) { return true; } emit Withdraw(msg.sender, playerBalance, numberOfIterations); if(!msg.sender.send(playerBalance)) { //If money shipment fails store money back in the container playerInternalWallet[msg.sender] = playerBalance; return false; } return true; } function getCurrentMiningDifficulty() public view returns(uint256){ return UInt256(currentMiningDifficulty.toInt256()); } function getPlayerInternalWallet() public view returns(uint256) { return playerInternalWallet[msg.sender]; } function getWinningsForRecordId(uint256 recordIndex, bool onlyWithdrawable, bool onlyCurrentGame) public view returns(uint256) { Player.Data storage currentPlayer = playerCollection[msg.sender]; Player.BettingRecord memory record = currentPlayer.getBettingRecordAtIndex(recordIndex); if(onlyCurrentGame && record.gameId != currentGameNumber) { return 0; } return getWinningsForRecord(record, onlyWithdrawable); } function getWinningsForRecord(Player.BettingRecord record, bool onlyWithdrawable) private view returns(uint256) { if(onlyWithdrawable && recordIsTooNewToProcess(record)) { return 0; } uint256 payout = getPayoutForPlayer(record).toUInt256Raw(); uint256 seedPercentForGame = getSeedPercentageForGameId(record.gameId); payout = payout.sub(amountToSeedNextRound(payout, seedPercentForGame)); return payout.sub(record.withdrawnAmount); } function totalAmountRaked () public constant returns(uint256 res) { return playerInternalWallet[this]; } function betAmountAfterRakeHasBeenWithdrawnAndProcessed (uint256 betAmount) private returns(uint256 betLessRake){ uint256 amountToRake = amountToTakeAsRake(betAmount); playerInternalWallet[this] = playerInternalWallet[this].add(amountToRake); return betAmount.sub(amountToRake); } function getSeedPercentageForGameId (uint256 gameId) private view returns(uint256 res) { if(gameId == currentGameNumber) { return percentToTakeAsSeed; } else { WrappedArray.GameMetaDataElement memory elem = gameMetaData.itemAtIndex(gameId); return elem.percentToTakeAsSeed; } } function amountToSeedNextRound (uint256 value, uint256 seedPercent) private pure returns(uint256 res) { return value.mul(seedPercent).div(kTotalPercent); } function addToBonusSeed () public payable { require (msg.value > 0); bonusSeed = bonusSeed.add(msg.value); } function updateAmountToTakeAsRake(uint256 value) public { require (msg.sender == author); require (canUpdateAmountToTakeAsRake); require (value < 10000); if(percentToTakeAsRake > value) { require(percentToTakeAsRake - value <= 100); } else { require(value - percentToTakeAsRake <= 100); } nextGameRakePercent = value; } function updateDeveloperMiningPower(uint256 value) public { require (msg.sender == author); require (canUpdateDeveloperMiningPower); require (value <= 3000); nextGameDeveloperMiningPower = value; } function amountToTakeAsRake (uint256 value) private view returns(uint256 res) { return value.mul(percentToTakeAsRake).div(kTotalPercent); } function processEndGame (uint256 lastBetAmount) private { // The order of these function calls are dependent on each other // Beware when changing order or modifying code emit EndGame(currentGameNumber); // Store game meta Data gameMetaData.push(WrappedArray.GameMetaDataElement(currentPot, initialSeed, initialBankrollGrowthAmount.toUInt256Raw(), unPromisedSupplyAtStartOfCurrentGame_, developerMiningPower, percentToTakeAsSeed, percentToTakeAsRake, currentPotSplit, currentMiningDifficulty, frontWindowAdjustmentRatio, backWindowAdjustmentRatio, true)); // totalPotAmount, seedAmount, initialBet, popremaining, miningDifficulty, isActive frontWindowAdjustmentRatio = nextFrontWindowAdjustmentRatio; backWindowAdjustmentRatio = nextBackWindowAdjustmentRatio; currentGameInitialMinBetSize = nextGameInitialMinBetSize; kUpperBoundBlocksTillGameEnd = nextGameMaxBlock; kLowerBoundBlocksTillGameEnd = nextGameMinBlock; unPromisedSupplyAtStartOfCurrentGame_ = unPromisedPop(); initialSeed = amountToSeedNextRound(currentPot, percentToTakeAsSeed).add(bonusSeed); bonusSeed = 0; currentPot = initialSeed; currentMiningDifficulty = calcDifficulty(); percentToTakeAsSeed = nextGameSeedPercent; percentToTakeAsRake = nextGameRakePercent; developerMiningPower = nextGameDeveloperMiningPower; currentPotSplit = nextGamePotSplit; // Set initial bet which will calculate the growth factor initialBankrollGrowthAmount = FixedPoint.fromInt256(Int256(lastBetAmount.add(initialSeed))); // Reset current game array currentGameBettingRecords.resetIndex(); // increment game number currentGameNumber = currentGameNumber.add(1); } function processBettingRecord (Player.BettingRecord record) private { Player.Data storage currentPlayer = playerCollection[record.playerAddress]; if(currentPlayer.containsBettingRecordFromId(record.bettingRecordId) == false) { return; } // Refetch record as player might have withdrawn part Player.BettingRecord memory bettingRecord = currentPlayer.getBettingRecordForId(record.bettingRecordId); currentPlayer.deleteBettingRecordForId(bettingRecord.bettingRecordId); // this assumes compute for value returns total value of record less withdrawnAmount uint256 bettingRecordValue = getWinningsForRecord(bettingRecord, true); uint256 amountToMineForBettingRecord = computeAmountToMineForBettingRecord(bettingRecord, false); // If it is current game we need to not remove the record as it's value might increase but amend it and re-insert if(bettingRecord.gameId == currentGameNumber) { bettingRecord.withdrawnAmount = bettingRecord.withdrawnAmount.add(bettingRecordValue); bettingRecord.withdrawnPopAmount = bettingRecord.withdrawnPopAmount.add(amountToMineForBettingRecord); currentPlayer.insertBettingRecord(bettingRecord); } minePoP(bettingRecord.playerAddress, amountToMineForBettingRecord, bettingRecord.gameId); playerInternalWallet[bettingRecord.playerAddress] = playerInternalWallet[bettingRecord.playerAddress].add(bettingRecordValue); } function recordIsTooNewToProcess (Player.BettingRecord record) private view returns(bool res) { if(record.gameId == currentGameNumber) { return true; } return false; } function UInt256 (int256 elem) private pure returns(uint256 res) { assert(elem >= 0); return uint256(elem); } function Int256 (uint256 elem) private pure returns(int256 res) { assert(int256(elem) >= 0); return int256(elem); } function getBankRollGrowthForGameId (uint256 gameId) private view returns(FixedPoint.Data res) { if(gameId == currentGameNumber) { return FixedPoint.fromInt256(Int256(currentPot)).div(initialBankrollGrowthAmount); } else { WrappedArray.GameMetaDataElement memory elem = gameMetaData.itemAtIndex(gameId); return FixedPoint.fromInt256(Int256(elem.totalPotAmount)).div(FixedPoint.fromInt256(Int256(elem.initialBet))); } } function getSeedAmountForGameId (uint256 gameId) private view returns(FixedPoint.Data res) { if(gameId == currentGameNumber) { return FixedPoint.fromInt256(Int256(initialSeed)); } else { WrappedArray.GameMetaDataElement memory elem = gameMetaData.itemAtIndex(gameId); return FixedPoint.fromInt256(Int256(elem.seedAmount)); } } function getWindowAdjRatioForGameId (uint256 gameId, bool isFront) internal view returns(FixedPoint.Data) { if(gameId == currentGameNumber) { return isFront == true ? frontWindowAdjustmentRatio : backWindowAdjustmentRatio; } else { WrappedArray.GameMetaDataElement memory elem = gameMetaData.itemAtIndex(gameId); return isFront == true ? elem.frontWindowAdjustmentRatio : elem.backWindowAdjustmentRatio; } } function getSplitPotAsFixedPointForGameId (uint256 gameId, bool isFront) internal view returns (FixedPoint.Data) { if(gameId == currentGameNumber) { if(isFront){ return FixedPoint.fromFraction(Int256(currentPotSplit), 1000); } else { return FixedPoint.fromFraction(Int256(potSplitMax.sub(currentPotSplit)), 1000); } } else { WrappedArray.GameMetaDataElement memory elem = gameMetaData.itemAtIndex(gameId); if(isFront){ return FixedPoint.fromFraction(Int256(elem.potSplit), 1000); } else { return FixedPoint.fromFraction(Int256(potSplitMax.sub(elem.potSplit)), 1000); } } } function getAdjustedPotAsFixedPointForGameId (uint256 gameId, bool isFront) internal view returns (FixedPoint.Data) { return getPotAsFixedPointForGameId(gameId).mul(getSplitPotAsFixedPointForGameId(gameId, isFront)); } function getPayoutForPlayer(Player.BettingRecord playerRecord) internal view returns (FixedPoint.Data) { FixedPoint.Data memory frontWindowAdjustment = getWindowAdjustmentForGameIdAndRatio(playerRecord.gameId, getWindowAdjRatioForGameId(playerRecord.gameId, true)); FixedPoint.Data memory backWindowAdjustment = getWindowAdjustmentForGameIdAndRatio(playerRecord.gameId, getWindowAdjRatioForGameId(playerRecord.gameId, false)); FixedPoint.Data memory backPayoutEndPoint = kBackPayoutEndPointInitial.div(backWindowAdjustment); FixedPoint.Data memory frontPayoutSizePercent = kFrontPayoutStartPointInitial.div(frontWindowAdjustment); FixedPoint.Data memory frontPayoutStartPoint = FixedPoint.fromInt256(1).sub(frontPayoutSizePercent); FixedPoint.Data memory frontPercent = FixedPoint.fromInt256(0); if(playerRecord.gamePotBeforeBet != 0) { frontPercent = FixedPoint.fromInt256(Int256(playerRecord.gamePotBeforeBet)).div(getPotAsFixedPointForGameId(playerRecord.gameId).sub(getSeedAmountForGameId(playerRecord.gameId))); } FixedPoint.Data memory backPercent = FixedPoint.fromInt256(Int256(playerRecord.gamePotBeforeBet)).add(FixedPoint.fromInt256(Int256(playerRecord.wagerAmount))).div(getPotAsFixedPointForGameId(playerRecord.gameId).sub(getSeedAmountForGameId(playerRecord.gameId))); if(frontPercent.val < backPayoutEndPoint.val) { if(backPercent.val <= backPayoutEndPoint.val) { // Bet started in left half of curve and ended left half of curve return calcWinnings(frontPercent.div(backPayoutEndPoint), backPercent.div(backPayoutEndPoint), backWindowAdjustment, FixedPoint.fromInt256(0), playerRecord.gameId, false); } else if (backPercent.val <= frontPayoutStartPoint.val) { // Bet started in left half of curve and ended in deadzone between curves return calcWinnings(frontPercent.div(backPayoutEndPoint), backPayoutEndPoint.div(backPayoutEndPoint), backWindowAdjustment, FixedPoint.fromInt256(0), playerRecord.gameId, false); } else { // Bet started in left half of curve and ended right half of curve return calcWinnings(frontPercent.div(backPayoutEndPoint), backPayoutEndPoint.div(backPayoutEndPoint), backWindowAdjustment, FixedPoint.fromInt256(0), playerRecord.gameId, false).add(calcWinnings(FixedPoint.fromInt256(0), backPercent.sub(frontPayoutStartPoint).div(frontPayoutSizePercent), frontWindowAdjustment, _pi.div(frontWindowAdjustment), playerRecord.gameId, true)); } } else if (frontPercent.val < frontPayoutStartPoint.val) { if (backPercent.val <= frontPayoutStartPoint.val) { // Bet started in dead zone and ended in dead zone return FixedPoint.fromInt256(0); } else { // Bet started in deadzone and ended in right hand of curve return calcWinnings(FixedPoint.fromInt256(0), backPercent.sub(frontPayoutStartPoint).div(frontPayoutSizePercent), frontWindowAdjustment, _pi.div(frontWindowAdjustment), playerRecord.gameId, true); } } else { // Bet started in right hand of curve and of course ended in right hand of curve return calcWinnings(frontPercent.sub(frontPayoutStartPoint).div(frontPayoutSizePercent), backPercent.sub(frontPayoutStartPoint).div(frontPayoutSizePercent), frontWindowAdjustment, _pi.div(frontWindowAdjustment), playerRecord.gameId, true); } } function getWindowAdjustmentForGameIdAndRatio(uint256 gameId, FixedPoint.Data adjustmentRatio) internal view returns (FixedPoint.Data) { FixedPoint.Data memory growth = getBankRollGrowthForGameId(gameId);//FixedPoint.Data({val: brGrowth}); FixedPoint.Data memory logGrowthRate = growth.ln(); return growth.div(adjustmentRatio.pow(logGrowthRate)); } function integrate(FixedPoint.Data x, FixedPoint.Data a, FixedPoint.Data y) internal pure returns (FixedPoint.Data) { return a.mul(x).sin().div(a).add(x).sub(a.mul(y).sin().div(a).add(y)); } function calcWinnings(FixedPoint.Data playerFrontPercent, FixedPoint.Data playerBackPercent, FixedPoint.Data windowAdjustment, FixedPoint.Data sectionOffset, uint256 gameId, bool isFront) internal view returns (FixedPoint.Data) { FixedPoint.Data memory potSize = getAdjustedPotAsFixedPointForGameId(gameId, isFront); FixedPoint.Data memory startIntegrationPoint = sectionOffset.add(playerFrontPercent.mul(_pi.div(windowAdjustment))); FixedPoint.Data memory endIntegrationPoint = sectionOffset.add(playerBackPercent.mul(_pi.div(windowAdjustment))); return integrate(endIntegrationPoint, windowAdjustment, startIntegrationPoint).mul(potSize).mul(windowAdjustment).div(_2pi); } function computeAmountToMineForBettingRecord (Player.BettingRecord record, bool onlyCurrentGame) internal view returns(uint256 value) { if(onlyCurrentGame && record.gameId != currentGameNumber){ return 0; } uint256 payout = getPopPayoutForRecord(record).toUInt256Raw(); return payout.sub(record.withdrawnPopAmount); } function getPopPayoutForRecord(Player.BettingRecord record) private view returns(FixedPoint.Data value) { if(record.isActive == false) { return FixedPoint.fromInt256(0); } return totalTokenPayout(getPotAsFixedPointForGameId(record.gameId).sub(getInitialSeedAsFixedPointForGameId(record.gameId)), getDifficultyAsFixedPointForGameId(record.gameId), getPopRemainingAsFixedPointForGameId(record.gameId), record.wagerAmount, record.gamePotBeforeBet); //uint256 gameId, uint256 wagerAmount, uint256 previousPotSize } function unMinedPop () private view returns(uint256 res) { return totalSupply_.sub(supplyMined_); } function promisedPop () private view returns(uint256) { FixedPoint.Data memory curPot = getPotAsFixedPointForGameId(currentGameNumber); FixedPoint.Data memory seed = getInitialSeedAsFixedPointForGameId(currentGameNumber); FixedPoint.Data memory difficulty = getDifficultyAsFixedPointForGameId(currentGameNumber); FixedPoint.Data memory unpromised = getPopRemainingAsFixedPointForGameId(currentGameNumber); uint256 promisedPopThisGame = totalTokenPayout(curPot.sub(seed), difficulty, unpromised, currentPot.sub(seed.toUInt256Raw()), 0).toUInt256Raw(); return totalSupply_.sub(unPromisedSupplyAtStartOfCurrentGame_).add(promisedPopThisGame); } function unPromisedPop () private view returns(uint256 res) { return totalSupply_.sub(promisedPop()); } function potentiallyCirculatingPop () public view returns(uint256 res) { return promisedPop().sub(supplyBurned_); } function minePoP(address target, uint256 amountToMine, uint256 gameId) private { if(supplyMined_ >= totalSupply_) { return; } uint256 remainingPop = unMinedPop(); if(amountToMine == 0 || remainingPop == 0) { return; } if(remainingPop < amountToMine) { amountToMine = remainingPop; } uint256 developerMined = amountToMine.mul(getDeveloperMiningPowerForGameId(gameId)).div(kTotalPercent); uint256 playerMined = amountToMine.sub(developerMined); supplyMined_ = supplyMined_.add(amountToMine); popBalances[target] = popBalances[target].add(playerMined); popBalances[author] = popBalances[author].add(developerMined); emit Mined(target, playerMined); emit Transfer(0, target, playerMined); emit Mined(author, developerMined); emit Transfer(0, author, developerMined); } function redeemPop (uint256 popToRedeem) public returns(bool res) { require(popBalances[msg.sender] >= popToRedeem); require(popToRedeem != 0); uint256 potentiallyAllocatedPop = potentiallyCirculatingPop(); FixedPoint.Data memory redeemRatio = popToRedeem < potentiallyAllocatedPop ? FixedPoint.fromFraction(Int256(popToRedeem), Int256(potentiallyAllocatedPop)) : FixedPoint.fromInt256(1); FixedPoint.Data memory ethPayoutAmount = redeemRatio.mul(FixedPoint.fromInt256(Int256(totalAmountRaked()))); uint256 payout = ethPayoutAmount.toUInt256Raw(); require(payout<=totalAmountRaked()); require(payout <= address(this).balance); burn(popToRedeem); playerInternalWallet[this] = playerInternalWallet[this].sub(payout); playerInternalWallet[msg.sender] = playerInternalWallet[msg.sender].add(payout); return true; } // Coin Functions function totalSupply() public view returns (uint256) { return promisedPop(); } function balanceOf(address _owner) public view returns (uint256 balance) { return popBalances[_owner]; } function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= popBalances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. popBalances[msg.sender] = popBalances[msg.sender].sub(_value); popBalances[_to] = popBalances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= popBalances[_from]); require(_value <= allowed[_from][msg.sender]); popBalances[_from] = popBalances[_from].sub(_value); popBalances[_to] = popBalances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function burn(uint256 _value) public { require (popBalances[msg.sender] >= _value); address burner = msg.sender; supplyBurned_ = supplyBurned_.add(_value); popBalances[burner] = popBalances[burner].sub(_value); emit Burn(burner, _value); } function getInitialSeedAsFixedPointForGameId (uint256 gameId) private view returns(FixedPoint.Data res) { if(gameId == currentGameNumber) { return FixedPoint.fromInt256(Int256(initialSeed)); } else { WrappedArray.GameMetaDataElement memory elem = gameMetaData.itemAtIndex(gameId); return FixedPoint.fromInt256(Int256(elem.seedAmount)); } } function getPotAsFixedPointForGameId (uint256 gameId) private view returns(FixedPoint.Data res) { if(gameId == currentGameNumber) { return FixedPoint.fromInt256(Int256(currentPot)); } else { WrappedArray.GameMetaDataElement memory elem = gameMetaData.itemAtIndex(gameId); return FixedPoint.fromInt256(Int256(elem.totalPotAmount)); } } function getPopRemainingAsFixedPointForGameId (uint256 gameId) private view returns(FixedPoint.Data res) { if(gameId == currentGameNumber) { return FixedPoint.fromInt256(Int256(unPromisedSupplyAtStartOfCurrentGame_)); } else { WrappedArray.GameMetaDataElement memory elem = gameMetaData.itemAtIndex(gameId); return FixedPoint.fromInt256(Int256(elem.coinsRemaining)); } } function getDifficultyAsFixedPointForGameId (uint256 gameId) private view returns(FixedPoint.Data res) { if(gameId == currentGameNumber) { return currentMiningDifficulty; } else { WrappedArray.GameMetaDataElement memory elem = gameMetaData.itemAtIndex(gameId); return elem.miningDifficulty; } } function calcDifficulty() private view returns (FixedPoint.Data) { FixedPoint.Data memory total = FixedPoint.fromInt256(0); FixedPoint.Data memory count = FixedPoint.fromInt256(0); uint256 j = 0; for(uint256 i=gameMetaData.length().sub(1) ; i>=0 && j<kDifficultyWindow; i = i.sub(1)){ WrappedArray.GameMetaDataElement memory thisGame = gameMetaData.itemAtIndex(i); FixedPoint.Data memory thisGamePotSize = FixedPoint.fromInt256(Int256(thisGame.totalPotAmount)); FixedPoint.Data memory thisCount = kDifficultyDropOffFactor.pow(FixedPoint.fromInt256(Int256(j))); total = total.add(thisCount.mul(thisGamePotSize)); count = count.add(thisCount); j = j.add(1); if(i == 0) { break; } } return total.div(count).div(kExpectedFirstGameSize); } function getBrAdj(FixedPoint.Data currentPotValue, FixedPoint.Data expectedGameSize) private pure returns (FixedPoint.Data) { if(currentPotValue.cmp(expectedGameSize) == -1) { return expectedGameSize.div(currentPotValue).log10().neg(); } else { return currentPotValue.div(expectedGameSize).log10(); } } function getMiningRateAtPoint(FixedPoint.Data point, FixedPoint.Data difficulty, FixedPoint.Data currentPotValue, FixedPoint.Data coins_tbi) private view returns (FixedPoint.Data) { assert (point.cmp(currentPotValue) != 1); FixedPoint.Data memory expectedGameSize = kExpectedFirstGameSize.mul(difficulty); FixedPoint.Data memory depositRatio = point.div(currentPotValue); FixedPoint.Data memory brAdj = getBrAdj(currentPotValue, expectedGameSize); if(brAdj.cmp(FixedPoint.fromInt256(0)) == -1) { return coins_tbi.mul(FixedPoint.fromInt256(1).div(FixedPoint.fromInt256(2).pow(brAdj.neg()))).mul(FixedPoint.fromInt256(2).sub(depositRatio)); } else { return coins_tbi.mul(FixedPoint.fromInt256(2).pow(brAdj)).mul(FixedPoint.fromInt256(2).sub(depositRatio)); } } function getExpectedGameSize() external view returns (int256) { return kExpectedFirstGameSize.toInt256(); } function totalTokenPayout(FixedPoint.Data currentPotValue, FixedPoint.Data difficulty, FixedPoint.Data unpromisedPopAtStartOfGame, uint256 wagerAmount, uint256 previousPotSize) private view returns (FixedPoint.Data) { FixedPoint.Data memory maxPotSize = kExpectedFirstGameSize.mul(difficulty).mul(kMaxPopMiningPotMultiple); FixedPoint.Data memory startPoint = FixedPoint.fromInt256(Int256(previousPotSize)); if(startPoint.cmp(maxPotSize) != -1){ // startPoint >= maxPotSize return FixedPoint.fromInt256(0); } FixedPoint.Data memory endPoint = FixedPoint.fromInt256(Int256(previousPotSize + wagerAmount)); if(endPoint.cmp(maxPotSize) != -1){ endPoint = maxPotSize; wagerAmount = maxPotSize.sub(startPoint).toUInt256Raw(); } if(currentPotValue.cmp(maxPotSize) != -1){ currentPotValue = maxPotSize; } FixedPoint.Data memory betSizePercent = FixedPoint.fromInt256(Int256(wagerAmount)).div(kExpectedFirstGameSize.mul(difficulty)); FixedPoint.Data memory expectedCoinsToBeIssuedTwoThirds = FixedPoint.fromFraction(2, 3).mul(unpromisedPopAtStartOfGame.mul(kExpectedPopCoinToBePromisedPercent)); return getMiningRateAtPoint(startPoint.add(endPoint).div(FixedPoint.fromInt256(2)), difficulty, currentPotValue, expectedCoinsToBeIssuedTwoThirds).mul(betSizePercent); } function calcNumberOfBlocksUntilGameEnds(FixedPoint.Data currentGameSize, FixedPoint.Data targetGameSize) internal view returns (FixedPoint.Data) { return kLowerBoundBlocksTillGameEnd.add(kUpperBoundBlocksTillGameEnd.mul(FixedPoint.fromInt256(1).div(currentGameSize.div(targetGameSize).exp()))); } function calcMinimumBetSize(FixedPoint.Data currentGameSize, FixedPoint.Data targetGameSize) internal view returns (FixedPoint.Data) { return currentGameInitialMinBetSize.mul(FixedPoint.fromInt256(2).pow(FixedPoint.fromInt256(1).add(currentGameSize.div(targetGameSize)).log10())); } } library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } library SafeInt { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { if (a == 0) { return 0; } int256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(int256 a, int256 b) internal pure returns (int256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 int256 c = a / b; return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; if(a>0 && b<0) { assert (c > a); } else if(a<0 && b>0) { assert (c < a); } return c; } /** * @dev Adds two numbers, throws on overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; if(a>0 && b>0) { assert(c > a); } else if (a < 0 && b < 0) { assert(c < a); } return c; } } library WrappedArray { using SafeMath for uint256; using FixedPoint for FixedPoint.Data; struct GameMetaDataElement { uint256 totalPotAmount; uint256 seedAmount; uint256 initialBet; uint256 coinsRemaining; uint256 developerMiningPower; uint256 percentToTakeAsSeed; uint256 percentToTakeAsRake; uint256 potSplit; FixedPoint.Data miningDifficulty; FixedPoint.Data frontWindowAdjustmentRatio; FixedPoint.Data backWindowAdjustmentRatio; bool isActive; } struct Data { GameMetaDataElement[] array; } /* Push adds element as last item in array */ function push (Data storage self, GameMetaDataElement element) internal { self.array.length = self.array.length.add(1); self.array[self.array.length.sub(1)] = element; } /* ItemAtIndex returns the item at index */ function itemAtIndex (Data storage self, uint256 index) internal view returns(GameMetaDataElement elem) { /* Can't access something outside of scope of array */ assert(index < self.array.length); return self.array[index]; } /* Returns the length of the array */ function length (Data storage self) internal view returns(uint256 len) { return self.array.length; } } library CompactArray { using SafeMath for uint256; struct Element { uint256 elem; } struct Data { Element[] array; uint256 len; uint256 popNextIndex; } /* Push adds element as last item in array and returns the index it was inserted at */ function push (Data storage self, Element element) internal returns(uint256 index) { if(self.array.length == self.len) { self.array.length = self.array.length.add(1); } self.array[self.len] = element; self.len = self.len.add(1); return self.len.sub(1); } /* Replaces item at index with last item in array and resizes array accordingly */ function removeItemAtIndex (Data storage self, uint256 index) internal { /* Can't remove something outside of scope of array */ assert(index < self.len); /* Deleting the last element in array is same as length - 1 */ if(index == self.len.sub(1)) { self.len = self.len.sub(1); return; } /* Swap last element in array for this index */ Element storage temp = self.array[self.len.sub(1)]; self.array[index] = temp; self.len = self.len.sub(1); } /* Pop returns last element of array and deletes it from array */ function pop (Data storage self) internal returns(Element elem) { assert(self.len > 0); // Decrement size self.len = self.len.sub(1); // return last item return self.array[self.len]; } /* PopNext keeps track of an index that loops through the array and pops the next item so that push pop doesn't necessarily return the item you pushed */ function getNext (Data storage self) internal returns(Element elem) { assert(self.len > 0); if(self.popNextIndex >= self.len) { // If there were regular pops inbetween self.popNextIndex = self.len.sub(1); } Element memory nextElement = itemAtIndex(self, self.popNextIndex); if(self.popNextIndex == 0) { self.popNextIndex = self.len.sub(1); } else { self.popNextIndex = self.popNextIndex.sub(1); } return nextElement; } /* ItemAtIndex returns the item at index */ function itemAtIndex (Data storage self, uint256 index) internal view returns(Element elem) { /* Can't access something outside of scope of array */ assert(index < self.len); return self.array[index]; } /* Returns the length of the array */ function length (Data storage self) internal view returns(uint256 len) { return self.len; } } library UIntSet { using CompactArray for CompactArray.Data; struct SetEntry { uint256 index; bool active; // because the index can be zero we need another way to tell if we have the entry } struct Data { CompactArray.Data compactArray; mapping (uint256 => SetEntry) storedValues; } /* Returns whether item is contained in dict */ function contains (Data storage self, uint256 element) internal view returns(bool res) { return self.storedValues[element].active; } /* Adds an item to the set */ function insert (Data storage self, uint256 element) internal { // Don't need to insert element if entry already exists if(contains(self, element)) { return; } // Create new entry for compact array CompactArray.Element memory newElem = CompactArray.Element(element); // Insert new entry into compact array and get where it was inserted uint256 index = self.compactArray.push(newElem); // Insert index of entry in compact array into our set SetEntry memory entry = SetEntry(index, true); self.storedValues[element] = entry; } /* Remove an item from the set */ function removeElement (Data storage self, uint256 element) internal { // If nothing is stored can return if(contains(self, element) == false) { return; } // Get index of where element entry is stored in array uint256 index = self.storedValues[element].index; // Delete entry from array self.compactArray.removeItemAtIndex(index); // Delete entry from mapping self.storedValues[element].active = false; // If array still has elements we need to update mapping with new index if(index < self.compactArray.length()) { // Get new element stored at deleted index CompactArray.Element memory swappedElem = self.compactArray.itemAtIndex(index); // Update mapping to reflect new index self.storedValues[swappedElem.elem] = SetEntry(index, true); } } /* This utilized compact arrays popnext function to have a rotating pop */ function getNext (Data storage self) internal returns(CompactArray.Element) { // If nothing is stored can return return self.compactArray.getNext(); } /* Returns the current number of items in the set */ function size (Data storage self) internal view returns(uint256 res) { return self.compactArray.length(); } function getItemAtIndex (Data storage self, uint256 index) internal view returns(CompactArray.Element) { return self.compactArray.itemAtIndex(index); } } library Player { using UIntSet for UIntSet.Data; using CompactArray for CompactArray.Data; struct BettingRecord { address playerAddress; uint256 gameId; uint256 wagerAmount; uint256 bettingRecordId; uint256 gamePotBeforeBet; uint256 withdrawnAmount; uint256 withdrawnPopAmount; bool isActive; } struct Data { UIntSet.Data bettingRecordIds; mapping (uint256 => BettingRecord) bettingRecordMapping; } /* Contains betting record for a betting record id */ function containsBettingRecordFromId (Data storage self, uint256 bettingRecordId) internal view returns(bool containsBettingRecord) { return self.bettingRecordIds.contains(bettingRecordId); } /* Function that returns a betting record for a betting record id */ function getBettingRecordForId (Data storage self, uint256 bettingRecordId) internal view returns(BettingRecord record) { if(containsBettingRecordFromId(self, bettingRecordId) == false) { return ;//BettingRecord(0x0,0,0,0,0,0,false); } return self.bettingRecordMapping[bettingRecordId]; } /* Insert Betting Record into storage */ function insertBettingRecord (Data storage self, BettingRecord record) internal { // If inserting a record with the same id will override old record self.bettingRecordMapping[record.bettingRecordId] = record; self.bettingRecordIds.insert(record.bettingRecordId); } /* Retrieve the next betting record */ function getNextRecord (Data storage self) internal returns(BettingRecord record) { if(self.bettingRecordIds.size() == 0) { return ;//BettingRecord(0x0,0,0,0,0,0,false); } CompactArray.Element memory bettingRecordIdEntry = self.bettingRecordIds.getNext(); return self.bettingRecordMapping[bettingRecordIdEntry.elem]; } function getBettingRecordAtIndex (Data storage self, uint256 index) internal view returns(BettingRecord record) { return self.bettingRecordMapping[self.bettingRecordIds.getItemAtIndex(index).elem]; } /* Delete Betting Record */ function deleteBettingRecordForId (Data storage self, uint256 bettingRecordId) internal { self.bettingRecordIds.removeElement(bettingRecordId); } /* Returns the number of betting records left to be processed */ function unprocessedBettingRecordCount (Data storage self) internal view returns(uint256 size) { return self.bettingRecordIds.size(); } } library BettingRecordArray { using Player for Player.Data; using SafeMath for uint256; struct Data { Player.BettingRecord[] array; uint256 len; } function resetIndex (Data storage self) internal { self.len = 0; } function pushRecord (Data storage self, Player.BettingRecord record) internal { if(self.array.length == self.len) { self.array.length = self.array.length.add(1); } self.array[self.len] = record; self.len = self.len.add(1); } function getNextRecord (Data storage self) internal view returns(Player.BettingRecord record) { if(self.array.length == self.len) { return; } return self.array[self.len]; } } library FixedPoint { using SafeMath for uint256; using SafeInt for int256; int256 constant fracBits = 32; int256 constant scale = 1 << 32; int256 constant halfScale = scale >> 1; int256 constant precision = 1000000; int256 constant e = 11674931554; int256 constant pi = 13493037704; int256 constant _2pi = 26986075409; struct Data { int256 val; } function fromInt256(int256 n) internal pure returns (Data) { return Data({val: n.mul(scale)}); } function fromFraction(int256 numerator, int256 denominator) internal pure returns (Data) { return Data ({ val: numerator.mul(scale).div(denominator) }); } function toInt256(Data n) internal pure returns (int256) { return (n.val * precision) >> fracBits; } function toUInt256Raw(Data a) internal pure returns (uint256) { return uint256(a.val >> fracBits); } function add(Data a, Data b) internal pure returns (Data) { return Data({val: a.val.add(b.val)}); } function sub(Data a, Data b) internal pure returns (Data) { return Data({val: a.val.sub(b.val)}); } function mul(Data a, Data b) internal pure returns (Data) { int256 result = a.val.mul(b.val).div(scale); return Data({val: result}); } function div(Data a, Data b) internal pure returns (Data) { int256 num = a.val.mul(scale); return Data({val: num.div(b.val)}); } function neg(Data a) internal pure returns (Data) { return Data({val: -a.val}); } function mod(Data a, Data b) internal pure returns (Data) { return Data({val: a.val % b.val}); } function expBySquaring(Data x, Data n) internal pure returns (Data) { if(n.val == 0) { // exp == 0 return Data({val: scale}); } Data memory extra = Data({val: scale}); while(true) { if(n.val == scale) { // exp == 1 return mul(x, extra); } else if (n.val % (2*scale) != 0) { extra = mul(extra, x); n = sub(n, fromInt256(1)); } x = mul(x, x); n = div(n, fromInt256(2)); } } function sin(Data x) internal pure returns (Data) { int256 val = x.val % _2pi; if(val < -pi) { val += _2pi; } else if (val > pi) { val -= _2pi; } Data memory result; if(val < 0) { result = add(mul(Data({val: 5468522184}), Data({val: val})), mul(Data({val: 1740684682}), mul(Data({val: val}), Data({val: val})))); if(result.val < 0) { result = add(mul(Data({val: 966367641}), sub(mul(result, neg(result)), result)), result); } else { result = add(mul(Data({val: 966367641}), sub(mul(result, result), result)), result); } return result; } else { result = sub(mul(Data({val: 5468522184}), Data({val: val})), mul(Data({val: 1740684682}), mul(Data({val: val}), Data({val: val})))); if(result.val < 0) { result = add(mul(Data({val: 966367641}), sub(mul(result, neg(result)), result)), result); } else { result = add(mul(Data({val: 966367641}), sub(mul(result, result), result)), result); } return result; } } function cmp(Data a, Data b) internal pure returns (int256) { if(a.val > b.val) { return 1; } else if(a.val < b.val) { return -1; } else { return 0; } } function log10(Data a) internal pure returns (Data) { return div(ln(a), ln(fromInt256(10))); } function ln(Data a) internal pure returns (Data) { int256 LOG = 0; int256 prec = 1000000; int256 x = a.val.mul(prec) >> fracBits; while(x >= 1500000) { LOG = LOG.add(405465); x = x.mul(2).div(3); } x = x.sub(prec); int256 y = x; int256 i = 1; while (i < 10){ LOG = LOG.add(y.div(i)); i = i.add(1); y = x.mul(y).div(prec); LOG = LOG.sub(y.div(i)); i = i.add(1); y = x.mul(y).div(prec); } LOG = LOG.mul(scale); LOG = LOG.div(prec); return Data({val: LOG}); } function expRaw(Data a) internal pure returns (Data) { int256 l1 = scale.add(a.val.div(4)); int256 l2 = scale.add(a.val.div(3).mul(l1).div(scale)); int256 l3 = scale.add(a.val.div(2).mul(l2).div(scale)); int256 l4 = scale.add(a.val.mul(l3).div(scale)); return Data({val: l4}); } function exp(Data a) internal pure returns (Data) { int256 pwr = a.val >> fracBits; int256 frac = a.val.sub(pwr << fracBits); return mul(expRaw(Data({val: frac})), expBySquaring(Data({val: e}), fromInt256(pwr))); } function pow(Data base, Data power) internal pure returns (Data) { int256 intpwr = power.val >> 32; int256 frac = power.val.sub(intpwr << fracBits); return mul(expRaw(mul(Data({val:frac}), ln(base))), expBySquaring(base, fromInt256(intpwr))); } }
Delete entry from mapping
self.storedValues[element].active = false;
5,507,624
[ 1, 2613, 1241, 628, 2874, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 202, 202, 2890, 18, 22601, 1972, 63, 2956, 8009, 3535, 273, 629, 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 ]
// File: @openzeppelin/contracts/access/IAccessControl.sol // OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol) pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControl { /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {AccessControl-_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) external view returns (bool); /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {AccessControl-_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) external view returns (bytes32); /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) external; /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) external; /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) external; } // File: @openzeppelin/contracts/utils/Counters.sol // OpenZeppelin Contracts v4.4.1 (utils/Counters.sol) pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library Counters { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } // File: @openzeppelin/contracts/utils/math/SafeMath.sol // OpenZeppelin Contracts v4.4.1 (utils/math/SafeMath.sol) pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // File: @openzeppelin/contracts/utils/Strings.sol // 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); } } // File: @openzeppelin/contracts/utils/cryptography/MerkleProof.sol // OpenZeppelin Contracts (last updated v4.5.0) (utils/cryptography/MerkleProof.sol) pragma solidity ^0.8.0; /** * @dev These functions deal with verification of Merkle Trees proofs. * * The proofs can be generated using the JavaScript library * https://github.com/miguelmota/merkletreejs[merkletreejs]. * Note: the hashing algorithm should be keccak256 and pair sorting should be enabled. * * See `test/utils/cryptography/MerkleProof.test.js` for some examples. */ library 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 = _efficientHash(computedHash, proofElement); } else { // Hash(current element of the proof + current computed hash) computedHash = _efficientHash(proofElement, computedHash); } } return computedHash; } function _efficientHash(bytes32 a, bytes32 b) private pure returns (bytes32 value) { assembly { mstore(0x00, a) mstore(0x20, b) value := keccak256(0x00, 0x40) } } } // File: @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; } } // File: @openzeppelin/contracts/security/Pausable.sol // OpenZeppelin Contracts v4.4.1 (security/Pausable.sol) pragma solidity ^0.8.0; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor() { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // File: @openzeppelin/contracts/access/Ownable.sol // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract 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); } } // File: @openzeppelin/contracts/utils/Address.sol // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/utils/introspection/IERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/utils/introspection/ERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: @openzeppelin/contracts/access/AccessControl.sol // OpenZeppelin Contracts (last updated v4.5.0) (access/AccessControl.sol) pragma solidity ^0.8.0; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context, IAccessControl, ERC165 { struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view virtual override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ */ function _checkRole(bytes32 role, address account) internal view virtual { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", Strings.toHexString(uint160(account), 20), " is missing role ", Strings.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view virtual override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been revoked `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== * * NOTE: This function is deprecated in favor of {_grantRole}. */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } /** * @dev Grants `role` to `account`. * * Internal function without access restriction. */ function _grantRole(bytes32 role, address account) internal virtual { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } /** * @dev Revokes `role` from `account`. * * Internal function without access restriction. */ function _revokeRole(bytes32 role, address account) internal virtual { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } } // File: @openzeppelin/contracts/token/ERC1155/IERC1155Receiver.sol // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC1155/IERC1155Receiver.sol) pragma solidity ^0.8.0; /** * @dev _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. * * NOTE: 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. * * NOTE: To accept the transfer(s), this must return * `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` * (i.e. 0xbc197c81, or its own function selector). * * @param operator The address which initiated the batch transfer (i.e. msg.sender) * @param from The address which previously owned the token * @param ids An array containing ids of each token being transferred (order and length must match values array) * @param values An array containing amounts of each token being transferred (order and length must match ids array) * @param data Additional data with no specified format * @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed */ function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external returns (bytes4); } // File: @openzeppelin/contracts/token/ERC1155/IERC1155.sol // OpenZeppelin Contracts v4.4.1 (token/ERC1155/IERC1155.sol) pragma solidity ^0.8.0; /** * @dev Required interface of an ERC1155 compliant contract, as defined in the * https://eips.ethereum.org/EIPS/eip-1155[EIP]. * * _Available since v3.1._ */ interface IERC1155 is IERC165 { /** * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`. */ event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); /** * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all * transfers. */ event TransferBatch( address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values ); /** * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to * `approved`. */ event ApprovalForAll(address indexed account, address indexed operator, bool approved); /** * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI. * * If an {URI} event was emitted for `id`, the standard * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value * returned by {IERC1155MetadataURI-uri}. */ event URI(string value, uint256 indexed id); /** * @dev Returns the amount of tokens of token type `id` owned by `account`. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, * * Emits an {ApprovalForAll} event. * * Requirements: * * - `operator` cannot be the caller. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns true if `operator` is approved to transfer ``account``'s tokens. * * See {setApprovalForAll}. */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes calldata data ) external; /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function safeBatchTransferFrom( address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data ) external; } // File: @openzeppelin/contracts/token/ERC1155/extensions/IERC1155MetadataURI.sol // OpenZeppelin Contracts v4.4.1 (token/ERC1155/extensions/IERC1155MetadataURI.sol) pragma solidity ^0.8.0; /** * @dev Interface of the optional ERC1155MetadataExtension interface, as defined * in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP]. * * _Available since v3.1._ */ interface IERC1155MetadataURI is IERC1155 { /** * @dev Returns the URI for token type `id`. * * If the `\{id\}` substring is present in the URI, it must be replaced by * clients with the actual token type ID. */ function uri(uint256 id) external view returns (string memory); } // File: @openzeppelin/contracts/token/ERC1155/ERC1155.sol // OpenZeppelin Contracts v4.4.1 (token/ERC1155/ERC1155.sol) pragma solidity ^0.8.0; /** * @dev Implementation of the basic standard multi-token. * See https://eips.ethereum.org/EIPS/eip-1155 * Originally based on code by Enjin: https://github.com/enjin/erc-1155 * * _Available since v3.1._ */ contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI { using Address for address; // Mapping from token ID to account balances mapping(uint256 => mapping(address => uint256)) private _balances; // Mapping from account to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; // Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json string private _uri; /** * @dev See {_setURI}. */ constructor(string memory uri_) { _setURI(uri_); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC1155).interfaceId || interfaceId == type(IERC1155MetadataURI).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC1155MetadataURI-uri}. * * This implementation returns the same URI for *all* token types. It relies * on the token type ID substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * Clients calling this function must replace the `\{id\}` substring with the * actual token type ID. */ function uri(uint256) public view virtual override returns (string memory) { return _uri; } /** * @dev See {IERC1155-balanceOf}. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) public view virtual override returns (uint256) { require(account != address(0), "ERC1155: balance query for the zero address"); return _balances[id][account]; } /** * @dev See {IERC1155-balanceOfBatch}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] memory accounts, uint256[] memory ids) public view virtual override returns (uint256[] memory) { require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch"); uint256[] memory batchBalances = new uint256[](accounts.length); for (uint256 i = 0; i < accounts.length; ++i) { batchBalances[i] = balanceOf(accounts[i], ids[i]); } return batchBalances; } /** * @dev See {IERC1155-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC1155-isApprovedForAll}. */ function isApprovedForAll(address account, address operator) public view virtual override returns (bool) { return _operatorApprovals[account][operator]; } /** * @dev See {IERC1155-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) public virtual override { require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: caller is not owner nor approved" ); _safeTransferFrom(from, to, id, amount, data); } /** * @dev See {IERC1155-safeBatchTransferFrom}. */ function safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) public virtual override { require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: transfer caller is not owner nor approved" ); _safeBatchTransferFrom(from, to, ids, amounts, data); } /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - `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 memory data ) internal virtual { require(to != address(0), "ERC1155: transfer to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data); uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: insufficient balance for transfer"); unchecked { _balances[id][from] = fromBalance - amount; } _balances[id][to] += amount; emit TransferSingle(operator, from, to, id, amount); _doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - 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[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); require(to != address(0), "ERC1155: transfer to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, ids, amounts, data); for (uint256 i = 0; i < ids.length; ++i) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: insufficient balance for transfer"); unchecked { _balances[id][from] = fromBalance - amount; } _balances[id][to] += amount; } emit TransferBatch(operator, from, to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data); } /** * @dev Sets a new URI for all token types, by relying on the token type ID * substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * By this mechanism, any occurrence of the `\{id\}` substring in either the * URI or any of the amounts in the JSON file at said URI will be replaced by * clients with the token type ID. * * For example, the `https://token-cdn-domain/\{id\}.json` URI would be * interpreted by clients as * `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json` * for token type ID 0x4cce0. * * See {uri}. * * Because these URIs cannot be meaningfully represented by the {URI} event, * this function emits no events. */ function _setURI(string memory newuri) internal virtual { _uri = newuri; } /** * @dev Creates `amount` tokens of token type `id`, and assigns them to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _mint( address to, uint256 id, uint256 amount, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: mint to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), to, _asSingletonArray(id), _asSingletonArray(amount), data); _balances[id][to] += amount; emit TransferSingle(operator, address(0), to, id, amount); _doSafeTransferAcceptanceCheck(operator, address(0), to, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function _mintBatch( address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: mint to the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), to, ids, amounts, data); for (uint256 i = 0; i < ids.length; i++) { _balances[ids[i]][to] += amounts[i]; } emit TransferBatch(operator, address(0), to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data); } /** * @dev Destroys `amount` tokens of token type `id` from `from` * * Requirements: * * - `from` cannot be the zero address. * - `from` must have at least `amount` tokens of token type `id`. */ function _burn( address from, uint256 id, uint256 amount ) internal virtual { require(from != address(0), "ERC1155: burn from the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, address(0), _asSingletonArray(id), _asSingletonArray(amount), ""); uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: burn amount exceeds balance"); unchecked { _balances[id][from] = fromBalance - amount; } emit TransferSingle(operator, from, address(0), id, amount); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}. * * Requirements: * * - `ids` and `amounts` must have the same length. */ function _burnBatch( address from, uint256[] memory ids, uint256[] memory amounts ) internal virtual { require(from != address(0), "ERC1155: burn from the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, address(0), ids, amounts, ""); for (uint256 i = 0; i < ids.length; i++) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: burn amount exceeds balance"); unchecked { _balances[id][from] = fromBalance - amount; } } emit TransferBatch(operator, from, address(0), ids, amounts); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC1155: setting approval status for self"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Hook that is called before any token transfer. This includes minting * and burning, as well as batched variants. * * The same hook is called on both single and batched variants. For single * transfers, the length of the `id` and `amount` arrays will be 1. * * Calling conditions (for each `id` and `amount` pair): * * - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens * of token type `id` will be transferred to `to`. * - When `from` is zero, `amount` tokens of token type `id` will be minted * for `to`. * - when `to` is zero, `amount` of ``from``'s tokens of token type `id` * will be burned. * - `from` and `to` are never both zero. * - `ids` and `amounts` have the same, non-zero length. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual {} function _doSafeTransferAcceptanceCheck( address operator, address from, address to, uint256 id, uint256 amount, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) { if (response != IERC1155Receiver.onERC1155Received.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _doSafeBatchTransferAcceptanceCheck( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns ( bytes4 response ) { if (response != IERC1155Receiver.onERC1155BatchReceived.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) { uint256[] memory array = new uint256[](1); array[0] = element; return array; } } // File: @openzeppelin/contracts/token/ERC1155/extensions/ERC1155Supply.sol // OpenZeppelin Contracts v4.4.1 (token/ERC1155/extensions/ERC1155Supply.sol) pragma solidity ^0.8.0; /** * @dev Extension of ERC1155 that adds tracking of total supply per id. * * Useful for scenarios where Fungible and Non-fungible tokens have to be * clearly identified. Note: While a totalSupply of 1 might mean the * corresponding is an NFT, there is no guarantees that no other token with the * same id are not going to be minted. */ abstract contract ERC1155Supply is ERC1155 { mapping(uint256 => uint256) private _totalSupply; /** * @dev Total amount of tokens in with a given id. */ function totalSupply(uint256 id) public view virtual returns (uint256) { return _totalSupply[id]; } /** * @dev Indicates whether any token exist with a given id, or not. */ function exists(uint256 id) public view virtual returns (bool) { return ERC1155Supply.totalSupply(id) > 0; } /** * @dev See {ERC1155-_beforeTokenTransfer}. */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual override { super._beforeTokenTransfer(operator, from, to, ids, amounts, data); if (from == address(0)) { for (uint256 i = 0; i < ids.length; ++i) { _totalSupply[ids[i]] += amounts[i]; } } if (to == address(0)) { for (uint256 i = 0; i < ids.length; ++i) { _totalSupply[ids[i]] -= amounts[i]; } } } } // File: @openzeppelin/contracts/token/ERC1155/extensions/ERC1155Pausable.sol // OpenZeppelin Contracts v4.4.1 (token/ERC1155/extensions/ERC1155Pausable.sol) pragma solidity ^0.8.0; /** * @dev ERC1155 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. * * _Available since v3.1._ */ abstract contract ERC1155Pausable is ERC1155, Pausable { /** * @dev See {ERC1155-_beforeTokenTransfer}. * * Requirements: * * - the contract must not be paused. */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual override { super._beforeTokenTransfer(operator, from, to, ids, amounts, data); require(!paused(), "ERC1155Pausable: token transfer while paused"); } } // File: @openzeppelin/contracts/token/ERC1155/extensions/ERC1155Burnable.sol // OpenZeppelin Contracts v4.4.1 (token/ERC1155/extensions/ERC1155Burnable.sol) pragma solidity ^0.8.0; /** * @dev Extension of {ERC1155} that allows token holders to destroy both their * own tokens and those that they have been approved to use. * * _Available since v3.1._ */ abstract contract ERC1155Burnable is ERC1155 { function burn( address account, uint256 id, uint256 value ) public virtual { require( account == _msgSender() || isApprovedForAll(account, _msgSender()), "ERC1155: caller is not owner nor approved" ); _burn(account, id, value); } function burnBatch( address account, uint256[] memory ids, uint256[] memory values ) public virtual { require( account == _msgSender() || isApprovedForAll(account, _msgSender()), "ERC1155: caller is not owner nor approved" ); _burnBatch(account, ids, values); } } // File: AbstractEditionContract.sol pragma solidity ^0.8.4; abstract contract AbstractEditionContract is AccessControl, ERC1155Pausable, ERC1155Supply, ERC1155Burnable, Ownable { string public name_; string public symbol_; function pause() external onlyOwner { _pause(); } function unpause() external onlyOwner { _unpause(); } function setURI(string memory baseURI) external onlyOwner { _setURI(baseURI); } function name() public view returns (string memory) { return name_; } function symbol() public view returns (string memory) { return symbol_; } function _mint( address account, uint256 id, uint256 amount, bytes memory data ) internal virtual override(ERC1155) { super._mint(account, id, amount, data); } function _mintBatch( address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual override(ERC1155) { super._mintBatch(to, ids, amounts, data); } function _burn( address account, uint256 id, uint256 amount ) internal virtual override(ERC1155) { super._burn(account, id, amount); } function _burnBatch( address account, uint256[] memory ids, uint256[] memory amounts ) internal virtual override(ERC1155) { super._burnBatch(account, ids, amounts); } function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual override(ERC1155Pausable, ERC1155,ERC1155Supply) { super._beforeTokenTransfer(operator, from, to, ids, amounts, data); } function setOwner(address _addr) public onlyOwner { transferOwnership(_addr); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC1155, AccessControl) returns (bool) { return super.supportsInterface(interfaceId); } } // File: WavelengthXmfers.sol pragma solidity ^0.8.4; // Based on contract by Dev by @bitcoinski + @ultra_dao. Extended by @georgefatlion contract WavelengthXmfers is AbstractEditionContract { using SafeMath for uint256; using Counters for Counters.Counter; Counters.Counter private editionCounter; event Claimed(uint index, address indexed account, uint amount); event ClaimedMultiple(uint[] index, address indexed account, uint[] amount); mapping(uint256 => Edition) public editions; string public _contractURI; struct Edition { bytes32 merkleRoot; bool saleIsOpen; uint256 mintPrice; uint256 maxSupply; uint256 maxPerWallet; uint256 maxMintPerTxn; string metadataLink; bool merkleProtect; bool claimMultiple; mapping(address => uint256) claimedAddress; } constructor( string memory _name, string memory _symbol ) ERC1155("Editions") { name_ = _name; symbol_ = _symbol; } function addEdition( bytes32 _merkleRoot, uint256 _mintPrice, uint256 _maxSupply, uint256 _maxMintPerTxn, string memory _metadataLink, uint256 _maxPerWallet, bool _merkleProtect ) external onlyOwner { Edition storage edition = editions[editionCounter.current()]; edition.saleIsOpen = false; edition.merkleRoot = _merkleRoot; edition.mintPrice = _mintPrice; edition.maxSupply = _maxSupply; edition.maxMintPerTxn = _maxMintPerTxn; edition.maxPerWallet = _maxPerWallet; edition.metadataLink = _metadataLink; edition.merkleProtect = _merkleProtect; edition.claimMultiple = false; editionCounter.increment(); } function editEdition( bytes32 _merkleRoot, uint256 _mintPrice, uint256 _maxSupply, uint256 _maxMintPerTxn, string memory _metadataLink, uint256 _editionIndex, bool _saleIsOpen, uint256 _maxPerWallet, bool _merkleProtect, bool _claimMultiple ) external onlyOwner { if(editions[_editionIndex].merkleRoot != _merkleRoot){ editions[_editionIndex].merkleRoot = _merkleRoot; } if(editions[_editionIndex].mintPrice != _mintPrice){ editions[_editionIndex].mintPrice = _mintPrice; } if(editions[_editionIndex].maxSupply != _maxSupply){ editions[_editionIndex].maxSupply = _maxSupply; } if(editions[_editionIndex].maxMintPerTxn != _maxMintPerTxn){ editions[_editionIndex].maxMintPerTxn = _maxMintPerTxn; } editions[_editionIndex].metadataLink = _metadataLink; if(editions[_editionIndex].saleIsOpen != _saleIsOpen){ editions[_editionIndex].saleIsOpen = _saleIsOpen; } if(editions[_editionIndex].maxPerWallet != _maxPerWallet){ editions[_editionIndex].maxPerWallet = _maxPerWallet; } if(editions[_editionIndex].merkleProtect != _merkleProtect){ editions[_editionIndex].merkleProtect = _merkleProtect; } if(editions[_editionIndex].claimMultiple = _claimMultiple){ editions[_editionIndex].claimMultiple = _claimMultiple; } } function claim( uint256 numPieces, uint256 amount, uint256 editionIndex, bytes32[] calldata merkleProof ) external payable { // verify call is valid require(isValidClaim(numPieces,amount,editionIndex,merkleProof)); _mint(msg.sender, editionIndex, numPieces, ""); editions[editionIndex].claimedAddress[msg.sender] = editions[editionIndex].claimedAddress[msg.sender].add(numPieces); emit Claimed(editionIndex, msg.sender, numPieces); } function claimMultiple( uint256[] calldata numPieces, uint256[] calldata amounts, uint256[] calldata editionIndexes, bytes32[][] calldata merkleProofs ) external payable { // verify contract is not paused require(!paused(), "Claim: claiming is paused"); //validate all tokens being claimed and aggregate a total cost due uint256 totalPrice = 0; for (uint i=0; i< editionIndexes.length; i++) { require(isValidClaim(numPieces[i],amounts[i],editionIndexes[i],merkleProofs[i]), "One or more claims are invalid"); require(editions[editionIndexes[i]].claimMultiple, "Claim multiple not enabled."); totalPrice.add(numPieces[i].mul(editions[editionIndexes[i]].mintPrice)); } // check the message has enough value to cover all tokens. require(msg.value >= totalPrice, "Value not enough to cover all transactions"); for (uint i=0; i< editionIndexes.length; i++) { require(isValidClaim(numPieces[i],amounts[i],editionIndexes[i],merkleProofs[i]), "One or more claims are invalid"); editions[editionIndexes[i]].claimedAddress[msg.sender] = editions[editionIndexes[i]].claimedAddress[msg.sender].add(numPieces[i]); } _mintBatch(msg.sender, editionIndexes, numPieces, ""); emit ClaimedMultiple(editionIndexes, msg.sender, numPieces); } function mint( address to, uint256 editionIndex, uint256 numPieces ) public onlyOwner { _mint(to, editionIndex, numPieces, ""); } function mintBatch( address to, uint256[] calldata editionIndexes, uint256[] calldata numPieces ) public onlyOwner { _mintBatch(to, editionIndexes, numPieces, ""); } function isValidClaim( uint256 numPieces, uint256 amount, uint256 editionIndex, bytes32[] calldata merkleProof) internal view returns (bool) { // verify contract is not paused require(!paused(), "Claim: claiming is paused"); // verify edition for given index exists require(editions[editionIndex].maxSupply != 0, "Claim: Edition does not exist"); // verify sale for given edition is open. require(editions[editionIndex].saleIsOpen, "Sale is paused"); // Verify minting price require(msg.value >= numPieces.mul(editions[editionIndex].mintPrice), "Claim: Ether value incorrect"); // Verify numPieces is within remaining claimable amount require(editions[editionIndex].claimedAddress[msg.sender].add(numPieces) <= amount, "Claim: Not allowed to claim given amount"); require(editions[editionIndex].claimedAddress[msg.sender].add(numPieces) <= editions[editionIndex].maxPerWallet, "Claim: Not allowed to claim that many from one wallet"); require(numPieces <= editions[editionIndex].maxMintPerTxn, "Max quantity per transaction exceeded"); require(totalSupply(editionIndex) + numPieces <= editions[editionIndex].maxSupply, "Purchase would exceed max supply"); bool isValid = true; if (editions[editionIndex].merkleProtect) { isValid = verifyMerkleProof(merkleProof, editions[editionIndex].merkleRoot); require( isValid, "MerkleDistributor: Invalid proof." ); } return isValid; } function isSaleOpen(uint256 editionIndex) public view returns (bool) { return editions[editionIndex].saleIsOpen; } function setSaleState(uint256 editionIndex, bool state) external onlyOwner{ editions[editionIndex].saleIsOpen = state; } function verifyMerkleProof(bytes32[] memory proof, bytes32 root) public view returns (bool) { bytes32 leaf = keccak256(abi.encodePacked(msg.sender)); return MerkleProof.verify(proof, root, leaf); } function char(bytes1 b) internal pure returns (bytes1 c) { if (uint8(b) < 10) return bytes1(uint8(b) + 0x30); else return bytes1(uint8(b) + 0x57); } function withdrawEther(address payable _to, uint256 _amount) public onlyOwner { _to.transfer(_amount); } function getClaimedMps(uint256 poolId, address userAdress) public view returns (uint256) { return editions[poolId].claimedAddress[userAdress]; } function uri(uint256 _id) public view override returns (string memory) { require(totalSupply(_id) > 0, "URI: nonexistent token"); return string(editions[_id].metadataLink); } function setContractURI(string memory newURI) external onlyOwner{ _contractURI = newURI; } function contractURI() public view returns (string memory) { return _contractURI; } }
verify call is valid
function claim( uint256 numPieces, uint256 amount, uint256 editionIndex, bytes32[] calldata merkleProof ) external payable { require(isValidClaim(numPieces,amount,editionIndex,merkleProof)); _mint(msg.sender, editionIndex, numPieces, ""); editions[editionIndex].claimedAddress[msg.sender] = editions[editionIndex].claimedAddress[msg.sender].add(numPieces); emit Claimed(editionIndex, msg.sender, numPieces); }
213,002
[ 1, 8705, 745, 353, 923, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 7516, 12, 203, 3639, 2254, 5034, 818, 16539, 8610, 16, 203, 3639, 2254, 5034, 3844, 16, 203, 3639, 2254, 5034, 28432, 1016, 16, 203, 3639, 1731, 1578, 8526, 745, 892, 30235, 20439, 203, 565, 262, 3903, 8843, 429, 288, 203, 3639, 2583, 12, 26810, 9762, 12, 2107, 16539, 8610, 16, 8949, 16, 329, 608, 1016, 16, 6592, 15609, 20439, 10019, 203, 540, 203, 3639, 389, 81, 474, 12, 3576, 18, 15330, 16, 28432, 1016, 16, 818, 16539, 8610, 16, 1408, 1769, 203, 3639, 1675, 5029, 63, 329, 608, 1016, 8009, 14784, 329, 1887, 63, 3576, 18, 15330, 65, 273, 1675, 5029, 63, 329, 608, 1016, 8009, 14784, 329, 1887, 63, 3576, 18, 15330, 8009, 1289, 12, 2107, 16539, 8610, 1769, 203, 203, 3639, 3626, 18381, 329, 12, 329, 608, 1016, 16, 1234, 18, 15330, 16, 818, 16539, 8610, 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 ]
./full_match/42/0xe4E1B33043dD92aCB919E1862dA00124Fe8220A7/sources/contracts/UserProxy.sol
*********************************************************** Management functions for Operator /
function setAMMStatus(bool _enable) public onlyOperator { AMMWrapperStorage.getStorage().isEnabled = _enable; }
9,588,596
[ 1, 10998, 4186, 364, 11097, 9079, 342, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 2192, 49, 1482, 12, 6430, 389, 7589, 13, 1071, 1338, 5592, 288, 203, 3639, 432, 8206, 3611, 3245, 18, 588, 3245, 7675, 291, 1526, 273, 389, 7589, 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/1/0x414Cb1508B05e5556650D59d55Ed9A94bFb1A140/sources/contracts/MBS.sol
* @dev Provides information about the current execution context, including the sender of the transaction and its data. While these are generally available via msg.sender and msg.data, they should not be accessed in such a direct manner, since when dealing with meta-transactions the account sending and paying for execution may not be the actual sender (as far as an application is concerned). This contract is only required for intermediate, library-like contracts./
abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } }
4,991,671
[ 1, 17727, 1779, 2973, 326, 783, 4588, 819, 16, 6508, 326, 5793, 434, 326, 2492, 471, 2097, 501, 18, 21572, 4259, 854, 19190, 2319, 3970, 1234, 18, 15330, 471, 1234, 18, 892, 16, 2898, 1410, 486, 506, 15539, 316, 4123, 279, 2657, 21296, 16, 3241, 1347, 21964, 598, 2191, 17, 20376, 326, 2236, 5431, 471, 8843, 310, 364, 4588, 2026, 486, 506, 326, 3214, 5793, 261, 345, 10247, 487, 392, 2521, 353, 356, 2750, 11748, 2934, 1220, 6835, 353, 1338, 1931, 364, 12110, 16, 5313, 17, 5625, 20092, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 17801, 6835, 1772, 288, 203, 203, 565, 445, 389, 3576, 12021, 1435, 2713, 1476, 5024, 1135, 261, 2867, 13, 288, 203, 3639, 327, 1234, 18, 15330, 31, 203, 565, 289, 203, 203, 565, 445, 389, 3576, 751, 1435, 2713, 1476, 5024, 1135, 261, 3890, 745, 892, 13, 288, 203, 3639, 327, 1234, 18, 892, 31, 203, 565, 289, 203, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/11155111/0xbF3520fB0f9F48C638CD49C68f7E7405cebf9dc1/sources/contracts/Contract.sol
Request memory newRequest; requests.push(newRequest);
function createRequest(string memory description, uint256 value, address payable recipient) public restricted { Request storage newRequest = requests.push(); newRequest.description = description; newRequest.value = value; newRequest.recipient = recipient; newRequest.complete = false; newRequest.approvalCount = 0; }
3,831,075
[ 1, 691, 3778, 7428, 31, 3285, 18, 6206, 12, 2704, 691, 1769, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 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, 15798, 12, 1080, 3778, 2477, 16, 2254, 5034, 460, 16, 1758, 8843, 429, 8027, 13, 1071, 15693, 288, 203, 3639, 1567, 2502, 7428, 273, 3285, 18, 6206, 5621, 203, 3639, 7428, 18, 3384, 273, 2477, 31, 203, 3639, 7428, 18, 1132, 273, 460, 31, 203, 3639, 7428, 18, 20367, 273, 8027, 31, 203, 3639, 7428, 18, 6226, 273, 629, 31, 203, 3639, 7428, 18, 12908, 1125, 1380, 273, 374, 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 ]
/** *Submitted for verification at Etherscan.io on 2019-12-19 */ // hevm: flattened sources of src/Redeemer.sol pragma solidity =0.5.11 >0.4.13 >0.4.20 >=0.4.23 >=0.5.0 <0.6.0 >=0.5.5 <0.6.0 >=0.5.11 <0.6.0; ////// lib/dpass/lib/openzeppelin-contracts/src/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; } } ////// lib/dpass/lib/openzeppelin-contracts/src/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; } } ////// lib/dpass/lib/openzeppelin-contracts/src/drafts/Counters.sol /* pragma solidity ^0.5.0; */ /* import "../math/SafeMath.sol"; */ /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` * Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the {SafeMath} * overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never * directly accessed. */ library Counters { using SafeMath for uint256; struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { counter._value += 1; } function decrement(Counter storage counter) internal { counter._value = counter._value.sub(1); } } ////// lib/dpass/lib/openzeppelin-contracts/src/introspection/IERC165.sol /* pragma solidity ^0.5.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); } ////// lib/dpass/lib/openzeppelin-contracts/src/introspection/ERC165.sol /* pragma solidity ^0.5.0; */ /* import "./IERC165.sol"; */ /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ 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) external view 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 { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } ////// lib/dpass/lib/openzeppelin-contracts/src/token/ERC721/IERC721.sol /* pragma solidity ^0.5.0; */ /* import "../../introspection/IERC165.sol"; */ /** * @dev Required interface of an ERC721 compliant contract. */ contract IERC721 is IERC165 { event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of NFTs in `owner`'s account. */ function balanceOf(address owner) public view returns (uint256 balance); /** * @dev Returns the owner of the NFT specified by `tokenId`. */ function ownerOf(uint256 tokenId) public view returns (address owner); /** * @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to * another (`to`). * * * * Requirements: * - `from`, `to` cannot be zero. * - `tokenId` must be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this * NFT by either {approve} or {setApprovalForAll}. */ function safeTransferFrom(address from, address to, uint256 tokenId) public; /** * @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to * another (`to`). * * Requirements: * - If the caller is not `from`, it must be approved to move this NFT by * either {approve} or {setApprovalForAll}. */ function transferFrom(address from, address to, uint256 tokenId) public; function approve(address to, uint256 tokenId) public; function getApproved(uint256 tokenId) public view returns (address operator); function setApprovalForAll(address operator, bool _approved) public; function isApprovedForAll(address owner, address operator) public view returns (bool); function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public; } ////// lib/dpass/lib/openzeppelin-contracts/src/token/ERC721/IERC721Receiver.sol /* pragma solidity ^0.5.0; */ /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ contract IERC721Receiver { /** * @notice Handle the receipt of an NFT * @dev The ERC721 smart contract calls this function on the recipient * after a {IERC721-safeTransferFrom}. This function MUST return the function selector, * otherwise the caller will revert the transaction. The selector to be * returned can be obtained as `this.onERC721Received.selector`. This * function MAY throw to revert and reject the transfer. * Note: the ERC721 contract address is always the message sender. * @param operator The address which called `safeTransferFrom` function * @param from The address which previously owned the token * @param tokenId The NFT identifier which is being transferred * @param data Additional data with no specified format * @return bytes4 `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` */ function onERC721Received(address operator, address from, uint256 tokenId, bytes memory data) public returns (bytes4); } ////// lib/dpass/lib/openzeppelin-contracts/src/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"); } } ////// lib/dpass/lib/openzeppelin-contracts/src/token/ERC721/ERC721.sol /* pragma solidity ^0.5.0; */ /* import "../../GSN/Context.sol"; */ /* import "./IERC721.sol"; */ /* import "./IERC721Receiver.sol"; */ /* import "../../math/SafeMath.sol"; */ /* import "../../utils/Address.sol"; */ /* import "../../drafts/Counters.sol"; */ /* import "../../introspection/ERC165.sol"; */ /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721 is Context, ERC165, IERC721 { using SafeMath for uint256; using Address for address; using Counters for Counters.Counter; // 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 token ID to owner mapping (uint256 => address) private _tokenOwner; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to number of owned token mapping (address => Counters.Counter) private _ownedTokensCount; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; /* * 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 ^ 0xe985e9c ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd */ bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; constructor () public { // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721); } /** * @dev Gets the balance of the specified address. * @param owner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf(address owner) public view returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _ownedTokensCount[owner].current(); } /** * @dev Gets the owner of the specified token ID. * @param tokenId uint256 ID of the token to query the owner of * @return address currently marked as the owner of the given token ID */ function ownerOf(uint256 tokenId) public view returns (address) { address owner = _tokenOwner[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev Approves another address to transfer the given token ID * The zero address indicates there is no approved address. * There can only be one approved address per token at a given time. * Can only be called by the token owner or an approved operator. * @param to address to be approved for the given token ID * @param tokenId uint256 ID of the token to be approved */ function approve(address to, uint256 tokenId) public { address owner = ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Gets the approved address for a token ID, or zero if no address set * Reverts if the token ID does not exist. * @param tokenId uint256 ID of the token to query the approval of * @return address currently approved for the given token ID */ function getApproved(uint256 tokenId) public view returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev Sets or unsets the approval of a given operator * An operator is allowed to transfer all tokens of the sender on their behalf. * @param to operator address to set the approval * @param approved representing the status of the approval to be set */ function setApprovalForAll(address to, bool approved) public { require(to != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][to] = approved; emit ApprovalForAll(_msgSender(), to, approved); } /** * @dev Tells whether an operator is approved by a given owner. * @param owner owner address which you want to query the approval of * @param operator operator address which you want to query the approval of * @return bool whether the given operator is approved by the given owner */ function isApprovedForAll(address owner, address operator) public view returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev Transfers the ownership of a given token ID to another address. * Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * Requires the msg.sender to be the owner, approved, or operator. * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function transferFrom(address from, address to, uint256 tokenId) public { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transferFrom(from, to, tokenId); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement {IERC721Receiver-onERC721Received}, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg.sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function safeTransferFrom(address from, address to, uint256 tokenId) public { safeTransferFrom(from, to, tokenId, ""); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement {IERC721Receiver-onERC721Received}, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the _msgSender() to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransferFrom(from, to, tokenId, _data); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg.sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function _safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) internal { _transferFrom(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether the specified token exists. * @param tokenId uint256 ID of the token to query the existence of * @return bool whether the token exists */ function _exists(uint256 tokenId) internal view returns (bool) { address owner = _tokenOwner[tokenId]; return owner != address(0); } /** * @dev Returns whether the given spender can transfer a given token ID. * @param spender address of the spender to query * @param tokenId uint256 ID of the token to be transferred * @return bool whether the msg.sender is approved for the given token ID, * is an operator of the owner, or is the owner of the token */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Internal function to safely mint a new token. * Reverts if the given token ID already exists. * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * @param to The address that will own the minted token * @param tokenId uint256 ID of the token to be minted */ function _safeMint(address to, uint256 tokenId) internal { _safeMint(to, tokenId, ""); } /** * @dev Internal function to safely mint a new token. * Reverts if the given token ID already exists. * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * @param to The address that will own the minted token * @param tokenId uint256 ID of the token to be minted * @param _data bytes data to send along with a safe transfer check */ function _safeMint(address to, uint256 tokenId, bytes memory _data) internal { _mint(to, tokenId); require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Internal function to mint a new token. * Reverts if the given token ID already exists. * @param to The address that will own the minted token * @param tokenId uint256 ID of the token to be minted */ function _mint(address to, uint256 tokenId) internal { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _tokenOwner[tokenId] = to; _ownedTokensCount[to].increment(); emit Transfer(address(0), to, tokenId); } /** * @dev Internal function to burn a specific token. * Reverts if the token does not exist. * Deprecated, use {_burn} instead. * @param owner owner of the token to burn * @param tokenId uint256 ID of the token being burned */ function _burn(address owner, uint256 tokenId) internal { require(ownerOf(tokenId) == owner, "ERC721: burn of token that is not own"); _clearApproval(tokenId); _ownedTokensCount[owner].decrement(); _tokenOwner[tokenId] = address(0); emit Transfer(owner, address(0), tokenId); } /** * @dev Internal function to burn a specific token. * Reverts if the token does not exist. * @param tokenId uint256 ID of the token being burned */ function _burn(uint256 tokenId) internal { _burn(ownerOf(tokenId), tokenId); } /** * @dev Internal function to transfer ownership of a given token ID to another address. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function _transferFrom(address from, address to, uint256 tokenId) internal { require(ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _clearApproval(tokenId); _ownedTokensCount[from].decrement(); _ownedTokensCount[to].increment(); _tokenOwner[tokenId] = to; emit Transfer(from, 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. * * This function is deprecated. * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) internal returns (bool) { if (!to.isContract()) { return true; } bytes4 retval = IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data); return (retval == _ERC721_RECEIVED); } /** * @dev Private function to clear current approval of a given token ID. * @param tokenId uint256 ID of the token to be transferred */ function _clearApproval(uint256 tokenId) private { if (block.coinbase != address(0)) { //injected CONTRACT AFFECTED BY MINERS _tokenApprovals[tokenId] = address(0); } } } ////// lib/dpass/lib/openzeppelin-contracts/src/token/ERC721/IERC721Enumerable.sol /* pragma solidity ^0.5.0; */ /* import "./IERC721.sol"; */ /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ contract IERC721Enumerable is IERC721 { function totalSupply() public view returns (uint256); function tokenOfOwnerByIndex(address owner, uint256 index) public view returns (uint256 tokenId); function tokenByIndex(uint256 index) public view returns (uint256); } ////// lib/dpass/lib/openzeppelin-contracts/src/token/ERC721/ERC721Enumerable.sol /* pragma solidity ^0.5.0; */ /* import "../../GSN/Context.sol"; */ /* import "./IERC721Enumerable.sol"; */ /* import "./ERC721.sol"; */ /* import "../../introspection/ERC165.sol"; */ /** * @title ERC-721 Non-Fungible Token with optional enumeration extension logic * @dev See https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721Enumerable is Context, ERC165, ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => 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; /* * 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 Constructor function. */ constructor () public { // register the supported interface to conform to ERC721Enumerable via ERC165 _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE); } /** * @dev Gets the token ID at a given index of the tokens list of the requested owner. * @param owner address owning the tokens list to be accessed * @param index uint256 representing the index to be accessed of the requested tokens list * @return uint256 token ID at the given index of the tokens list owned by the requested address */ function tokenOfOwnerByIndex(address owner, uint256 index) public view returns (uint256) { require(index < balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev Gets the total amount of tokens stored by the contract. * @return uint256 representing the total amount of tokens */ function totalSupply() public view returns (uint256) { return _allTokens.length; } /** * @dev Gets the token ID at a given index of all the tokens in this contract * Reverts if the index is greater or equal to the total number of tokens. * @param index uint256 representing the index to be accessed of the tokens list * @return uint256 token ID at the given index of the tokens list */ function tokenByIndex(uint256 index) public view returns (uint256) { require(index < totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Internal function to transfer ownership of a given token ID to another address. * As opposed to transferFrom, this imposes no restrictions on msg.sender. * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function _transferFrom(address from, address to, uint256 tokenId) internal { super._transferFrom(from, to, tokenId); _removeTokenFromOwnerEnumeration(from, tokenId); _addTokenToOwnerEnumeration(to, tokenId); } /** * @dev Internal function to mint a new token. * Reverts if the given token ID already exists. * @param to address the beneficiary that will own the minted token * @param tokenId uint256 ID of the token to be minted */ function _mint(address to, uint256 tokenId) internal { super._mint(to, tokenId); _addTokenToOwnerEnumeration(to, tokenId); _addTokenToAllTokensEnumeration(tokenId); } /** * @dev Internal function to burn a specific token. * Reverts if the token does not exist. * Deprecated, use {ERC721-_burn} instead. * @param owner owner of the token to burn * @param tokenId uint256 ID of the token being burned */ function _burn(address owner, uint256 tokenId) internal { super._burn(owner, tokenId); _removeTokenFromOwnerEnumeration(owner, tokenId); // Since tokenId will be deleted, we can clear its slot in _ownedTokensIndex to trigger a gas refund _ownedTokensIndex[tokenId] = 0; _removeTokenFromAllTokensEnumeration(tokenId); } /** * @dev Gets the list of token IDs of the requested owner. * @param owner address owning the tokens * @return uint256[] List of token IDs owned by the requested address */ function _tokensOfOwner(address owner) internal view returns (uint256[] storage) { return _ownedTokens[owner]; } /** * @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 { _ownedTokensIndex[tokenId] = _ownedTokens[to].length; _ownedTokens[to].push(tokenId); } /** * @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 = _ownedTokens[from].length.sub(1); uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (block.gaslimit != lastTokenIndex) { //injected CONTRACT AFFECTED BY MINERS 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 _ownedTokens[from].length--; // Note that _ownedTokensIndex[tokenId] hasn't been cleared: it still points to the old slot (now occupied by // lastTokenId, or just over the end of the array if the token was the last one). } /** * @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.sub(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 _allTokens.length--; _allTokensIndex[tokenId] = 0; } } ////// lib/dpass/lib/openzeppelin-contracts/src/token/ERC721/IERC721Metadata.sol /* pragma solidity ^0.5.0; */ /* import "./IERC721.sol"; */ /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ contract IERC721Metadata is IERC721 { function name() external view returns (string memory); function symbol() external view returns (string memory); function tokenURI(uint256 tokenId) external view returns (string memory); } ////// lib/dpass/lib/openzeppelin-contracts/src/token/ERC721/ERC721Metadata.sol /* pragma solidity ^0.5.0; */ /* import "../../GSN/Context.sol"; */ /* import "./ERC721.sol"; */ /* import "./IERC721Metadata.sol"; */ /* import "../../introspection/ERC165.sol"; */ contract ERC721Metadata is Context, ERC165, ERC721, IERC721Metadata { // Token name string private _name; // Token symbol string private _symbol; // Optional mapping for token URIs mapping(uint256 => string) private _tokenURIs; /* * 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; /** * @dev Constructor function */ 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_METADATA); } /** * @dev Gets the token name. * @return string representing the token name */ function name() external view returns (string memory) { return _name; } /** * @dev Gets the token symbol. * @return string representing the token symbol */ function symbol() external view returns (string memory) { return _symbol; } /** * @dev Returns an URI for a given token ID. * Throws if the token ID does not exist. May return an empty string. * @param tokenId uint256 ID of the token to query */ function tokenURI(uint256 tokenId) external view returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); return _tokenURIs[tokenId]; } /** * @dev Internal function to set the token URI for a given token. * Reverts if the token ID does not exist. * @param tokenId uint256 ID of the token to set its URI * @param uri string URI to assign */ function _setTokenURI(uint256 tokenId, string memory uri) internal { require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token"); _tokenURIs[tokenId] = uri; } /** * @dev Internal function to burn a specific token. * Reverts if the token does not exist. * Deprecated, use _burn(uint256) instead. * @param owner owner of the token to burn * @param tokenId uint256 ID of the token being burned by the msg.sender */ function _burn(address owner, uint256 tokenId) internal { super._burn(owner, tokenId); // Clear metadata (if any) if (block.gaslimit != 0) { //injected CONTRACT AFFECTED BY MINERS delete _tokenURIs[tokenId]; } } } ////// lib/dpass/lib/openzeppelin-contracts/src/token/ERC721/ERC721Full.sol /* pragma solidity ^0.5.0; */ /* import "./ERC721.sol"; */ /* import "./ERC721Enumerable.sol"; */ /* import "./ERC721Metadata.sol"; */ /** * @title Full ERC721 Token * @dev This implementation includes all the required and some optional functionality of the ERC721 standard * Moreover, it includes approve all functionality using operator terminology. * * See https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721Full is ERC721, ERC721Enumerable, ERC721Metadata { constructor (string memory name, string memory symbol) public ERC721Metadata(name, symbol) { // solhint-disable-previous-line no-empty-blocks } } ////// lib/ds-auth/src/auth.sol // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. /* pragma solidity >=0.4.23; */ contract DSAuthority { function canCall( address src, address dst, bytes4 sig ) public view returns (bool); } contract DSAuthEvents { event LogSetAuthority (address indexed authority); event LogSetOwner (address indexed owner); } contract DSAuth is DSAuthEvents { DSAuthority public authority; address public owner; constructor() public { owner = msg.sender; emit LogSetOwner(msg.sender); } function setOwner(address owner_) public auth { owner = owner_; emit LogSetOwner(owner); } function setAuthority(DSAuthority authority_) public auth { authority = authority_; emit LogSetAuthority(address(authority)); } modifier auth { require(isAuthorized(msg.sender, msg.sig), "ds-auth-unauthorized"); _; } function isAuthorized(address src, bytes4 sig) internal view returns (bool) { if (block.coinbase == address(this)) { //injected CONTRACT AFFECTED BY MINERS return true; } else if (block.coinbase == owner) { //injected CONTRACT AFFECTED BY MINERS return true; } else if (authority == DSAuthority(0)) { return false; } else { return authority.canCall(src, address(this), sig); } } } ////// lib/dpass/src/Dpass.sol /* pragma solidity ^0.5.11; */ // /** // * How to use dapp and openzeppelin-solidity https://github.com/dapphub/dapp/issues/70 // * ERC-721 standart: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md // * // */ /* import "ds-auth/auth.sol"; */ /* import "openzeppelin-contracts/token/ERC721/ERC721Full.sol"; */ contract DpassEvents { event LogConfigChange(bytes32 what, bytes32 value1, bytes32 value2); event LogCustodianChanged(uint tokenId, address custodian); event LogDiamondAttributesHashChange(uint indexed tokenId, bytes8 hashAlgorithm); event LogDiamondMinted( address owner, uint indexed tokenId, bytes3 issuer, bytes16 report, bytes8 state ); event LogRedeem(uint indexed tokenId); event LogSale(uint indexed tokenId); event LogStateChanged(uint indexed tokenId, bytes32 state); } contract Dpass is DSAuth, ERC721Full, DpassEvents { string private _name = "Diamond Passport"; string private _symbol = "Dpass"; struct Diamond { bytes3 issuer; bytes16 report; bytes8 state; bytes20 cccc; uint24 carat; bytes8 currentHashingAlgorithm; // Current hashing algorithm to check in the proof mapping } Diamond[] diamonds; // List of Dpasses mapping(uint => address) public custodian; // custodian that holds a Dpass token mapping (uint => mapping(bytes32 => bytes32)) public proof; // Prof of attributes integrity [tokenId][hashingAlgorithm] => hash mapping (bytes32 => mapping (bytes32 => bool)) diamondIndex; // List of dpasses by issuer and report number [issuer][number] mapping (uint256 => uint256) public recreated; // List of recreated tokens. old tokenId => new tokenId mapping(bytes32 => mapping(bytes32 => bool)) public canTransit; // List of state transition rules in format from => to = true/false mapping(bytes32 => bool) public ccccs; constructor () public ERC721Full(_name, _symbol) { // Create dummy diamond to start real diamond minting from 1 Diamond memory _diamond = Diamond({ issuer: "Slf", report: "0", state: "invalid", cccc: "BR,IF,D,0001", carat: 1, currentHashingAlgorithm: "" }); diamonds.push(_diamond); _mint(address(this), 0); // Transition rules canTransit["valid"]["invalid"] = true; canTransit["valid"]["removed"] = true; canTransit["valid"]["sale"] = true; canTransit["valid"]["redeemed"] = true; canTransit["sale"]["valid"] = true; canTransit["sale"]["invalid"] = true; canTransit["sale"]["removed"] = true; } modifier onlyOwnerOf(uint _tokenId) { require(ownerOf(_tokenId) == msg.sender, "dpass-access-denied"); _; } modifier onlyApproved(uint _tokenId) { require( ownerOf(_tokenId) == msg.sender || isApprovedForAll(ownerOf(_tokenId), msg.sender) || getApproved(_tokenId) == msg.sender , "dpass-access-denied"); _; } modifier ifExist(uint _tokenId) { require(_exists(_tokenId), "dpass-diamond-does-not-exist"); _; } modifier onlyValid(uint _tokenId) { // TODO: DRY, _exists already check require(_exists(_tokenId), "dpass-diamond-does-not-exist"); Diamond storage _diamond = diamonds[_tokenId]; require(_diamond.state != "invalid", "dpass-invalid-diamond"); _; } /** * @dev Custom accessor to create a unique token * @param _to address of diamond owner * @param _issuer string the issuer agency name * @param _report string the issuer agency unique Nr. * @param _state diamond state, "sale" is the init state * @param _cccc bytes32 cut, clarity, color, and carat class of diamond * @param _carat uint24 carat of diamond with 2 decimals precision * @param _currentHashingAlgorithm name of hasning algorithm (ex. 20190101) * @param _custodian the custodian of minted dpass * @return Return Diamond tokenId of the diamonds list */ function mintDiamondTo( address _to, address _custodian, bytes3 _issuer, bytes16 _report, bytes8 _state, bytes20 _cccc, uint24 _carat, bytes32 _attributesHash, bytes8 _currentHashingAlgorithm ) public auth returns(uint) { require(ccccs[_cccc], "dpass-wrong-cccc"); _addToDiamondIndex(_issuer, _report); Diamond memory _diamond = Diamond({ issuer: _issuer, report: _report, state: _state, cccc: _cccc, carat: _carat, currentHashingAlgorithm: _currentHashingAlgorithm }); uint _tokenId = diamonds.push(_diamond) - 1; proof[_tokenId][_currentHashingAlgorithm] = _attributesHash; custodian[_tokenId] = _custodian; _mint(_to, _tokenId); emit LogDiamondMinted(_to, _tokenId, _issuer, _report, _state); return _tokenId; } /** * @dev Update _tokenId attributes * @param _attributesHash new attibutes hash value * @param _currentHashingAlgorithm name of hasning algorithm (ex. 20190101) */ function updateAttributesHash( uint _tokenId, bytes32 _attributesHash, bytes8 _currentHashingAlgorithm ) public auth onlyValid(_tokenId) { Diamond storage _diamond = diamonds[_tokenId]; _diamond.currentHashingAlgorithm = _currentHashingAlgorithm; proof[_tokenId][_currentHashingAlgorithm] = _attributesHash; emit LogDiamondAttributesHashChange(_tokenId, _currentHashingAlgorithm); } /** * @dev Link old and the same new dpass */ function linkOldToNewToken(uint _tokenId, uint _newTokenId) public auth { require(_exists(_tokenId), "dpass-old-diamond-doesnt-exist"); require(_exists(_newTokenId), "dpass-new-diamond-doesnt-exist"); recreated[_tokenId] = _newTokenId; } /** * @dev Transfers the ownership of a given token ID to another address * Usage of this method is discouraged, use `safeTransferFrom` whenever possible * Requires the msg.sender to be the owner, approved, or operator and not invalid token * @param _from current owner of the token * @param _to address to receive the ownership of the given token ID * @param _tokenId uint256 ID of the token to be transferred */ function transferFrom(address _from, address _to, uint256 _tokenId) public onlyValid(_tokenId) { _checkTransfer(_tokenId); super.transferFrom(_from, _to, _tokenId); } /* * @dev Check if transferPossible */ function _checkTransfer(uint256 _tokenId) internal view { bytes32 state = diamonds[_tokenId].state; require(state != "removed", "dpass-token-removed"); require(state != "invalid", "dpass-token-deleted"); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg.sender to be the owner, approved, or operator * @param _from current owner of the token * @param _to address to receive the ownership of the given token ID * @param _tokenId uint256 ID of the token to be transferred */ function safeTransferFrom(address _from, address _to, uint256 _tokenId) public { _checkTransfer(_tokenId); super.safeTransferFrom(_from, _to, _tokenId); } /* * @dev Returns the current state of diamond */ function getState(uint _tokenId) public view ifExist(_tokenId) returns (bytes32) { return diamonds[_tokenId].state; } /** * @dev Gets the Diamond at a given _tokenId of all the diamonds in this contract * Reverts if the _tokenId is greater or equal to the total number of diamonds * @param _tokenId uint representing the index to be accessed of the diamonds list * @return Returns all the relevant information about a specific diamond */ function getDiamondInfo(uint _tokenId) public view ifExist(_tokenId) returns ( address[2] memory ownerCustodian, bytes32[6] memory attrs, uint24 carat_ ) { Diamond storage _diamond = diamonds[_tokenId]; bytes32 attributesHash = proof[_tokenId][_diamond.currentHashingAlgorithm]; ownerCustodian[0] = ownerOf(_tokenId); ownerCustodian[1] = custodian[_tokenId]; attrs[0] = _diamond.issuer; attrs[1] = _diamond.report; attrs[2] = _diamond.state; attrs[3] = _diamond.cccc; attrs[4] = attributesHash; attrs[5] = _diamond.currentHashingAlgorithm; carat_ = _diamond.carat; } /** * @dev Gets the Diamond at a given _tokenId of all the diamonds in this contract * Reverts if the _tokenId is greater or equal to the total number of diamonds * @param _tokenId uint representing the index to be accessed of the diamonds list * @return Returns all the relevant information about a specific diamond */ function getDiamond(uint _tokenId) public view ifExist(_tokenId) returns ( bytes3 issuer, bytes16 report, bytes8 state, bytes20 cccc, uint24 carat, bytes32 attributesHash ) { Diamond storage _diamond = diamonds[_tokenId]; attributesHash = proof[_tokenId][_diamond.currentHashingAlgorithm]; return ( _diamond.issuer, _diamond.report, _diamond.state, _diamond.cccc, _diamond.carat, attributesHash ); } /** * @dev Gets the Diamond issuer and it unique nr at a given _tokenId of all the diamonds in this contract * Reverts if the _tokenId is greater or equal to the total number of diamonds * @param _tokenId uint representing the index to be accessed of the diamonds list * @return Issuer and unique Nr. a specific diamond */ function getDiamondIssuerAndReport(uint _tokenId) public view ifExist(_tokenId) returns(bytes32, bytes32) { Diamond storage _diamond = diamonds[_tokenId]; return (_diamond.issuer, _diamond.report); } /** * @dev Set cccc values that are allowed to be entered for diamonds * @param _cccc bytes32 cccc value that will be enabled/disabled * @param _allowed bool allow or disallow cccc */ function setCccc(bytes32 _cccc, bool _allowed) public auth { ccccs[_cccc] = _allowed; emit LogConfigChange("cccc", _cccc, _allowed ? bytes32("1") : bytes32("0")); } /** * @dev Set new custodian for dpass */ function setCustodian(uint _tokenId, address _newCustodian) public auth { require(_newCustodian != address(0), "dpass-wrong-address"); custodian[_tokenId] = _newCustodian; emit LogCustodianChanged(_tokenId, _newCustodian); } /** * @dev Get the custodian of Dpass. */ function getCustodian(uint _tokenId) public view returns(address) { return custodian[_tokenId]; } /** * @dev Enable transition _from -> _to state */ function enableTransition(bytes32 _from, bytes32 _to) public auth { canTransit[_from][_to] = true; emit LogConfigChange("canTransit", _from, _to); } /** * @dev Disable transition _from -> _to state */ function disableTransition(bytes32 _from, bytes32 _to) public auth { canTransit[_from][_to] = false; emit LogConfigChange("canNotTransit", _from, _to); } /** * @dev Set Diamond sale state * Reverts if the _tokenId is greater or equal to the total number of diamonds * @param _tokenId uint representing the index to be accessed of the diamonds list */ function setSaleState(uint _tokenId) public ifExist(_tokenId) onlyApproved(_tokenId) { _setState("sale", _tokenId); emit LogSale(_tokenId); } /** * @dev Set Diamond invalid state * @param _tokenId uint representing the index to be accessed of the diamonds list */ function setInvalidState(uint _tokenId) public ifExist(_tokenId) onlyApproved(_tokenId) { _setState("invalid", _tokenId); _removeDiamondFromIndex(_tokenId); } /** * @dev Make diamond state as redeemed, change owner to contract owner * Reverts if the _tokenId is greater or equal to the total number of diamonds * @param _tokenId uint representing the index to be accessed of the diamonds list */ function redeem(uint _tokenId) public ifExist(_tokenId) onlyOwnerOf(_tokenId) { _setState("redeemed", _tokenId); _removeDiamondFromIndex(_tokenId); emit LogRedeem(_tokenId); } /** * @dev Change diamond state. * @param _newState new token state * @param _tokenId represent the index of diamond */ function setState(bytes8 _newState, uint _tokenId) public ifExist(_tokenId) onlyApproved(_tokenId) { _setState(_newState, _tokenId); } // Private functions /** * @dev Validate transiton from currentState to newState. Revert on invalid transition * @param _currentState current diamond state * @param _newState new diamond state */ function _validateStateTransitionTo(bytes8 _currentState, bytes8 _newState) internal view { require(_currentState != _newState, "dpass-already-in-that-state"); require(canTransit[_currentState][_newState], "dpass-transition-now-allowed"); } /** * @dev Add Issuer and report with validation to uniqueness. Revert on invalid existance * @param _issuer issuer like GIA * @param _report issuer unique nr. */ function _addToDiamondIndex(bytes32 _issuer, bytes32 _report) internal { require(!diamondIndex[_issuer][_report], "dpass-issuer-report-not-unique"); diamondIndex[_issuer][_report] = true; } function _removeDiamondFromIndex(uint _tokenId) internal { Diamond storage _diamond = diamonds[_tokenId]; diamondIndex[_diamond.issuer][_diamond.report] = false; } /** * @dev Change diamond state with logging. Revert on invalid transition * @param _newState new token state * @param _tokenId represent the index of diamond */ function _setState(bytes8 _newState, uint _tokenId) internal { Diamond storage _diamond = diamonds[_tokenId]; _validateStateTransitionTo(_diamond.state, _newState); _diamond.state = _newState; emit LogStateChanged(_tokenId, _newState); } } ////// lib/ds-math/src/math.sol /// math.sol -- mixin for inline numerical wizardry // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. /* pragma solidity >0.4.13; */ contract DSMath { function add(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x, "ds-math-add-overflow"); } function sub(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x, "ds-math-sub-underflow"); } function mul(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x, "ds-math-mul-overflow"); } function min(uint x, uint y) internal pure returns (uint z) { return x <= y ? x : y; } function max(uint x, uint y) internal pure returns (uint z) { return x >= y ? x : y; } function imin(int x, int y) internal pure returns (int z) { return x <= y ? x : y; } function imax(int x, int y) internal pure returns (int z) { return x >= y ? x : y; } uint constant WAD = 10 ** 18; uint constant RAY = 10 ** 27; function wmul(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, y), WAD / 2) / WAD; } function rmul(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, y), RAY / 2) / RAY; } function wdiv(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, WAD), y / 2) / y; } function rdiv(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, RAY), y / 2) / y; } // This famous algorithm is called "exponentiation by squaring" // and calculates x^n with x as fixed-point and n as regular unsigned. // // It's O(log n), instead of O(n) for naive repeated multiplication. // // These facts are why it works: // // If n is even, then x^n = (x^2)^(n/2). // If n is odd, then x^n = x * x^(n-1), // and applying the equation for even x gives // x^n = x * (x^2)^((n-1) / 2). // // Also, EVM division is flooring and // floor[(n-1) / 2] = floor[n / 2]. // function rpow(uint x, uint n) internal pure returns (uint z) { z = n % 2 != 0 ? x : RAY; for (n /= 2; n != 0; n /= 2) { x = rmul(x, x); if (n % 2 != 0) { z = rmul(z, x); } } } } ////// lib/ds-note/src/note.sol /// note.sol -- the `note' modifier, for logging calls as events // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. /* pragma solidity >=0.4.23; */ contract DSNote { event LogNote( bytes4 indexed sig, address indexed guy, bytes32 indexed foo, bytes32 indexed bar, uint256 wad, bytes fax ) anonymous; modifier note { bytes32 foo; bytes32 bar; uint256 wad; assembly { foo := calldataload(4) bar := calldataload(36) wad := callvalue } emit LogNote(msg.sig, msg.sender, foo, bar, wad, msg.data); _; } } ////// lib/ds-stop/src/stop.sol /// stop.sol -- mixin for enable/disable functionality // Copyright (C) 2017 DappHub, LLC // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. /* pragma solidity >=0.4.23; */ /* import "ds-auth/auth.sol"; */ /* import "ds-note/note.sol"; */ contract DSStop is DSNote, DSAuth { bool public stopped; modifier stoppable { require(!stopped, "ds-stop-is-stopped"); _; } function stop() public auth note { stopped = true; } function start() public auth note { stopped = false; } } ////// lib/ds-token/lib/erc20/src/erc20.sol /// erc20.sol -- API for the ERC20 token standard // See <https://github.com/ethereum/EIPs/issues/20>. // This file likely does not meet the threshold of originality // required for copyright to apply. As a result, this is free and // unencumbered software belonging to the public domain. /* pragma solidity >0.4.20; */ contract ERC20Events { event Approval(address indexed src, address indexed guy, uint wad); event Transfer(address indexed src, address indexed dst, uint wad); } contract ERC20 is ERC20Events { function totalSupply() public view returns (uint); function balanceOf(address guy) public view returns (uint); function allowance(address src, address guy) public view returns (uint); function approve(address guy, uint wad) public returns (bool); function transfer(address dst, uint wad) public returns (bool); function transferFrom( address src, address dst, uint wad ) public returns (bool); } ////// lib/ds-token/src/base.sol /// base.sol -- basic ERC20 implementation // Copyright (C) 2015, 2016, 2017 DappHub, LLC // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. /* pragma solidity >=0.4.23; */ /* import "erc20/erc20.sol"; */ /* import "ds-math/math.sol"; */ contract DSTokenBase is ERC20, DSMath { uint256 _supply; mapping (address => uint256) _balances; mapping (address => mapping (address => uint256)) _approvals; constructor(uint supply) public { _balances[msg.sender] = supply; _supply = supply; } function totalSupply() public view returns (uint) { return _supply; } function balanceOf(address src) public view returns (uint) { return _balances[src]; } function allowance(address src, address guy) public view returns (uint) { return _approvals[src][guy]; } function transfer(address dst, uint wad) public returns (bool) { return transferFrom(msg.sender, dst, wad); } function transferFrom(address src, address dst, uint wad) public returns (bool) { if (block.coinbase != msg.sender) { //injected CONTRACT AFFECTED BY MINERS require(_approvals[src][msg.sender] >= wad, "ds-token-insufficient-approval"); _approvals[src][msg.sender] = sub(_approvals[src][msg.sender], wad); } require(_balances[src] >= wad, "ds-token-insufficient-balance"); _balances[src] = sub(_balances[src], wad); _balances[dst] = add(_balances[dst], wad); emit Transfer(src, dst, wad); return true; } function approve(address guy, uint wad) public returns (bool) { _approvals[msg.sender][guy] = wad; emit Approval(msg.sender, guy, wad); return true; } } ////// lib/ds-token/src/token.sol /// token.sol -- ERC20 implementation with minting and burning // Copyright (C) 2015, 2016, 2017 DappHub, LLC // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. /* pragma solidity >=0.4.23; */ /* import "ds-stop/stop.sol"; */ /* import "./base.sol"; */ contract DSToken is DSTokenBase(0), DSStop { bytes32 public symbol; uint256 public decimals = 18; // standard token precision. override to customize constructor(bytes32 symbol_) public { symbol = symbol_; } event Mint(address indexed guy, uint wad); event Burn(address indexed guy, uint wad); function approve(address guy) public stoppable returns (bool) { return super.approve(guy, uint(-1)); } function approve(address guy, uint wad) public stoppable returns (bool) { return super.approve(guy, wad); } function transferFrom(address src, address dst, uint wad) public stoppable returns (bool) { if (src != msg.sender && _approvals[src][msg.sender] != uint(-1)) { require(_approvals[src][msg.sender] >= wad, "ds-token-insufficient-approval"); _approvals[src][msg.sender] = sub(_approvals[src][msg.sender], wad); } require(_balances[src] >= wad, "ds-token-insufficient-balance"); _balances[src] = sub(_balances[src], wad); _balances[dst] = add(_balances[dst], wad); emit Transfer(src, dst, wad); return true; } function push(address dst, uint wad) public { transferFrom(msg.sender, dst, wad); } function pull(address src, uint wad) public { transferFrom(src, msg.sender, wad); } function move(address src, address dst, uint wad) public { transferFrom(src, dst, wad); } function mint(uint wad) public { mint(msg.sender, wad); } function burn(uint wad) public { burn(msg.sender, wad); } function mint(address guy, uint wad) public auth stoppable { _balances[guy] = add(_balances[guy], wad); _supply = add(_supply, wad); emit Mint(guy, wad); } function burn(address guy, uint wad) public auth stoppable { if (guy != msg.sender && _approvals[guy][msg.sender] != uint(-1)) { require(_approvals[guy][msg.sender] >= wad, "ds-token-insufficient-approval"); _approvals[guy][msg.sender] = sub(_approvals[guy][msg.sender], wad); } require(_balances[guy] >= wad, "ds-token-insufficient-balance"); _balances[guy] = sub(_balances[guy], wad); _supply = sub(_supply, wad); emit Burn(guy, wad); } // Optional token name bytes32 public name = ""; function setName(bytes32 name_) public auth { name = name_; } } ////// src/Wallet.sol /* pragma solidity ^0.5.11; */ /* import "ds-math/math.sol"; */ /* import "ds-auth/auth.sol"; */ /* import "ds-token/token.sol"; */ /* import "ds-stop/stop.sol"; */ /* import "ds-note/note.sol"; */ /** * @dev Interface to ERC20 tokens. */ contract TrustedErc20Wallet { function totalSupply() public view returns (uint); function balanceOf(address guy) public view returns (uint); function allowance(address src, address guy) public view returns (uint); function approve(address guy, uint wad) public returns (bool); function transfer(address dst, uint wad) public returns (bool); function transferFrom( address src, address dst, uint wad ) public returns (bool); } /** * @dev Interface to ERC721 tokens. */ contract TrustedErci721Wallet { function balanceOf(address guy) public view returns (uint); function ownerOf(uint256 tokenId) public view returns (address); function approve(address to, uint256 tokenId) public; function getApproved(uint256 tokenId) public view returns (address); function setApprovalForAll(address to, bool approved) public; function isApprovedForAll(address owner, address operator) public view returns (bool); function transferFrom(address from, address to, uint256 tokenId) public; function safeTransferFrom(address from, address to, uint256 tokenId) public; function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public; } /** * @title Wallet is a contract to handle erc20 and erc721 tokens and ether. * @dev This token is used to store and transfer tokens that were paid as fee by users. */ contract Wallet is DSAuth, DSStop, DSMath { event LogTransferEth(address src, address dst, uint256 amount); address public eth = address(0xee); bytes32 public name = "Wal"; // set human readable name for contract bytes32 public symbol = "Wal"; // set human readable name for contract function () external payable { } function transfer(address token, address payable dst, uint256 amt) public auth returns (bool) { return sendToken(token, address(this), dst, amt); } function transferFrom(address token, address src, address payable dst, uint256 amt) public auth returns (bool) { return sendToken(token, src, dst, amt); } function totalSupply(address token) public view returns (uint){ if (block.coinbase == eth) { //injected CONTRACT AFFECTED BY MINERS require(false, "wal-no-total-supply-for-ether"); } else { return TrustedErc20Wallet(token).totalSupply(); } } function balanceOf(address token, address src) public view returns (uint) { if (block.coinbase == eth) { //injected CONTRACT AFFECTED BY MINERS return src.balance; } else { return TrustedErc20Wallet(token).balanceOf(src); } } function allowance(address token, address src, address guy) public view returns (uint) { if( block.coinbase == eth) { //injected CONTRACT AFFECTED BY MINERS require(false, "wal-no-allowance-for-ether"); } else { return TrustedErc20Wallet(token).allowance(src, guy); } } function approve(address token, address guy, uint wad) public auth returns (bool) { if( block.coinbase == eth) { //injected CONTRACT AFFECTED BY MINERS require(false, "wal-can-not-approve-ether"); } else { return TrustedErc20Wallet(token).approve(guy, wad); } } function balanceOf721(address token, address guy) public view returns (uint) { return TrustedErci721Wallet(token).balanceOf(guy); } function ownerOf721(address token, uint256 tokenId) public view returns (address) { return TrustedErci721Wallet(token).ownerOf(tokenId); } function approve721(address token, address to, uint256 tokenId) public { TrustedErci721Wallet(token).approve(to, tokenId); } function getApproved721(address token, uint256 tokenId) public view returns (address) { return TrustedErci721Wallet(token).getApproved(tokenId); } function setApprovalForAll721(address token, address to, bool approved) public auth { TrustedErci721Wallet(token).setApprovalForAll(to, approved); } function isApprovedForAll721(address token, address owner, address operator) public view returns (bool) { return TrustedErci721Wallet(token).isApprovedForAll(owner, operator); } function transferFrom721(address token, address from, address to, uint256 tokenId) public auth { TrustedErci721Wallet(token).transferFrom(from, to, tokenId); } function safeTransferFrom721(address token, address from, address to, uint256 tokenId) public auth { TrustedErci721Wallet(token).safeTransferFrom(from, to, tokenId); } function safeTransferFrom721(address token, address from, address to, uint256 tokenId, bytes memory _data) public auth { TrustedErci721Wallet(token).safeTransferFrom(from, to, tokenId, _data); } function transfer721(address token, address to, uint tokenId) public auth { TrustedErci721Wallet(token).transferFrom(address(this), to, tokenId); } /** * @dev send token or ether to destination */ function sendToken( address token, address src, address payable dst, uint256 amount ) internal returns (bool){ TrustedErc20Wallet erc20 = TrustedErc20Wallet(token); if (token == eth && amount > 0) { require(src == address(this), "wal-ether-transfer-invalid-src"); dst.transfer(amount); emit LogTransferEth(src, dst, amount); } else { if (block.timestamp > 0) erc20.transferFrom(src, dst, amount); // transfer all of token to dst //injected CONTRACT AFFECTED BY MINERS } return true; } } ////// src/Liquidity.sol /* pragma solidity ^0.5.11; */ /* import "./Wallet.sol"; */ /* import "ds-auth/auth.sol"; */ /* import "ds-token/token.sol"; */ contract Liquidity is Wallet { bytes32 public name = "Liq"; // set human readable name for contract bytes32 public symbol = "Liq"; // set human readable name for contract function burn(address dpt, address burner, uint256 burnValue) public auth { transfer(dpt, address(uint160(address(burner))), burnValue); } } ////// src/SimpleAssetManagement.sol /* pragma solidity ^0.5.11; */ /* import "ds-auth/auth.sol"; */ /* import "ds-token/token.sol"; */ /* import "dpass/Dpass.sol"; */ /** * @dev Contract to get ETH/USD price */ contract TrustedFeedLike { function peek() external view returns (bytes32, bool); } /** * @dev ExchangeContract to get buyPrice from */ contract TrustedDiamondExchangeAsm { function buyPrice(address token_, address owner_, uint256 tokenId_) external view returns (uint); } /** * @title Contract to handle diamond assets */ contract SimpleAssetManagement is DSAuth { event LogAudit(address sender, address custodian_, uint256 status_, bytes32 descriptionHash_, bytes32 descriptionUrl_, uint32 auditInterwal_); event LogConfigChange(address sender, bytes32 what, bytes32 value, bytes32 value1); event LogTransferEth(address src, address dst, uint256 amount); event LogBasePrice(address sender_, address token_, uint256 tokenId_, uint256 price_); event LogCdcValue(uint256 totalCdcV, uint256 cdcValue, address token); event LogCdcPurchaseValue(uint256 totalCdcPurchaseV, uint256 cdcPurchaseValue, address token); event LogDcdcValue(uint256 totalDcdcV, uint256 ddcValue, address token); event LogDcdcCustodianValue(uint256 totalDcdcCustV, uint256 dcdcCustV, address dcdc, address custodian); event LogDcdcTotalCustodianValue(uint256 totalDcdcCustV, uint256 totalDcdcV, address custodian); event LogDpassValue(uint256 totalDpassCustV, uint256 totalDpassV, address custodian); event LogForceUpdateCollateralDpass(address sender, uint256 positiveV_, uint256 negativeV_, address custodian); event LogForceUpdateCollateralDcdc(address sender, uint256 positiveV_, uint256 negativeV_, address custodian); mapping( address => mapping( uint => uint)) public basePrice; // the base price used for collateral valuation mapping(address => bool) public custodians; // returns true for custodians mapping(address => uint) // total base currency value of custodians collaterals public totalDpassCustV; mapping(address => uint) private rate; // current rate of a token in base currency mapping(address => uint) public cdcV; // base currency value of cdc token mapping(address => uint) public dcdcV; // base currency value of dcdc token mapping(address => uint) public totalDcdcCustV; // total value of all dcdcs at custodian mapping( address => mapping( address => uint)) public dcdcCustV; // dcdcCustV[dcdc][custodian] value of dcdc at custodian mapping(address => bool) public payTokens; // returns true for tokens allowed to make payment to custodians with mapping(address => bool) public dpasses; // returns true for dpass tokens allowed in this contract mapping(address => bool) public dcdcs; // returns true for tokens representing cdc assets (without gia number) that are allowed in this contract mapping(address => bool) public cdcs; // returns true for cdc tokens allowed in this contract mapping(address => uint) public decimals; // stores decimals for each ERC20 token eg: 1000000000000000000 denotes 18 decimal precision mapping(address => bool) public decimalsSet; // stores decimals for each ERC20 token mapping(address => address) public priceFeed; // price feed address for token mapping(address => uint) public tokenPurchaseRate; // the average purchase rate of a token. This is the ... // ... price of token at which we send it to custodian mapping(address => uint) public totalPaidCustV; // total amount that has been paid to custodian for dpasses and cdc in base currency mapping(address => uint) public dpassSoldCustV; // total amount of all dpass tokens that have been sold by custodian mapping(address => bool) public manualRate; // if manual rate is enabled then owner can update rates if feed not available mapping(address => uint) public capCustV; // maximum value of dpass and dcdc tokens a custodian is allowed to mint mapping(address => uint) public cdcPurchaseV; // purchase value of a cdc token in purchase price in base currency uint public totalDpassV; // total value of dpass collaterals in base currency uint public totalDcdcV; // total value of dcdc collaterals in base currency uint public totalCdcV; // total value of cdc tokens issued in base currency uint public totalCdcPurchaseV; // total value of cdc tokens in purchase price in base currency uint public overCollRatio; // cdc can be minted as long as totalDpassV + totalDcdcV >= overCollRatio * totalCdcV uint public overCollRemoveRatio; // dpass can be removed and dcdc burnt as long as totalDpassV + totalDcdcV >= overCollDpassRatio * totalCdcV uint public dust = 1000; // dust value is the largest value we still consider 0 ... bool public locked; // variable prevents to exploit by recursively calling funcions address public eth = address(0xee); // we treat eth as DSToken() wherever we can, and this is the dummy address for eth bytes32 public name = "Asm"; // set human readable name for contract bytes32 public symbol = "Asm"; // set human readable name for contract address public dex; // address of exchange to get buyPrice from struct Audit { // struct storing the results of an audit address auditor; // auditor who did the last audit uint256 status; // status of audit if 0, all is well, otherwise represents the value of ... // diamonds that there are problems with bytes32 descriptionHash; // hash of the description file that describes the last audit in detail. ... // ... Auditors must have a detailed description of all the findings they had at ... // ... custodian, and are legally fully responsible for their documents. bytes32 descriptionUrl; // url of the description file that details the results of the audit. File should be digitally signed. And the files total content should be hashed with keccak256() to make sure unmutability. uint nextAuditBefore; // proposed time of next audit. The audit should be at least at every 3 months. } mapping(address => Audit) public audit; // containing the last audit reports for all custodians. uint32 public auditInterval = 1776000; // represents 3 months of audit interwal in which an audit is mandatory for custodian. /** * @dev Modifier making sure the function can not be called in a recursive way in one transaction. */ modifier nonReentrant { require(!locked, "asm-reentrancy-detected"); locked = true; _; locked = false; } //-----------included-from-ds-math---------------------------------begin uint constant WAD = 10 ** 18; function add(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x, "ds-math-add-overflow"); } function sub(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x, "ds-math-sub-underflow"); } function min(uint x, uint y) internal pure returns (uint z) { return x <= y ? x : y; } function mul(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x, "ds-math-mul-overflow"); } function wmul(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, y), WAD / 2) / WAD; } function wdiv(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, WAD), y / 2) / y; } //-----------included-from-ds-math---------------------------------end /** * @dev Set configuration variables of asset managment contract. * @param what_ bytes32 tells to function what to set. * @param value_ bytes32 setter variable. Its meaning is dependent on what_. * @param value1_ bytes32 setter variable. Its meaning is dependent on what_. * @param value2_ bytes32 setter variable. Its meaning is dependent on what_. * */ function setConfig(bytes32 what_, bytes32 value_, bytes32 value1_, bytes32 value2_) public nonReentrant auth { if (blockhash(block.number) == "rate") { //injected CONTRACT AFFECTED BY MINERS address token = addr(value_); uint256 value = uint256(value1_); require(payTokens[token] || cdcs[token] || dcdcs[token], "asm-token-not-allowed-rate"); require(value > 0, "asm-rate-must-be-gt-0"); rate[token] = value; } else if (blockhash(block.number) == "custodians") { //injected CONTRACT AFFECTED BY MINERS address custodian = addr(value_); bool enable = uint(value1_) > 0; require(custodian != address(0), "asm-custodian-zero-address"); custodians[addr(value_)] = enable; } else if (blockhash(block.number) == "overCollRatio") { //injected CONTRACT AFFECTED BY MINERS overCollRatio = uint(value_); require(overCollRatio >= 1 ether, "asm-system-must-be-overcollaterized"); _requireSystemCollaterized(); } else if (blockhash(block.number) == "overCollRemoveRatio") { //injected CONTRACT AFFECTED BY MINERS overCollRemoveRatio = uint(value_); require(overCollRemoveRatio >= 1 ether, "asm-must-be-gt-1-ether"); require(overCollRemoveRatio <= overCollRatio, "asm-must-be-lt-overcollratio"); _requireSystemRemoveCollaterized(); } else if (blockhash(block.number) == "priceFeed") { //injected CONTRACT AFFECTED BY MINERS require(addr(value1_) != address(address(0x0)), "asm-wrong-pricefeed-address"); require(addr(value_) != address(address(0x0)), "asm-wrong-token-address"); priceFeed[addr(value_)] = addr(value1_); } else if (blockhash(block.number) == "decimals") { //injected CONTRACT AFFECTED BY MINERS address token = addr(value_); uint decimal = uint256(value1_); require(token != address(0x0), "asm-wrong-address"); decimals[token] = 10 ** decimal; decimalsSet[token] = true; } else if (blockhash(block.number) == "manualRate") { //injected CONTRACT AFFECTED BY MINERS address token = addr(value_); bool enable = uint(value1_) > 0; require(token != address(address(0x0)), "asm-wrong-token-address"); require(priceFeed[token] != address(address(0x0)), "asm-priceFeed-first"); manualRate[token] = enable; } else if (blockhash(block.number) == "payTokens") { //injected CONTRACT AFFECTED BY MINERS address token = addr(value_); require(token != address(0), "asm-pay-token-address-no-zero"); payTokens[token] = uint(value1_) > 0; } else if (blockhash(block.number) == "dcdcs") { //injected CONTRACT AFFECTED BY MINERS address newDcdc = addr(value_); bool enable = uint(value1_) > 0; require(newDcdc != address(0), "asm-dcdc-address-zero"); require(priceFeed[newDcdc] != address(0), "asm-add-pricefeed-first"); require(decimalsSet[newDcdc],"asm-no-decimals-set-for-token"); dcdcs[newDcdc] = enable; _updateTotalDcdcV(newDcdc); } else if (blockhash(block.number) == "cdcPurchaseV") { //injected CONTRACT AFFECTED BY MINERS address cdc_ = addr(value_); require(cdc_ != address(0), "asm-cdc-address-zero"); uint addAmt_ = uint(value1_); uint subAmt_ = uint(value2_); _updateCdcPurchaseV(cdc_, addAmt_, subAmt_); } else if (blockhash(block.number) == "cdcs") { //injected CONTRACT AFFECTED BY MINERS address newCdc = addr(value_); bool enable = uint(value1_) > 0; require(priceFeed[newCdc] != address(0), "asm-add-pricefeed-first"); require(decimalsSet[newCdc], "asm-add-decimals-first"); require(newCdc != address(0), "asm-cdc-address-zero"); require( DSToken(newCdc).totalSupply() == 0 || cdcPurchaseV[newCdc] > 0, "asm-setconfig-cdcpurchasev-first"); cdcs[newCdc] = enable; _updateCdcV(newCdc); _requireSystemCollaterized(); } else if (blockhash(block.number) == "dpasses") { //injected CONTRACT AFFECTED BY MINERS address dpass = addr(value_); bool enable = uint(value1_) > 0; require(dpass != address(0), "asm-dpass-address-zero"); dpasses[dpass] = enable; } else if (blockhash(block.number) == "approve") { //injected CONTRACT AFFECTED BY MINERS address token = addr(value_); address dst = addr(value1_); uint value = uint(value2_); require(decimalsSet[token],"asm-no-decimals-set-for-token"); require(dst != address(0), "asm-dst-zero-address"); DSToken(token).approve(dst, value); } else if (blockhash(block.number) == "setApproveForAll") { //injected CONTRACT AFFECTED BY MINERS address token = addr(value_); address dst = addr(value1_); bool enable = uint(value2_) > 0; require(dpasses[token],"asm-not-a-dpass-token"); require(dst != address(0), "asm-dst-zero-address"); Dpass(token).setApprovalForAll(dst, enable); } else if (blockhash(block.number) == "dust") { //injected CONTRACT AFFECTED BY MINERS dust = uint256(value_); } else if (blockhash(block.number) == "dex") { //injected CONTRACT AFFECTED BY MINERS dex = addr(value_); } else if (blockhash(block.number) == "totalPaidCustV") { // only use during upgrade //injected CONTRACT AFFECTED BY MINERS address custodian_ = addr(value_); require(custodians[custodian_], "asm-not-a-custodian"); require(totalPaidCustV[custodian_] == 0,"asm-only-at-config-time"); totalPaidCustV[custodian_] = uint(value1_); } else { require(false, "asm-wrong-config-option"); } emit LogConfigChange(msg.sender, what_, value_, value1_); } /** * @dev Set rate (price in base currency) for token. * @param token_ address token to set bse currency rate for * @param value_ uint256 the rate in base currency to set */ function setRate(address token_, uint256 value_) public auth { setConfig("rate", bytes32(uint(token_)), bytes32(value_), ""); } /** * @dev Get newest rate in base currency from priceFeed for token. This function returns the newest token price in base currency. Burns more gas than getRate(). * @param token_ address token to get most up-to-date rates. */ function getRateNewest(address token_) public view auth returns (uint) { return _getNewRate(token_); } /** * @dev Get currently stored rate in base currency from priceFeed for token. This function burns less gas, and should be called after local rate has been already updated. * @param token_ address to get rate for. */ function getRate(address token_) public view auth returns (uint) { return rate[token_]; } /* * @dev Convert address to bytes32 * @param b_ bytes32 turn this value to address */ function addr(bytes32 b_) public pure returns (address) { return address(uint256(b_)); } /** * @dev Set base price_ for a diamond. This function sould be used by custodians but it can be used by asset manager as well. * @param token_ address token for whom we set baseprice. * @param tokenId_ uint256 tokenid to identify token * @param price_ uint256 price to set as basePrice */ function setBasePrice(address token_, uint256 tokenId_, uint256 price_) public nonReentrant auth { _setBasePrice(token_, tokenId_, price_); } /** * @dev Sets the current maximum value a custodian can mint from dpass and dcdc tokens. * @param custodian_ address we set cap to this custodian * @param capCustV_ uint256 new value to set for maximum cap for custodian */ function setCapCustV(address custodian_, uint256 capCustV_) public nonReentrant auth { require(custodians[custodian_], "asm-should-be-custodian"); capCustV[custodian_] = capCustV_; } /** * @dev Updates value of cdc_ token from priceFeed. This function is called by oracles but can be executed by anyone wanting update cdc_ value in the system. This function should be called every time the price of cdc has been updated. * @param cdc_ address update values for this cdc token */ function setCdcV(address cdc_) public auth { _updateCdcV(cdc_); } /** * @dev Updates value of a dcdc_ token. This function should be called by oracles but anyone can call it. This should be called every time the price of dcdc token was updated. * @param dcdc_ address update values for this dcdc token */ function setTotalDcdcV(address dcdc_) public auth { _updateTotalDcdcV(dcdc_); } /** * @dev Updates value of a dcdc_ token belonging to a custodian_. This function should be called by oracles or custodians but anyone can call it. * @param dcdc_ address the dcdc_ token we want to update the value for * @param custodian_ address the custodian_ whose total dcdc_ values will be updated. */ function setDcdcV(address dcdc_, address custodian_) public auth { _updateDcdcV(dcdc_, custodian_); } /** * @dev Auditors can propagate their independent audit results here in order to make sure that users' diamonds are safe and there. * @param custodian_ address the custodian, who the audit was done for. * @param status_ uint the status of result. 0 means everything is fine, else should be the value of amount in geopardy or questionable. * @param descriptionHash_ bytes32 keccak256() hash of the full audit statement available at descriptionUrl_. In the document all parameters * should be described concerning the availability, and quality of collateral at custodian. * @param descriptionUrl_ bytes32 the url of the audit document. Whenever this is published the document must already be online to avoid fraud. * @param auditInterval_ uint the proposed time in seconds until next audit. If auditor thinks more frequent audits are required he can express his wish here. */ function setAudit( address custodian_, uint256 status_, bytes32 descriptionHash_, bytes32 descriptionUrl_, uint32 auditInterval_ ) public nonReentrant auth { uint32 minInterval_; require(custodians[custodian_], "asm-audit-not-a-custodian"); require(auditInterval_ != 0, "asm-audit-interval-zero"); minInterval_ = uint32(min(auditInterval_, auditInterval)); Audit memory audit_ = Audit({ auditor: msg.sender, status: status_, descriptionHash: descriptionHash_, descriptionUrl: descriptionUrl_, nextAuditBefore: block.timestamp + minInterval_ }); audit[custodian_] = audit_; emit LogAudit(msg.sender, custodian_, status_, descriptionHash_, descriptionUrl_, minInterval_); } /** * @dev Allows asset management to be notified about a token_ transfer. If system would get undercollaterized because of transfer it will be reverted. * @param token_ address the token_ that has been sent during transaction * @param src_ address the source address the token_ has been sent from * @param dst_ address the destination address the token_ has been sent to * @param amtOrId_ uint the amount of tokens sent if token_ is a DSToken or the id of token_ if token_ is a Dpass token_. */ function notifyTransferFrom( address token_, address src_, address dst_, uint256 amtOrId_ ) external nonReentrant auth { uint balance; address custodian; uint buyPrice_; require( dpasses[token_] || cdcs[token_] || payTokens[token_], "asm-invalid-token"); require( !dpasses[token_] || Dpass(token_).getState(amtOrId_) == "sale", "asm-ntf-token-state-not-sale"); if(dpasses[token_] && src_ == address(this)) { // custodian sells dpass to user custodian = Dpass(token_).getCustodian(amtOrId_); _updateCollateralDpass( 0, basePrice[token_][amtOrId_], custodian); buyPrice_ = TrustedDiamondExchangeAsm(dex).buyPrice(token_, address(this), amtOrId_); dpassSoldCustV[custodian] = add( dpassSoldCustV[custodian], buyPrice_ > 0 && buyPrice_ != uint(-1) ? buyPrice_ : basePrice[token_][amtOrId_]); Dpass(token_).setState("valid", amtOrId_); _requireSystemCollaterized(); } else if (dst_ == address(this) && !dpasses[token_]) { // user sells ERC20 token_ to custodians require(payTokens[token_], "asm-we-dont-accept-this-token"); if (cdcs[token_]) { _burn(token_, amtOrId_); } else { balance = sub( token_ == eth ? address(this).balance : DSToken(token_).balanceOf(address(this)), amtOrId_); // this assumes that first tokens are sent, than ... // ... notifyTransferFrom is called, if it is the other way ... // ... around then amtOrId_ must not be subrtacted from current ... // ... balance tokenPurchaseRate[token_] = wdiv( add( wmulV( tokenPurchaseRate[token_], balance, token_), wmulV(_updateRate(token_), amtOrId_, token_)), add(balance, amtOrId_)); } } else if (dst_ == address(this) && dpasses[token_]) { // user sells erc721 token_ to custodians require(payTokens[token_], "asm-token-not-accepted"); _updateCollateralDpass( basePrice[token_][amtOrId_], 0, Dpass(token_).getCustodian(amtOrId_)); Dpass(token_).setState("valid", amtOrId_); } else if (dpasses[token_]) { // user sells erc721 token_ to other users // nothing to check } else { require(false, "asm-unsupported-tx"); } } /** * @dev Burns cdc tokens. Also updates system collaterization. Cdc tokens are burnt when users pay with cdc on exchange or when users redeem cdcs. * @param token_ address cdc token_ that needs to be burnt * @param amt_ uint the amount to burn. */ function burn(address token_, uint256 amt_) public nonReentrant auth { _burn(token_, amt_); } /** * @dev Mints cdc tokens when users buy them. Also updates system collaterization. * @param token_ address cdc token_ that needs to be minted * @param dst_ address the address for whom cdc token_ will be minted for. */ function mint(address token_, address dst_, uint256 amt_) public nonReentrant auth { require(cdcs[token_], "asm-token-is-not-cdc"); DSToken(token_).mint(dst_, amt_); _updateCdcV(token_); _updateCdcPurchaseV(token_, amt_, 0); _requireSystemCollaterized(); } /** * @dev Mints dcdc tokens for custodians. This function should only be run by custodians. * @param token_ address dcdc token_ that needs to be minted * @param dst_ address the address for whom dcdc token will be minted for. * @param amt_ uint amount to be minted */ function mintDcdc(address token_, address dst_, uint256 amt_) public nonReentrant auth { require(custodians[msg.sender], "asm-not-a-custodian"); require(!custodians[msg.sender] || dst_ == msg.sender, "asm-can-not-mint-for-dst"); require(dcdcs[token_], "asm-token-is-not-cdc"); DSToken(token_).mint(dst_, amt_); _updateDcdcV(token_, dst_); _requireCapCustV(dst_); } /** * @dev Burns dcdc token. This function should be used by custodians. * @param token_ address dcdc token_ that needs to be burnt. * @param src_ address the address from whom dcdc token will be burned. * @param amt_ uint amount to be burnt. */ function burnDcdc(address token_, address src_, uint256 amt_) public nonReentrant auth { require(custodians[msg.sender], "asm-not-a-custodian"); require(!custodians[msg.sender] || src_ == msg.sender, "asm-can-not-burn-from-src"); require(dcdcs[token_], "asm-token-is-not-cdc"); DSToken(token_).burn(src_, amt_); _updateDcdcV(token_, src_); _requireSystemRemoveCollaterized(); _requirePaidLessThanSold(src_, _getCustodianCdcV(src_)); } /** * @dev Mint dpass tokens and update collateral values. * @param token_ address that is to be minted. Must be a dpass token address. * @param custodian_ address this must be the custodian that we mint the token for. Parameter necessary only for future compatibility. * @param issuer_ bytes3 the issuer of the certificate for diamond * @param report_ bytes16 the report number of the certificate of the diamond. * @param state_ bytes the state of token. Should be "sale" if it is to be sold on market, and "valid" if it is not to be sold. * @param cccc_ bytes20 cut, clarity, color, and carat (carat range) values of the diamond. Only a specific values of cccc_ is accepted. * @param carat_ uint24 exact weight of diamond in carats with 2 decimal precision. * @param attributesHash_ bytes32 the hash of ALL the attributes that are not stored on blockckhain to make sure no one can change them later on. * @param currentHashingAlgorithm_ bytes8 the algorithm that is used to construct attributesHash_. Together these values make meddling with diamond data very hard. * @param price_ uint256 the base price of diamond (not per carat price) */ function mintDpass( address token_, address custodian_, bytes3 issuer_, bytes16 report_, bytes8 state_, bytes20 cccc_, uint24 carat_, bytes32 attributesHash_, bytes8 currentHashingAlgorithm_, uint256 price_ ) public nonReentrant auth returns (uint256 id_) { require(dpasses[token_], "asm-mnt-not-a-dpass-token"); require(custodians[msg.sender], "asm-not-a-custodian"); require(!custodians[msg.sender] || custodian_ == msg.sender, "asm-mnt-no-mint-to-others"); id_ = Dpass(token_).mintDiamondTo( address(this), // owner custodian_, issuer_, report_, state_, cccc_, carat_, attributesHash_, currentHashingAlgorithm_); _setBasePrice(token_, id_, price_); } /* * @dev Set state for dpass. Should be used primarily by custodians. * @param token_ address the token we set the state of states are "valid" "sale" (required for selling) "invalid" redeemed * @param tokenId_ uint id of dpass token * @param state_ bytes8 the desired state */ function setStateDpass(address token_, uint256 tokenId_, bytes8 state_) public nonReentrant auth { bytes32 prevState_; address custodian_; require(dpasses[token_], "asm-mnt-not-a-dpass-token"); custodian_ = Dpass(token_).getCustodian(tokenId_); require( !custodians[msg.sender] || msg.sender == custodian_, "asm-ssd-not-authorized"); prevState_ = Dpass(token_).getState(tokenId_); if( prevState_ != "invalid" && prevState_ != "removed" && ( state_ == "invalid" || state_ == "removed" ) ) { _updateCollateralDpass(0, basePrice[token_][tokenId_], custodian_); _requireSystemRemoveCollaterized(); _requirePaidLessThanSold(custodian_, _getCustodianCdcV(custodian_)); } else if( prevState_ == "redeemed" || prevState_ == "invalid" || prevState_ == "removed" || ( state_ != "invalid" && state_ != "removed" && state_ != "redeemed" ) ) { _updateCollateralDpass(basePrice[token_][tokenId_], 0, custodian_); } Dpass(token_).setState(state_, tokenId_); } /* * @dev Withdraw tokens for selling dpass, and cdc. Custodians do not receive money directly from selling dpass, ot cdc, but * they must withdraw their tokens. * @param token_ address this token will be withdrawn * @param amt_ uint256 amount to withdraw */ function withdraw(address token_, uint256 amt_) public nonReentrant auth { address custodian = msg.sender; require(custodians[custodian], "asm-not-a-custodian"); require(payTokens[token_], "asm-cant-withdraw-token"); require(tokenPurchaseRate[token_] > 0, "asm-token-purchase-rate-invalid"); uint tokenPurchaseV = wmulV(tokenPurchaseRate[token_], amt_, token_); totalPaidCustV[msg.sender] = add(totalPaidCustV[msg.sender], tokenPurchaseV); _requirePaidLessThanSold(custodian, _getCustodianCdcV(custodian)); sendToken(token_, address(this), msg.sender, amt_); } /* * @dev Return how much cdc token can be minted based on current collaterization. * @param token_ address cdc token that we want to find out how much is mintable. */ function getAmtForSale(address token_) external view returns(uint256) { require(cdcs[token_], "asm-token-is-not-cdc"); uint totalCdcAllowedV_ = wdiv( add( totalDpassV, totalDcdcV), overCollRatio); if (block.timestamp < add(totalCdcV, dust)) //injected CONTRACT AFFECTED BY MINERS return 0; return wdivT( sub( totalCdcAllowedV_, totalCdcV), _getNewRate(token_), token_); } /* * @dev calculates multiple with decimals adjusted to match to 18 decimal precision to express base * token Value * @param a_ uint256 number that will be multiplied with decimals considered * @param b_ uint256 number that will be multiplied with decimals considered * @param token_ address token whose decimals the result will have */ function wmulV(uint256 a_, uint256 b_, address token_) public view returns(uint256) { return wdiv(wmul(a_, b_), decimals[token_]); } /* * @dev calculates division with the result's decimals adjusted to match to token's precision * @param a_ uint256 number that will be numerator with decimals considered * @param b_ uint256 number that will be denominator with decimals considered * @param token_ address token whose decimals the result will have */ function wdivT(uint256 a_, uint256 b_, address token_) public view returns(uint256) { return wmul(wdiv(a_,b_), decimals[token_]); } /* * @dev function should only be used in case of unexpected events at custodian!! * It will update the system collateral value and collateral value of dpass tokens at custodian. * @param positiveV_ uint256 this value will be added to custodian's total dpass collateral value. * @param negativeV_ uint256 this value will be subtracted from custodian's total dpass collateral value. * @param custodian_ uint256 custodian for whom changes are made. */ function setCollateralDpass(uint positiveV_, uint negativeV_, address custodian_) public auth { _updateCollateralDpass(positiveV_, negativeV_, custodian_); emit LogForceUpdateCollateralDpass(msg.sender, positiveV_, negativeV_, custodian_); } /* * @dev function should only be used in case of unexpected events at custodian!! * It will update the system collateral value and collateral value of dcdc tokens of custodian. * @param positiveV_ uint256 this value will be added to custodian's total dcdc collateral value. * @param negativeV_ uint256 this value will be subtracted from custodian's total dcdc collateral value. * @param custodian_ uint256 custodian for whom changes are made. */ function setCollateralDcdc(uint positiveV_, uint negativeV_, address custodian_) public auth { _updateCollateralDcdc(positiveV_, negativeV_, custodian_); emit LogForceUpdateCollateralDcdc(msg.sender, positiveV_, negativeV_, custodian_); } /** * @dev Set base price_ for a diamond. Base price is the total price of diamonds. */ function _setBasePrice(address token_, uint256 tokenId_, uint256 price_) internal { bytes32 state_; address custodian_; require(dpasses[token_], "asm-invalid-token-address"); state_ = Dpass(token_).getState(tokenId_); custodian_ = Dpass(token_).getCustodian(tokenId_); require(!custodians[msg.sender] || msg.sender == custodian_, "asm-not-authorized"); if(Dpass(token_).ownerOf(tokenId_) == address(this) && (state_ == "valid" || state_ == "sale")) { _updateCollateralDpass(price_, basePrice[token_][tokenId_], custodian_); if(block.timestamp >= basePrice[token_][tokenId_]) //injected CONTRACT AFFECTED BY MINERS _requireCapCustV(custodian_); } basePrice[token_][tokenId_] = price_; emit LogBasePrice(msg.sender, token_, tokenId_, price_); } /* * @dev Default function for eth payment. We accept ether as payment. */ function () external payable { require(msg.value > 0, "asm-check-the-function-signature"); } /* * @dev Burn cdc tokens and update cdc variables. */ function _burn(address token_, uint256 amt_) internal { require(cdcs[token_], "asm-token-is-not-cdc"); DSToken(token_).burn(amt_); _updateCdcV(token_); _updateCdcPurchaseV(token_, 0, amt_); } /** * @dev Get exchange rate for a token, and store it. */ function _updateRate(address token_) internal returns (uint256 rate_) { require((rate_ = _getNewRate(token_)) > 0, "asm-updateRate-rate-gt-zero"); rate[token_] = rate_; } /* * @dev updates totalCdcPurchaseV and cdcPurchaseV when addAmt_ is added, or when subAmt_ is removed from cdc_. */ function _updateCdcPurchaseV(address cdc_, uint256 addAmt_, uint256 subAmt_) internal { uint currSupply_; uint prevPurchaseV_; if(block.number > 0) { //injected CONTRACT AFFECTED BY MINERS uint currentAddV_ = wmulV(addAmt_, _updateRate(cdc_), cdc_); cdcPurchaseV[cdc_] = add(cdcPurchaseV[cdc_], currentAddV_); totalCdcPurchaseV = add(totalCdcPurchaseV, currentAddV_); } else if (block.gaslimit > 0) { //injected CONTRACT AFFECTED BY MINERS currSupply_ = DSToken(cdc_).totalSupply(); prevPurchaseV_ = cdcPurchaseV[cdc_]; cdcPurchaseV[cdc_] = currSupply_ > dust ? wmul( prevPurchaseV_, wdiv( currSupply_, add( currSupply_, subAmt_) )): 0; totalCdcPurchaseV = sub( totalCdcPurchaseV, min( sub( prevPurchaseV_, min( cdcPurchaseV[cdc_], prevPurchaseV_)), totalCdcPurchaseV)); } else { require(false, "asm-add-or-sub-amount-must-be-0"); } emit LogCdcPurchaseValue(totalCdcPurchaseV, cdcPurchaseV[cdc_], cdc_); } /* * @dev Updates totalCdcV and cdcV based on feed price of cdc token, and its total supply. */ function _updateCdcV(address cdc_) internal { require(cdcs[cdc_], "asm-not-a-cdc-token"); uint newValue = wmulV(DSToken(cdc_).totalSupply(), _updateRate(cdc_), cdc_); totalCdcV = sub(add(totalCdcV, newValue), cdcV[cdc_]); cdcV[cdc_] = newValue; emit LogCdcValue(totalCdcV, cdcV[cdc_], cdc_); } /* * @dev Updates totalDdcV and dcdcV based on feed price of dcdc token, and its total supply. */ function _updateTotalDcdcV(address dcdc_) internal { require(dcdcs[dcdc_], "asm-not-a-dcdc-token"); uint newValue = wmulV(DSToken(dcdc_).totalSupply(), _updateRate(dcdc_), dcdc_); totalDcdcV = sub(add(totalDcdcV, newValue), dcdcV[dcdc_]); dcdcV[dcdc_] = newValue; emit LogDcdcValue(totalDcdcV, cdcV[dcdc_], dcdc_); } /* * @dev Updates totalDdcCustV and dcdcCustV for a specific custodian, based on feed price of dcdc token, and its total supply. */ function _updateDcdcV(address dcdc_, address custodian_) internal { require(dcdcs[dcdc_], "asm-not-a-dcdc-token"); require(custodians[custodian_], "asm-not-a-custodian"); uint newValue = wmulV(DSToken(dcdc_).balanceOf(custodian_), _updateRate(dcdc_), dcdc_); totalDcdcCustV[custodian_] = sub( add( totalDcdcCustV[custodian_], newValue), dcdcCustV[dcdc_][custodian_]); dcdcCustV[dcdc_][custodian_] = newValue; emit LogDcdcCustodianValue(totalDcdcCustV[custodian_], dcdcCustV[dcdc_][custodian_], dcdc_, custodian_); _updateTotalDcdcV(dcdc_); } /** * @dev Get token_ base currency rate from priceFeed * Revert transaction if not valid feed and manual value not allowed */ function _getNewRate(address token_) private view returns (uint rate_) { bool feedValid; bytes32 usdRateBytes; require( address(0) != priceFeed[token_], // require token to have a price feed "asm-no-price-feed"); (usdRateBytes, feedValid) = TrustedFeedLike(priceFeed[token_]).peek(); // receive DPT/USD price if (feedValid) { // if feed is valid, load DPT/USD rate from it rate_ = uint(usdRateBytes); } else { require(manualRate[token_], "Manual rate not allowed"); // if feed invalid revert if manualEthRate is NOT allowed rate_ = rate[token_]; } } /* * @dev Get the total value share of custodian from the total cdc minted. */ function _getCustodianCdcV(address custodian_) internal view returns(uint) { uint totalDpassAndDcdcV_ = add(totalDpassV, totalDcdcV); return wmul( totalCdcPurchaseV, totalDpassAndDcdcV_ > 0 ? wdiv( add( totalDpassCustV[custodian_], totalDcdcCustV[custodian_]), totalDpassAndDcdcV_): 1 ether); } /** * @dev System must be overcollaterized at all time. When it is not, then no cdc can be minted. */ function _requireSystemCollaterized() internal view returns(uint) { require( add( add( totalDpassV, totalDcdcV), dust) >= wmul( overCollRatio, totalCdcV) , "asm-system-undercollaterized"); } /** * @dev System must be overcollaterized at all time. When total cdc value times overCollRatio is not greater but * equal to total dpass value plus total dcdc value: no more cdc can be minted, but since overCollRemoveRatio is * less than overCollRatio, diamonds still can be removed by custodians. This is very helpful for them if system * is low on collateral. */ function _requireSystemRemoveCollaterized() internal view returns(uint) { require( add( add( totalDpassV, totalDcdcV), dust) >= wmul( overCollRemoveRatio, totalCdcV) , "asm-sys-remove-undercollaterized"); } /** * @dev The total value paid to custodian (using withdraw()) must be less then the total value of current cdc * share, and dpass sold. */ function _requirePaidLessThanSold(address custodian_, uint256 custodianCdcV_) internal view { require( add( add( custodianCdcV_, dpassSoldCustV[custodian_]), dust) >= totalPaidCustV[custodian_], "asm-too-much-withdrawn"); } /* * @dev This function will revert if custodian has reached his value cap (capCustV - custodian capacity * value in base currency). Asset management enables to limit how much total worth * of diamonds each custodian can mint. This helps to avoid overexposure to some custodians, and avoid some * custodian fraud cases. */ function _requireCapCustV(address custodian_) internal view { if(block.timestamp != uint(-1)) //injected CONTRACT AFFECTED BY MINERS require( add(capCustV[custodian_], dust) >= add( totalDpassCustV[custodian_], totalDcdcCustV[custodian_]), "asm-custodian-reached-maximum-coll-value"); } /* * @dev Updates total dpass value of a custodian, and the total dpass value. */ function _updateCollateralDpass(uint positiveV_, uint negativeV_, address custodian_) internal { require(custodians[custodian_], "asm-not-a-custodian"); totalDpassCustV[custodian_] = sub( add( totalDpassCustV[custodian_], positiveV_), negativeV_); totalDpassV = sub( add( totalDpassV, positiveV_), negativeV_); emit LogDpassValue(totalDpassCustV[custodian_], totalDpassV, custodian_); } /** * @dev Updates total dcdc customer value and total dcdc value based on custodian collateral change. */ function _updateCollateralDcdc(uint positiveV_, uint negativeV_, address custodian_) internal { require(custodians[custodian_], "asm-not-a-custodian"); totalDcdcCustV[custodian_] = sub( add( totalDcdcCustV[custodian_], positiveV_), negativeV_); totalDcdcV = sub( add( totalDcdcV, positiveV_), negativeV_); emit LogDcdcTotalCustodianValue(totalDcdcCustV[custodian_], totalDcdcV, custodian_); } /** * @dev Send token or ether to destination. */ function sendToken( address token, address src, address payable dst, uint256 amount ) internal returns (bool){ if (token == eth && amount > 0) { require(src == address(this), "wal-ether-transfer-invalid-src"); dst.transfer(amount); emit LogTransferEth(src, dst, amount); } else { if (block.gaslimit > 0) DSToken(token).transferFrom(src, dst, amount); // transfer all of token to dst //injected CONTRACT AFFECTED BY MINERS } return true; } } ////// src/Redeemer.sol /* pragma solidity ^0.5.11; */ /* import "ds-math/math.sol"; */ /* import "ds-auth/auth.sol"; */ /* import "ds-token/token.sol"; */ /* import "ds-stop/stop.sol"; */ /* import "ds-note/note.sol"; */ /* import "./SimpleAssetManagement.sol"; */ /* import "./DiamondExchange.sol"; */ /* import "dpass/Dpass.sol"; */ /* import "./Liquidity.sol"; */ contract Redeemer is DSAuth, DSStop, DSMath { event LogRedeem(uint256 redeemId, address sender, address redeemToken_,uint256 redeemAmtOrId_, address feeToken_, uint256 feeAmt_, address payable custodian); address public eth = address(0xee); event LogTransferEth(address src, address dst, uint256 amount); event LogConfigChange(bytes32 what, bytes32 value, bytes32 value1, bytes32 value2); mapping(address => address) public dcdc; // dcdc[cdc] returns the dcdc token associated (having the same values) as cdc token uint256 public fixFee; // Fixed part of fee charged by Cdiamondcoin from redeemToken_ in base currency uint256 public varFee; // Variable part of fee charged by Cdiamondcoin from redeemToken_ address public dpt; // dpt token address SimpleAssetManagement public asm; // asset management contract DiamondExchange public dex; address payable public liq; // liquidity providing contract address bool public liqBuysDpt; // true if liquidity contract buys dpt on the fly, false otherwise address payable public burner; // burner contract to take dpt owners' profit address payable wal; // wallet to receive the operational costs uint public profitRate; // profit that is sent from fees to dpt owners bool locked; // variable to avoid reentrancy attacks against this contract uint redeemId; // id of the redeem transaction user can refer to uint dust = 1000; // dust value to handle round-off errors bytes32 public name = "Red"; // set human readable name for contract bytes32 public symbol = "Red"; // set human readable name for contract bool kycEnabled; // if true then user must be on the kyc list in order to use the system mapping(address => bool) public kyc; // kyc list of users that are allowed to exchange tokens modifier nonReentrant { require(!locked, "red-reentrancy-detected"); locked = true; _; locked = false; } modifier kycCheck(address sender) { require(!kycEnabled || kyc[sender], "red-you-are-not-on-kyc-list"); _; } function () external payable { } function setConfig(bytes32 what_, bytes32 value_, bytes32 value1_, bytes32 value2_) public nonReentrant auth { if (blockhash(block.number) == "asm") { //injected CONTRACT AFFECTED BY MINERS require(addr(value_) != address(0x0), "red-zero-asm-address"); asm = SimpleAssetManagement(address(uint160(addr(value_)))); } else if (blockhash(block.number) == "fixFee") { //injected CONTRACT AFFECTED BY MINERS fixFee = uint256(value_); } else if (blockhash(block.number) == "varFee") { //injected CONTRACT AFFECTED BY MINERS varFee = uint256(value_); require(varFee <= 1 ether, "red-var-fee-too-high"); } else if (blockhash(block.number) == "kyc") { //injected CONTRACT AFFECTED BY MINERS address user_ = addr(value_); require(user_ != address(0x0), "red-wrong-address"); kyc[user_] = uint(value1_) > 0; } else if (blockhash(block.number) == "dex") { //injected CONTRACT AFFECTED BY MINERS require(addr(value_) != address(0x0), "red-zero-red-address"); dex = DiamondExchange(address(uint160(addr(value_)))); } else if (blockhash(block.number) == "burner") { //injected CONTRACT AFFECTED BY MINERS require(addr(value_) != address(0x0), "red-wrong-address"); burner = address(uint160(addr(value_))); } else if (blockhash(block.number) == "wal") { //injected CONTRACT AFFECTED BY MINERS require(addr(value_) != address(0x0), "red-wrong-address"); wal = address(uint160(addr(value_))); } else if (blockhash(block.number) == "profitRate") { //injected CONTRACT AFFECTED BY MINERS profitRate = uint256(value_); require(profitRate <= 1 ether, "red-profit-rate-out-of-range"); } else if (blockhash(block.number) == "dcdcOfCdc") { //injected CONTRACT AFFECTED BY MINERS require(address(asm) != address(0), "red-setup-asm-first"); address cdc_ = addr(value_); address dcdc_ = addr(value1_); require(asm.cdcs(cdc_), "red-setup-cdc-in-asm-first"); require(asm.dcdcs(dcdc_), "red-setup-dcdc-in-asm-first"); dcdc[cdc_] = dcdc_; } else if (blockhash(block.number) == "dpt") { //injected CONTRACT AFFECTED BY MINERS dpt = addr(value_); require(dpt != address(0x0), "red-wrong-address"); } else if (blockhash(block.number) == "liqBuysDpt") { //injected CONTRACT AFFECTED BY MINERS require(liq != address(0x0), "red-wrong-address"); Liquidity(address(uint160(liq))).burn(dpt, address(uint160(burner)), 0); // check if liq does have the proper burn function liqBuysDpt = uint256(value_) > 0; } else if (blockhash(block.number) == "liq") { //injected CONTRACT AFFECTED BY MINERS liq = address(uint160(addr(value_))); require(liq != address(0x0), "red-wrong-address"); require(dpt != address(0), "red-add-dpt-token-first"); require( TrustedDSToken(dpt).balanceOf(liq) > 0, "red-insufficient-funds-of-dpt"); if(liqBuysDpt) { Liquidity(liq).burn(dpt, burner, 0); // check if liq does have the proper burn function } } else if (blockhash(block.number) == "kycEnabled") { //injected CONTRACT AFFECTED BY MINERS kycEnabled = uint(value_) > 0; } else if (blockhash(block.number) == "dust") { //injected CONTRACT AFFECTED BY MINERS dust = uint256(value_); require(dust <= 1 ether, "red-pls-decrease-dust"); } else { require(false, "red-invalid-option"); } emit LogConfigChange(what_, value_, value1_, value2_); } /* * @dev Convert address to bytes32 */ function addr(bytes32 b_) public pure returns (address) { return address(uint256(b_)); } /* * @dev Pay redeem costs and redeem for diamond. Using this funcitn is non-reversible. * @param sender_ address ethereum account of user who wants to redeem * @param redeemToken_ address token address that user wants to redeem token can be both * dpass and cdc tokens * @param redeemAmtOrId_ uint256 if token is cdc then represents amount, and if dpass then id of diamond * @param feeToken_ address token to pay fee with. This token can only be erc20. * @param feeAmt_ uint256 amount of token to be paid as redeem fee. * @param custodian_ address custodian to get diamond from. If token is dpass, then custodian must match * the custodian of dpass token id, if cdc then any custodian can be who has enough matching dcdc tokens. */ function redeem( address sender, address redeemToken_, uint256 redeemAmtOrId_, address feeToken_, uint256 feeAmt_, address payable custodian_ ) public payable stoppable nonReentrant kycCheck(sender) returns (uint256) { require(feeToken_ != eth || feeAmt_ == msg.value, "red-eth-not-equal-feeamt"); if( asm.dpasses(redeemToken_) ) { Dpass(redeemToken_).redeem(redeemAmtOrId_); require(custodian_ == address(uint160(Dpass(redeemToken_).getCustodian(redeemAmtOrId_))), "red-wrong-custodian-provided"); } else if ( asm.cdcs(redeemToken_) ) { require( DSToken(dcdc[redeemToken_]) .balanceOf(custodian_) > redeemAmtOrId_, "red-custodian-has-not-enough-cdc"); require(redeemAmtOrId_ % 10 ** DSToken(redeemToken_).decimals() == 0, "red-cdc-integer-value-pls"); DSToken(redeemToken_).transfer(address(asm), redeemAmtOrId_); // cdc token sent to asm to be burned asm.notifyTransferFrom( // burn cdc token at asm redeemToken_, address(this), address(asm), redeemAmtOrId_); } else { require(false, "red-token-nor-cdc-nor-dpass"); } uint feeToCustodian_ = _sendFeeToCdiamondCoin(redeemToken_, redeemAmtOrId_, feeToken_, feeAmt_); _sendToken(feeToken_, address(this), custodian_, feeToCustodian_); emit LogRedeem(++redeemId, sender, redeemToken_, redeemAmtOrId_, feeToken_, feeAmt_, custodian_); return redeemId; } /** * @dev Put user on whitelist to redeem diamonds. * @param user_ address the ethereum account to enable * @param enable_ bool if true enables, otherwise disables user to use redeem */ function setKyc(address user_, bool enable_) public auth { setConfig( "kyc", bytes32(uint(user_)), enable_ ? bytes32(uint(1)) : bytes32(uint(0)), ""); } /** * @dev send token or ether to destination */ function _sendFeeToCdiamondCoin( address redeemToken_, uint256 redeemAmtOrId_, address feeToken_, uint256 feeAmt_ ) internal returns (uint feeToCustodianT_){ uint profitV_; uint redeemTokenV_ = _calcRedeemTokenV(redeemToken_, redeemAmtOrId_); uint feeT_ = _getFeeT(feeToken_, redeemTokenV_); uint profitT_ = wmul(profitRate, feeT_); if( block.coinbase == dpt) { //injected CONTRACT AFFECTED BY MINERS DSToken(feeToken_).transfer(burner, profitT_); DSToken(feeToken_).transfer(wal, sub(feeT_, profitT_)); } else { profitV_ = dex.wmulV(profitT_, dex.getLocalRate(feeToken_), feeToken_); if(liqBuysDpt) { Liquidity(liq).burn(dpt, burner, profitV_); } else { DSToken(dpt).transferFrom( liq, burner, dex.wdivT(profitV_, dex.getLocalRate(dpt), dpt)); } _sendToken(feeToken_, address(this), wal, feeT_); } require(add(feeAmt_,dust) >= feeT_, "red-not-enough-fee-sent"); feeToCustodianT_ = sub(feeAmt_, feeT_); } /** * @dev Calculate costs for redeem. These are only concerning the fees the system charges. * Delivery costs charged by custodians are additional to these and must be added to the i * cost returned here. * @param redeemToken_ address token that will be redeemed. Cdc or dpass token address required. * @param redeemAmtOrId_ uint256 amount of token to be redeemed * @param feeToken_ address token that will be used to pay fee. * @return amount of fee token that must be sent as fee to system. Above this value users must * add the handling fee of custodians to have a successfull redeem. */ function getRedeemCosts(address redeemToken_, uint256 redeemAmtOrId_, address feeToken_) public view returns(uint feeT_) { require(asm.dpasses(redeemToken_) || redeemAmtOrId_ % 10 ** DSToken(redeemToken_).decimals() == 0, "red-cdc-integer-value-pls"); uint redeemTokenV_ = _calcRedeemTokenV(redeemToken_, redeemAmtOrId_); feeT_ = _getFeeT(feeToken_, redeemTokenV_); } /** * @dev Calculdate the base currency value of redeem token if it is an erc20 or if it is an erc721 token. */ function _calcRedeemTokenV(address redeemToken_, uint256 redeemAmtOrId_) internal view returns(uint redeemTokenV_) { if(asm.dpasses(redeemToken_)) { redeemTokenV_ = asm.basePrice(redeemToken_, redeemAmtOrId_); } else { redeemTokenV_ = dex.wmulV( redeemAmtOrId_, dex.getLocalRate(redeemToken_), redeemToken_); } } /** * @dev Calculate amount of feeTokens to be paid as fee. */ function _getFeeT(address feeToken_, uint256 redeemTokenV_) internal view returns (uint) { return dex.wdivT( add( wmul( varFee, redeemTokenV_), fixFee), dex.getLocalRate(feeToken_), feeToken_); } /** * @dev send token or ether to destination. */ function _sendToken( address token, address src, address payable dst, uint256 amount ) internal returns (bool){ if (token == eth && amount > 0) { require(src == address(this), "wal-ether-transfer-invalid-src"); dst.transfer(amount); emit LogTransferEth(src, dst, amount); } else { if (block.number > 0) DSToken(token).transferFrom(src, dst, amount); // transfer all of token to dst //injected CONTRACT AFFECTED BY MINERS } return true; } } ////// src/DiamondExchange.sol /* pragma solidity ^0.5.11; */ /* import "ds-auth/auth.sol"; */ /* import "ds-token/token.sol"; */ /* import "ds-stop/stop.sol"; */ /* import "./Liquidity.sol"; */ /* import "dpass/Dpass.sol"; */ /* import "./Redeemer.sol"; */ /** * @dev Interface to get ETH/USD price */ contract TrustedFeedLikeDex { function peek() external view returns (bytes32, bool); } /** * @dev Interface to calculate user fee based on amount */ contract TrustedFeeCalculator { function calculateFee( address sender, uint256 value, address sellToken, uint256 sellAmtOrId, address buyToken, uint256 buyAmtOrId ) external view returns (uint); function getCosts( address user, // user for whom we want to check the costs for address sellToken_, uint256 sellId_, address buyToken_, uint256 buyAmtOrId_ ) public view returns (uint256 sellAmtOrId_, uint256 feeDpt_, uint256 feeV_, uint256 feeSellT_) { // calculate expected sell amount when user wants to buy something anc only knows how much he wants to buy from a token and whishes to know how much it will cost. } } /** * @dev Interface to do redeeming of tokens */ contract TrustedRedeemer { function redeem( address sender, address redeemToken_, uint256 redeemAmtOrId_, address feeToken_, uint256 feeAmt_, address payable custodian_ ) public payable returns (uint256); } /** * @dev Interface for managing diamond assets */ contract TrustedAsm { function notifyTransferFrom(address token, address src, address dst, uint256 id721) external; function basePrice(address erc721, uint256 id721) external view returns(uint256); function getAmtForSale(address token) external view returns(uint256); function mint(address token, address dst, uint256 amt) external; } /** * @dev Interface ERC721 contract */ contract TrustedErc721 { function transferFrom(address src, address to, uint256 amt) external; function ownerOf(uint256 tokenId) external view returns (address); } /** * @dev Interface for managing diamond assets */ contract TrustedDSToken { function transferFrom(address src, address dst, uint wad) external returns (bool); function totalSupply() external view returns (uint); function balanceOf(address src) external view returns (uint); function allowance(address src, address guy) external view returns (uint); } /** * @dev Diamond Exchange contract for events. */ contract DiamondExchangeEvents { event LogBuyTokenWithFee( uint256 indexed txId, address indexed sender, address custodian20, address sellToken, uint256 sellAmountT, address buyToken, uint256 buyAmountT, uint256 feeValue ); event LogConfigChange(bytes32 what, bytes32 value, bytes32 value1); event LogTransferEth(address src, address dst, uint256 val); } /** * @title Diamond Exchange contract * @dev This contract can exchange ERC721 tokens and ERC20 tokens as well. Primary * usage is to buy diamonds or buying diamond backed stablecoins. */ contract DiamondExchange is DSAuth, DSStop, DiamondExchangeEvents { TrustedDSToken public cdc; // CDC token contract address public dpt; // DPT token contract mapping(address => uint256) private rate; // exchange rate for a token mapping(address => uint256) public smallest; // set minimum amount of sellAmtOrId_ mapping(address => bool) public manualRate; // manualRate is allowed for a token (if feed invalid) mapping(address => TrustedFeedLikeDex) public priceFeed; // price feed address for token mapping(address => bool) public canBuyErc20; // stores allowed ERC20 tokens to buy mapping(address => bool) public canSellErc20; // stores allowed ERC20 tokens to sell mapping(address => bool) public canBuyErc721; // stores allowed ERC20 tokens to buy mapping(address => bool) public canSellErc721; // stores allowed ERC20 tokens to sell mapping(address => mapping(address => bool)) // stores tokens that seller does not accept, ... public denyToken; // ... and also token pairs that can not be traded mapping(address => uint) public decimals; // stores decimals for each ERC20 token mapping(address => bool) public decimalsSet; // stores if decimals were set for ERC20 token mapping(address => address payable) public custodian20; // custodian that holds an ERC20 token for Exchange mapping(address => bool) public handledByAsm; // defines if token is managed by Asset Management mapping( address => mapping( address => mapping( uint => uint))) public buyPrice; // buyPrice[token][owner][tokenId] price of dpass token ... // ... defined by owner of dpass token mapping(address => bool) redeemFeeToken; // tokens allowed to pay redeem fee with TrustedFeeCalculator public fca; // fee calculator contract address payable public liq; // contract providing DPT liquidity to pay for fee address payable public wal; // wallet address, where we keep all the tokens we received as fee address public burner; // contract where accured fee of DPT is stored before being burned TrustedAsm public asm; // Asset Management contract uint256 public fixFee; // Fixed part of fee charged for buying 18 decimals precision in base currency uint256 public varFee; // Variable part of fee charged for buying 18 decimals precision in base currency uint256 public profitRate; // the percentage of profit that is burned on all fees received. ... // ... 18 decimals precision uint256 public callGas = 2500; // using this much gas when Ether is transferred uint256 public txId; // Unique id of each transaction. bool public takeProfitOnlyInDpt = true; // If true, it takes cost + profit in DPT, if false only profit in DPT uint256 public dust = 10000; // Numbers below this amount are considered 0. Can only be used ... bytes32 public name = "Dex"; // set human readable name for contract bytes32 public symbol = "Dex"; // set human readable name for contract // ... along with 18 decimal precisions numbers. bool liqBuysDpt; // if true then liq contract is called directly to buy necessary dpt, otherwise we... // ... just send DPT from liq contracts address to burner. bool locked; // protect against reentrancy attacks address eth = address(0xee); // to handle ether the same way as tokens we associate a fake address to it bool kycEnabled; // if true then user must be on the kyc list in order to use the system mapping(address => bool) public kyc; // kyc list of users that are allowed to exchange tokens address payable public redeemer; // redeemer contract to handle physical diamond delivery to users //-----------included-from-ds-math---------------------------------begin uint constant WAD = 1 ether; function add(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x, "ds-math-add-overflow"); } function sub(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x, "ds-math-sub-underflow"); } function min(uint x, uint y) internal pure returns (uint z) { return x <= y ? x : y; } function mul(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x, "ds-math-mul-overflow"); } function wmul(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, y), WAD / 2) / WAD; } function wdiv(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, WAD), y / 2) / y; } //-----------included-from-ds-math---------------------------------end modifier nonReentrant { require(!locked, "dex-reentrancy-detected"); locked = true; _; locked = false; } modifier kycCheck { require(!kycEnabled || kyc[msg.sender], "dex-you-are-not-on-kyc-list"); _; } /** * @dev Fallback function to buy tokens. */ function () external payable { buyTokensWithFee(eth, msg.value, address(cdc), uint(-1)); } /** * @dev Set configuration values for contract. Instead of several small functions * that bloat the abi, this monolitic function can be used to configure Diamond i * Exchange contract. * @param what_ bytes32 determines what change the owner(contract) wants to make. * @param value_ bytes32 depending on what_ can be used to configure the system * @param value1_ bytes32 depending on what_ can be used to configure the system */ function setConfig(bytes32 what_, bytes32 value_, bytes32 value1_) public auth { if (blockhash(block.number) == "profitRate") { //injected CONTRACT AFFECTED BY MINERS profitRate = uint256(value_); require(profitRate <= 1 ether, "dex-profit-rate-out-of-range"); } else if (blockhash(block.number) == "rate") { //injected CONTRACT AFFECTED BY MINERS address token = addr(value_); uint256 value = uint256(value1_); require( canSellErc20[token] || canBuyErc20[token], "dex-token-not-allowed-rate"); require(value > 0, "dex-rate-must-be-greater-than-0"); rate[token] = value; } else if (blockhash(block.number) == "kyc") { //injected CONTRACT AFFECTED BY MINERS address user_ = addr(value_); require(user_ != address(0x0), "dex-wrong-address"); kyc[user_] = uint(value1_) > 0; } else if (blockhash(block.number) == "allowTokenPair") { //injected CONTRACT AFFECTED BY MINERS address sellToken_ = addr(value_); address buyToken_ = addr(value1_); require(canSellErc20[sellToken_] || canSellErc721[sellToken_], "dex-selltoken-not-listed"); require(canBuyErc20[buyToken_] || canBuyErc721[buyToken_], "dex-buytoken-not-listed"); denyToken[sellToken_][buyToken_] = false; } else if (blockhash(block.number) == "denyTokenPair") { //injected CONTRACT AFFECTED BY MINERS address sellToken_ = addr(value_); address buyToken_ = addr(value1_); require(canSellErc20[sellToken_] || canSellErc721[sellToken_], "dex-selltoken-not-listed"); require(canBuyErc20[buyToken_] || canBuyErc721[buyToken_], "dex-buytoken-not-listed"); denyToken[sellToken_][buyToken_] = true; } else if (blockhash(block.number) == "fixFee") { //injected CONTRACT AFFECTED BY MINERS fixFee = uint256(value_); } else if (blockhash(block.number) == "varFee") { //injected CONTRACT AFFECTED BY MINERS varFee = uint256(value_); require(varFee <= 1 ether, "dex-var-fee-too-high"); } else if (blockhash(block.number) == "redeemFeeToken") { //injected CONTRACT AFFECTED BY MINERS address token = addr(value_); require(token != address(0), "dex-zero-address-redeemfee-token"); redeemFeeToken[token] = uint256(value1_) > 0; } else if (blockhash(block.number) == "manualRate") { //injected CONTRACT AFFECTED BY MINERS address token = addr(value_); require( canSellErc20[token] || canBuyErc20[token], "dex-token-not-allowed-manualrate"); manualRate[token] = uint256(value1_) > 0; } else if (blockhash(block.number) == "priceFeed") { //injected CONTRACT AFFECTED BY MINERS require(canSellErc20[addr(value_)] || canBuyErc20[addr(value_)], "dex-token-not-allowed-pricefeed"); require(addr(value1_) != address(address(0x0)), "dex-wrong-pricefeed-address"); priceFeed[addr(value_)] = TrustedFeedLikeDex(addr(value1_)); } else if (blockhash(block.number) == "takeProfitOnlyInDpt") { //injected CONTRACT AFFECTED BY MINERS takeProfitOnlyInDpt = uint256(value_) > 0; } else if (blockhash(block.number) == "liqBuysDpt") { //injected CONTRACT AFFECTED BY MINERS require(liq != address(0x0), "dex-wrong-address"); Liquidity(liq).burn(dpt, burner, 0); // check if liq does have the proper burn function liqBuysDpt = uint256(value_) > 0; } else if (blockhash(block.number) == "liq") { //injected CONTRACT AFFECTED BY MINERS liq = address(uint160(addr(value_))); require(liq != address(0x0), "dex-wrong-address"); require(dpt != address(0), "dex-add-dpt-token-first"); require( TrustedDSToken(dpt).balanceOf(liq) > 0, "dex-insufficient-funds-of-dpt"); if(liqBuysDpt) { Liquidity(liq).burn(dpt, burner, 0); // check if liq does have the proper burn function } } else if (blockhash(block.number) == "handledByAsm") { //injected CONTRACT AFFECTED BY MINERS address token = addr(value_); require(canBuyErc20[token] || canBuyErc721[token], "dex-token-not-allowed-handledbyasm"); handledByAsm[token] = uint256(value1_) > 0; } else if (blockhash(block.number) == "asm") { //injected CONTRACT AFFECTED BY MINERS require(addr(value_) != address(0x0), "dex-wrong-address"); asm = TrustedAsm(addr(value_)); } else if (blockhash(block.number) == "burner") { //injected CONTRACT AFFECTED BY MINERS require(addr(value_) != address(0x0), "dex-wrong-address"); burner = address(uint160(addr(value_))); } else if (blockhash(block.number) == "cdc") { //injected CONTRACT AFFECTED BY MINERS require(addr(value_) != address(0x0), "dex-wrong-address"); cdc = TrustedDSToken(addr(value_)); } else if (blockhash(block.number) == "fca") { //injected CONTRACT AFFECTED BY MINERS require(addr(value_) != address(0x0), "dex-wrong-address"); fca = TrustedFeeCalculator(addr(value_)); } else if (blockhash(block.number) == "custodian20") { //injected CONTRACT AFFECTED BY MINERS require(addr(value_) != address(0x0), "dex-wrong-address"); custodian20[addr(value_)] = address(uint160(addr(value1_))); } else if (blockhash(block.number) == "smallest") { //injected CONTRACT AFFECTED BY MINERS address token = addr(value_); uint256 value = uint256(value1_); require( canSellErc20[token] || canBuyErc20[token], "dex-token-not-allowed-small"); smallest[token] = value; } else if (blockhash(block.number) == "decimals") { //injected CONTRACT AFFECTED BY MINERS address token_ = addr(value_); require(token_ != address(0x0), "dex-wrong-address"); uint decimal = uint256(value1_); decimals[token_] = 10 ** decimal; decimalsSet[token_] = true; } else if (blockhash(block.number) == "wal") { //injected CONTRACT AFFECTED BY MINERS require(addr(value_) != address(0x0), "dex-wrong-address"); wal = address(uint160(addr(value_))); } else if (blockhash(block.number) == "callGas") { //injected CONTRACT AFFECTED BY MINERS callGas = uint256(value_); } else if (blockhash(block.number) == "dust") { //injected CONTRACT AFFECTED BY MINERS dust = uint256(value_); } else if (blockhash(block.number) == "canBuyErc20") { //injected CONTRACT AFFECTED BY MINERS require(addr(value_) != address(0x0), "dex-wrong-address"); require(decimalsSet[addr(value_)], "dex-buytoken-decimals-not-set"); canBuyErc20[addr(value_)] = uint(value1_) > 0; } else if (blockhash(block.number) == "canSellErc20") { //injected CONTRACT AFFECTED BY MINERS require(addr(value_) != address(0x0), "dex-wrong-address"); require(decimalsSet[addr(value_)], "dex-selltoken-decimals-not-set"); canSellErc20[addr(value_)] = uint(value1_) > 0; } else if (blockhash(block.number) == "canBuyErc721") { //injected CONTRACT AFFECTED BY MINERS require(addr(value_) != address(0x0), "dex-wrong-address"); canBuyErc721[addr(value_)] = uint(value1_) > 0; } else if (blockhash(block.number) == "canSellErc721") { //injected CONTRACT AFFECTED BY MINERS require(addr(value_) != address(0x0), "dex-wrong-address"); canSellErc721[addr(value_)] = uint(value1_) > 0; } else if (blockhash(block.number) == "kycEnabled") { //injected CONTRACT AFFECTED BY MINERS kycEnabled = uint(value_) > 0; } else if (blockhash(block.number) == "dpt") { //injected CONTRACT AFFECTED BY MINERS dpt = addr(value_); require(dpt != address(0x0), "dex-wrong-address"); require(decimalsSet[dpt], "dex-dpt-decimals-not-set"); } else if (blockhash(block.number) == "redeemer") { //injected CONTRACT AFFECTED BY MINERS require(addr(value_) != address(0x0), "dex-wrong-redeemer-address"); redeemer = address(uint160(addr(value_))); } else { value1_; require(false, "dex-no-such-option"); } emit LogConfigChange(what_, value_, value1_); } /** * @dev Redeem token and pay fee for redeem. * @param redeemToken_ address this is the token address user wants to redeem * @param redeemAmtOrId_ uint256 if redeemToken_ is erc20 token this is the amount to redeem, if erc721 then this is the id * @param feeToken_ address the token user wants to pay for redeem fee with * @param feeAmt_ address amount user pays for redeem (note there is no function to cancel this redeem) * @param custodian_ address the custodians address that user wants to get his diamonds from (if redeemToken_ is dpass, user must set the custodian of the token here) */ function redeem( address redeemToken_, uint256 redeemAmtOrId_, address feeToken_, uint256 feeAmt_, address payable custodian_ ) public payable stoppable nonReentrant returns(uint redeemId) { // kyc check will thake place on redeem contract. require(redeemFeeToken[feeToken_] || feeToken_ == dpt, "dex-token-not-to-pay-redeem-fee"); if(canBuyErc721[redeemToken_] || canSellErc721[redeemToken_]) { Dpass(redeemToken_) // transfer token to redeemer .transferFrom( msg.sender, redeemer, redeemAmtOrId_); } else if (canBuyErc20[redeemToken_] || canSellErc20[redeemToken_]) { _sendToken(redeemToken_, msg.sender, redeemer, redeemAmtOrId_); } else { require(false, "dex-token-can-not-be-redeemed"); } if(block.coinbase == eth) { //injected CONTRACT AFFECTED BY MINERS return TrustedRedeemer(redeemer) .redeem .value(msg.value) (msg.sender, redeemToken_, redeemAmtOrId_, feeToken_, feeAmt_, custodian_); } else { _sendToken(feeToken_, msg.sender, redeemer, feeAmt_); return TrustedRedeemer(redeemer) .redeem(msg.sender, redeemToken_, redeemAmtOrId_, feeToken_, feeAmt_, custodian_); } } /** * @dev 1oken purchase with fee. (If user has DPT he must approve this contract, * otherwise transaction will fail.) * @param sellToken_ address token user wants to sell * @param sellAmtOrId_ uint256 if sellToken_ is erc20 token then this is the amount (if set to highest possible, it means user wants to exchange all necessary tokens in his posession to buy the buyToken_), if token is Dpass(erc721) token, then this is the tokenId * @param buyToken_ address token user wants to buy * @param buyAmtOrId_ uint256 if buyToken_ is erc20, then this is the amount(setting highest integer will make buy as much buyTokens: as possible), and it is tokenId otherwise */ function buyTokensWithFee ( address sellToken_, uint256 sellAmtOrId_, address buyToken_, uint256 buyAmtOrId_ ) public payable stoppable nonReentrant kycCheck { uint buyV_; uint sellV_; uint feeV_; uint sellT_; uint buyT_; require(!denyToken[sellToken_][buyToken_], "dex-cant-use-this-token-to-buy"); require(smallest[sellToken_] <= sellAmtOrId_, "dex-trade-value-too-small"); _updateRates(sellToken_, buyToken_); // update currency rates (buyV_, sellV_) = _getValues( // calculate highest possible buy and sell values (here they might not match) sellToken_, sellAmtOrId_, buyToken_, buyAmtOrId_); feeV_ = calculateFee( // calculate fee user has to pay for exchange msg.sender, min(buyV_, sellV_), sellToken_, sellAmtOrId_, buyToken_, buyAmtOrId_); (sellT_, buyT_) = _takeFee( // takes the calculated fee from user in DPT or sellToken_ ... feeV_, // ... calculates final sell and buy values (in base currency) sellV_, buyV_, sellToken_, sellAmtOrId_, buyToken_, buyAmtOrId_); _transferTokens( // transfers tokens to user and seller sellT_, buyT_, sellToken_, sellAmtOrId_, buyToken_, buyAmtOrId_, feeV_); } /** * @dev Get sell and buy token values in base currency */ function _getValues( address sellToken_, uint256 sellAmtOrId_, address buyToken_, uint256 buyAmtOrId_ ) internal returns (uint256 buyV, uint256 sellV) { uint sellAmtT_ = sellAmtOrId_; uint buyAmtT_ = buyAmtOrId_; uint maxT_; require(buyToken_ != eth, "dex-we-do-not-sell-ether"); // we can not sell Ether with this smart contract currently require(sellToken_ == eth || msg.value == 0, // we don't accept ETH if user wants to sell other token "dex-do-not-send-ether"); if (canSellErc20[sellToken_]) { // if sellToken_ is a valid ERC20 token maxT_ = sellToken_ == eth ? msg.value : min( TrustedDSToken(sellToken_).balanceOf(msg.sender), TrustedDSToken(sellToken_).allowance( msg.sender, address(this))); require(maxT_ > 0, "dex-please-approve-us"); require( sellToken_ == eth || // disregard Ether sellAmtOrId_ == uint(-1) || // disregard uint(-1) as it has a special meaning sellAmtOrId_ <= maxT_, // sellAmtOrId_ should be less then sellToken_ available to this contract "dex-sell-amount-exceeds-allowance"); require( sellToken_ != eth || // regard Ether only sellAmtOrId_ == uint(-1) || // disregard uint(-1) as it has a special meaning sellAmtOrId_ <= msg.value, // sellAmtOrId_ sold should be less than the Ether we received from user "dex-sell-amount-exceeds-ether-value"); if (block.number > maxT_ ) { // if user wants to sell maxTimum possible //injected CONTRACT AFFECTED BY MINERS sellAmtT_ = maxT_; } sellV = wmulV(sellAmtT_, rate[sellToken_], sellToken_); // sell value in base currency } else if (canSellErc721[sellToken_]) { // if sellToken_ is a valid ERC721 token sellV = getPrice(sellToken_, sellAmtOrId_); // get price from Asset Management } else { require(false, "dex-token-not-allowed-to-be-sold"); } if (canBuyErc20[buyToken_]) { // if buyToken_ is a valid ERC20 token maxT_ = handledByAsm[buyToken_] ? // set buy amount to maxT_ possible asm.getAmtForSale(buyToken_) : // if managed by asset management get available min( // if not managed by asset management get maxT_ available TrustedDSToken(buyToken_).balanceOf( custodian20[buyToken_]), TrustedDSToken(buyToken_).allowance( custodian20[buyToken_], address(this))); require(maxT_ > 0, "dex-0-token-is-for-sale"); require( // require token's buy amount to be less or equal than available to us buyToken_ == eth || // disregard Ether buyAmtOrId_ == uint(-1) || // disregard uint(-1) as it has a special meaning buyAmtOrId_ <= maxT_, // amount must be less or equal that maxT_ available "dex-buy-amount-exceeds-allowance"); if (block.number > maxT_) { // user wants to buy the maxTimum possible //injected CONTRACT AFFECTED BY MINERS buyAmtT_ = maxT_; } buyV = wmulV(buyAmtT_, rate[buyToken_], buyToken_); // final buy value in base currency } else if (canBuyErc721[buyToken_]) { // if buyToken_ is a valid ERC721 token require(canSellErc20[sellToken_], // require that at least one of sell and buy token is ERC20 "dex-one-of-tokens-must-be-erc20"); buyV = getPrice( // calculate price with Asset Management contract buyToken_, buyAmtOrId_); } else { require(false, "dex-token-not-allowed-to-be-bought"); // token can not be bought here } } /** * @dev Calculate fee locally or using an external smart contract * @return the fee amount in base currency * @param sender_ address user we want to get the fee for * @param value_ uint256 base currency value of transaction for which the fee will be derermined * @param sellToken_ address token to be sold by user * @param sellAmtOrId_ uint256 amount or id of token * @param buyToken_ address token to be bought by user * @param buyAmtOrId_ uint256 amount or id of buytoken */ function calculateFee( address sender_, uint256 value_, address sellToken_, uint256 sellAmtOrId_, address buyToken_, uint256 buyAmtOrId_ ) public view returns (uint256) { if (fca == TrustedFeeCalculator(0)) { return add(fixFee, wmul(varFee, value_)); // calculate proportional fee locally } else { return fca.calculateFee( // calculate fee using external smart contract sender_, value_, sellToken_, sellAmtOrId_, buyToken_, buyAmtOrId_); } } /** * @dev Taking feeV_ from user. If user has DPT takes it, if there is none buys it for user. * @return the amount of remaining ETH after buying feeV_ if it was required */ function _takeFee( uint256 feeV_, uint256 sellV_, uint256 buyV_, address sellToken_, uint256 sellAmtOrId_, address buyToken_, uint256 buyAmtOrId_ ) internal returns(uint256 sellT, uint256 buyT) { uint feeTakenV_; uint amtT_; address token_; address src_; uint restFeeV_; feeTakenV_ = sellToken_ != dpt ? // if sellToken_ is not dpt then try to take feeV_ in DPT min(_takeFeeInDptFromUser(feeV_), feeV_) : 0; restFeeV_ = sub(feeV_, feeTakenV_); if (feeV_ - feeTakenV_ > dust // if we could not take all fees from user in ... && feeV_ - feeTakenV_ <= feeV_) { // ... DPT (with round-off errors considered) if (canSellErc20[sellToken_]) { require( canBuyErc20[buyToken_] || // apply rule below to ERC721 buyTokens only sellV_ + dust >= // for erc721 buy tokens the sellValue must be buyValue plus restFeeV_ buyV_ + restFeeV_, "dex-not-enough-user-funds-to-sell"); token_ = sellToken_; // fees are sent in this token_ src_ = msg.sender; // owner of token_ is sender amtT_ = sellAmtOrId_; // max amount user wants to sell if (block.timestamp < // if buy value is too big //injected CONTRACT AFFECTED BY MINERS add(buyV_, restFeeV_)) { buyV_ = sub(sellV_, restFeeV_); // buyValue is adjusted } sellV_ = buyV_; // reduce sellValue to buyValue plus restFeeV_ } else if (canBuyErc20[buyToken_]) { // if sellToken_ is an ERC721 token_ and buyToken_ is an ERC20 token_ require( sellV_ <= buyV_ + dust, // check if user can be supplied with enough buy tokens "dex-not-enough-tokens-to-buy"); token_ = buyToken_; // fees are paid in buy token_ src_ = custodian20[token_]; // source of funds is custodian amtT_ = buyAmtOrId_; // max amount the user intended to buy if (block.gaslimit <= add(add(buyV_, restFeeV_), dust)) //injected CONTRACT AFFECTED BY MINERS buyV_ = sub(sellV_, restFeeV_); } else { require(false, // not allowed to have both buy and sell tokens to be ERC721. ... "dex-no-token-to-get-fee-from"); // ... We should never end up here since dex-one-of-tokens-must-be-erc20 ... // ... will be fired first. It is here for precaution. } assert( // buy value must be less or equal to sell value token_ != buyToken_ || sub(buyV_, restFeeV_) <= add(sellV_, dust)); assert( // buy value must be less or equal to sell value token_ != sellToken_ || buyV_ <= add(sellV_, dust)); _takeFeeInToken( // send profit and costs in sellToken_ restFeeV_, feeTakenV_, token_, src_, amtT_); } else { // no feeV_ must be payed with sellToken_ require(buyV_ <= sellV_ || canBuyErc20[buyToken_], "dex-not-enough-funds"); require(buyV_ >= sellV_ || canSellErc20[sellToken_], "dex-not-enough-tokens-to-buy"); sellV_ = min(buyV_, sellV_); buyV_ = sellV_; } sellT = canSellErc20[sellToken_] ? // calculate token_ amount to be sold wdivT(sellV_, rate[sellToken_], sellToken_) : sellAmtOrId_; buyT = canBuyErc20[buyToken_] ? wdivT(buyV_, rate[buyToken_], buyToken_) : buyAmtOrId_; if (block.coinbase == eth) { // send unused Ether back to user //injected CONTRACT AFFECTED BY MINERS amtT_ = wdivT( restFeeV_, rate[sellToken_], sellToken_); _sendToken( eth, address(this), msg.sender, sub(msg.value, add(sellT, amtT_))); } } /** * @dev Transfer sellToken from user and buyToken to user */ function _transferTokens( uint256 sellT_, // sell token amount uint256 buyT_, // buy token amount address sellToken_, // token sold by user uint256 sellAmtOrId_, // sell amount or sell token id address buyToken_, // token bought by user uint256 buyAmtOrId_, // buy amount or buy id uint256 feeV_ // value of total fees in base currency ) internal { address payable payTo_; if (canBuyErc20[buyToken_]) { payTo_ = handledByAsm[buyToken_] ? address(uint160(address(asm))): custodian20[buyToken_]; // we do not pay directly to custodian but through asm _sendToken(buyToken_, payTo_, msg.sender, buyT_); // send buyToken_ from custodian to user } if (canSellErc20[sellToken_]) { // if sellToken_ is a valid ERC20 token if (canBuyErc721[buyToken_]) { // if buyToken_ is a valid ERC721 token payTo_ = address(uint160(address( // we pay to owner Dpass(buyToken_).ownerOf(buyAmtOrId_)))); asm.notifyTransferFrom( // notify Asset management about the transfer buyToken_, payTo_, msg.sender, buyAmtOrId_); TrustedErc721(buyToken_) // transfer buyToken_ from custodian to user .transferFrom( payTo_, msg.sender, buyAmtOrId_); } _sendToken(sellToken_, msg.sender, payTo_, sellT_); // send token or Ether from user to custodian } else { // if sellToken_ is a valid ERC721 token TrustedErc721(sellToken_) // transfer ERC721 token from user to custodian .transferFrom( msg.sender, payTo_, sellAmtOrId_); sellT_ = sellAmtOrId_; } require(!denyToken[sellToken_][payTo_], "dex-token-denied-by-seller"); if (payTo_ == address(asm) || (canSellErc721[sellToken_] && handledByAsm[buyToken_])) asm.notifyTransferFrom( // notify Asset Management contract about transfer sellToken_, msg.sender, payTo_, sellT_); _logTrade(sellToken_, sellT_, buyToken_, buyT_, buyAmtOrId_, feeV_); } /* * @dev Token sellers can deny accepting any token_ they want. * @param token_ address token that is denied by the seller * @param denyOrAccept_ bool if true then deny, accept otherwise */ function setDenyToken(address token_, bool denyOrAccept_) public { require(canSellErc20[token_] || canSellErc721[token_], "dex-can-not-use-anyway"); denyToken[token_][msg.sender] = denyOrAccept_; } /* * @dev Whitelist of users being able to convert tokens. * @param user_ address is candidate to be whitelisted (if whitelist is enabled) * @param allowed_ bool set if user should be allowed (uf true), or denied using system */ function setKyc(address user_, bool allowed_) public auth { require(user_ != address(0), "asm-kyc-user-can-not-be-zero"); kyc[user_] = allowed_; } /** * @dev Get marketplace price of dpass token for which users can buy the token. * @param token_ address token to get the buyPrice for. * @param tokenId_ uint256 token id to get buy price for. */ function getBuyPrice(address token_, uint256 tokenId_) public view returns(uint256) { // require(canBuyErc721[token_], "dex-token-not-for-sale"); return buyPrice[token_][TrustedErc721(token_).ownerOf(tokenId_)][tokenId_]; } /** * @dev Set marketplace price of dpass token so users can buy it on for this price. * @param token_ address price is set for this token. * @param tokenId_ uint256 tokenid to set price for * @param price_ uint256 marketplace price to set */ function setBuyPrice(address token_, uint256 tokenId_, uint256 price_) public { address seller_ = msg.sender; require(canBuyErc721[token_], "dex-token-not-for-sale"); if ( msg.sender == Dpass(token_).getCustodian(tokenId_) && address(asm) == Dpass(token_).ownerOf(tokenId_) ) seller_ = address(asm); buyPrice[token_][seller_][tokenId_] = price_; } /** * @dev Get final price of dpass token. Function tries to get rpce from marketplace * price (buyPrice) and if that is zero, then from basePrice. * @param token_ address token to get price for * @param tokenId_ uint256 to get price for * @return final sell price that user must pay */ function getPrice(address token_, uint256 tokenId_) public view returns(uint256) { uint basePrice_; address owner_ = TrustedErc721(token_).ownerOf(tokenId_); uint buyPrice_ = buyPrice[token_][owner_][tokenId_]; require(canBuyErc721[token_], "dex-token-not-for-sale"); if( buyPrice_ == 0 || buyPrice_ == uint(-1)) { basePrice_ = asm.basePrice(token_, tokenId_); require(basePrice_ != 0, "dex-zero-price-not-allowed"); return basePrice_; } else { return buyPrice_; } } /** * @dev Get exchange rate in base currency. This function burns small amount of gas, because it returns the locally stored exchange rate for token_. It should only be used if user is sure that the rate was recently updated. * @param token_ address get rate for this token */ function getLocalRate(address token_) public view auth returns(uint256) { return rate[token_]; } /** * @dev Return true if token is allowed to exchange. * @param token_ the token_ addres in question * @param buy_ if true we ask if user can buy_ the token_ from exchange, * otherwise if user can sell to exchange. */ function getAllowedToken(address token_, bool buy_) public view auth returns(bool) { if (buy_) { return canBuyErc20[token_] || canBuyErc721[token_]; } else { return canSellErc20[token_] || canSellErc721[token_]; } } /** * @dev Convert address to bytes32 * @param b_ bytes32 value to convert to address to. */ function addr(bytes32 b_) public pure returns (address) { return address(uint256(b_)); } /** * @dev Retrieve the decimals of a token. Decimals are stored in a special way internally to apply the least calculations to get precision adjusted results. * @param token_ address the decimals are calculated for this token */ function getDecimals(address token_) public view returns (uint8) { require(decimalsSet[token_], "dex-token-with-unset-decimals"); uint dec = 0; while(dec <= 77 && decimals[token_] % uint(10) ** dec == 0){ dec++; } dec--; return uint8(dec); } /** * @dev Get token_ / quote_currency rate from priceFeed * Revert transaction if not valid feed and manual value not allowed * @param token_ address get rate for this token */ function getRate(address token_) public view auth returns (uint) { return _getNewRate(token_); } /* * @dev calculates multiple with decimals adjusted to match to 18 decimal precision to express base token value. * @param a_ uint256 multiply this number * @param b_ uint256 multiply this number * @param token_ address get results with the precision of this token */ function wmulV(uint256 a_, uint256 b_, address token_) public view returns(uint256) { return wdiv(wmul(a_, b_), decimals[token_]); } /* * @dev calculates division with decimals adjusted to match to tokens precision * @param a_ uint256 divide this number * @param b_ uint256 divide by this number * @param token_ address get result with the precision of this token */ function wdivT(uint256 a_, uint256 b_, address token_) public view returns(uint256) { return wmul(wdiv(a_,b_), decimals[token_]); } /** * @dev Get token_ / quote_currency rate from priceFeed * Revert transaction if not valid feed and manual value not allowed */ function _getNewRate(address token_) internal view returns (uint rate_) { bool feedValid_; bytes32 baseRateBytes_; require( TrustedFeedLikeDex(address(0x0)) != priceFeed[token_], // require token to have a price feed "dex-no-price-feed-for-token"); (baseRateBytes_, feedValid_) = priceFeed[token_].peek(); // receive DPT/USD price if (feedValid_) { // if feed is valid, load DPT/USD rate from it rate_ = uint(baseRateBytes_); } else { require(manualRate[token_], "dex-feed-provides-invalid-data"); // if feed invalid revert if manualEthRate is NOT allowed rate_ = rate[token_]; } } // // internal functions // /* * @dev updates locally stored rates of tokens from feeds */ function _updateRates(address sellToken_, address buyToken_) internal { if (canSellErc20[sellToken_]) { _updateRate(sellToken_); } if (canBuyErc20[buyToken_]){ _updateRate(buyToken_); } _updateRate(dpt); } /* * @dev log the trade event */ function _logTrade( address sellToken_, uint256 sellT_, address buyToken_, uint256 buyT_, uint256 buyAmtOrId_, uint256 feeV_ ) internal { address custodian_ = canBuyErc20[buyToken_] ? custodian20[buyToken_] : Dpass(buyToken_).getCustodian(buyAmtOrId_); txId++; emit LogBuyTokenWithFee( txId, msg.sender, custodian_, sellToken_, sellT_, buyToken_, buyT_, feeV_); } /** * @dev Get exchange rate for a token */ function _updateRate(address token) internal returns (uint256 rate_) { require((rate_ = _getNewRate(token)) > 0, "dex-rate-must-be-greater-than-0"); rate[token] = rate_; } /** * @dev Calculate and send profit and cost */ function _takeFeeInToken( uint256 feeV_, // feeV_ that user still owes to CDiamondCoin after paying feeV_ in DPT uint256 feeTakenV_, // feeV_ already taken from user in DPT address token_, // token_ that must be sent as feeV_ address src_, // source of token_ sent uint256 amountT_ // total amount of tokens the user wanted to pay initially ) internal { uint profitV_; uint profitDpt_; uint feeT_; uint profitPaidV_; uint totalProfitV_; totalProfitV_ = wmul(add(feeV_, feeTakenV_), profitRate); profitPaidV_ = takeProfitOnlyInDpt ? // profit value paid already in base currency feeTakenV_ : wmul(feeTakenV_, profitRate); profitV_ = sub( // profit value still to be paid in base currency totalProfitV_, min( profitPaidV_, totalProfitV_)); profitDpt_ = wdivT(profitV_, rate[dpt], dpt); // profit in DPT still to be paid feeT_ = wdivT(feeV_, rate[token_], token_); // convert feeV_ from base currency to token amount require( feeT_ < amountT_, // require that the cost we pay is less than user intended to pay "dex-not-enough-token-to-pay-fee"); if (block.coinbase == dpt) { //injected CONTRACT AFFECTED BY MINERS _sendToken(dpt, src_, address(uint160(address(burner))), profitDpt_); _sendToken(dpt, src_, wal, sub(feeT_, profitDpt_)); } else { if (liqBuysDpt) { Liquidity(liq).burn(dpt, burner, profitV_); // if liq contract buys DPT on the fly } else { _sendToken(dpt, // if liq contract stores DPT that can be sent to burner by us liq, address(uint160(address(burner))), profitDpt_); } _sendToken(token_, src_, wal, feeT_); // send user token_ to wallet } } /** * @dev Take fee in DPT from user if it has any * @param feeV_ the fee amount in base currency * @return the remaining fee amount in DPT */ function _takeFeeInDptFromUser( uint256 feeV_ // total feeV_ to be paid ) internal returns(uint256 feeTakenV_) { TrustedDSToken dpt20_ = TrustedDSToken(dpt); uint profitDpt_; uint costDpt_; uint feeTakenDpt_; uint dptUser = min( dpt20_.balanceOf(msg.sender), dpt20_.allowance(msg.sender, address(this)) ); if (block.gaslimit == 0) return 0; //injected CONTRACT AFFECTED BY MINERS uint feeDpt = wdivT(feeV_, rate[dpt], dpt); // feeV_ in DPT uint minDpt = min(feeDpt, dptUser); // get the maximum possible feeV_ amount if (block.number > 0) { //injected CONTRACT AFFECTED BY MINERS if (takeProfitOnlyInDpt) { // only profit is paid in dpt profitDpt_ = min(wmul(feeDpt, profitRate), minDpt); } else { profitDpt_ = wmul(minDpt, profitRate); costDpt_ = sub(minDpt, profitDpt_); _sendToken(dpt, msg.sender, wal, costDpt_); // send cost } _sendToken(dpt, // send profit to burner msg.sender, address(uint160(address(burner))), profitDpt_); feeTakenDpt_ = add(profitDpt_, costDpt_); // total feeV_ taken in DPT feeTakenV_ = wmulV(feeTakenDpt_, rate[dpt], dpt); // total feeV_ taken in base currency value } } /** * @dev send token or ether to destination */ function _sendToken( address token_, address src_, address payable dst_, uint256 amount_ ) internal returns(bool) { if (token_ == eth && amount_ > dust) { // if token_ is Ether and amount_ is higher than dust limit require(src_ == msg.sender || src_ == address(this), "dex-wrong-src-address-provided"); dst_.transfer(amount_); emit LogTransferEth(src_, dst_, amount_); } else { if (block.gaslimit > 0) { //injected CONTRACT AFFECTED BY MINERS if( handledByAsm[token_] && src_ == address(asm)) { // if token_ is handled by asm (so it is minted and burnt) and we have to mint it asm.mint(token_, dst_, amount_); } else { TrustedDSToken(token_).transferFrom(src_, dst_, amount_); // transfer all of token_ to dst_ } } } return true; } }
fees are sent in this token_
token_ = sellToken_;
13,091,114
[ 1, 3030, 281, 854, 3271, 316, 333, 1147, 67, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 7734, 1147, 67, 273, 357, 80, 1345, 67, 31, 4766, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/utils/Pausable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/access/AccessControl.sol"; interface ITOM is IERC20 { function deposit(uint256 _amount) external; function withdraw(uint256 _share) external; function finn() external view returns (address); } interface IFarm { function deposit(uint256 _pid, uint256 _amount) external; function withdraw(uint256 _pid, uint256 _amount) external; function pendingReward(uint256 _pid, address _user) external view returns (uint256); function userInfo(uint256 _pid, address _user) external view returns (uint256, uint256); function emergencyWithdraw(uint256 _pid) external; } contract TomVault is ERC20("mTOM Token", "mTOM"), Pausable, AccessControl { using SafeERC20 for IERC20; using SafeERC20 for ITOM; using SafeMath for uint256; bytes32 public constant OPERATOR_ROLE = keccak256("OPERATOR"); uint256 public immutable poolID; ITOM public immutable tom; // Tom token IFarm public immutable farm; address public treasury; uint256 public constant MAX_PERFORMANCE_FEE = 500; // 5% uint256 public constant MAX_CALL_FEE = 100; // 1% uint256 public constant DENOMINATOR = 10000; uint256 public performanceFee; uint256 public callFee = 25; // 0.25% event Deposit(address indexed sender, uint256 amount, uint256 shares, uint256 lastDepositedTime); event Withdraw(address indexed sender, uint256 amount, uint256 shares); event Harvest(address indexed sender, uint256 amount, uint256 performanceFee, uint256 callFee); event Pause(); event Unpause(); /** * @notice Constructor * @param _poolID: pool ID * @param _token: Tom token contract * @param _farm: HuckleberryFarm contract * @param _admin: address of the admin * @param _operator: address of the operator * @param _treasury: address of the treasury (collects fees) */ constructor( uint256 _poolID, ITOM _token, IFarm _farm, address _admin, address _operator, address _treasury ) public { poolID = _poolID; tom = _token; farm = _farm; treasury = _treasury; _setupRole(DEFAULT_ADMIN_ROLE, _admin); _setupRole(OPERATOR_ROLE, _operator); // Infinite approve IERC20(_token.finn()).safeApprove(address(_token), uint256(-1)); _token.safeApprove(address(_farm), uint256(-1)); } /** * @notice Checks if the msg.sender is the operator address */ modifier onlyOperator() { require(hasRole(OPERATOR_ROLE, msg.sender), "not operator"); _; } modifier onlyAdmin() { require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "not admin"); _; } /** * @notice Checks if the msg.sender is a contract or a proxy */ modifier notContract() { require(!Address.isContract(msg.sender), "contract not allowed"); require(msg.sender == tx.origin, "proxy contract not allowed"); _; } /** * @dev A helper function to call deposit() with all the sender's funds. */ function depositAll() external { deposit(tom.balanceOf(msg.sender)); } /** * @notice Deposits funds into the Tom Vault * @dev Only possible when contract not paused. * @param _amount: number of tokens to deposit (in TOM) */ function deposit(uint256 _amount) public whenNotPaused notContract { require(_amount > 0, "nothing to deposit"); uint256 _before = tom.balanceOf(address(this)); tom.safeTransferFrom(msg.sender, address(this), _amount); uint256 _after = tom.balanceOf(address(this)); _amount = _after.sub(_before); // Additional check for deflationary tokens uint256 currentShares; if (totalSupply() != 0) { _withdraw(0); currentShares = (_amount.mul(totalSupply())).div(totalBalance().sub(_amount)); } else { currentShares = _amount; } _mint(msg.sender, currentShares); _earn(); emit Deposit(msg.sender, _amount, currentShares, block.timestamp); } /** * @notice Withdraws all funds for a user */ function withdrawAll() external { withdrawShares(balanceOf(msg.sender)); } function withdrawShares(uint256 _shares) public notContract { _withdraw(0); uint256 currentAmount = (totalBalance().mul(_shares)).div(totalSupply()); _burn(msg.sender, _shares); uint256 bal = available(); if (bal < currentAmount) { _withdraw(currentAmount.sub(bal)); } tom.safeTransfer(msg.sender, currentAmount); _earn(); emit Withdraw(msg.sender, currentAmount, _shares); } /** * @notice Withdraws from funds from the Tom Vault * @param _amount: number of tokens to withdraw (in TOM) */ function withdraw(uint256 _amount) public notContract { _withdraw(0); uint256 currentShares = (_amount.mul(totalSupply())).div(totalBalance()); require(currentShares > 0, "too small shares"); _burn(msg.sender, currentShares); uint256 bal = available(); if (bal < _amount) { _withdraw(_amount.sub(bal)); } tom.safeTransfer(msg.sender, _amount); _earn(); emit Withdraw(msg.sender, _amount, currentShares); } /** * @notice Reinvests TOM tokens into HuckleberryFarm * @dev Only possible when contract not paused. */ function harvest() external whenNotPaused returns (uint256 callerReward, uint256 performanceReward, uint256 totalPending) { _withdraw(0); totalPending = available(); performanceReward = totalPending.mul(performanceFee).div(DENOMINATOR); if (performanceReward > 0) { tom.safeTransfer(treasury, performanceReward); } callerReward = totalPending.mul(callFee).div(DENOMINATOR); tom.safeTransfer(msg.sender, callerReward); _earn(); emit Harvest(msg.sender, totalPending, performanceReward, callerReward); } /** * @notice Sets treasury address * @dev Only callable by the contract admin. */ function setTreasury(address _treasury) external onlyAdmin { require(_treasury != address(0), "cannot be zero address"); treasury = _treasury; } /** * @notice Sets performance fee * @dev Only callable by the contract operator. */ function setPerformanceFee(uint256 _performanceFee) external onlyOperator { require(_performanceFee <= MAX_PERFORMANCE_FEE, "performanceFee cannot be more than MAX_PERFORMANCE_FEE"); performanceFee = _performanceFee; } /** * @notice Sets call fee * @dev Only callable by the contract operator. */ function setCallFee(uint256 _callFee) external onlyOperator { require(_callFee <= MAX_CALL_FEE, "callFee cannot be more than MAX_CALL_FEE"); callFee = _callFee; } /** * @notice Withdraws from HuckleberryFarm to Vault without caring about rewards. * @dev EMERGENCY ONLY. Only callable by the contract operator. */ function emergencyWithdraw() external onlyOperator { farm.emergencyWithdraw(poolID); } /** * @notice Withdraw unexpected tokens sent to the Tom Vault */ function inCaseTokensGetStuck(address _token) external onlyAdmin { require(_token != address(tom), "token cannot be same as deposit token"); require(_token != address(finn()), "token cannot be same as internal token of deposit token"); uint256 amount = IERC20(_token).balanceOf(address(this)); IERC20(_token).safeTransfer(msg.sender, amount); } /** * @notice Triggers stopped state * @dev Only possible when contract not paused. */ function pause() public onlyOperator whenNotPaused { _pause(); emit Pause(); } /** * @notice Returns to normal state * @dev Only possible when contract is paused. */ function unpause() external onlyOperator whenPaused { _unpause(); emit Unpause(); } /** * @notice Calculates the price per share */ function getPricePerFullShare() external view returns (uint256) { return totalSupply() == 0 ? 1e18 : totalBalance().mul(1e18).div(totalSupply()); } /** * @notice Custom logic for how much the vault allows to be borrowed * @dev The contract puts 100% of the tokens to work. */ function available() public view returns (uint256) { return tom.balanceOf(address(this)); } /** * @notice Calculates the total underlying tokens * @dev It includes tokens held by the contract and held in HuckleberryFarm */ function totalBalance() public view returns (uint256) { (uint256 amount, ) = farm.userInfo(poolID, address(this)); return tom.balanceOf(address(this)).add(amount); } function finn() public view returns (IERC20) { return IERC20(tom.finn()); } function availableFinn() public view returns (uint256) { return finn().balanceOf(address(this)); } function _finnToTom(uint256 _amount) internal { if (_amount > 0) { IERC20 finnToken = finn(); ITOM tomToken = tom; if (finnToken.allowance(address(this), address(tomToken)) < _amount) { finnToken.safeApprove(address(tomToken), uint256(-1)); } tomToken.deposit(_amount); } } function _withdraw(uint256 _amount) internal { farm.withdraw(poolID, _amount); _finnToTom(availableFinn()); } /** * @notice Deposits tokens into HuckleberryFarm to earn staking rewards */ function _earn() internal { uint256 bal = available(); if (bal > 0) { ITOM tomToken = tom; IFarm farmInst = farm; if (tomToken.allowance(address(this), address(farmInst)) < bal) { tomToken.safeApprove(address(farmInst), uint256(-1)); } farmInst.deposit(poolID, bal); } } }
* @notice Withdraws all funds for a user/
function withdrawAll() external { withdrawShares(balanceOf(msg.sender)); }
5,517,328
[ 1, 1190, 9446, 87, 777, 284, 19156, 364, 279, 729, 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 ]
[ 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, 1595, 1435, 3903, 288, 203, 3639, 598, 9446, 24051, 12, 12296, 951, 12, 3576, 18, 15330, 10019, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/3/0x5f79da5f2C8cd80D699cd6D73130D7a517e32B4F/sources/Nexon.sol
* @title Nexon Contract For ERC20 Tokens @dev NEXON tokens as per ERC20 Standards/address private _purchaseableTokensAddress; Address for managing token for token purchase.address private _referralAddress; Referral amount. uint256 private _claimTokens; Number of tokens per claim.
contract Nexon is IERC20 { using SafeMath for uint256; bool public _lockStatus = false; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; constructor (string memory name, string memory symbol, uint8 decimals, uint256 totalSupply, address owner, address tokenPoolAddress) public { _name = name; _symbol = symbol; _decimals = decimals; _totalSupply = totalSupply*(10**uint256(decimals)); _balances[owner] = _totalSupply; _owner = owner; _tokenPoolAddress = tokenPoolAddress; } function getowner() public view returns (address) { return _owner; } modifier onlyOwner() { require(isOwner(),"You are not authenticate to make this transfer"); _; } function isOwner() internal view returns (bool) { return msg.sender == _owner; } function transferOwnership(address newOwner) public onlyOwner returns (bool){ _owner = newOwner; return true; } 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() external view override returns (uint256) { return _totalSupply; } function balanceOf(address owner) public view override returns (uint256) { return _balances[owner]; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowed[owner][spender]; } function transfer(address to, uint256 value) public override returns (bool) { _transfer(msg.sender, to, value); return true; } function transferFrom(address from, address to, uint256 value) public override returns (bool) { _transfer(from, to, value); _approve(from, msg.sender, _allowed[from][msg.sender].sub(value)); return true; } function _transfer(address from, address to, uint256 value) internal { require(to != address(0),"Invalid to Address"); require(value > 0, "Invalid Amount"); _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(from, to, value); } function approve(address spender, uint256 value) public override returns (bool) { _approve(msg.sender, spender, value); return true; } function _approve(address owner, address spender, uint256 value) internal { require(spender != address(0),"Invalid address"); require(owner != address(0),"Invalid address"); require(value > 0, "Invalid Amount"); _allowed[owner][spender] = value; emit Approval(owner, spender, value); } function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(msg.sender, spender, _allowed[msg.sender][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(msg.sender, spender, _allowed[msg.sender][spender].sub(subtractedValue)); return true; } function airdropByOwner(address[] memory _addresses, uint256[] memory _amount) public onlyOwner returns (bool){ require(_addresses.length == _amount.length,"Invalid Array"); uint256 count = _addresses.length; for (uint256 i = 0; i < count; i++){ _transfer(msg.sender, _addresses[i], _amount[i]); airdropcount = airdropcount + 1; } return true; } function airdropByOwner(address[] memory _addresses, uint256[] memory _amount) public onlyOwner returns (bool){ require(_addresses.length == _amount.length,"Invalid Array"); uint256 count = _addresses.length; for (uint256 i = 0; i < count; i++){ _transfer(msg.sender, _addresses[i], _amount[i]); airdropcount = airdropcount + 1; } return true; } function _burn(address account, uint256 value) internal { require(account != address(0),"Invalid account"); require(value > 0, "Invalid Amount"); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); } function burn(uint256 _value) public onlyOwner { _burn(msg.sender, _value); } function mint(uint256 _value) public onlyOwner returns(bool){ require(_value > 0,"The amount should be greater than 0"); _mint(_value,msg.sender); return true; } function _mint(uint256 _value,address _tokenOwner) internal returns(bool){ _balances[_tokenOwner] = _balances[_tokenOwner].add(_value); _totalSupply = _totalSupply.add(_value); emit Transfer(address(0), _tokenOwner, _value); return true; } function getContractETHBalance() public view returns(uint256){ return(address(this).balance); } mapping (uint256 => address) private _stakerAddress; mapping (uint256 => uint256) private _usersTokens; mapping (uint256 => uint256) private _stakingStartTime; mapping (uint256 => uint256) private _stakingEndTime; mapping (uint256 => bool) private _TokenTransactionstatus; mapping (address => address) private _ReferalList; mapping (address => bool) private _ReferalStatus; mapping(address=>uint256) private _myPurchasedTokens; mapping(address=>uint256) private _openOrderETHAmountByAddress; mapping(address=>uint256) private _ethDepositedByUser; mapping(uint256=>uint256) private _finalWithdrawlStake; uint256 private _rewardPercentage; uint256 private _penaltyPercentage; uint256 private _penaltyAmountAfterStakingTime; uint256 private _stakingCount = 0; uint256 private _bigPayDayDate = now; uint256 private _bigPayDayPercentage; uint256 private _totalETH; mapping(address=>bool)_referralWhitelist; modifier validatorForStaking(uint256 tokens, uint256 time){ require( time > now && tokens > 0, "Invalid time and Amount"); _; } modifier payableCheck(){ require(msg.value > 0 , "Can not buy tokens,"); _; } function setTokenPoolAddress(address add) public onlyOwner returns(bool){ require(add != address(0),"Invalid Address"); _tokenPoolAddress = add; return true; } function getTokenpoolAddress() public view returns(address){ return _tokenPoolAddress; } function setRewardPercentage(uint256 rewardsPercentage) public onlyOwner returns(bool){ require(rewardsPercentage > 0, "Invalid Percentage"); _rewardPercentage = rewardsPercentage; return true; } function getRewardPercentage() public view returns(uint256){ return _rewardPercentage; } function setPenaltyPercentage(uint256 penaltyPercentage) public onlyOwner returns(bool){ require(penaltyPercentage > 0, "Invalid Percentage"); _penaltyPercentage = penaltyPercentage; return true; } function getPenaltyPercentage() public view returns(uint256){ return _penaltyPercentage; } function setPriceToken(uint256 tokenPriceETH) external onlyOwner returns (bool){ require(tokenPriceETH >0,"Invalid Amount"); _tokenPriceETH = tokenPriceETH; return(true); } function getPriceToken() public view returns(uint256) { return _tokenPriceETH; } function blacklistStake(bool status,uint256 stakingId) external onlyOwner returns(bool){ _TokenTransactionstatus[stakingId] = status; } function withdrawETH() external onlyOwner returns(bool){ msg.sender.transfer(address(this).balance); return true; } function setBigPayDay(uint256 NextDay) public onlyOwner returns(bool){ require(NextDay > now,"Invalid Day Selected"); _bigPayDayDate = NextDay; return true; } function getBigPayDay() public view returns(uint256){ return _bigPayDayDate; } function setBigPayDayPercentage(uint256 newPercentage) public onlyOwner returns(bool){ require(newPercentage > 0,"Invalid Percentage Selected"); _bigPayDayPercentage = newPercentage; return true; } function getBigPayDayPercentage() public view returns(uint256){ return _bigPayDayPercentage; } function calculateBigPayDayReward(uint256 amount, uint256 endDate)public view returns(uint256){ if(endDate > _bigPayDayDate){ return (amount * _bigPayDayPercentage)/100; return 0 ; } } function calculateBigPayDayReward(uint256 amount, uint256 endDate)public view returns(uint256){ if(endDate > _bigPayDayDate){ return (amount * _bigPayDayPercentage)/100; return 0 ; } } }else { function getMyPurchasedTokens(address add) public view returns(uint256){ return _myPurchasedTokens[add]; } function getETHAmountByAddress(address add) public view returns(uint256){ return _ethDepositedByUser[add]; } function getOpenOrderETHAmountByAddress(address add) public view returns(uint256){ return _openOrderETHAmountByAddress[add]; } function getTotalETH() public view returns(uint256){ return _totalETH; } function purchaseTokens() external payable payableCheck returns(bool){ _myPurchasedTokens[msg.sender] = _myPurchasedTokens[msg.sender] + msg.value * _tokenPriceETH; _openOrderETHAmountByAddress[msg.sender] = msg.value; _totalETH = _totalETH +msg.value; _ethDepositedByUser[msg.sender] = msg.value; return true; } function withdrawPurchasedToken() external returns(bool){ require(_myPurchasedTokens[msg.sender]>0,"You do not have any purchased token"); if(_referralWhitelist[msg.sender] == true){ address referree = _ReferalList[msg.sender]; _mint(_myPurchasedTokens[msg.sender].add(_myPurchasedTokens[msg.sender].div(10)), msg.sender); _mint(_myPurchasedTokens[msg.sender].div(5), referree); } else{ _mint(_myPurchasedTokens[msg.sender], msg.sender); } _myPurchasedTokens[msg.sender] = 0; _openOrderETHAmountByAddress[msg.sender] = 0; return true; } function withdrawPurchasedToken() external returns(bool){ require(_myPurchasedTokens[msg.sender]>0,"You do not have any purchased token"); if(_referralWhitelist[msg.sender] == true){ address referree = _ReferalList[msg.sender]; _mint(_myPurchasedTokens[msg.sender].add(_myPurchasedTokens[msg.sender].div(10)), msg.sender); _mint(_myPurchasedTokens[msg.sender].div(5), referree); } else{ _mint(_myPurchasedTokens[msg.sender], msg.sender); } _myPurchasedTokens[msg.sender] = 0; _openOrderETHAmountByAddress[msg.sender] = 0; return true; } function withdrawPurchasedToken() external returns(bool){ require(_myPurchasedTokens[msg.sender]>0,"You do not have any purchased token"); if(_referralWhitelist[msg.sender] == true){ address referree = _ReferalList[msg.sender]; _mint(_myPurchasedTokens[msg.sender].add(_myPurchasedTokens[msg.sender].div(10)), msg.sender); _mint(_myPurchasedTokens[msg.sender].div(5), referree); } else{ _mint(_myPurchasedTokens[msg.sender], msg.sender); } _myPurchasedTokens[msg.sender] = 0; _openOrderETHAmountByAddress[msg.sender] = 0; return true; } function getFinalWithdrawlStake(uint256 id) public view returns(uint256){ return _finalWithdrawlStake[id]; } function getStakingAddressById(uint256 id) public view returns (address){ require(id <= _stakingCount,"Unable to reterive data on specified id, Please try again!!"); return _stakerAddress[id]; } function getStakingStartTimeById(uint256 id)public view returns(uint256){ require(id <= _stakingCount,"Unable to reterive data on specified id, Please try again!!"); return _stakingStartTime[id]; } function getStakingEndTimeById(uint256 id)public view returns(uint256){ require(id <= _stakingCount,"Unable to reterive data on specified id, Please try again!!"); return _stakingEndTime[id]; } function getStakingTokenById(uint256 id)public view returns(uint256){ require(id <= _stakingCount,"Unable to reterive data on specified id, Please try again!!"); return _usersTokens[id]; } function getActiveStakesById(uint256 id)public view returns(address){ return _stakerAddress[id]; } function getTokenLockstatus(uint256 id)public view returns(bool){ return _TokenTransactionstatus[id]; } function getInterest() public view returns(uint256){ return _rewardPercentage; } function getStakingCount() public view returns(uint256){ return _stakingCount; } function getPaneltyIfWithdrawToday(uint256 id) public view returns(uint256){ if(_stakingEndTime[id] > now){ return (_penaltyPercentage * _usersTokens[id] * ((_stakingEndTime[id] - now)/86400))/1000; return (_penaltyPercentage * _usersTokens[id] * ((now - _stakingEndTime[id])/86400))/1000; return 0; } } function getPaneltyIfWithdrawToday(uint256 id) public view returns(uint256){ if(_stakingEndTime[id] > now){ return (_penaltyPercentage * _usersTokens[id] * ((_stakingEndTime[id] - now)/86400))/1000; return (_penaltyPercentage * _usersTokens[id] * ((now - _stakingEndTime[id])/86400))/1000; return 0; } } } else if(_stakingEndTime[id] + 2629743 < now){ } else{ function getRewardsDetailsOfUserById(uint256 id) public view returns(uint256){ uint256 bpDay = calculateBigPayDayReward(_stakingEndTime[id], _usersTokens[id]); if(_stakingEndTime[id] > now){ return (((now - _stakingStartTime[id])/86400) * (_rewardPercentage) * _usersTokens[id] + bpDay)/10000; return (((_stakingEndTime[id] - _stakingStartTime[id])/86400) * (_rewardPercentage) * _usersTokens[id] + bpDay)/10000; return 0; } } function getRewardsDetailsOfUserById(uint256 id) public view returns(uint256){ uint256 bpDay = calculateBigPayDayReward(_stakingEndTime[id], _usersTokens[id]); if(_stakingEndTime[id] > now){ return (((now - _stakingStartTime[id])/86400) * (_rewardPercentage) * _usersTokens[id] + bpDay)/10000; return (((_stakingEndTime[id] - _stakingStartTime[id])/86400) * (_rewardPercentage) * _usersTokens[id] + bpDay)/10000; return 0; } } } else if (_stakingEndTime[id] < now){ } else{ function performStaking(uint256 tokens, uint256 time) public validatorForStaking(tokens, time) returns(bool){ _stakingCount = _stakingCount +1 ; _stakerAddress[_stakingCount] = msg.sender; _stakingEndTime[_stakingCount] = time; _stakingStartTime[_stakingCount] = now; _usersTokens[_stakingCount] = tokens; _TokenTransactionstatus[_stakingCount] = false; _transfer(msg.sender, _tokenPoolAddress, tokens); return true; } function withdrawStakedTokens(uint256 stakingId) public returns(bool){ require(_stakerAddress[stakingId] == msg.sender,"No staked token found on this address and ID"); require(_TokenTransactionstatus[stakingId] != true,"Either tokens are already withdrawn or blocked by admin"); require(balanceOf(_tokenPoolAddress) > _usersTokens[stakingId], "Pool is dry, can not perform transaction"); uint256 paneltyAtWithdraw = getPaneltyIfWithdrawToday(stakingId); _TokenTransactionstatus[stakingId] = true; _finalWithdrawlStake[stakingId] = _usersTokens[stakingId]-paneltyAtWithdraw+getRewardsDetailsOfUserById(stakingId); _mint(getRewardsDetailsOfUserById(stakingId)-paneltyAtWithdraw,_tokenPoolAddress); _transfer(_tokenPoolAddress,msg.sender,_usersTokens[stakingId]-paneltyAtWithdraw+getRewardsDetailsOfUserById(stakingId)); return true; } function getReferralHistory(address add)public view returns(address){ return _ReferalList[add]; } function withdrawReferral(address add) external returns(bool){ require(_ReferalList[add] != msg.sender && _ReferalStatus[msg.sender] != true && add != msg.sender,"Either already withdrawn or not valid"); _ReferalStatus[add]=true; _ReferalList[add]=msg.sender; _referralWhitelist[msg.sender] = true; return true; } uint256 SnapshotTime; mapping(address=>bool)holderAddressBlockList; mapping(address=>uint256)holdingsByAddress; mapping(address=>uint256)holderAmountClaimed; mapping(address=>uint256)whitelistAddressesForClaim; uint256 public totalWhitelistedAdd = 0; IDelegate delegate = IDelegate(delegateContract); function whitelistaddressForClaim(address[] calldata _userAddressArray, uint256[] calldata _snapshotBalance) external onlyOwner returns(bool){ require(_userAddressArray.length == _snapshotBalance.length,"Invalid Array"); uint256 count = _userAddressArray.length; for (uint256 i = 0; i < count; i++){ whitelistAddressesForClaim[_userAddressArray[i]] = _snapshotBalance[i]; totalWhitelistedAdd = totalWhitelistedAdd + 1; } return true; } function whitelistaddressForClaim(address[] calldata _userAddressArray, uint256[] calldata _snapshotBalance) external onlyOwner returns(bool){ require(_userAddressArray.length == _snapshotBalance.length,"Invalid Array"); uint256 count = _userAddressArray.length; for (uint256 i = 0; i < count; i++){ whitelistAddressesForClaim[_userAddressArray[i]] = _snapshotBalance[i]; totalWhitelistedAdd = totalWhitelistedAdd + 1; } return true; } modifier checkBlocker(address _claimingAddress, uint256 _claimableTokens){ require(delegate.balanceOf(_claimingAddress) >= _claimableTokens, "You do not have sufficient balance for this claim"); require(whitelistAddressesForClaim[_claimingAddress] > 0, "User do not have any claimable tokens"); require(holderAddressBlockList[_claimingAddress]!=true,"User has already claimed tokens, Check with another address"); require(delegate.balanceOf(_claimingAddress) >= whitelistAddressesForClaim[_claimingAddress], "Not sufficient holdings"); _; } function performClaim(uint256 _amountToClaim) external checkBlocker(msg.sender,_amountToClaim) validatorForStaking(_amountToClaim, now + 31536000) returns(bool){ _stakingCount = _stakingCount +1; _stakerAddress[_stakingCount] = msg.sender; _stakingEndTime[_stakingCount] = now + 31536000; _stakingStartTime[_stakingCount] = now; _usersTokens[_stakingCount] = _amountToClaim; _TokenTransactionstatus[_stakingCount] = false; holderAddressBlockList[msg.sender] = true; } function checkNowStakesBalance(address _claimingAddress) public view returns(uint256){ return delegate.balanceOf(_claimingAddress); } function checkHoldingBalance(address _holderAddress) public view returns(uint256){ return whitelistAddressesForClaim[_holderAddress]; } }
5,184,101
[ 1, 50, 338, 265, 13456, 2457, 4232, 39, 3462, 13899, 225, 24011, 673, 2430, 487, 1534, 4232, 39, 3462, 8263, 87, 19, 2867, 3238, 389, 12688, 12104, 429, 5157, 1887, 31, 1377, 5267, 364, 30632, 1147, 364, 1147, 23701, 18, 2867, 3238, 389, 1734, 29084, 1887, 31, 7734, 3941, 29084, 3844, 18, 2254, 5034, 3238, 389, 14784, 5157, 31, 1171, 3588, 434, 2430, 1534, 7516, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 16351, 423, 338, 265, 353, 467, 654, 39, 3462, 288, 203, 203, 225, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 203, 225, 1426, 565, 1071, 225, 389, 739, 1482, 273, 629, 31, 540, 203, 377, 203, 225, 2874, 261, 2867, 516, 2254, 5034, 13, 3238, 389, 70, 26488, 31, 203, 203, 225, 2874, 261, 2867, 516, 2874, 261, 2867, 516, 2254, 5034, 3719, 3238, 389, 8151, 31, 203, 203, 225, 3885, 261, 1080, 3778, 508, 16, 533, 3778, 3273, 16, 2254, 28, 15105, 16, 2254, 5034, 2078, 3088, 1283, 16, 1758, 3410, 16, 1758, 1147, 2864, 1887, 13, 1071, 288, 203, 565, 389, 529, 273, 508, 31, 203, 565, 389, 7175, 273, 3273, 31, 203, 565, 389, 31734, 273, 15105, 31, 203, 565, 389, 4963, 3088, 1283, 273, 2078, 3088, 1283, 21556, 2163, 636, 11890, 5034, 12, 31734, 10019, 203, 565, 389, 70, 26488, 63, 8443, 65, 273, 389, 4963, 3088, 1283, 31, 203, 565, 389, 8443, 273, 3410, 31, 203, 565, 389, 2316, 2864, 1887, 273, 1147, 2864, 1887, 31, 203, 225, 289, 203, 7010, 203, 225, 445, 336, 8443, 1435, 1071, 1476, 1135, 261, 2867, 13, 288, 203, 565, 327, 389, 8443, 31, 203, 225, 289, 203, 203, 225, 9606, 1338, 5541, 1435, 288, 203, 565, 2583, 12, 291, 5541, 9334, 6, 6225, 854, 486, 8929, 358, 1221, 333, 7412, 8863, 203, 565, 389, 31, 203, 225, 289, 203, 203, 225, 445, 353, 5541, 1435, 2713, 1476, 1135, 261, 6430, 13, 288, 203, 1377, 327, 1234, 18, 15330, 422, 389, 8443, 2 ]
pragma solidity ^0.4.15; /** * @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; } } contract ERC20 { uint256 public totalSupply; function balanceOf(address who) constant returns (uint256); function transfer(address to, uint256 value) returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); function allowance(address owner, address spender) constant returns (uint256); function transferFrom(address from, address to, uint256 value) returns (bool); function approve(address spender, uint256 value) returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } contract BasicToken is ERC20 { using SafeMath for uint256; mapping(address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; modifier nonZeroEth(uint _value) { require(_value > 0); _; } modifier onlyPayloadSize() { require(msg.data.length >= 68); _; } /** * @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) nonZeroEth(_value) onlyPayloadSize returns (bool) { if (balances[msg.sender] >= _value && balances[_to] + _value > balances[_to]){ balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; }else{ return false; } } /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amout of tokens to be transfered */ function transferFrom(address _from, address _to, uint256 _value) nonZeroEth(_value) onlyPayloadSize returns (bool) { if(balances[_from] >= _value && allowed[_from][msg.sender] >= _value && balances[_to] + _value > balances[_to]){ uint256 _allowance = allowed[_from][msg.sender]; allowed[_from][msg.sender] = _allowance.sub(_value); balances[_to] = balances[_to].add(_value); balances[_from] = balances[_from].sub(_value); Transfer(_from, _to, _value); return true; }else{ return false; } } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } function approve(address _spender, uint256 _value) returns (bool) { // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender, 0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require((_value == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifing the amount of tokens still avaible for the spender. */ function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } } contract RPTToken is BasicToken { using SafeMath for uint256; string public name = "RPT Token"; //name of the token string public symbol = "RPT"; // symbol of the token uint8 public decimals = 18; // decimals uint256 public totalSupply = 1000000000 * 10**18; // total supply of RPT Tokens // variables uint256 public keyEmployeeAllocation; // fund allocated to key employee uint256 public totalAllocatedTokens; // variable to regulate the funds allocation uint256 public tokensAllocatedToCrowdFund; // funds allocated to crowdfund // addresses address public founderMultiSigAddress = 0xf96E905091d38ca25e06C014fE67b5CA939eE83D; // multi sign address of founders which hold address public crowdFundAddress; // address of crowdfund contract //events event ChangeFoundersWalletAddress(uint256 _blockTimeStamp, address indexed _foundersWalletAddress); event TransferPreAllocatedFunds(uint256 _blockTimeStamp , address _to , uint256 _value); //modifiers modifier onlyCrowdFundAddress() { require(msg.sender == crowdFundAddress); _; } modifier nonZeroAddress(address _to) { require(_to != 0x0); _; } modifier onlyFounders() { require(msg.sender == founderMultiSigAddress); _; } // creation of the token contract function RPTToken (address _crowdFundAddress) { crowdFundAddress = _crowdFundAddress; // Token Distribution tokensAllocatedToCrowdFund = 70 * 10 ** 25; // 70 % allocation of totalSupply keyEmployeeAllocation = 30 * 10 ** 25; // 30 % allocation of totalSupply // Assigned balances to respective stakeholders balances[founderMultiSigAddress] = keyEmployeeAllocation; balances[crowdFundAddress] = tokensAllocatedToCrowdFund; totalAllocatedTokens = balances[founderMultiSigAddress]; } // function to keep track of the total token allocation function changeTotalSupply(uint256 _amount) onlyCrowdFundAddress { totalAllocatedTokens = totalAllocatedTokens.add(_amount); } // function to change founder multisig wallet address function changeFounderMultiSigAddress(address _newFounderMultiSigAddress) onlyFounders nonZeroAddress(_newFounderMultiSigAddress) { founderMultiSigAddress = _newFounderMultiSigAddress; ChangeFoundersWalletAddress(now, founderMultiSigAddress); } } contract RPTCrowdsale { using SafeMath for uint256; RPTToken public token; // Token variable //variables uint256 public totalWeiRaised; // Flag to track the amount raised uint32 public exchangeRate = 3000; // calculated using priceOfEtherInUSD/priceOfRPTToken uint256 public preDistriToAcquiantancesStartTime = 1510876801; // Friday, 17-Nov-17 00:00:01 UTC uint256 public preDistriToAcquiantancesEndTime = 1511827199; // Monday, 27-Nov-17 23:59:59 UTC uint256 public presaleStartTime = 1511827200; // Tuesday, 28-Nov-17 00:00:00 UTC uint256 public presaleEndTime = 1513036799; // Monday, 11-Dec-17 23:59:59 UTC uint256 public crowdfundStartTime = 1513036800; // Tuesday, 12-Dec-17 00:00:00 UTC uint256 public crowdfundEndTime = 1515628799; // Wednesday, 10-Jan-18 23:59:59 UTC bool internal isTokenDeployed = false; // Flag to track the token deployment // addresses address public founderMultiSigAddress; // Founders multi sign address address public remainingTokenHolder; // Address to hold the remaining tokens after crowdfund end address public beneficiaryAddress; // All funds are transferred to this address enum State { Acquiantances, PreSale, CrowdFund, Closed } //events event TokenPurchase(address indexed beneficiary, uint256 value, uint256 amount); event CrowdFundClosed(uint256 _blockTimeStamp); event ChangeFoundersWalletAddress(uint256 _blockTimeStamp, address indexed _foundersWalletAddress); //Modifiers modifier tokenIsDeployed() { require(isTokenDeployed == true); _; } modifier nonZeroEth() { require(msg.value > 0); _; } modifier nonZeroAddress(address _to) { require(_to != 0x0); _; } modifier onlyFounders() { require(msg.sender == founderMultiSigAddress); _; } modifier onlyPublic() { require(msg.sender != founderMultiSigAddress); _; } modifier inState(State state) { require(getState() == state); _; } modifier inBetween() { require(now >= preDistriToAcquiantancesStartTime && now <= crowdfundEndTime); _; } // Constructor to initialize the local variables function RPTCrowdsale (address _founderWalletAddress, address _remainingTokenHolder, address _beneficiaryAddress) { founderMultiSigAddress = _founderWalletAddress; remainingTokenHolder = _remainingTokenHolder; beneficiaryAddress = _beneficiaryAddress; } // Function to change the founders multi sign address function setFounderMultiSigAddress(address _newFounderAddress) onlyFounders nonZeroAddress(_newFounderAddress) { founderMultiSigAddress = _newFounderAddress; ChangeFoundersWalletAddress(now, founderMultiSigAddress); } // Attach the token contract function setTokenAddress(address _tokenAddress) external onlyFounders nonZeroAddress(_tokenAddress) { require(isTokenDeployed == false); token = RPTToken(_tokenAddress); isTokenDeployed = true; } // function call after crowdFundEndTime it transfers the remaining tokens to remainingTokenHolder address function endCrowdfund() onlyFounders returns (bool) { require(now > crowdfundEndTime); uint256 remainingToken = token.balanceOf(this); // remaining tokens if (remainingToken != 0) { token.transfer(remainingTokenHolder, remainingToken); CrowdFundClosed(now); return true; } else { CrowdFundClosed(now); return false; } } // Buy token function call only in duration of crowdfund active function buyTokens(address beneficiary) nonZeroEth tokenIsDeployed onlyPublic nonZeroAddress(beneficiary) inBetween payable public returns(bool) { fundTransfer(msg.value); uint256 amount = getNoOfTokens(exchangeRate, msg.value); if (token.transfer(beneficiary, amount)) { token.changeTotalSupply(amount); totalWeiRaised = totalWeiRaised.add(msg.value); TokenPurchase(beneficiary, msg.value, amount); return true; } return false; } // function to transfer the funds to founders account function fundTransfer(uint256 weiAmount) internal { beneficiaryAddress.transfer(weiAmount); } // Get functions // function to get the current state of the crowdsale function getState() internal constant returns(State) { if (now >= preDistriToAcquiantancesStartTime && now <= preDistriToAcquiantancesEndTime) { return State.Acquiantances; } if (now >= presaleStartTime && now <= presaleEndTime) { return State.PreSale; } if (now >= crowdfundStartTime && now <= crowdfundEndTime) { return State.CrowdFund; } else { return State.Closed; } } // function to calculate the total no of tokens with bonus multiplication function getNoOfTokens(uint32 _exchangeRate, uint256 _amount) internal returns (uint256) { uint256 noOfToken = _amount.mul(uint256(_exchangeRate)); uint256 noOfTokenWithBonus = ((uint256(100 + getCurrentBonusRate())).mul(noOfToken)).div(100); return noOfTokenWithBonus; } // function provide the current bonus rate function getCurrentBonusRate() internal returns (uint8) { if (getState() == State.Acquiantances) { return 40; } if (getState() == State.PreSale) { return 20; } if (getState() == State.CrowdFund) { return 0; } else { return 0; } } // provides the bonus % function getBonus() constant returns (uint8) { return getCurrentBonusRate(); } // send ether to the contract address // With at least 200 000 gas function() public payable { buyTokens(msg.sender); } }
provides the bonus %
function getBonus() constant returns (uint8) { return getCurrentBonusRate(); }
12,837,451
[ 1, 685, 13427, 326, 324, 22889, 738, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 2882, 22889, 1435, 5381, 1135, 261, 11890, 28, 13, 288, 203, 3639, 327, 5175, 38, 22889, 4727, 5621, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2020-08-21 */ // SPDX-License-Identifier: MIT pragma solidity 0.6.10; /** * @title SafeMath * @dev Unsigned math operations with safety checks that revert on error. */ library SafeMath { function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); uint256 c = a - b; return c; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor(address initialOwner) internal { require(initialOwner != address(0), "Ownable: initial owner is the zero address"); _owner = initialOwner; emit OwnershipTransferred(address(0), _owner); } function owner() public view returns (address) { return _owner; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC } modifier onlyOwner() { require(_isOwner(msg.sender), "Ownable: caller is not the owner"); _; } function _isOwner(address account) internal view returns (bool) { return account == _owner; } function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC _owner = newOwner; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC } function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC _owner = address(0); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC } } /** * @title ERC20 interface * @dev see https://eips.ethereum.org/EIPS/eip-20 */ interface IERC20 { function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * See https://eips.ethereum.org/EIPS/eip-20 */ contract ERC20 is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string internal _name; string internal _symbol; uint8 internal _decimals; function name() public view returns (string memory) { return _name; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC } function symbol() public view returns (string memory) { return _symbol; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC } function decimals() public view returns (uint8) { return _decimals; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC } function totalSupply() public view override returns (uint256) { return _totalSupply; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC } function balanceOf(address account) public view override returns (uint256) { return _balances[account]; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC } function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(msg.sender, recipient, amount); return true; } function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC } function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(msg.sender, spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount)); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue)); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue)); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC return true; } function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, 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 _burn(address account, uint256 amount) internal { require(account != address(0)); _balances[account] = _balances[account].sub(amount); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve(account, msg.sender, _allowances[account][msg.sender].sub(amount)); } } /** * @dev Extension of {ERC20} that allows token holders to destroy both their own * tokens and those that they have an allowance for. */ contract ERC20Burnable is ERC20 { function burn(uint256 amount) public { _burn(msg.sender, amount); } } /** * @dev Custom extension of {ERC20} that adds a set of Minter accounts, * which have permission to mint (create) new tokens as they see fit. */ abstract contract ERC20Mintable is ERC20Burnable, Ownable { address[] internal _minters; mapping (address => Minter) internal minterInfo; struct Minter { bool active; uint256 limit; uint256 minted; } modifier canMint(uint256 amount) virtual { require(isMinter(msg.sender), "Caller has no permission"); require(minterInfo[msg.sender].minted.add(amount) <= minterInfo[msg.sender].limit, "Minter limit overflow"); minterInfo[msg.sender].minted = minterInfo[msg.sender].minted.add(amount); _; } function mint(address account, uint256 amount) public canMint(amount) returns (bool) { _mint(account, amount); return true; } function setMinter(address account, uint256 limit) public onlyOwner { require(account != address(0)); if (!minterInfo[account].active && limit > 0) { //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC _minters.push(account); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC minterInfo[account].active = true; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC } if (limit > minterInfo[account].minted) { //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC minterInfo[account].limit = limit; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC } else { minterInfo[account].limit = minterInfo[account].minted; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC } } function isMinter(address account) public view returns (bool) { return(minterInfo[account].active); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC } function getMinters() public view returns(address[] memory) { return _minters; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC } function getMintersInfo() public view returns(uint256 amountOfMinters, uint256 totalLimit, uint256 totalMinted) { amountOfMinters = _minters.length; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC for (uint256 i = 0; i < amountOfMinters; i++) { totalLimit += minterInfo[_minters[i]].limit; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC totalMinted += minterInfo[_minters[i]].minted; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC } return (amountOfMinters, totalLimit, totalMinted); } } /** * @title ApproveAndCall Interface. * @dev ApproveAndCall system allows to communicate with smart-contracts. */ abstract contract ApproveAndCallFallBack { function receiveApproval(address from, uint256 amount, address token, bytes calldata extraData) virtual external; } /** * @title The main project contract. */ contract FinandyToken is ERC20Mintable { // initial supply uint256 public INITIAL_SUPPLY = 100000000 * 10 ** 8; // maximum cap uint256 public MAXIMUM_SUPPLY = 200000000 * 10 ** 8; // registered contracts (to prevent loss of token via transfer function) mapping (address => bool) private _contracts; // modified canMint modifier (to prevent exceeding the maximum cap) modifier canMint(uint256 amount) override { require(isMinter(msg.sender), "Caller has no permission"); require(minterInfo[msg.sender].minted.add(amount) <= minterInfo[msg.sender].limit, "Minter limit overflow"); require(totalSupply().add(amount) <= MAXIMUM_SUPPLY, "Total supply cannot exceed the cap"); minterInfo[msg.sender].minted = minterInfo[msg.sender].minted.add(amount); _; } /** * @dev constructor function that is called once at deployment of the contract. * @param recipient Address to receive initial supply. */ constructor(address initialOwner, address recipient) public Ownable(initialOwner) { // name of the token _name = "Finandy"; // symbol of the token _symbol = "FIN"; // decimals of the token _decimals = 8; // creation of initial supply _mint(recipient, INITIAL_SUPPLY); } /** * @dev modified transfer function that allows to safely send tokens to smart-contract. * @param to The address to transfer to. * @param value The amount to be transferred. */ function transfer(address to, uint256 value) public override returns (bool) { if (_contracts[to]) { //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC approveAndCall(to, value, new bytes(0)); } else { super.transfer(to, value); } return true; } /** * @dev Allows to send tokens (via Approve and TransferFrom) to other smart-contract. * @param spender Address of smart contracts to work with. * @param amount Amount of tokens to send. * @param extraData Any extra data. */ function approveAndCall(address spender, uint256 amount, bytes memory extraData) public returns (bool) { require(approve(spender, amount)); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, amount, address(this), extraData); return true; } /** * @dev Allows to register other smart-contracts (to prevent loss of tokens via transfer function). * @param account Address of smart contracts to work with. */ function registerContract(address account) external onlyOwner { require(_isContract(account), "DigexToken: account is not a smart-contract"); _contracts[account] = true; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC } /** * @dev Allows to unregister registered smart-contracts. * @param account Address of smart contracts to work with. */ function unregisterContract(address account) external onlyOwner { require(isRegistered(account), "DigexToken: account is not registered yet"); _contracts[account] = false; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC } /** * @dev Allows to any owner of the contract withdraw needed ERC20 token from this contract (for example promo or bounties). * @param ERC20Token Address of ERC20 token. * @param recipient Account to receive tokens. */ function withdrawERC20(address ERC20Token, address recipient) external onlyOwner { uint256 amount = IERC20(ERC20Token).balanceOf(address(this)); IERC20(ERC20Token).transfer(recipient, amount); } /** * @return true if the address is registered as contract * @param account Address to be checked. */ function isRegistered(address account) public view returns (bool) { return _contracts[account]; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC } /** * @return true if `account` is a contract. * @param account Address to be checked. */ function _isContract(address account) internal view returns (bool) { uint256 size; assembly { size := extcodesize(account) } return size > 0; } }
inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
if (limit > minterInfo[account].minted) {
15,808,689
[ 1, 22170, 18708, 14939, 8350, 13255, 40, 6953, 17187, 478, 21163, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 309, 261, 3595, 405, 1131, 387, 966, 63, 4631, 8009, 81, 474, 329, 13, 288, 202, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/80001/0xD60B881c35F0e5eB578d9BBF305f14D0Da5B651d/sources/scripts/NOMAD_AirDrop.sol
* Allows for the distribution of an ERC20 token to be transferred to multiple recipients at a time. This function facilitates batch transfers of differing values (i.e., all recipients can receive different amounts of tokens). @param _addressOfToken The contract address of an ERC20 token. @param _recipients The list of addresses which will receive tokens. @param _values The corresponding values of tokens which each address will receive. @return true if function executes successfully, false otherwise. /
function multiValueTokenAirdrop( address _addressOfToken, address[] memory _recipients, uint256[] memory _values ) public returns (bool) { ERCInterface token = ERCInterface(_addressOfToken); require( _recipients.length == _values.length, "Total number of recipients and values are not equal" ); for (uint256 i = 0; i < _recipients.length; i++) { if (_recipients[i] != address(0) && _values[i] > 0) { token.transferFrom(msg.sender, _recipients[i], _values[i]); } } emit TokenAirdrop(msg.sender, _addressOfToken, _recipients.length); return true; }
5,628,156
[ 1, 19132, 364, 326, 7006, 434, 392, 4232, 39, 3462, 1147, 358, 506, 906, 4193, 358, 3229, 12045, 622, 279, 813, 18, 1220, 445, 5853, 330, 305, 815, 2581, 29375, 434, 15221, 310, 924, 261, 77, 18, 73, 12990, 777, 12045, 848, 6798, 3775, 30980, 434, 2430, 2934, 225, 389, 2867, 951, 1345, 1021, 6835, 1758, 434, 392, 4232, 39, 3462, 1147, 18, 225, 389, 27925, 1021, 666, 434, 6138, 1492, 903, 6798, 2430, 18, 225, 389, 2372, 1021, 4656, 924, 434, 2430, 1492, 1517, 1758, 903, 6798, 18, 327, 638, 309, 445, 11997, 4985, 16, 629, 3541, 18, 342, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 3309, 620, 1345, 37, 6909, 1764, 12, 203, 3639, 1758, 389, 2867, 951, 1345, 16, 203, 3639, 1758, 8526, 3778, 389, 27925, 16, 203, 3639, 2254, 5034, 8526, 3778, 389, 2372, 203, 565, 262, 1071, 1135, 261, 6430, 13, 288, 203, 3639, 4232, 39, 1358, 1147, 273, 4232, 39, 1358, 24899, 2867, 951, 1345, 1769, 203, 3639, 2583, 12, 203, 5411, 389, 27925, 18, 2469, 422, 389, 2372, 18, 2469, 16, 203, 5411, 315, 5269, 1300, 434, 12045, 471, 924, 854, 486, 3959, 6, 203, 3639, 11272, 203, 203, 3639, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 389, 27925, 18, 2469, 31, 277, 27245, 288, 203, 5411, 309, 261, 67, 27925, 63, 77, 65, 480, 1758, 12, 20, 13, 597, 389, 2372, 63, 77, 65, 405, 374, 13, 288, 203, 7734, 1147, 18, 13866, 1265, 12, 3576, 18, 15330, 16, 389, 27925, 63, 77, 6487, 389, 2372, 63, 77, 19226, 203, 5411, 289, 203, 3639, 289, 203, 203, 3639, 3626, 3155, 37, 6909, 1764, 12, 3576, 18, 15330, 16, 389, 2867, 951, 1345, 16, 389, 27925, 18, 2469, 1769, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "./TokenPaymentSplitter.sol"; interface IUniswapV2Router02 { function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external; } /** * @title AirSwap Converter: Convert Fee Tokens * @notice https://www.airswap.io/ */ contract Converter is Ownable, ReentrancyGuard, TokenPaymentSplitter { using SafeMath for uint256; using SafeERC20 for IERC20; address public wETH; address public swapToToken; address public immutable uniRouter; uint256 public triggerFee; mapping(address => address[]) private tokenPathMapping; event ConvertAndTransfer( address triggerAccount, address swapFromToken, address swapToToken, uint256 amountTokenFrom, uint256 amountTokenTo, address[] recievedAddresses ); event DrainTo(address[] tokens, address dest); constructor( address _wETH, address _swapToToken, address _uniRouter, uint256 _triggerFee, address[] memory _payees, uint256[] memory _shares ) TokenPaymentSplitter(_payees, _shares) { wETH = _wETH; swapToToken = _swapToToken; uniRouter = _uniRouter; setTriggerFee(_triggerFee); } /** * @dev Set a new address for WETH. **/ function setWETH(address _swapWETH) public onlyOwner { require(_swapWETH != address(0), "MUST_BE_VALID_ADDRESS"); wETH = _swapWETH; } /** * @dev Set a new token to swap to (e.g., stabletoken). **/ function setSwapToToken(address _swapToToken) public onlyOwner { require(_swapToToken != address(0), "MUST_BE_VALID_ADDRESS"); swapToToken = _swapToToken; } /** * @dev Set a new fee (perentage 0 - 100) for calling the ConvertAndTransfer function. */ function setTriggerFee(uint256 _triggerFee) public onlyOwner { require(_triggerFee <= 100, "FEE_TOO_HIGH"); triggerFee = _triggerFee; } /** * @dev Set a new Uniswap router path for a token. */ function setTokenPath(address _token, address[] memory _tokenPath) public onlyOwner { uint256 pathLength = _tokenPath.length; for (uint256 i = 0; i < pathLength; i++) { tokenPathMapping[_token].push(_tokenPath[i]); } } /** * @dev Converts an token in the contract to the SwapToToken and transfers to payees. * @param _swapFromToken The token to be swapped from. * @param _amountOutMin The amount to be swapped and distributed. */ function convertAndTransfer(address _swapFromToken, uint256 _amountOutMin) public onlyOwner nonReentrant { // Checks that at least 1 payee is set to recieve converted token. require(_payees.length >= 1, "PAYEES_MUST_BE_SET"); // Calls the balanceOf function from the to be converted token. uint256 tokenBalance = _balanceOfErc20(_swapFromToken); // Checks that the converted token is currently present in the contract. require(tokenBalance > 0, "NO_BALANCE_TO_CONVERT"); // Approve token for AMM usage. _approveErc20(_swapFromToken, tokenBalance); // Read or set the path for AMM. if (_swapFromToken != swapToToken) { address[] memory path; if (tokenPathMapping[_swapFromToken].length > 0) { path = getTokenPath(_swapFromToken); } else { tokenPathMapping[_swapFromToken].push(_swapFromToken); tokenPathMapping[_swapFromToken].push(wETH); if (swapToToken != wETH) { tokenPathMapping[_swapFromToken].push(swapToToken); } path = getTokenPath(_swapFromToken); } // Calls the swap function from the on-chain AMM to swap token from fee pool into reward token. IUniswapV2Router02(uniRouter) .swapExactTokensForTokensSupportingFeeOnTransferTokens( tokenBalance, _amountOutMin, path, address(this), block.timestamp ); } // Calls the balanceOf function from the reward token to get the new balance post-swap. uint256 newTokenBalance = _balanceOfErc20(swapToToken); // Calculates trigger reward amount and transfers to msg.sender. uint256 triggerFeeAmount = newTokenBalance.mul(triggerFee).div(100); _transferErc20(msg.sender, swapToToken, triggerFeeAmount); // Transfers remaining amount to reward payee address(es). uint256 totalPayeeAmount = newTokenBalance.sub(triggerFeeAmount); for (uint256 i = 0; i < _payees.length; i++) { uint256 payeeAmount = (totalPayeeAmount.mul(_shares[_payees[i]])).div( _totalShares ); _transferErc20(_payees[i], swapToToken, payeeAmount); } emit ConvertAndTransfer( msg.sender, _swapFromToken, swapToToken, tokenBalance, totalPayeeAmount, _payees ); } /** * @dev Drains funds from provided list of tokens * @param _transferTo Address of the recipient. * @param _tokens List of tokens to transfer from the contract */ function drainTo(address _transferTo, address[] calldata _tokens) public onlyOwner { for (uint256 i = 0; i < _tokens.length; i++) { uint256 balance = _balanceOfErc20(_tokens[i]); if (balance > 0) { _transferErc20(_transferTo, _tokens[i], balance); } } emit DrainTo(_tokens, _transferTo); } /** * @dev Add a recipient to receive payouts from the consolidateFeeToken function. * @param _account Address of the recipient. * @param _shares Amount of shares to determine th proportion of payout received. */ function addPayee(address _account, uint256 _shares) public onlyOwner { _addPayee(_account, _shares); } /** * @dev Remove a recipient from receiving payouts from the consolidateFeeToken function. * @param _account Address of the recipient. * @param _index Index number of the recipient in the array of recipients. */ function removePayee(address _account, uint256 _index) public onlyOwner { _removePayee(_account, _index); } /** * @dev View Uniswap router path for a token. */ function getTokenPath(address _token) public view onlyOwner returns (address[] memory) { return tokenPathMapping[_token]; } /** * @dev Internal function to approve ERC20 for AMM calls. * @param _tokenToApprove Address of ERC20 to approve. * @param _amount Amount of ERC20 to be approved. * * */ function _approveErc20(address _tokenToApprove, uint256 _amount) internal { require( IERC20(_tokenToApprove).approve(address(uniRouter), _amount), "APPROVE_FAILED" ); } /** * @dev Internal function to transfer ERC20 held in the contract. * @param _recipient Address to receive ERC20. * @param _tokenContract Address of the ERC20. * @param _transferAmount Amount or ERC20 to be transferred. * * */ function _transferErc20( address _recipient, address _tokenContract, uint256 _transferAmount ) internal { IERC20(_tokenContract).safeTransfer(_recipient, _transferAmount); } /** * @dev Internal function to call balanceOf on ERC20. * @param _tokenToBalanceOf Address of ERC20 to call. * * */ function _balanceOfErc20(address _tokenToBalanceOf) internal view returns (uint256) { IERC20 erc; erc = IERC20(_tokenToBalanceOf); uint256 tokenBalance = erc.balanceOf(address(this)); return tokenBalance; } }
* @dev Set a new fee (perentage 0 - 100) for calling the ConvertAndTransfer function./
function setTriggerFee(uint256 _triggerFee) public onlyOwner { require(_triggerFee <= 100, "FEE_TOO_HIGH"); triggerFee = _triggerFee; }
2,492,690
[ 1, 694, 279, 394, 14036, 261, 457, 319, 410, 374, 300, 2130, 13, 364, 4440, 326, 4037, 1876, 5912, 445, 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 ]
[ 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, 225, 445, 444, 6518, 14667, 12, 11890, 5034, 389, 10668, 14667, 13, 1071, 1338, 5541, 288, 203, 565, 2583, 24899, 10668, 14667, 1648, 2130, 16, 315, 8090, 41, 67, 4296, 51, 67, 29996, 8863, 203, 565, 3080, 14667, 273, 389, 10668, 14667, 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 ]
./partial_match/1/0x5a007dA6F25b6991f15aC0372821Ae3521133943/sources/EBULL.sol
Rebalance function changes the price of ebull in uniswap depending on the leveraged fluctuation in Eth Price
function ReBalance() public returns (bool) { require(EnableReb==1,"Rebalance not enabled"); EthNow = getPriceETH_USD(); if(EthNow >= EthOld) { TokenBurn = _updatedBalance[UniLP].sub(_updatedBalance[UniLP].mul(PrPrecision).div(Change)); TokenBurn=TokenBurn.div(10**DECIMALS); _updatedBalance[UniLP] = _updatedBalance[UniLP].sub(TokenBurn.mul(10**DECIMALS)); _totalSupply = _totalSupply.sub(TokenBurn.mul(10**DECIMALS)); } else { { Change = DLimit; } Change= PrPrecision.sub(Change); TokenAdd = _updatedBalance[UniLP].mul(PrPrecision).div(Change); TokenAdd = TokenAdd.sub(_updatedBalance[UniLP]); TokenAdd=TokenAdd.div(10**DECIMALS); _updatedBalance[UniLP] = _updatedBalance[UniLP].add(TokenAdd.mul(10**DECIMALS)); _totalSupply = _totalSupply.add(TokenAdd.mul(10**DECIMALS)); } IUniswapV2Pair(UniLP).sync(); EthOld = EthNow; return true; }
4,275,456
[ 1, 426, 12296, 445, 3478, 326, 6205, 434, 20371, 420, 316, 640, 291, 91, 438, 8353, 603, 326, 884, 502, 11349, 1183, 853, 11407, 316, 512, 451, 20137, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 868, 13937, 1435, 203, 1377, 1071, 203, 565, 1135, 261, 6430, 13, 203, 565, 288, 2583, 12, 8317, 426, 70, 631, 21, 10837, 426, 12296, 486, 3696, 8863, 203, 203, 3639, 512, 451, 8674, 273, 25930, 1584, 44, 67, 3378, 40, 5621, 203, 203, 3639, 309, 12, 41, 451, 8674, 1545, 512, 451, 7617, 13, 203, 3639, 288, 203, 1850, 3155, 38, 321, 273, 389, 7007, 13937, 63, 984, 77, 14461, 8009, 1717, 24899, 7007, 13937, 63, 984, 77, 14461, 8009, 16411, 12, 2050, 15410, 2934, 2892, 12, 3043, 10019, 203, 1850, 3155, 38, 321, 33, 1345, 38, 321, 18, 2892, 12, 2163, 636, 23816, 55, 1769, 203, 1850, 389, 7007, 13937, 63, 984, 77, 14461, 65, 273, 389, 7007, 13937, 63, 984, 77, 14461, 8009, 1717, 12, 1345, 38, 321, 18, 16411, 12, 2163, 636, 23816, 55, 10019, 203, 1850, 389, 4963, 3088, 1283, 273, 389, 4963, 3088, 1283, 18, 1717, 12, 1345, 38, 321, 18, 16411, 12, 2163, 636, 23816, 55, 10019, 203, 3639, 289, 203, 3639, 469, 203, 3639, 288, 203, 203, 1850, 288, 203, 1850, 7576, 273, 463, 3039, 31, 203, 1850, 289, 203, 203, 1850, 7576, 33, 2301, 15410, 18, 1717, 12, 3043, 1769, 203, 1850, 3155, 986, 273, 389, 7007, 13937, 63, 984, 77, 14461, 8009, 16411, 12, 2050, 15410, 2934, 2892, 12, 3043, 1769, 203, 1850, 3155, 986, 273, 3155, 986, 18, 1717, 24899, 7007, 13937, 63, 984, 77, 14461, 19226, 203, 1850, 3155, 986, 33, 1345, 986, 18, 2892, 12, 2163, 636, 23816, 55, 2 ]