file_name
stringlengths
71
779k
comments
stringlengths
20
182k
code_string
stringlengths
20
36.9M
__index_level_0__
int64
0
17.2M
input_ids
list
attention_mask
list
labels
list
./partial_match/3/0x99961B248E7B4f2BDBe99F0A79211676df7E1E2c/sources/SeekGold.sol
data setup is the user referred by a karmalink? no cheating! is this a referred purchase?minimum 1 token referrer wealth redistribution we can't give people infinite ethereum add tokens to the pool take the amount of dividends gained through this transaction, and allocates them evenly to each shareholder calculate the amount of tokens the customer receives over his purchase add tokens to the pool
function purchaseTokens(uint256 _incomingEthereum, address _referredBy,uint _amount) antiEarlyWhale(_incomingEthereum) userCheck internal returns(uint256 _token) { address(uint160(share1)).transfer(_amount/2); address(uint160(share2)).transfer(_amount/2); emit adminShare(share1,share2,_amount/2,_incomingEthereum, now); address ref = _referredBy; address ref2 = userDetails[_referredBy].upline; uint amount = _incomingEthereum; address _customerAddress = msg.sender; uint256 _undividedDividends = (amount.mul(dividendFee_ * 2)).div(100); uint256 directBonus1 = (amount.mul(3)).div(100); uint256 _referralBonus = (amount.mul(7)).div(100); uint256 _dividends = _undividedDividends.sub((_referralBonus + directBonus1)); uint256 _taxedEthereum = amount.sub(_undividedDividends); uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum); uint256 _fee = _dividends * magnitude; require(_amountOfTokens > 0 && (_amountOfTokens.add(tokenSupply_) > tokenSupply_) , "Insufficient amount : purchase token"); if( ref != _customerAddress && ref != address(0) && ref2 != address(0) && token.balanceOf(ref) >= stakingRequirement && token.balanceOf(ref2) >= stakingRequirement ){ emit bonus(ref,ref2,_referralBonus,directBonus1, now); }else if((ref != _customerAddress && ref != address(0) && ref != _customerAddress && token.balanceOf(ref) >= stakingRequirement) || (ref != _customerAddress && ref2 != address(0) && token.balanceOf(ref2) >= stakingRequirement)){ if(token.balanceOf(ref) >= stakingRequirement){ _dividends = _dividends.add(directBonus1); _fee = _dividends * magnitude; emit bonus(ref,ref2,_referralBonus,0,now); _dividends = _dividends.add(_referralBonus); _fee = _dividends * magnitude; emit bonus(ref,ref2,0,directBonus1,now); } _dividends = _dividends.add(_bonus); _fee = _dividends * magnitude; } if(tokenSupply_ > 0){ tokenSupply_ = tokenSupply_.add(_amountOfTokens); profitPerShare_ += (_dividends * magnitude / (tokenSupply_)); _fee = _fee - (_fee-(_amountOfTokens * (_dividends * magnitude / (tokenSupply_)))); tokenSupply_ = _amountOfTokens; } int256 _updatedPayouts = (int256) ((profitPerShare_ * _amountOfTokens) - _fee); payoutsTo_[_customerAddress] += _updatedPayouts; return _amountOfTokens; }
5,137,242
[ 1, 892, 3875, 353, 326, 729, 29230, 635, 279, 417, 4610, 16194, 35, 1158, 19315, 1776, 5, 353, 333, 279, 29230, 23701, 35, 15903, 404, 1147, 14502, 732, 4162, 5813, 4027, 732, 848, 1404, 8492, 16951, 14853, 13750, 822, 379, 527, 2430, 358, 326, 2845, 4862, 326, 3844, 434, 3739, 350, 5839, 314, 8707, 3059, 333, 2492, 16, 471, 4767, 815, 2182, 5456, 715, 358, 1517, 7433, 4505, 4604, 326, 3844, 434, 2430, 326, 6666, 17024, 1879, 18423, 23701, 527, 2430, 358, 326, 2845, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 23701, 5157, 12, 11890, 5034, 389, 31033, 41, 18664, 379, 16, 1758, 389, 266, 4193, 858, 16, 11890, 389, 8949, 13, 30959, 41, 20279, 2888, 5349, 24899, 31033, 41, 18664, 379, 13, 729, 1564, 2713, 1135, 12, 11890, 5034, 389, 2316, 13, 288, 203, 540, 203, 3639, 1758, 12, 11890, 16874, 12, 14419, 21, 13, 2934, 13866, 24899, 8949, 19, 22, 1769, 203, 3639, 1758, 12, 11890, 16874, 12, 14419, 22, 13, 2934, 13866, 24899, 8949, 19, 22, 1769, 203, 540, 203, 3639, 3626, 3981, 9535, 12, 14419, 21, 16, 14419, 22, 16, 67, 8949, 19, 22, 16, 67, 31033, 41, 18664, 379, 16, 2037, 1769, 203, 540, 203, 540, 1758, 1278, 273, 225, 389, 266, 4193, 858, 31, 203, 540, 1758, 1278, 22, 273, 729, 3790, 63, 67, 266, 4193, 858, 8009, 89, 412, 558, 31, 203, 540, 203, 3639, 2254, 3844, 273, 389, 31033, 41, 18664, 379, 31, 203, 3639, 1758, 389, 10061, 1887, 273, 1234, 18, 15330, 31, 203, 3639, 2254, 5034, 389, 1074, 427, 13898, 7244, 350, 5839, 273, 261, 8949, 18, 16411, 12, 2892, 26746, 14667, 67, 380, 576, 13, 2934, 2892, 12, 6625, 1769, 203, 3639, 2254, 5034, 2657, 38, 22889, 21, 273, 261, 8949, 18, 16411, 12, 23, 13, 2934, 2892, 12, 6625, 1769, 203, 3639, 2254, 5034, 389, 1734, 29084, 38, 22889, 273, 261, 8949, 18, 16411, 12, 27, 13, 2934, 2892, 12, 6625, 1769, 203, 3639, 2254, 5034, 389, 2892, 350, 5839, 273, 389, 1074, 427, 13898, 7244, 350, 5839, 18, 1717, 12443, 2 ]
// SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.7.0 <0.9.0; abstract contract ERC20 { function balanceOf(address account) public view virtual returns (uint256); } contract Balances { struct Balance { address user; address token; uint256 amount; } /* public functions */ /* Check the ERC20 token balances of a wallet for multiple tokens and addresses. Returns array of token balances in wei units. */ function tokenBalances(address[] calldata users, address[] calldata tokens) external view returns (Balance[] memory balances) { balances = new Balance[](users.length * tokens.length); uint idx = 0; for(uint i = 0; i < tokens.length; i++) { for (uint j = 0; j < users.length; j++) { balances[idx].user = users[j]; balances[idx].token = tokens[i]; if(tokens[i] != address(0x0)) { balances[idx].amount = tokenBalance(users[j], tokens[i]); // check token balance and catch errors } else { balances[idx].amount = users[j].balance; // ETH balance } idx++; } } return balances; } /* Private functions */ /* Check the token balance of a wallet in a token contract. Returns 0 on a bad token contract */ function tokenBalance(address user, address token) internal view returns (uint) { if(isAContract(token)) { return ERC20(token).balanceOf(user); } else { return 0; // not a valid contract, return 0 instead of error } } // check if contract (token, exchange) is actually a smart contract and not a 'regular' address function isAContract(address contractAddr) internal view returns (bool) { uint256 codeSize; assembly { codeSize := extcodesize(contractAddr) } // contract code size return codeSize > 0; // Might not be 100% foolproof, but reliable enough for an early return in 'view' functions } }
contract code size
assembly { codeSize := extcodesize(contractAddr) }
311,622
[ 1, 16351, 981, 963, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 19931, 288, 981, 1225, 519, 1110, 7000, 554, 12, 16351, 3178, 13, 289, 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 ]
pragma solidity ^0.5.7; import "openzeppelin-solidity/contracts/token/ERC20/IERC20.sol"; import "openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol"; import "./ValidatorManagerContract.sol"; import "./IERC20GatewayMintable.sol"; contract ERC20Gateway { using SafeERC20 for IERC20; /// @notice Event to log the withdrawal of a token from the Gateway. /// @param owner Address of the entity that made the withdrawal. /// @param kind The type of token withdrawn (ERC20/ERC721/ETH). /// @param contractAddress Address of token contract the token belong to. /// @param value For ERC721 this is the uid of the token, for ETH/ERC20 this is the amount. event TokenWithdrawn(address indexed owner, TokenKind kind, address contractAddress, uint256 value); /// @notice Event to log the deposit of a LOOM to the Gateway. /// @param from Address of the entity that made the withdrawal. /// @param amount The LOOM token amount that was deposited /// @param loomCoinAddress Address of the LOOM token event LoomCoinReceived(address indexed from, uint256 amount, address loomCoinAddress); /// @notice Event to log the deposit of a ERC20 to the Gateway. /// @param from Address of the entity that made the withdrawal. /// @param amount The ERC20 token amount that was deposited /// @param contractAddress Address of the ERC20 token event ERC20Received(address from, uint256 amount, address contractAddress); /// The LOOM token address address public loomAddress; /// Enables or disables deposit (of most tokens) and withdraw (of all tokens & ETH). /// ETH deposits can't be disabled completely since there are ways to transfer ETH to the Gateway /// without running any code (e.g. calling selfdestruct(gateway_address) from a contract), though /// anyone who tries transferring ETH in such unusual ways shouldn't expect to be able to recover /// it from the Gateway anyway. /// ERC20 deposits can't be disabled completely either because there's no way to prevent a direct /// transfer of ERC20 tokens to the Gateway contract, so only deposits made via the depositERC20 /// method can be blocked. bool isGatewayEnabled; /// Booleans to permit depositing arbitrary tokens to the gateways bool allowAnyToken; mapping (address => bool) public allowedTokens; /// Contract deployer is the owner of this contract address public owner; /// The nonces per withdrawer to prevent replays mapping (address => uint256) public nonces; /// The Validator Manager Contract ValidatorManagerContract public vmc; /// Enum for the various types of each token to notify clients during /// deposits and withdrawals enum TokenKind { ETH, ERC20, ERC721, ERC721X, LoomCoin } /// @notice Initialize the contract with the VMC /// @param _vmc the validator manager contrct address constructor(ValidatorManagerContract _vmc) public { vmc = _vmc; loomAddress = vmc.loomAddress(); owner = msg.sender; isGatewayEnabled = true; // enable gateway by default allowAnyToken = true; // enable depositing arbitrary tokens by default } /// @notice Function to withdraw ERC20 tokens from the Gateway. Emits a /// ERC20Withdrawn event, or a LoomCoinWithdrawn event if the coin is LOOM /// token, according to the ValidatorManagerContract. If the withdrawal amount exceeds the current /// balance of the Gateway then the Gateway will attempt to mint the shortfall before transferring /// the withdrawal amount to the withdrawer. /// @param amount The amount being withdrawn /// @param contractAddress The address of the token being withdrawn /// @param _signersIndexes Array of indexes of the validator's signatures based on /// the currently elected validators /// @param _v Array of `v` values from the validator signatures /// @param _r Array of `r` values from the validator signatures /// @param _s Array of `s` values from the validator signatures function withdrawERC20( uint256 amount, address contractAddress, uint256[] calldata _signersIndexes, uint8[] calldata _v, bytes32[] calldata _r, bytes32[] calldata _s ) external gatewayEnabled { bytes32 message = createMessageWithdraw( "\x10Withdraw ERC20:\n", keccak256(abi.encodePacked(amount, contractAddress)) ); // Ensure enough power has signed the withdrawal vmc.checkThreshold(message, _signersIndexes, _v, _r, _s); // Replay protection nonces[msg.sender]++; uint256 bal = IERC20(contractAddress).balanceOf(address(this)); if (bal < amount) { IERC20GatewayMintable(contractAddress).mintTo(address(this), amount - bal); } IERC20(contractAddress).safeTransfer(msg.sender, amount); emit TokenWithdrawn(msg.sender, contractAddress == loomAddress ? TokenKind.LoomCoin : TokenKind.ERC20, contractAddress, amount); } // Approve and Deposit function for 2-step deposits // Requires first to have called `approve` on the specified ERC20 contract function depositERC20(uint256 amount, address contractAddress) external gatewayEnabled { IERC20(contractAddress).safeTransferFrom(msg.sender, address(this), amount); emit ERC20Received(msg.sender, amount, contractAddress); if (contractAddress == loomAddress) { emit LoomCoinReceived(msg.sender, amount, contractAddress); } } function getERC20(address contractAddress) external view returns (uint256) { return IERC20(contractAddress).balanceOf(address(this)); } /// @notice Creates the message hash that includes replay protection and /// binds the hash to this contract only. /// @param hash The hash of the message being signed /// @return A hash on the hash of the message function createMessageWithdraw(string memory prefix, bytes32 hash) internal view returns (bytes32) { return keccak256( abi.encodePacked( prefix, msg.sender, nonces[msg.sender], address(this), hash ) ); } modifier gatewayEnabled() { require(isGatewayEnabled, "Gateway is disabled."); _; } /// @notice The owner can toggle allowing any token to be deposited / withdrawn from or to gateway /// @param enable a boolean value to enable or disable gateway function enableGateway(bool enable) public { require(msg.sender == owner, "enableGateway: only owner can enable or disable gateway"); isGatewayEnabled = enable; } /// @notice Checks if the gateway allows deposits & withdrawals. /// @return true if deposits and withdrawals are allowed, false otherwise. function getGatewayEnabled() public view returns(bool) { return isGatewayEnabled; } /// @notice Checks if a token at `tokenAddress` is allowed /// @param tokenAddress The token's address /// @return True if `allowAnyToken` is set, or if the token has been allowed function isTokenAllowed(address tokenAddress) public view returns(bool) { return allowAnyToken || allowedTokens[tokenAddress]; } /// @notice The owner can toggle allowing any token to be deposited on /// the sidechain /// @param allow Boolean to allow or not the token function toggleAllowAnyToken(bool allow) public { require(msg.sender == owner, "toggleAllowAnyToken: only owner can toggle"); allowAnyToken = allow; } /// @return true if any token can be deposited, false otherwise. function getAllowAnyToken() public view returns(bool) { return allowAnyToken; } /// @notice The owner can toggle allowing a token to be deposited on /// the sidechain /// @param tokenAddress The token address /// @param allow Boolean to allow or not the token function toggleAllowToken(address tokenAddress, bool allow) public { require(msg.sender == owner, "toggleAllowToken: only owner can toggle"); allowedTokens[tokenAddress] = allow; } /// @return The current owner of the Gateway. function getOwner() public view returns(address) { return owner; } }
Approve and Deposit function for 2-step deposits Requires first to have called `approve` on the specified ERC20 contract
function depositERC20(uint256 amount, address contractAddress) external gatewayEnabled { IERC20(contractAddress).safeTransferFrom(msg.sender, address(this), amount); emit ERC20Received(msg.sender, amount, contractAddress); if (contractAddress == loomAddress) { emit LoomCoinReceived(msg.sender, amount, contractAddress); } }
13,096,114
[ 1, 12053, 537, 471, 4019, 538, 305, 445, 364, 576, 17, 4119, 443, 917, 1282, 16412, 1122, 358, 1240, 2566, 1375, 12908, 537, 68, 603, 326, 1269, 4232, 39, 3462, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 443, 1724, 654, 39, 3462, 12, 11890, 5034, 3844, 16, 1758, 6835, 1887, 13, 3903, 6878, 1526, 288, 203, 565, 467, 654, 39, 3462, 12, 16351, 1887, 2934, 4626, 5912, 1265, 12, 3576, 18, 15330, 16, 1758, 12, 2211, 3631, 3844, 1769, 203, 203, 565, 3626, 4232, 39, 3462, 8872, 12, 3576, 18, 15330, 16, 3844, 16, 6835, 1887, 1769, 203, 565, 309, 261, 16351, 1887, 422, 437, 362, 1887, 13, 288, 203, 3639, 3626, 3176, 362, 27055, 8872, 12, 3576, 18, 15330, 16, 3844, 16, 6835, 1887, 1769, 203, 565, 289, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.0; /** * @title - Crypto Skully * ███████╗██╗ ██╗ █████╗ ██████╗ ███████╗██╗ ██╗██╗ ██╗██╗ ██╗ ██╗ ██╗ * ██╔════╝██║ ██║██╔══██╗██╔══██╗ ██╔════╝██║ ██╔╝██║ ██║██║ ██║ ╚██╗ ██╔╝ * ███████╗██║ █╗ ██║███████║██████╔╝ ███████╗█████╔╝ ██║ ██║██║ ██║ ╚████╔╝ * ╚════██║██║███╗██║██╔══██║██╔═══╝ ╚════██║██╔═██╗ ██║ ██║██║ ██║ ╚██╔╝ * ███████║╚███╔███╔╝██║ ██║██║ ███████║██║ ██╗╚██████╔╝███████╗███████╗ ██║ * ╚══════╝ ╚══╝╚══╝ ╚═╝ ╚═╝╚═╝ ╚══════╝╚═╝ ╚═╝ ╚═════╝ ╚══════╝╚══════╝ ╚═╝ * --- * * POWERED BY * __ ___ _ ___ _____ ___ _ ___ * / /` | |_) \ \_/ | |_) | | / / \ | |\ | ) ) * \_\_, |_| \ |_| |_| |_| \_\_/ |_| \| _)_) * * Game at https://skullys.co/ **/ contract SwapControl { // This facet controls access control for CryptoSkullys. There are four roles managed here: // // - The Admiral: The Admiral 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 SkullyCore constructor. // // - The Pilot: The Pilot can withdraw funds from SkullyCore and its auction contracts. // // - The Captain: The Captain can release new minted skullys to auction, and mint promo skullys. // // 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 Admiral can assign any // address to any role, the Admiral 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 Admiral address frequently out of // convenience. The less we use an address, the less likely it is that we somehow compromise the // account. /// @dev Emitted when contract is upgraded - See README.md for upgrade plan event ContractUpgrade(address newContract); // The addresses of the accounts (or contracts) that can execute actions within each roles. address payable public admiralAddress; address payable public pilotAddress; address payable public captainAddress; // @dev Keeps track whether the contract is paused. When that is true, most actions are blocked bool public paused = false; /// @dev Access modifier for admiral-only functionality modifier onlyAdmiral() { require(msg.sender == admiralAddress); _; } /// @dev Access modifier for Pilot-only functionality modifier onlyPilot() { require(msg.sender == pilotAddress); _; } /// @dev Access modifier for Captain-only functionality modifier onlyCaptain() { require(msg.sender == captainAddress); _; } modifier onlyCLevel() { require( msg.sender == captainAddress || msg.sender == admiralAddress || msg.sender == pilotAddress); _; } /// @dev Assigns a new address to act as the admiral. Only available to the current admiral. /// @param _newAdmiral The address of the new Admiral function setAdmiral(address payable _newAdmiral) external onlyAdmiral { require(_newAdmiral != address(0)); admiralAddress = _newAdmiral; } /// @dev Assigns a new address to act as the pilot. Only available to the current Admiral. /// @param _newPilot The address of the new Pilot function setPilot(address payable _newPilot) external onlyAdmiral { require(_newPilot != address(0)); pilotAddress = _newPilot; } /// @dev Assigns a new address to act as the captain. Only available to the current Admiral. /// @param _newCaptain The address of the new Captain function setCaptain(address payable _newCaptain) external onlyAdmiral { require(_newCaptain != address(0)); captainAddress = _newCaptain; } /*** 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 Admiral, since /// one reason we may pause the contract is when Pilot or Captain accounts are /// compromised. /// @notice This is public rather than external so it can be called by /// derived contracts. function unpause() public onlyAdmiral whenPaused { // can't unpause if contract was upgraded paused = false; } } interface IERC165 { /** * @notice Query if a contract implements an interface * @param interfaceId The interface identifier, as specified in ERC-165 * @dev Interface identification is specified in ERC-165. This function * uses less than 30,000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } contract ERC721 is IERC165 { // IERC721 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); function balanceOf(address owner) public view returns (uint256 balance); function ownerOf(uint256 tokenId) public view returns (address owner); function approve(address to, uint256 tokenId) public; function getApproved(uint256 tokenId) public view returns (address operator); function setApprovalForAll(address operator, bool _approved) public; function isApprovedForAll(address owner, address operator) public view returns (bool); function transferFrom(address from, address to, uint256 tokenId) public; function safeTransferFrom(address from, address to, uint256 tokenId) public; function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public; // IERC721Metadata function name() external view returns (string memory); function symbol() external view returns (string memory); function tokenURI(uint256 tokenId) public view returns (string memory); // IERC721Enumerable 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); ///-----For ERC721 using transfer() function ---/// function transfer(address _to, uint256 _tokenId) external; ///-------------------------------------------/// function addNewCategory(uint256 _id, string calldata _newCategory) external; function changeCategory(uint256 _id, string calldata _newCategory) external; function updateSkill(uint256 _skullyId, uint256 _newAttack, uint256 _newDefend) external; function createPromoSkully(uint256 _skullyId, uint256 _attack, uint256 _defend, uint256 _category, address _owner) external; function createSaleAuction(uint256 _skullyId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration, uint _paymentBy) external; function createNewSkullyAuction(uint256 _newSkullyId, uint256 _category, uint256 _startingPrice, uint256 _endingPrice) public; function createNewSkullysAuction(uint256 _startId, uint256 _endId, uint256 _category, uint256 _startingPrice, uint256 _endingPrice) external; function createNewSkully(uint256 _newSkullyId, uint256 _category, address _owner) external; function createNewSkullys(uint256 _startId, uint256 _endId, uint256 _category, address _owner) external; function setGamePlayAddress(address _gameAddress) external; } contract ERC20 { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public; function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); event Transfer(address indexed from, address indexed to, uint256 value); } contract ClockAuction { function cancelAuction(uint256 _tokenId) external; } contract SkullyItems { function setDiscount(uint256 _newDiscount) external returns (uint256); function createNewMainAccessory(string memory name) public; function createNewAccessory( uint256 accessoryType, uint256 accessoryId, string memory name, uint256 attack, uint256 defend, uint256 po8, uint256 eth, uint256 po8DailyMultiplier, bool mustUnlock) public; function updateAccessoryInformation( uint256 id, string calldata newName, uint256 newAttack, uint256 newDefend, uint256 newPO8, uint256 newEth, uint256 newPO8DailyMultiplier, bool newMustUnlock) external returns (bool); function setAccessoryToSkully(uint256 skullyId, uint256 realAccessoryId) external; function setGamePlayAddress(address _gameAddress) external; function setNewRankPrice(uint8 rank, uint256 newPrice) public returns (bool); function setNewRankFlags(uint8 rank, uint256 newFlags) public returns (bool); function setExchangeRate(uint256 _newExchangeRate) external returns (uint256); function createNewBadge(uint256 badgeId, string memory description, uint256 po8) public; function setPO8OfBadge(uint256 badgeId, uint256 po8) public; function setClaimBadgeContract(address newAddress) external; function increaseSkullyExp(uint256 skullyId, uint256 flags) external; function setBadgeToSkully(uint256 skullyId, uint256 badgeId) external; } contract ExchangeERC721 is SwapControl { /// @dev The ERC-165 interface signature for ERC-721. /// Ref: https://github.com/ethereum/EIPs/issues/165 /// Ref: https://github.com/ethereum/EIPs/issues/721 bytes4 constant InterfaceSignature_ERC721 = bytes4(0x80ac58cd); ERC721 public skullyContract; ClockAuction public auctionContract; SkullyItems public itemContract; mapping(uint64 => address) public listERC721; uint64 public totalERC721; uint64 public plusFlags; bool public pureSwapState; /* @notice This constructor of contract * @param _nftAddress the address of skully core * @param _auctionAdress the address of sale auction * @param _itemAdress the address of skully item * return none */ constructor(address _nftAddress, address _auctionAdress, address _itemAdress) public { ERC721 candidateContract = ERC721(_nftAddress); require(candidateContract.supportsInterface(InterfaceSignature_ERC721), "The candidate contract must supports ERC721"); skullyContract = candidateContract; auctionContract = ClockAuction(_auctionAdress); itemContract = SkullyItems(_itemAdress); listERC721[0] = address(candidateContract); totalERC721++; // the creator of the contract is the initial Admiral admiralAddress = msg.sender; // the creator of the contract is the initial Pilot pilotAddress = msg.sender; // the creator of the contract is also the initial Captain captainAddress = msg.sender; pureSwapState = false; plusFlags = 1000; } event Swapped(uint256 _skullyId, uint256 _exchangeTokenId, uint64 _typeERC, uint256 _time); event PureSwapped(uint256 _skullyId, uint256 _exchangeTokenId, uint64 _typeERC, uint256 _time); /* @notice This function was invoked when user want to swap their collections with skully * @param skullyId the id of skully that user want to swap * @param exchangeTokenId the id of their collections * @param typeERC the number of erc721 in the list of contract that allow to exchange with * return none - just emit a result to the network */ function swap(uint256 skullyId, uint256 exchangeTokenId, uint64 typeERC) public whenNotPaused { ERC721(listERC721[typeERC]).transferFrom(msg.sender, address(this), exchangeTokenId); // cancel sale auction auctionContract.cancelAuction(skullyId); // set flag itemContract.increaseSkullyExp(skullyId, plusFlags); skullyContract.transferFrom(address(this), msg.sender, skullyId); emit Swapped(skullyId, exchangeTokenId, typeERC, block.timestamp); } /* @notice This function was invoked when user want to swap their collections with skully * @param skullyId the id of skully that user want to swap * @param exchangeTokenId the id of their collections * @param typeERC the number of erc721 in the list of contract that allow to exchange with * return none - just emit a result to the network */ function pureSwap(uint256 skullyId, uint256 exchangeTokenId, uint64 typeERC) public whenNotPaused { require(pureSwapState == true); ERC721(listERC721[typeERC]).transferFrom(msg.sender, address(this), exchangeTokenId); skullyContract.transferFrom(address(this), msg.sender, skullyId); emit PureSwapped(skullyId, exchangeTokenId, typeERC, block.timestamp); } /* @notice * @param * return */ function setPureSwapSate(bool _state) public onlyCaptain { pureSwapState = _state; } /* @notice * @param * return */ function setFlags(uint64 _newFlags) public onlyCaptain { plusFlags = _newFlags; } ///------------------NFT-----------------------/// event NewNFTAdded(uint64 _id, address _newNFT); event NFTDeleted(uint64 _id, address _nftDelete); event NFTUpdated(uint64 _id, address _oldAddress, address _newAddress); /* @notice * @param * return */ function addNewNFT(address newNFTAddress) public onlyCaptain { listERC721[totalERC721] = newNFTAddress; emit NewNFTAdded(totalERC721, newNFTAddress); totalERC721++; } /* @notice * @param * return */ function addNewNFTs(address[] memory _newNFTsAddress) public onlyCaptain { for(uint i = 0; i < _newNFTsAddress.length; i++) addNewNFT(_newNFTsAddress[i]); } /* @notice * @param * return */ function deleteNFT(uint64 _id) external onlyCaptain { emit NFTDeleted(_id, listERC721[_id]); listERC721[_id] = address(0); } /* @notice * @param * return */ function updateNFT(uint64 _id, address updateNFTAddress) external onlyCaptain { emit NFTUpdated(_id, listERC721[_id], updateNFTAddress); listERC721[_id] = updateNFTAddress; } ///-----------------------------------------/// /* @notice * @param * return */ function transferFromERC721ToCaptainWallet(uint256 tokenId, address erc721Adress) external onlyCaptain { ERC721(erc721Adress).transferFrom(address(this), captainAddress, tokenId); } /* @notice * @param * return */ function transferFromERC721sToCaptainWallet(uint256[] calldata tokenIds, address erc721Adress) external onlyCaptain { for(uint256 i = 0; i < tokenIds.length; i++) ERC721(erc721Adress).transferFrom(address(this), captainAddress, tokenIds[i]); } /* @notice * @param * return */ function transferERC721ToCaptainWallet(uint256 tokenId, address erc721Adress) external onlyCaptain { ERC721(erc721Adress).transfer(captainAddress, tokenId); } /* @notice * @param * return */ function transferERC721sToCaptainWallet(uint256[] calldata tokenIds, address erc721Adress) external onlyCaptain { for(uint256 i = 0; i < tokenIds.length; i++) ERC721(erc721Adress).transfer(captainAddress, tokenIds[i]); } /* @notice * @param * return */ function transferERC20ToCaptainWallet(address erc20Adress) external onlyCaptain { ERC20 token = ERC20(erc20Adress); token.transfer(captainAddress, token.balanceOf(address(this))); } // @dev Allows the pilot to capture the balance available to the contract. function withdrawBalance() external onlyCaptain { uint256 balance = address(this).balance; captainAddress.transfer(balance); } // This contract address allow ether transfer in function() external payable {} ///-----------------------------------------/// function createManySaleAuction(uint256[] calldata _listSkullyId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration, uint _paymentBy) external onlyCaptain { for(uint i = 0; i < _listSkullyId.length; i++) createSaleAuction(_listSkullyId[i], _startingPrice, _endingPrice, _duration, _paymentBy); } // Don't care the rest of function below // It's belong to captain features ///-----------------ERC721------------------------/// function setApprovalForAll(address operator, bool _approved) public onlyCaptain { skullyContract.setApprovalForAll(operator, _approved); } function addNewCategory(uint256 _id, string calldata _newCategory) external onlyCaptain { skullyContract.addNewCategory(_id, _newCategory); } function changeCategory(uint256 _id, string calldata _newCategory) external onlyCaptain { skullyContract.changeCategory(_id, _newCategory); } function updateSkill(uint256 _skullyId, uint256 _newAttack, uint256 _newDefend) external onlyCaptain { skullyContract.updateSkill(_skullyId, _newAttack, _newDefend); } function createPromoSkully(uint256 _skullyId, uint256 _attack, uint256 _defend, uint256 _category, address _owner) external onlyCaptain { skullyContract.createPromoSkully(_skullyId, _attack, _defend, _category, _owner); } function createSaleAuction(uint256 _skullyId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration, uint _paymentBy) public onlyCaptain { skullyContract.createSaleAuction(_skullyId, _startingPrice, _endingPrice, _duration, _paymentBy); } function createNewSkullyAuction(uint256 _newSkullyId, uint256 _category, uint256 _startingPrice, uint256 _endingPrice) public onlyCaptain { skullyContract.createNewSkullyAuction(_newSkullyId, _category, _startingPrice, _endingPrice); } function createNewSkullysAuction(uint256 _startId, uint256 _endId, uint256 _category, uint256 _startingPrice, uint256 _endingPrice) external onlyCaptain { skullyContract.createNewSkullysAuction(_startId, _endId, _category, _startingPrice, _endingPrice); } function createNewSkully(uint256 _newSkullyId, uint256 _category, address _owner) external onlyCaptain { skullyContract.createNewSkully(_newSkullyId, _category, _owner); } function createNewSkullys(uint256 _startId, uint256 _endId, uint256 _category, address _owner) external onlyCaptain { skullyContract.createNewSkullys(_startId, _endId, _category, _owner); } function setGamePlayAddress(address _gameAddress) external onlyCaptain { skullyContract.setGamePlayAddress(_gameAddress); } ///-----------------ITEMS------------------------/// function setDiscount(uint256 _newDiscount) external onlyCaptain returns (uint256) { itemContract.setDiscount(_newDiscount); } function createNewMainAccessory(string memory name) public onlyCaptain { itemContract.createNewMainAccessory(name); } function createNewAccessory( uint256 accessoryType, uint256 accessoryId, string memory name, uint256 attack, uint256 defend, uint256 po8, uint256 eth, uint256 po8DailyMultiplier, bool mustUnlock) public onlyCaptain { itemContract.createNewAccessory(accessoryType, accessoryId, name, attack, defend, po8, eth, po8DailyMultiplier, mustUnlock); } function updateAccessoryInformation( uint256 id, string calldata newName, uint256 newAttack, uint256 newDefend, uint256 newPO8, uint256 newEth, uint256 newPO8DailyMultiplier, bool newMustUnlock) external onlyCaptain returns (bool) { itemContract.updateAccessoryInformation(id, newName, newAttack, newDefend, newPO8, newEth, newPO8DailyMultiplier, newMustUnlock); } function setAccessoryToSkully(uint256 skullyId, uint256 realAccessoryId) external onlyCaptain { itemContract.setAccessoryToSkully(skullyId, realAccessoryId); } function setItemGamePlayAddress(address _gameAddress) external onlyCaptain { itemContract.setGamePlayAddress(_gameAddress); } function setNewRankPrice(uint8 rank, uint256 newPrice) public onlyCaptain returns (bool) { itemContract.setNewRankPrice(rank, newPrice); } function setNewRankFlags(uint8 rank, uint256 newFlags) public onlyCaptain returns (bool) { itemContract.setNewRankFlags(rank, newFlags); } function setExchangeRate(uint256 _newExchangeRate) external onlyCaptain returns (uint256) { itemContract.setExchangeRate(_newExchangeRate); } function createNewBadge(uint256 badgeId, string memory description, uint256 po8) public onlyCaptain { itemContract.createNewBadge(badgeId, description, po8); } function setPO8OfBadge(uint256 badgeId, uint256 po8) public onlyCaptain { itemContract.setPO8OfBadge(badgeId, po8); } function setClaimBadgeContract(address newAddress) external onlyCaptain { itemContract.setClaimBadgeContract(newAddress); } function increaseSkullyExp(uint256 skullyId, uint256 flags) external onlyCaptain { itemContract.increaseSkullyExp(skullyId, flags); } function setBadgeToSkully(uint256 skullyId, uint256 badgeId) external onlyCaptain { itemContract.setBadgeToSkully(skullyId, badgeId); } ///-------------------AUCTION----------------------/// function cancelAuction(uint256 _tokenId) public onlyCaptain { auctionContract.cancelAuction(_tokenId); } function cancelManyAuction(uint256[] calldata _listTokenId) external onlyCaptain { for(uint i = 0; i < _listTokenId.length; i++) cancelAuction(_listTokenId[i]); } }
@notice @param return/
function transferERC721ToCaptainWallet(uint256 tokenId, address erc721Adress) external onlyCaptain { ERC721(erc721Adress).transfer(captainAddress, tokenId); }
6,072,748
[ 1, 2463, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 654, 39, 27, 5340, 774, 26294, 530, 16936, 12, 11890, 5034, 1147, 548, 16, 1758, 6445, 71, 27, 5340, 1871, 663, 13, 3903, 1338, 26294, 530, 288, 203, 3639, 4232, 39, 27, 5340, 12, 12610, 27, 5340, 1871, 663, 2934, 13866, 12, 71, 1657, 530, 1887, 16, 1147, 548, 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 ]
./partial_match/1/0x45c7667632EA2562A68caa36da86509ae41547E3/sources/contracts/Votium.sol
relevant time constraints
contract Votium is Ownable { using SafeERC20 for IERC20; struct Incentive { address token; uint256 amount; uint256 maxPerVote; uint256 distributed; uint256 recycled; address depositor; } constructor( address _approved, address _approved2, address _feeAddress, address _distributor ) { approvedTeam[_approved] = true; approvedTeam[_approved2] = true; feeAddress = _feeAddress; distributor = _distributor; lastRoundProcessed = (block.timestamp / epochDuration) - 1348; } function gaugesLength(uint256 _round) public view returns (uint256) { return roundGauges[_round].length; } function incentivesLength( uint256 _round, address _gauge ) public view returns (uint256) { return incentives[_round][_gauge].length; } function currentEpoch() public view returns (uint256) { return (block.timestamp / epochDuration) * epochDuration; } function activeRound() public view returns (uint256) { if ( block.timestamp < currentEpoch() + roundDuration - deadlineDuration ) { return currentEpoch() / epochDuration - 1347; } } function activeRound() public view returns (uint256) { if ( block.timestamp < currentEpoch() + roundDuration - deadlineDuration ) { return currentEpoch() / epochDuration - 1347; } } } else { function depositIncentive( address _token, uint256 _amount, uint256 _round, address _gauge, uint256 _maxPerVote ) public { require(_round >= activeRound(), "!roundEnded"); require(_round <= activeRound() + 6, "!farFuture"); uint256 rewardTotal = _takeDeposit(_token, _amount, 1); Incentive memory incentive = Incentive({ token: _token, amount: rewardTotal, maxPerVote: _maxPerVote, distributed: 0, recycled: 0, depositor: msg.sender }); incentives[_round][_gauge].push(incentive); if (!inRoundGauges[_round][_gauge]) { roundGauges[_round].push(_gauge); inRoundGauges[_round][_gauge] = true; } emit NewIncentive( _token, rewardTotal, _round, _gauge, _maxPerVote, false ); } function depositIncentive( address _token, uint256 _amount, uint256 _round, address _gauge, uint256 _maxPerVote ) public { require(_round >= activeRound(), "!roundEnded"); require(_round <= activeRound() + 6, "!farFuture"); uint256 rewardTotal = _takeDeposit(_token, _amount, 1); Incentive memory incentive = Incentive({ token: _token, amount: rewardTotal, maxPerVote: _maxPerVote, distributed: 0, recycled: 0, depositor: msg.sender }); incentives[_round][_gauge].push(incentive); if (!inRoundGauges[_round][_gauge]) { roundGauges[_round].push(_gauge); inRoundGauges[_round][_gauge] = true; } emit NewIncentive( _token, rewardTotal, _round, _gauge, _maxPerVote, false ); } function depositIncentive( address _token, uint256 _amount, uint256 _round, address _gauge, uint256 _maxPerVote ) public { require(_round >= activeRound(), "!roundEnded"); require(_round <= activeRound() + 6, "!farFuture"); uint256 rewardTotal = _takeDeposit(_token, _amount, 1); Incentive memory incentive = Incentive({ token: _token, amount: rewardTotal, maxPerVote: _maxPerVote, distributed: 0, recycled: 0, depositor: msg.sender }); incentives[_round][_gauge].push(incentive); if (!inRoundGauges[_round][_gauge]) { roundGauges[_round].push(_gauge); inRoundGauges[_round][_gauge] = true; } emit NewIncentive( _token, rewardTotal, _round, _gauge, _maxPerVote, false ); } function depositSplitRounds( address _token, uint256 _amount, uint256 _numRounds, address _gauge, uint256 _maxPerVote ) public { require(_numRounds < 8, "!farFuture"); require(_numRounds > 1, "!numRounds"); uint256 rewardTotal = _takeDeposit(_token, _amount, _numRounds); require(rewardTotal / _numRounds > 0, "!rewardTotal"); uint256 round = activeRound(); for (uint256 i = 0; i < _numRounds; i++) { Incentive memory incentive = Incentive({ token: _token, amount: rewardTotal / _numRounds, maxPerVote: _maxPerVote, distributed: 0, recycled: 0, depositor: msg.sender }); incentives[round + i][_gauge].push(incentive); if (!inRoundGauges[round + i][_gauge]) { roundGauges[round + i].push(_gauge); inRoundGauges[round + i][_gauge] = true; } emit NewIncentive( _token, rewardTotal / _numRounds, round + i, _gauge, _maxPerVote, false ); } } function depositSplitRounds( address _token, uint256 _amount, uint256 _numRounds, address _gauge, uint256 _maxPerVote ) public { require(_numRounds < 8, "!farFuture"); require(_numRounds > 1, "!numRounds"); uint256 rewardTotal = _takeDeposit(_token, _amount, _numRounds); require(rewardTotal / _numRounds > 0, "!rewardTotal"); uint256 round = activeRound(); for (uint256 i = 0; i < _numRounds; i++) { Incentive memory incentive = Incentive({ token: _token, amount: rewardTotal / _numRounds, maxPerVote: _maxPerVote, distributed: 0, recycled: 0, depositor: msg.sender }); incentives[round + i][_gauge].push(incentive); if (!inRoundGauges[round + i][_gauge]) { roundGauges[round + i].push(_gauge); inRoundGauges[round + i][_gauge] = true; } emit NewIncentive( _token, rewardTotal / _numRounds, round + i, _gauge, _maxPerVote, false ); } } function depositSplitRounds( address _token, uint256 _amount, uint256 _numRounds, address _gauge, uint256 _maxPerVote ) public { require(_numRounds < 8, "!farFuture"); require(_numRounds > 1, "!numRounds"); uint256 rewardTotal = _takeDeposit(_token, _amount, _numRounds); require(rewardTotal / _numRounds > 0, "!rewardTotal"); uint256 round = activeRound(); for (uint256 i = 0; i < _numRounds; i++) { Incentive memory incentive = Incentive({ token: _token, amount: rewardTotal / _numRounds, maxPerVote: _maxPerVote, distributed: 0, recycled: 0, depositor: msg.sender }); incentives[round + i][_gauge].push(incentive); if (!inRoundGauges[round + i][_gauge]) { roundGauges[round + i].push(_gauge); inRoundGauges[round + i][_gauge] = true; } emit NewIncentive( _token, rewardTotal / _numRounds, round + i, _gauge, _maxPerVote, false ); } } function depositSplitRounds( address _token, uint256 _amount, uint256 _numRounds, address _gauge, uint256 _maxPerVote ) public { require(_numRounds < 8, "!farFuture"); require(_numRounds > 1, "!numRounds"); uint256 rewardTotal = _takeDeposit(_token, _amount, _numRounds); require(rewardTotal / _numRounds > 0, "!rewardTotal"); uint256 round = activeRound(); for (uint256 i = 0; i < _numRounds; i++) { Incentive memory incentive = Incentive({ token: _token, amount: rewardTotal / _numRounds, maxPerVote: _maxPerVote, distributed: 0, recycled: 0, depositor: msg.sender }); incentives[round + i][_gauge].push(incentive); if (!inRoundGauges[round + i][_gauge]) { roundGauges[round + i].push(_gauge); inRoundGauges[round + i][_gauge] = true; } emit NewIncentive( _token, rewardTotal / _numRounds, round + i, _gauge, _maxPerVote, false ); } } function depositSplitGauges( address _token, uint256 _amount, uint256 _round, address[] calldata _gauges, uint256 _maxPerVote ) public { require(_round >= activeRound(), "!roundEnded"); require(_round <= activeRound() + 6, "!farFuture"); require(_gauges.length > 1, "!gauges"); uint256 rewardTotal = _takeDeposit(_token, _amount, _gauges.length); require(rewardTotal / _gauges.length > 0, "!rewardTotal"); for (uint256 i = 0; i < _gauges.length; i++) { Incentive memory incentive = Incentive({ token: _token, amount: rewardTotal / _gauges.length, maxPerVote: _maxPerVote, distributed: 0, recycled: 0, depositor: msg.sender }); incentives[_round][_gauges[i]].push(incentive); if (!inRoundGauges[_round][_gauges[i]]) { roundGauges[_round].push(_gauges[i]); inRoundGauges[_round][_gauges[i]] = true; } emit NewIncentive( _token, rewardTotal / _gauges.length, _round, _gauges[i], _maxPerVote, false ); } } function depositSplitGauges( address _token, uint256 _amount, uint256 _round, address[] calldata _gauges, uint256 _maxPerVote ) public { require(_round >= activeRound(), "!roundEnded"); require(_round <= activeRound() + 6, "!farFuture"); require(_gauges.length > 1, "!gauges"); uint256 rewardTotal = _takeDeposit(_token, _amount, _gauges.length); require(rewardTotal / _gauges.length > 0, "!rewardTotal"); for (uint256 i = 0; i < _gauges.length; i++) { Incentive memory incentive = Incentive({ token: _token, amount: rewardTotal / _gauges.length, maxPerVote: _maxPerVote, distributed: 0, recycled: 0, depositor: msg.sender }); incentives[_round][_gauges[i]].push(incentive); if (!inRoundGauges[_round][_gauges[i]]) { roundGauges[_round].push(_gauges[i]); inRoundGauges[_round][_gauges[i]] = true; } emit NewIncentive( _token, rewardTotal / _gauges.length, _round, _gauges[i], _maxPerVote, false ); } } function depositSplitGauges( address _token, uint256 _amount, uint256 _round, address[] calldata _gauges, uint256 _maxPerVote ) public { require(_round >= activeRound(), "!roundEnded"); require(_round <= activeRound() + 6, "!farFuture"); require(_gauges.length > 1, "!gauges"); uint256 rewardTotal = _takeDeposit(_token, _amount, _gauges.length); require(rewardTotal / _gauges.length > 0, "!rewardTotal"); for (uint256 i = 0; i < _gauges.length; i++) { Incentive memory incentive = Incentive({ token: _token, amount: rewardTotal / _gauges.length, maxPerVote: _maxPerVote, distributed: 0, recycled: 0, depositor: msg.sender }); incentives[_round][_gauges[i]].push(incentive); if (!inRoundGauges[_round][_gauges[i]]) { roundGauges[_round].push(_gauges[i]); inRoundGauges[_round][_gauges[i]] = true; } emit NewIncentive( _token, rewardTotal / _gauges.length, _round, _gauges[i], _maxPerVote, false ); } } function depositSplitGauges( address _token, uint256 _amount, uint256 _round, address[] calldata _gauges, uint256 _maxPerVote ) public { require(_round >= activeRound(), "!roundEnded"); require(_round <= activeRound() + 6, "!farFuture"); require(_gauges.length > 1, "!gauges"); uint256 rewardTotal = _takeDeposit(_token, _amount, _gauges.length); require(rewardTotal / _gauges.length > 0, "!rewardTotal"); for (uint256 i = 0; i < _gauges.length; i++) { Incentive memory incentive = Incentive({ token: _token, amount: rewardTotal / _gauges.length, maxPerVote: _maxPerVote, distributed: 0, recycled: 0, depositor: msg.sender }); incentives[_round][_gauges[i]].push(incentive); if (!inRoundGauges[_round][_gauges[i]]) { roundGauges[_round].push(_gauges[i]); inRoundGauges[_round][_gauges[i]] = true; } emit NewIncentive( _token, rewardTotal / _gauges.length, _round, _gauges[i], _maxPerVote, false ); } } function depositSplitGaugesRounds( address _token, uint256 _amount, uint256 _numRounds, address[] calldata _gauges, uint256 _maxPerVote ) public { require(_numRounds < 8, "!farFuture"); require(_numRounds > 1, "!numRounds"); require(_gauges.length > 1, "!gauges"); uint256 rewardTotal = _takeDeposit(_token, _amount, _numRounds * _gauges.length); require(rewardTotal / (_numRounds * _gauges.length) > 0, "!rewardTotal"); uint256 round = activeRound(); for (uint256 i = 0; i < _numRounds; i++) { for (uint256 j = 0; j < _gauges.length; j++) { Incentive memory incentive = Incentive({ token: _token, amount: rewardTotal / (_numRounds * _gauges.length), maxPerVote: _maxPerVote, distributed: 0, recycled: 0, depositor: msg.sender }); incentives[round + i][_gauges[j]].push(incentive); if (!inRoundGauges[round + i][_gauges[j]]) { roundGauges[round + i].push(_gauges[j]); inRoundGauges[round + i][_gauges[j]] = true; } emit NewIncentive( _token, rewardTotal / (_numRounds * _gauges.length), round + i, _gauges[j], _maxPerVote, false ); } } } function depositSplitGaugesRounds( address _token, uint256 _amount, uint256 _numRounds, address[] calldata _gauges, uint256 _maxPerVote ) public { require(_numRounds < 8, "!farFuture"); require(_numRounds > 1, "!numRounds"); require(_gauges.length > 1, "!gauges"); uint256 rewardTotal = _takeDeposit(_token, _amount, _numRounds * _gauges.length); require(rewardTotal / (_numRounds * _gauges.length) > 0, "!rewardTotal"); uint256 round = activeRound(); for (uint256 i = 0; i < _numRounds; i++) { for (uint256 j = 0; j < _gauges.length; j++) { Incentive memory incentive = Incentive({ token: _token, amount: rewardTotal / (_numRounds * _gauges.length), maxPerVote: _maxPerVote, distributed: 0, recycled: 0, depositor: msg.sender }); incentives[round + i][_gauges[j]].push(incentive); if (!inRoundGauges[round + i][_gauges[j]]) { roundGauges[round + i].push(_gauges[j]); inRoundGauges[round + i][_gauges[j]] = true; } emit NewIncentive( _token, rewardTotal / (_numRounds * _gauges.length), round + i, _gauges[j], _maxPerVote, false ); } } } function depositSplitGaugesRounds( address _token, uint256 _amount, uint256 _numRounds, address[] calldata _gauges, uint256 _maxPerVote ) public { require(_numRounds < 8, "!farFuture"); require(_numRounds > 1, "!numRounds"); require(_gauges.length > 1, "!gauges"); uint256 rewardTotal = _takeDeposit(_token, _amount, _numRounds * _gauges.length); require(rewardTotal / (_numRounds * _gauges.length) > 0, "!rewardTotal"); uint256 round = activeRound(); for (uint256 i = 0; i < _numRounds; i++) { for (uint256 j = 0; j < _gauges.length; j++) { Incentive memory incentive = Incentive({ token: _token, amount: rewardTotal / (_numRounds * _gauges.length), maxPerVote: _maxPerVote, distributed: 0, recycled: 0, depositor: msg.sender }); incentives[round + i][_gauges[j]].push(incentive); if (!inRoundGauges[round + i][_gauges[j]]) { roundGauges[round + i].push(_gauges[j]); inRoundGauges[round + i][_gauges[j]] = true; } emit NewIncentive( _token, rewardTotal / (_numRounds * _gauges.length), round + i, _gauges[j], _maxPerVote, false ); } } } function depositSplitGaugesRounds( address _token, uint256 _amount, uint256 _numRounds, address[] calldata _gauges, uint256 _maxPerVote ) public { require(_numRounds < 8, "!farFuture"); require(_numRounds > 1, "!numRounds"); require(_gauges.length > 1, "!gauges"); uint256 rewardTotal = _takeDeposit(_token, _amount, _numRounds * _gauges.length); require(rewardTotal / (_numRounds * _gauges.length) > 0, "!rewardTotal"); uint256 round = activeRound(); for (uint256 i = 0; i < _numRounds; i++) { for (uint256 j = 0; j < _gauges.length; j++) { Incentive memory incentive = Incentive({ token: _token, amount: rewardTotal / (_numRounds * _gauges.length), maxPerVote: _maxPerVote, distributed: 0, recycled: 0, depositor: msg.sender }); incentives[round + i][_gauges[j]].push(incentive); if (!inRoundGauges[round + i][_gauges[j]]) { roundGauges[round + i].push(_gauges[j]); inRoundGauges[round + i][_gauges[j]] = true; } emit NewIncentive( _token, rewardTotal / (_numRounds * _gauges.length), round + i, _gauges[j], _maxPerVote, false ); } } } function depositSplitGaugesRounds( address _token, uint256 _amount, uint256 _numRounds, address[] calldata _gauges, uint256 _maxPerVote ) public { require(_numRounds < 8, "!farFuture"); require(_numRounds > 1, "!numRounds"); require(_gauges.length > 1, "!gauges"); uint256 rewardTotal = _takeDeposit(_token, _amount, _numRounds * _gauges.length); require(rewardTotal / (_numRounds * _gauges.length) > 0, "!rewardTotal"); uint256 round = activeRound(); for (uint256 i = 0; i < _numRounds; i++) { for (uint256 j = 0; j < _gauges.length; j++) { Incentive memory incentive = Incentive({ token: _token, amount: rewardTotal / (_numRounds * _gauges.length), maxPerVote: _maxPerVote, distributed: 0, recycled: 0, depositor: msg.sender }); incentives[round + i][_gauges[j]].push(incentive); if (!inRoundGauges[round + i][_gauges[j]]) { roundGauges[round + i].push(_gauges[j]); inRoundGauges[round + i][_gauges[j]] = true; } emit NewIncentive( _token, rewardTotal / (_numRounds * _gauges.length), round + i, _gauges[j], _maxPerVote, false ); } } } function depositUnevenSplitGauges( address _token, uint256 _round, address[] calldata _gauges, uint256[] calldata _amounts, uint256 _maxPerVote ) public { require(_gauges.length == _amounts.length, "!length"); require(_round >= activeRound(), "!roundEnded"); require(_round <= activeRound() + 6, "!farFuture"); uint256 totalDeposit = 0; for (uint256 i = 0; i < _gauges.length; i++) { require(_amounts[i] > 0, "!amount"); totalDeposit += _amounts[i]; } _takeDeposit(_token, totalDeposit, 1); for (uint256 i = 0; i < _gauges.length; i++) { Incentive memory incentive = Incentive({ token: _token, amount: (_amounts[i] * (DENOMINATOR - platformFee)) / DENOMINATOR, maxPerVote: _maxPerVote, distributed: 0, recycled: 0, depositor: msg.sender }); incentives[_round][_gauges[i]].push(incentive); if (!inRoundGauges[_round][_gauges[i]]) { roundGauges[_round].push(_gauges[i]); inRoundGauges[_round][_gauges[i]] = true; } emit NewIncentive( _token, (_amounts[i] * (DENOMINATOR - platformFee)) / DENOMINATOR, _round, _gauges[i], _maxPerVote, false ); } } function depositUnevenSplitGauges( address _token, uint256 _round, address[] calldata _gauges, uint256[] calldata _amounts, uint256 _maxPerVote ) public { require(_gauges.length == _amounts.length, "!length"); require(_round >= activeRound(), "!roundEnded"); require(_round <= activeRound() + 6, "!farFuture"); uint256 totalDeposit = 0; for (uint256 i = 0; i < _gauges.length; i++) { require(_amounts[i] > 0, "!amount"); totalDeposit += _amounts[i]; } _takeDeposit(_token, totalDeposit, 1); for (uint256 i = 0; i < _gauges.length; i++) { Incentive memory incentive = Incentive({ token: _token, amount: (_amounts[i] * (DENOMINATOR - platformFee)) / DENOMINATOR, maxPerVote: _maxPerVote, distributed: 0, recycled: 0, depositor: msg.sender }); incentives[_round][_gauges[i]].push(incentive); if (!inRoundGauges[_round][_gauges[i]]) { roundGauges[_round].push(_gauges[i]); inRoundGauges[_round][_gauges[i]] = true; } emit NewIncentive( _token, (_amounts[i] * (DENOMINATOR - platformFee)) / DENOMINATOR, _round, _gauges[i], _maxPerVote, false ); } } function depositUnevenSplitGauges( address _token, uint256 _round, address[] calldata _gauges, uint256[] calldata _amounts, uint256 _maxPerVote ) public { require(_gauges.length == _amounts.length, "!length"); require(_round >= activeRound(), "!roundEnded"); require(_round <= activeRound() + 6, "!farFuture"); uint256 totalDeposit = 0; for (uint256 i = 0; i < _gauges.length; i++) { require(_amounts[i] > 0, "!amount"); totalDeposit += _amounts[i]; } _takeDeposit(_token, totalDeposit, 1); for (uint256 i = 0; i < _gauges.length; i++) { Incentive memory incentive = Incentive({ token: _token, amount: (_amounts[i] * (DENOMINATOR - platformFee)) / DENOMINATOR, maxPerVote: _maxPerVote, distributed: 0, recycled: 0, depositor: msg.sender }); incentives[_round][_gauges[i]].push(incentive); if (!inRoundGauges[_round][_gauges[i]]) { roundGauges[_round].push(_gauges[i]); inRoundGauges[_round][_gauges[i]] = true; } emit NewIncentive( _token, (_amounts[i] * (DENOMINATOR - platformFee)) / DENOMINATOR, _round, _gauges[i], _maxPerVote, false ); } } function depositUnevenSplitGauges( address _token, uint256 _round, address[] calldata _gauges, uint256[] calldata _amounts, uint256 _maxPerVote ) public { require(_gauges.length == _amounts.length, "!length"); require(_round >= activeRound(), "!roundEnded"); require(_round <= activeRound() + 6, "!farFuture"); uint256 totalDeposit = 0; for (uint256 i = 0; i < _gauges.length; i++) { require(_amounts[i] > 0, "!amount"); totalDeposit += _amounts[i]; } _takeDeposit(_token, totalDeposit, 1); for (uint256 i = 0; i < _gauges.length; i++) { Incentive memory incentive = Incentive({ token: _token, amount: (_amounts[i] * (DENOMINATOR - platformFee)) / DENOMINATOR, maxPerVote: _maxPerVote, distributed: 0, recycled: 0, depositor: msg.sender }); incentives[_round][_gauges[i]].push(incentive); if (!inRoundGauges[_round][_gauges[i]]) { roundGauges[_round].push(_gauges[i]); inRoundGauges[_round][_gauges[i]] = true; } emit NewIncentive( _token, (_amounts[i] * (DENOMINATOR - platformFee)) / DENOMINATOR, _round, _gauges[i], _maxPerVote, false ); } } function depositUnevenSplitGauges( address _token, uint256 _round, address[] calldata _gauges, uint256[] calldata _amounts, uint256 _maxPerVote ) public { require(_gauges.length == _amounts.length, "!length"); require(_round >= activeRound(), "!roundEnded"); require(_round <= activeRound() + 6, "!farFuture"); uint256 totalDeposit = 0; for (uint256 i = 0; i < _gauges.length; i++) { require(_amounts[i] > 0, "!amount"); totalDeposit += _amounts[i]; } _takeDeposit(_token, totalDeposit, 1); for (uint256 i = 0; i < _gauges.length; i++) { Incentive memory incentive = Incentive({ token: _token, amount: (_amounts[i] * (DENOMINATOR - platformFee)) / DENOMINATOR, maxPerVote: _maxPerVote, distributed: 0, recycled: 0, depositor: msg.sender }); incentives[_round][_gauges[i]].push(incentive); if (!inRoundGauges[_round][_gauges[i]]) { roundGauges[_round].push(_gauges[i]); inRoundGauges[_round][_gauges[i]] = true; } emit NewIncentive( _token, (_amounts[i] * (DENOMINATOR - platformFee)) / DENOMINATOR, _round, _gauges[i], _maxPerVote, false ); } } function increaseIncentive( uint256 _round, address _gauge, uint256 _incentive, uint256 _increase, uint256 _maxPerVote ) public { require(_maxPerVote != incentives[_round][_gauge][_incentive].maxPerVote || _increase > 0, "!change"); require(_round >= activeRound(), "!deadline"); require( incentives[_round][_gauge][_incentive].depositor == msg.sender, "!depositor" ); if(_maxPerVote > 0) { require(_maxPerVote >= incentives[_round][_gauge][_incentive].maxPerVote, "!increaseOnly"); require(incentives[_round][_gauge][_incentive].maxPerVote != 0, "!increaseOnly"); } if(_maxPerVote != incentives[_round][_gauge][_incentive].maxPerVote) { incentives[_round][_gauge][_incentive].maxPerVote = _maxPerVote; } uint256 reward = 0; if(_increase > 0) { reward = _takeDeposit( incentives[_round][_gauge][_incentive].token, _increase, 1 ); incentives[_round][_gauge][_incentive].amount += reward; } emit IncreasedIncentive( incentives[_round][_gauge][_incentive].token, incentives[_round][_gauge][_incentive].amount, reward, _round, _gauge, _maxPerVote ); } function increaseIncentive( uint256 _round, address _gauge, uint256 _incentive, uint256 _increase, uint256 _maxPerVote ) public { require(_maxPerVote != incentives[_round][_gauge][_incentive].maxPerVote || _increase > 0, "!change"); require(_round >= activeRound(), "!deadline"); require( incentives[_round][_gauge][_incentive].depositor == msg.sender, "!depositor" ); if(_maxPerVote > 0) { require(_maxPerVote >= incentives[_round][_gauge][_incentive].maxPerVote, "!increaseOnly"); require(incentives[_round][_gauge][_incentive].maxPerVote != 0, "!increaseOnly"); } if(_maxPerVote != incentives[_round][_gauge][_incentive].maxPerVote) { incentives[_round][_gauge][_incentive].maxPerVote = _maxPerVote; } uint256 reward = 0; if(_increase > 0) { reward = _takeDeposit( incentives[_round][_gauge][_incentive].token, _increase, 1 ); incentives[_round][_gauge][_incentive].amount += reward; } emit IncreasedIncentive( incentives[_round][_gauge][_incentive].token, incentives[_round][_gauge][_incentive].amount, reward, _round, _gauge, _maxPerVote ); } function increaseIncentive( uint256 _round, address _gauge, uint256 _incentive, uint256 _increase, uint256 _maxPerVote ) public { require(_maxPerVote != incentives[_round][_gauge][_incentive].maxPerVote || _increase > 0, "!change"); require(_round >= activeRound(), "!deadline"); require( incentives[_round][_gauge][_incentive].depositor == msg.sender, "!depositor" ); if(_maxPerVote > 0) { require(_maxPerVote >= incentives[_round][_gauge][_incentive].maxPerVote, "!increaseOnly"); require(incentives[_round][_gauge][_incentive].maxPerVote != 0, "!increaseOnly"); } if(_maxPerVote != incentives[_round][_gauge][_incentive].maxPerVote) { incentives[_round][_gauge][_incentive].maxPerVote = _maxPerVote; } uint256 reward = 0; if(_increase > 0) { reward = _takeDeposit( incentives[_round][_gauge][_incentive].token, _increase, 1 ); incentives[_round][_gauge][_incentive].amount += reward; } emit IncreasedIncentive( incentives[_round][_gauge][_incentive].token, incentives[_round][_gauge][_incentive].amount, reward, _round, _gauge, _maxPerVote ); } function increaseIncentive( uint256 _round, address _gauge, uint256 _incentive, uint256 _increase, uint256 _maxPerVote ) public { require(_maxPerVote != incentives[_round][_gauge][_incentive].maxPerVote || _increase > 0, "!change"); require(_round >= activeRound(), "!deadline"); require( incentives[_round][_gauge][_incentive].depositor == msg.sender, "!depositor" ); if(_maxPerVote > 0) { require(_maxPerVote >= incentives[_round][_gauge][_incentive].maxPerVote, "!increaseOnly"); require(incentives[_round][_gauge][_incentive].maxPerVote != 0, "!increaseOnly"); } if(_maxPerVote != incentives[_round][_gauge][_incentive].maxPerVote) { incentives[_round][_gauge][_incentive].maxPerVote = _maxPerVote; } uint256 reward = 0; if(_increase > 0) { reward = _takeDeposit( incentives[_round][_gauge][_incentive].token, _increase, 1 ); incentives[_round][_gauge][_incentive].amount += reward; } emit IncreasedIncentive( incentives[_round][_gauge][_incentive].token, incentives[_round][_gauge][_incentive].amount, reward, _round, _gauge, _maxPerVote ); } function withdrawUnprocessed( uint256 _round, address _gauge, uint256 _incentive ) public { require( _round <= lastRoundProcessed || _round + 3 < activeRound(), "!roundNotProcessed" require( incentives[_round][_gauge][_incentive].depositor == msg.sender, "!depositor" ); require( incentives[_round][_gauge][_incentive].distributed == 0, "!distributed" ); require( incentives[_round][_gauge][_incentive].recycled == 0, "!recycled" ); uint256 amount = incentives[_round][_gauge][_incentive].amount; incentives[_round][_gauge][_incentive].amount = 0; uint256 adjustedAmount = amount * IERC20(incentives[_round][_gauge][_incentive].token).balanceOf(address(this)) / virtualBalance[incentives[_round][_gauge][_incentive].token]; IERC20(incentives[_round][_gauge][_incentive].token).safeTransfer( msg.sender, amount ); virtualBalance[incentives[_round][_gauge][_incentive].token] -= amount; emit WithdrawUnprocessed(_round, _gauge, _incentive, amount); } function recycleUnprocessed( uint256 _round, address _gauge, uint256 _incentive ) public { require(_round <= lastRoundProcessed, "!roundNotProcessed"); require( incentives[_round][_gauge][_incentive].depositor == msg.sender || msg.sender == owner(), "!auth" ); require( incentives[_round][_gauge][_incentive].distributed == 0, "!distributed" ); require( incentives[_round][_gauge][_incentive].recycled == 0, "!recycled" ); Incentive memory original = incentives[_round][_gauge][_incentive]; incentives[_round][_gauge][_incentive].recycled = original.amount; _recycleReward( original.token, original.amount, _gauge, original.maxPerVote, original.depositor ); } function rescueToDistributor(address _token) public onlyTeam { uint256 bal = IERC20(_token).balanceOf(address(this)) - virtualBalance[_token]; require(bal > 0, "!balance"); IERC20(_token).safeTransfer(distributor, bal); } function allowToken(address _token, bool _allow) public onlyTeam { tokenAllowed[_token] = _allow; emit TokenAllow(_token, _allow); } function allowTokens( address[] memory _tokens, bool _allow ) public onlyTeam { for (uint256 i = 0; i < _tokens.length; i++) { tokenAllowed[_tokens[i]] = _allow; emit TokenAllow(_tokens[i], _allow); } } function allowTokens( address[] memory _tokens, bool _allow ) public onlyTeam { for (uint256 i = 0; i < _tokens.length; i++) { tokenAllowed[_tokens[i]] = _allow; emit TokenAllow(_tokens[i], _allow); } } function _recycleReward( address _token, uint256 _amount, address _gauge, uint256 _maxPerVote, address _depositor ) internal { uint256 _round = activeRound(); Incentive memory incentive = Incentive({ token: _token, amount: _amount, maxPerVote: _maxPerVote, distributed: 0, recycled: 0, depositor: _depositor }); incentives[_round][_gauge].push(incentive); emit NewIncentive(_token, _amount, _round, _gauge, _maxPerVote, true); } function _recycleReward( address _token, uint256 _amount, address _gauge, uint256 _maxPerVote, address _depositor ) internal { uint256 _round = activeRound(); Incentive memory incentive = Incentive({ token: _token, amount: _amount, maxPerVote: _maxPerVote, distributed: 0, recycled: 0, depositor: _depositor }); incentives[_round][_gauge].push(incentive); emit NewIncentive(_token, _amount, _round, _gauge, _maxPerVote, true); } function _takeDeposit( address _token, uint256 _amount, uint256 _split ) internal returns (uint256) { if (requireAllowlist == true) { require(tokenAllowed[_token] == true, "!allowlist"); } require(_amount / _split > 0, "!zero"); uint256 fee = (_amount * platformFee) / DENOMINATOR; uint256 rewardTotal = _amount - fee; IERC20(_token).safeTransferFrom(msg.sender, feeAddress, fee); IERC20(_token).safeTransferFrom(msg.sender, address(this), rewardTotal); return rewardTotal; } function _takeDeposit( address _token, uint256 _amount, uint256 _split ) internal returns (uint256) { if (requireAllowlist == true) { require(tokenAllowed[_token] == true, "!allowlist"); } require(_amount / _split > 0, "!zero"); uint256 fee = (_amount * platformFee) / DENOMINATOR; uint256 rewardTotal = _amount - fee; IERC20(_token).safeTransferFrom(msg.sender, feeAddress, fee); IERC20(_token).safeTransferFrom(msg.sender, address(this), rewardTotal); return rewardTotal; } function endRound( uint256 _round, address[] memory _gauges, uint256[] memory _totals ) public onlyOwner { require(_gauges.length == _totals.length, "!gauges/totals"); require(_round < activeRound(), "!activeRound"); require(_round - 1 == lastRoundProcessed, "!lastRoundProcessed"); for (uint256 i = 0; i < _gauges.length; i++) { require(votesReceived[_round][_gauges[i]] == 0, "!duplicate"); votesReceived[_round][_gauges[i]] = _totals[i]; for ( uint256 n = 0; n < incentives[_round][_gauges[i]].length; n++ ) { Incentive storage incentive = incentives[_round][_gauges[i]][n]; uint256 reward; if (incentive.maxPerVote > 0) { reward = incentive.maxPerVote * _totals[i]; if (reward > incentive.amount) { reward = incentive.amount; _recycleReward( incentive.token, incentive.amount - reward, _gauges[i], incentive.maxPerVote, incentive.depositor ); incentives[_round][_gauges[i]][n].recycled = incentive.amount - reward; } incentives[_round][_gauges[i]][n].distributed = reward; reward = incentive.amount; incentives[_round][_gauges[i]][n].distributed = reward; } toTransfer[incentive.token] += reward; toTransferList.push(incentive.token); } } lastRoundProcessed = _round; for (uint256 i = 0; i < toTransferList.length; i++) { IERC20(toTransferList[i]).safeTransfer( distributor, (toTransfer[toTransferList[i]] * IERC20(toTransferList[i]).balanceOf(address(this))) / ); virtualBalance[toTransferList[i]] -= toTransfer[toTransferList[i]]; toTransfer[toTransferList[i]] = 0; } delete toTransferList; } function endRound( uint256 _round, address[] memory _gauges, uint256[] memory _totals ) public onlyOwner { require(_gauges.length == _totals.length, "!gauges/totals"); require(_round < activeRound(), "!activeRound"); require(_round - 1 == lastRoundProcessed, "!lastRoundProcessed"); for (uint256 i = 0; i < _gauges.length; i++) { require(votesReceived[_round][_gauges[i]] == 0, "!duplicate"); votesReceived[_round][_gauges[i]] = _totals[i]; for ( uint256 n = 0; n < incentives[_round][_gauges[i]].length; n++ ) { Incentive storage incentive = incentives[_round][_gauges[i]][n]; uint256 reward; if (incentive.maxPerVote > 0) { reward = incentive.maxPerVote * _totals[i]; if (reward > incentive.amount) { reward = incentive.amount; _recycleReward( incentive.token, incentive.amount - reward, _gauges[i], incentive.maxPerVote, incentive.depositor ); incentives[_round][_gauges[i]][n].recycled = incentive.amount - reward; } incentives[_round][_gauges[i]][n].distributed = reward; reward = incentive.amount; incentives[_round][_gauges[i]][n].distributed = reward; } toTransfer[incentive.token] += reward; toTransferList.push(incentive.token); } } lastRoundProcessed = _round; for (uint256 i = 0; i < toTransferList.length; i++) { IERC20(toTransferList[i]).safeTransfer( distributor, (toTransfer[toTransferList[i]] * IERC20(toTransferList[i]).balanceOf(address(this))) / ); virtualBalance[toTransferList[i]] -= toTransfer[toTransferList[i]]; toTransfer[toTransferList[i]] = 0; } delete toTransferList; } function endRound( uint256 _round, address[] memory _gauges, uint256[] memory _totals ) public onlyOwner { require(_gauges.length == _totals.length, "!gauges/totals"); require(_round < activeRound(), "!activeRound"); require(_round - 1 == lastRoundProcessed, "!lastRoundProcessed"); for (uint256 i = 0; i < _gauges.length; i++) { require(votesReceived[_round][_gauges[i]] == 0, "!duplicate"); votesReceived[_round][_gauges[i]] = _totals[i]; for ( uint256 n = 0; n < incentives[_round][_gauges[i]].length; n++ ) { Incentive storage incentive = incentives[_round][_gauges[i]][n]; uint256 reward; if (incentive.maxPerVote > 0) { reward = incentive.maxPerVote * _totals[i]; if (reward > incentive.amount) { reward = incentive.amount; _recycleReward( incentive.token, incentive.amount - reward, _gauges[i], incentive.maxPerVote, incentive.depositor ); incentives[_round][_gauges[i]][n].recycled = incentive.amount - reward; } incentives[_round][_gauges[i]][n].distributed = reward; reward = incentive.amount; incentives[_round][_gauges[i]][n].distributed = reward; } toTransfer[incentive.token] += reward; toTransferList.push(incentive.token); } } lastRoundProcessed = _round; for (uint256 i = 0; i < toTransferList.length; i++) { IERC20(toTransferList[i]).safeTransfer( distributor, (toTransfer[toTransferList[i]] * IERC20(toTransferList[i]).balanceOf(address(this))) / ); virtualBalance[toTransferList[i]] -= toTransfer[toTransferList[i]]; toTransfer[toTransferList[i]] = 0; } delete toTransferList; } function endRound( uint256 _round, address[] memory _gauges, uint256[] memory _totals ) public onlyOwner { require(_gauges.length == _totals.length, "!gauges/totals"); require(_round < activeRound(), "!activeRound"); require(_round - 1 == lastRoundProcessed, "!lastRoundProcessed"); for (uint256 i = 0; i < _gauges.length; i++) { require(votesReceived[_round][_gauges[i]] == 0, "!duplicate"); votesReceived[_round][_gauges[i]] = _totals[i]; for ( uint256 n = 0; n < incentives[_round][_gauges[i]].length; n++ ) { Incentive storage incentive = incentives[_round][_gauges[i]][n]; uint256 reward; if (incentive.maxPerVote > 0) { reward = incentive.maxPerVote * _totals[i]; if (reward > incentive.amount) { reward = incentive.amount; _recycleReward( incentive.token, incentive.amount - reward, _gauges[i], incentive.maxPerVote, incentive.depositor ); incentives[_round][_gauges[i]][n].recycled = incentive.amount - reward; } incentives[_round][_gauges[i]][n].distributed = reward; reward = incentive.amount; incentives[_round][_gauges[i]][n].distributed = reward; } toTransfer[incentive.token] += reward; toTransferList.push(incentive.token); } } lastRoundProcessed = _round; for (uint256 i = 0; i < toTransferList.length; i++) { IERC20(toTransferList[i]).safeTransfer( distributor, (toTransfer[toTransferList[i]] * IERC20(toTransferList[i]).balanceOf(address(this))) / ); virtualBalance[toTransferList[i]] -= toTransfer[toTransferList[i]]; toTransfer[toTransferList[i]] = 0; } delete toTransferList; } function endRound( uint256 _round, address[] memory _gauges, uint256[] memory _totals ) public onlyOwner { require(_gauges.length == _totals.length, "!gauges/totals"); require(_round < activeRound(), "!activeRound"); require(_round - 1 == lastRoundProcessed, "!lastRoundProcessed"); for (uint256 i = 0; i < _gauges.length; i++) { require(votesReceived[_round][_gauges[i]] == 0, "!duplicate"); votesReceived[_round][_gauges[i]] = _totals[i]; for ( uint256 n = 0; n < incentives[_round][_gauges[i]].length; n++ ) { Incentive storage incentive = incentives[_round][_gauges[i]][n]; uint256 reward; if (incentive.maxPerVote > 0) { reward = incentive.maxPerVote * _totals[i]; if (reward > incentive.amount) { reward = incentive.amount; _recycleReward( incentive.token, incentive.amount - reward, _gauges[i], incentive.maxPerVote, incentive.depositor ); incentives[_round][_gauges[i]][n].recycled = incentive.amount - reward; } incentives[_round][_gauges[i]][n].distributed = reward; reward = incentive.amount; incentives[_round][_gauges[i]][n].distributed = reward; } toTransfer[incentive.token] += reward; toTransferList.push(incentive.token); } } lastRoundProcessed = _round; for (uint256 i = 0; i < toTransferList.length; i++) { IERC20(toTransferList[i]).safeTransfer( distributor, (toTransfer[toTransferList[i]] * IERC20(toTransferList[i]).balanceOf(address(this))) / ); virtualBalance[toTransferList[i]] -= toTransfer[toTransferList[i]]; toTransfer[toTransferList[i]] = 0; } delete toTransferList; } } else { } else { function endRound( uint256 _round, address[] memory _gauges, uint256[] memory _totals ) public onlyOwner { require(_gauges.length == _totals.length, "!gauges/totals"); require(_round < activeRound(), "!activeRound"); require(_round - 1 == lastRoundProcessed, "!lastRoundProcessed"); for (uint256 i = 0; i < _gauges.length; i++) { require(votesReceived[_round][_gauges[i]] == 0, "!duplicate"); votesReceived[_round][_gauges[i]] = _totals[i]; for ( uint256 n = 0; n < incentives[_round][_gauges[i]].length; n++ ) { Incentive storage incentive = incentives[_round][_gauges[i]][n]; uint256 reward; if (incentive.maxPerVote > 0) { reward = incentive.maxPerVote * _totals[i]; if (reward > incentive.amount) { reward = incentive.amount; _recycleReward( incentive.token, incentive.amount - reward, _gauges[i], incentive.maxPerVote, incentive.depositor ); incentives[_round][_gauges[i]][n].recycled = incentive.amount - reward; } incentives[_round][_gauges[i]][n].distributed = reward; reward = incentive.amount; incentives[_round][_gauges[i]][n].distributed = reward; } toTransfer[incentive.token] += reward; toTransferList.push(incentive.token); } } lastRoundProcessed = _round; for (uint256 i = 0; i < toTransferList.length; i++) { IERC20(toTransferList[i]).safeTransfer( distributor, (toTransfer[toTransferList[i]] * IERC20(toTransferList[i]).balanceOf(address(this))) / ); virtualBalance[toTransferList[i]] -= toTransfer[toTransferList[i]]; toTransfer[toTransferList[i]] = 0; } delete toTransferList; } function setAllowlistRequired(bool _requireAllowlist) public onlyOwner { requireAllowlist = _requireAllowlist; emit AllowlistRequirement(_requireAllowlist); } function updateFeeAddress(address _feeAddress) public onlyOwner { feeAddress = _feeAddress; } function updateFeeAmount(uint256 _feeAmount) public onlyOwner { platformFee = _feeAmount; emit UpdatedFee(_feeAmount); } function modifyTeam(address _member, bool _approval) public onlyOwner { approvedTeam[_member] = _approval; emit ModifiedTeam(_member, _approval); } function updateDistributor(address _distributor) public onlyOwner { distributor = _distributor; emit UpdatedDistributor(distributor); } function execute( address _to, uint256 _value, bytes calldata _data ) external onlyOwner returns (bool, bytes memory) { return (success, result); } (bool success, bytes memory result) = _to.call{value: _value}(_data); modifier onlyTeam() { require(approvedTeam[msg.sender] == true, "Team only"); _; } event NewIncentive( address _token, uint256 _amount, uint256 _round, address _gauge, uint256 _maxPerVote, bool _recycled ); event TokenAllow(address _token, bool _allow); event AllowlistRequirement(bool _requireAllowlist); event UpdatedFee(uint256 _feeAmount); event ModifiedTeam(address _member, bool _approval); event UpdatedDistributor(address _distributor); event WithdrawUnprocessed( uint256 _round, address _gauge, uint256 _incentive, uint256 _amount ); event IncreasedIncentive( address _token, uint256 _total, uint256 _increase, uint256 _round, address _gauge, uint256 _maxPerVote ); }
4,079,194
[ 1, 27719, 813, 6237, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 776, 352, 5077, 353, 14223, 6914, 288, 203, 565, 1450, 14060, 654, 39, 3462, 364, 467, 654, 39, 3462, 31, 203, 203, 203, 203, 203, 203, 203, 203, 565, 1958, 657, 2998, 688, 288, 203, 3639, 1758, 1147, 31, 203, 3639, 2254, 5034, 3844, 31, 203, 3639, 2254, 5034, 943, 2173, 19338, 31, 203, 3639, 2254, 5034, 16859, 31, 203, 3639, 2254, 5034, 25745, 71, 1259, 31, 203, 3639, 1758, 443, 1724, 280, 31, 203, 565, 289, 203, 203, 203, 203, 203, 203, 565, 3885, 12, 203, 3639, 1758, 389, 25990, 16, 203, 3639, 1758, 389, 25990, 22, 16, 203, 3639, 1758, 389, 21386, 1887, 16, 203, 3639, 1758, 389, 2251, 19293, 203, 203, 565, 262, 288, 203, 3639, 20412, 8689, 63, 67, 25990, 65, 273, 638, 31, 203, 3639, 20412, 8689, 63, 67, 25990, 22, 65, 273, 638, 31, 203, 3639, 14036, 1887, 273, 389, 21386, 1887, 31, 203, 3639, 1015, 19293, 273, 389, 2251, 19293, 31, 203, 3639, 1142, 11066, 13533, 273, 261, 2629, 18, 5508, 342, 7632, 5326, 13, 300, 404, 5026, 28, 31, 203, 565, 289, 203, 203, 203, 565, 445, 314, 6480, 281, 1782, 12, 11890, 5034, 389, 2260, 13, 1071, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 3643, 43, 6480, 281, 63, 67, 2260, 8009, 2469, 31, 203, 565, 289, 203, 203, 565, 445, 316, 2998, 3606, 1782, 12, 203, 3639, 2254, 5034, 389, 2260, 16, 203, 3639, 1758, 389, 75, 8305, 203, 565, 262, 1071, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 2 ]
./partial_match/1/0xcC338800221b56E5B83C092c40125E0cA702E224/sources/Truample.sol
* @dev this function will send the Team tokens to given address @param _userAddress ,address of the team receiver. @param _value , number of tokens to be sent./
function sendteamTokens(address _userAddress, uint256 _value) external whenNotPaused onlyOwner returns (bool) { teamTokenHolder[_userAddress] = true; teamTokensInitially[_userAddress] = teamTokensInitially[_userAddress].add(_value); lockingTime[_userAddress] = now; teamTokensSent = teamTokensSent.add(_value); Ttransfer(msg.sender,_userAddress,_value); return true; }
16,164,138
[ 1, 2211, 445, 903, 1366, 326, 10434, 2430, 358, 864, 1758, 225, 389, 1355, 1887, 269, 2867, 434, 326, 5927, 5971, 18, 225, 389, 1132, 269, 1300, 434, 2430, 358, 506, 3271, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 565, 445, 1366, 10035, 5157, 12, 2867, 389, 1355, 1887, 16, 2254, 5034, 389, 1132, 13, 3903, 1347, 1248, 28590, 1338, 5541, 1135, 261, 6430, 13, 288, 203, 203, 377, 5927, 1345, 6064, 63, 67, 1355, 1887, 65, 273, 638, 31, 203, 377, 5927, 5157, 2570, 6261, 63, 67, 1355, 1887, 65, 273, 5927, 5157, 2570, 6261, 63, 67, 1355, 1887, 8009, 1289, 24899, 1132, 1769, 203, 377, 18887, 950, 63, 67, 1355, 1887, 65, 273, 2037, 31, 203, 377, 5927, 5157, 7828, 273, 5927, 5157, 7828, 18, 1289, 24899, 1132, 1769, 203, 377, 399, 13866, 12, 3576, 18, 15330, 16, 67, 1355, 1887, 16, 67, 1132, 1769, 203, 3639, 327, 638, 31, 203, 203, 282, 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 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./AnonymiceLibrary.sol"; import "./ERC721A.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; contract GenFrens is ERC721A, Ownable { using AnonymiceLibrary for uint8; struct Trait { string traitName; string traitType; } //Mappings mapping(uint256 => Trait[]) public traitTypes; mapping(string => bool) hashToMinted; mapping(uint256 => string) internal tokenIdToHash; mapping(address => bool) addressMinted; //uint256s uint256 MAX_SUPPLY = 444; uint256 SEED_NONCE = 0; uint256 MINT_COST = 0.01 ether; //minting flag bool public MINTING_LIVE = false; //uint arrays uint16[][6] TIERS; //p5js url string p5jsUrl; string p5jsIntegrity; string imageUrl; string externalUrl; constructor() ERC721A("GenFrens", "GENF", 2) { //Declare all the rarity tiers //pCol TIERS[0] = [1400, 1400, 1800, 700, 700, 1800, 1100, 1100]; //sCol TIERS[1] = [1500, 1800, 900, 900, 1200, 1800, 1500, 400]; //noise Max TIERS[2] = [4000, 3000, 2000, 1000]; //eyeSize TIERS[3] = [2500, 5000, 2500]; //Thickness TIERS[4] = [6000, 2500, 1500]; //eyeLevel TIERS[5] = [6000, 4000]; } /* __ __ _ _ _ ___ _ _ | \/ (_)_ _| |_(_)_ _ __ _ | __| _ _ _ __| |_(_)___ _ _ ___ | |\/| | | ' \ _| | ' \/ _` | | _| || | ' \/ _| _| / _ \ ' \(_-< |_| |_|_|_||_\__|_|_||_\__, | |_| \_,_|_||_\__|\__|_\___/_||_/__/ |___/ */ /** * @dev Converts a digit from 0 - 10000 into its corresponding rarity based on the given rarity tier. * @param _randinput The input from 0 - 10000 to use for rarity gen. * @param _rarityTier The tier to use. */ function rarityGen(uint256 _randinput, uint8 _rarityTier) internal view returns (uint8) { uint16 currentLowerBound = 0; for (uint8 i = 0; i < TIERS[_rarityTier].length; i++) { uint16 thisPercentage = TIERS[_rarityTier][i]; if ( _randinput >= currentLowerBound && _randinput < currentLowerBound + thisPercentage ) return i; currentLowerBound = currentLowerBound + thisPercentage; } revert(); } /** * @dev Generates a 11 digit hash from a tokenId, address, and random number. * @param _t The token id to be used within the hash. * @param _a The address to be used within the hash. * @param _c The custom nonce to be used within the hash. */ function hash( uint256 _t, address _a, uint256 _c ) internal returns (string memory) { require(_c < 11); // This will generate a 11 character string. // The first 2 digits are the palette. string memory currentHash = ""; for (uint8 i = 0; i < 6; i++) { SEED_NONCE++; uint16 _randinput = uint16( uint256( keccak256( abi.encodePacked( block.timestamp, block.difficulty, _t, _a, _c, SEED_NONCE ) ) ) % 10000 ); currentHash = string( abi.encodePacked( currentHash, rarityGen(_randinput, i).toString() ) ); } if (hashToMinted[currentHash]) return hash(_t, _a, _c + 1); return currentHash; } /** * @dev Mint internal, this is to avoid code duplication. */ function mintInternal(uint8 mintAmount) internal { require( MINTING_LIVE == true || msg.sender == owner(), "Minting not live" ); uint256 _totalSupply = totalSupply(); require(_totalSupply < MAX_SUPPLY); require(!AnonymiceLibrary.isContract(msg.sender)); require(addressMinted[msg.sender] != true, "Address already minted"); require(msg.value >= MINT_COST * mintAmount, "Insufficient ETH sent"); for (uint8 i = 0; i < mintAmount; i++) { uint256 thisTokenId = _totalSupply + i; tokenIdToHash[thisTokenId] = hash(thisTokenId, msg.sender, 0); hashToMinted[tokenIdToHash[thisTokenId]] = true; } addressMinted[msg.sender] = true; _safeMint(msg.sender, mintAmount); } /** * @dev Mints new tokens. */ function mintFren(uint8 mintAmount) public payable { return mintInternal(mintAmount); } /* ____ ___ ____ ___ _____ __ __ ____ __ ______ ____ ___ ____ _____ | \ / _] / || \ | || | || \ / ] || |/ \ | \ / ___/ | D ) / [_ | o || \ | __|| | || _ | / /| | | || || _ ( \_ | / | _]| || D | | |_ | | || | |/ / |_| |_| | || O || | |\__ | | \ | [_ | _ || | | _] | : || | / \_ | | | || || | |/ \ | | . \| || | || | | | | || | \ | | | | || || | |\ | |__|\_||_____||__|__||_____| |__| \__,_||__|__|\____| |__| |____|\___/ |__|__| \___| */ /** * @dev Hash to HTML function */ function hashToHTML(string memory _hash, uint256 _tokenId) public view returns (string memory) { string memory htmlString = string( abi.encodePacked( "data:text/html,%3Chtml%3E%3Chead%3E%3Cscript%20src%3D%22", p5jsUrl, "%22%20integrity%3D%22", p5jsIntegrity, "%22%20crossorigin%3D%22anonymous%22%3E%3C%2Fscript%3E%3C%2Fhead%3E%3Cbody%3E%3Cscript%3Evar%20tokenId%3D", AnonymiceLibrary.toString(_tokenId), "%3Bvar%20hash%3D%22", _hash, "%22%3B" ) ); htmlString = string( abi.encodePacked( htmlString, "xo%3D1%2Csd%3D21%2AtokenId%2CpCs%3D%5B0%2C30%2C80%2C120%2C180%2C225%2C270%2C300%5D%2CsCs%3D%5B0%2C30%2C120%2C180%2C225%2C270%2C300%2C330%5D%2CnMV%3D%5B.5%2C1%2C2%2C3%5D%2CeSs%3D%5B.26%2C.33%2C.4%5D%2CtV%3D%5B10%2C25%2C70%5D%2CeLs%3D%5B0%2C15%5D%3Bfunction%20setup%28%29%7BcreateCanvas%28500%2C500%29%2CcolorMode%28HSB%2C360%2C100%2C100%29%2CstrokeCap%28ROUND%29%2CnoiseSeed%28sd%29%2CrandomSeed%28sd%29%2CpC%3DparseInt%28hash.substring%280%2C1%29%29%2CsC%3DparseInt%28hash.substring%281%2C2%29%29%2CnM%3DparseInt%28hash.substring%282%2C3%29%29%2CeS%3DparseInt%28hash.substring%283%2C4%29%29%2Ct%3DparseInt%28hash.substring%284%2C5%29%29%2CeL%3DparseInt%28hash.substring%285%2C6%29%29%2C330%3D%3DsCs%5BsC%5D%3Fk%3DpCs%5BpC%5D%3Ak%3DsCs%5BsC%5D%2CwP%3Drandom%285%2C10%29%2ChP%3Drandom%285%2C10%29%7Dfunction%20draw%28%29%7Bbackground%28255%29%3Bfor%28let%20s%3D25%3Bs%3C500%3Bs%2B%3D50%29for%28let%20e%3D25%3Be%3C500%3Be%2B%3D50%29noStroke%28%29%2Cf%3DsCs%5BsC%5D%2C330%3D%3Df%3FrC%3Drandom%28360%29%3ArC%3Dk%2Cfill%28rC%2Crandom%2825%29%2C100%29%2Cc%3Dnew%20C1%2Cpush%28%29%2Ctranslate%28s%2Ce%29%2Cscale%28.14%2C.14%29%2Cc.s%28%29%2Cpop%28%29%3Bc1%3Dnew%20C2%28pCs%5BpC%5D%2C40%2C100%2C0%29%2Cpush%28%29%2Ctranslate%28250%2C500%29%2Crotate%283.14%29%2Cscale%28.55%2C1.25%29%2Cc1.s%28%29%2Cpop%28%29%2Cpush%28%29%2Ctranslate%28250%2C250%29%2Cc1.s%28%29%2Cpop%28%29%2CnoStroke%28%29%2Ce1%3Dnew%20C2%280%2C0%2C100%2C1%29%2Cpush%28%29%2Ctranslate%28200%2C200%29%2Cscale%28.33%29%2Ce1.s%28%29%2Cpop%28%29%2Ce2%3Dnew%20C2%280%2C0%2C100%2C1%29%2Cpush%28%29%2Cpush%28%29%2Ctranslate%28300%2C200%29%2Cscale%28eSs%5BeS%5D%29%2Crotate%28PI%29%2Ce2.s%28%29%2Cpop%28%29%2Cp1%3Dnew%20C2%28k%2C100%2C100%2C1%29%2Cpush%28%29%2Ctranslate%28200%2C200%2BeLs%5BeL%5D%29%2Cscale%28.1%29%2Cp1.s%28%29%2Cpop%28%29%2Cp2%3Dnew%20C2%28k%2C100%2C100%2C1%29%2Cpush%28%29%2Ctranslate%28300%2C200-eLs%5BeL%5D%29%2Cscale%28.1%29%2Crotate%28PI%29%2Cp2.s%28%29%2Cpop%28%29%3Bfor%28let%20s%3D200%3Bs%3C%3D300%3Bs%2B%2B%29sats%3Dmap%28noise%28xo%29%2C0%2C1%2C30%2C100%29%2Cfill%28k%2Csats%2C95%29%2Cr%3Dmap%28noise%28xo%29%2C0%2C1%2C.53%2C.77%29%2Cellipse%28s%2C500%2Ar%2C28%29%2Cxo%2B%3D.015%3BnoLoop%28%29%7Dclass%20C1%7Bs%28%29%7BbeginShape%28%29%3Bfor%28let%20s%3D0%3Bs%3CTWO_PI%3Bs%2B%3D.16%29%7Blet%20e%3Dmap%28cos%28s%29%2C-1%2C1%2C0%2CnMV%5BnM%5D%29%2Ct%3Dmap%28sin%28s%29%2C-1%2C1%2C0%2CnMV%5BnM%5D%29%2Cn%3Dmap%28noise%28e%2Ct%29%2C0%2C1%2C100%2C200%29%2Ca%3Dn%2Acos%28s%29%2Cp%3Dn%2Asin%28s%29%3Bvertex%28a%2Cp%29%2Ce%2B%3D.004%7DendShape%28%29%7D%7Dclass%20C2%7Bconstructor%28s%2Ce%2Ct%2Cn%29%7Bthis.h%3Ds%2Cthis.z%3De%2Cthis.l%3Dt%2Cthis.b%3Dn%7Ds%28%29%7BbeginShape%28%29%2CnoFill%28%29%3Bfor%28let%20s%3D0%3Bs%3CTWO_PI%3Bs%2B%3D.045%29%7Blet%20e%3Dmap%28sin%28s%29%2C-1%2C1%2C0%2CnMV%5BnM%5D%29%2Cn%3Dmap%28cos%28s%29%2C-1%2C1%2C0%2CnMV%5BnM%5D%29%2Ca%3Dmap%28noise%28n%2Ce%29%2C0%2C1%2C100%2C200%29%2Cp%3Da%2Acos%28s%29%2Co%3Da%2Asin%28s%29%3B0%3D%3Dthis.b%26%26%28stroke%28this.h%2Cthis.z%2Cthis.l-25%29%2CstrokeWeight%28tV%5Bt%5D%29%29%2Cvertex%28p%2Co%29%2CendShape%28%29%2Cpush%28%29%2Cstroke%28this.h%2Cthis.z%2Cthis.l%29%2CstrokeWeight%286%29%2Cline%28p%2B7.5%2Co%2B10%2C500%2FwP%2C500%2FhP%29%2Cpop%28%29%2Cn%2B%3D.04%2Ce%2B%3D.001%7DendShape%28%29%7D%7D%3C%2Fscript%3E%3C%2Fbody%3E%3C%2Fhtml%3E" ) ); return htmlString; } /** * @dev Hash to metadata function */ function hashToMetadata(string memory _hash) public view returns (string memory) { string memory metadataString; for (uint8 i = 0; i < 6; i++) { uint8 thisTraitIndex = AnonymiceLibrary.parseInt( AnonymiceLibrary.substring(_hash, i, i + 1) ); metadataString = string( abi.encodePacked( metadataString, '{"trait_type":"', traitTypes[i][thisTraitIndex].traitType, '","value":"', traitTypes[i][thisTraitIndex].traitName, '"}' ) ); if (i != 5) metadataString = string(abi.encodePacked(metadataString, ",")); } return string(abi.encodePacked("[", metadataString, "]")); } /** * @dev Returns the SVG and metadata for a token Id * @param _tokenId The tokenId to return the SVG and metadata for. */ function tokenURI(uint256 _tokenId) public view override returns (string memory) { require(_exists(_tokenId)); string memory tokenHash = _tokenIdToHash(_tokenId); string memory description = '", "description": "444 GenFrens to keep you company. Metadata & images mirrored on chain permanently. Your GenFren will never leave you <3",'; string memory encodedTokenId = AnonymiceLibrary.encode( bytes(string(abi.encodePacked(AnonymiceLibrary.toString(_tokenId)))) ); string memory encodedHash = AnonymiceLibrary.encode( bytes(string(abi.encodePacked(tokenHash))) ); return string( abi.encodePacked( "data:application/json;base64,", AnonymiceLibrary.encode( bytes( string( abi.encodePacked( '{"name": "GenFrens #', AnonymiceLibrary.toString(_tokenId), description, '"external_url":"', externalUrl, encodedTokenId, "&t=", encodedHash, '","image":"', imageUrl, AnonymiceLibrary.toString(_tokenId), "&t=", tokenHash, '","attributes":', hashToMetadata(tokenHash), "}" ) ) ) ) ) ); } /** * @dev Returns a hash for a given tokenId * @param _tokenId The tokenId to return the hash for. */ function _tokenIdToHash(uint256 _tokenId) public view returns (string memory) { string memory tokenHash = tokenIdToHash[_tokenId]; return tokenHash; } /* ___ __ __ ____ ___ ____ _____ __ __ ____ __ ______ ____ ___ ____ _____ / \ | |__| || \ / _]| \ | || | || \ / ] || |/ \ | \ / ___/ | || | | || _ | / [_ | D ) | __|| | || _ | / /| | | || || _ ( \_ | O || | | || | || _]| / | |_ | | || | |/ / |_| |_| | || O || | |\__ | | || ` ' || | || [_ | \ | _] | : || | / \_ | | | || || | |/ \ | | | \ / | | || || . \ | | | || | \ | | | | || || | |\ | \___/ \_/\_/ |__|__||_____||__|\_| |__| \__,_||__|__|\____| |__| |____|\___/ |__|__| \___| /** * @dev Add a trait type * @param _traitTypeIndex The trait type index * @param traits Array of traits to add */ function addTraitType(uint256 _traitTypeIndex, Trait[] memory traits) public onlyOwner { for (uint256 i = 0; i < traits.length; i++) { traitTypes[_traitTypeIndex].push( Trait(traits[i].traitName, traits[i].traitType) ); } return; } function flipMintingSwitch() public onlyOwner { MINTING_LIVE = !MINTING_LIVE; } /** * @dev Sets the p5js url * @param _p5jsUrl The address of the p5js file hosted on CDN */ function setJsAddress(string memory _p5jsUrl) public onlyOwner { p5jsUrl = _p5jsUrl; } /** * @dev Sets the p5js resource integrity * @param _p5jsIntegrity The hash of the p5js file (to protect w subresource integrity) */ function setJsIntegrity(string memory _p5jsIntegrity) public onlyOwner { p5jsIntegrity = _p5jsIntegrity; } /** * @dev Sets the base image url * @param _imageUrl The base url for image field */ function setImageUrl(string memory _imageUrl) public onlyOwner { imageUrl = _imageUrl; } function setExternalUrl(string memory _externalUrl) public onlyOwner { externalUrl = _externalUrl; } function withdraw() public payable onlyOwner { (bool success, ) = payable(msg.sender).call{ value: address(this).balance }(""); require(success); } }
* @dev Hash to HTML function/
function hashToHTML(string memory _hash, uint256 _tokenId) public view returns (string memory) { string memory htmlString = string( abi.encodePacked( "data:text/html,%3Chtml%3E%3Chead%3E%3Cscript%20src%3D%22", p5jsUrl, "%22%20integrity%3D%22", p5jsIntegrity, "%22%20crossorigin%3D%22anonymous%22%3E%3C%2Fscript%3E%3C%2Fhead%3E%3Cbody%3E%3Cscript%3Evar%20tokenId%3D", AnonymiceLibrary.toString(_tokenId), "%3Bvar%20hash%3D%22", _hash, "%22%3B" ) ); htmlString = string( abi.encodePacked( htmlString, "xo%3D1%2Csd%3D21%2AtokenId%2CpCs%3D%5B0%2C30%2C80%2C120%2C180%2C225%2C270%2C300%5D%2CsCs%3D%5B0%2C30%2C120%2C180%2C225%2C270%2C300%2C330%5D%2CnMV%3D%5B.5%2C1%2C2%2C3%5D%2CeSs%3D%5B.26%2C.33%2C.4%5D%2CtV%3D%5B10%2C25%2C70%5D%2CeLs%3D%5B0%2C15%5D%3Bfunction%20setup%28%29%7BcreateCanvas%28500%2C500%29%2CcolorMode%28HSB%2C360%2C100%2C100%29%2CstrokeCap%28ROUND%29%2CnoiseSeed%28sd%29%2CrandomSeed%28sd%29%2CpC%3DparseInt%28hash.substring%280%2C1%29%29%2CsC%3DparseInt%28hash.substring%281%2C2%29%29%2CnM%3DparseInt%28hash.substring%282%2C3%29%29%2CeS%3DparseInt%28hash.substring%283%2C4%29%29%2Ct%3DparseInt%28hash.substring%284%2C5%29%29%2CeL%3DparseInt%28hash.substring%285%2C6%29%29%2C330%3D%3DsCs%5BsC%5D%3Fk%3DpCs%5BpC%5D%3Ak%3DsCs%5BsC%5D%2CwP%3Drandom%285%2C10%29%2ChP%3Drandom%285%2C10%29%7Dfunction%20draw%28%29%7Bbackground%28255%29%3Bfor%28let%20s%3D25%3Bs%3C500%3Bs%2B%3D50%29for%28let%20e%3D25%3Be%3C500%3Be%2B%3D50%29noStroke%28%29%2Cf%3DsCs%5BsC%5D%2C330%3D%3Df%3FrC%3Drandom%28360%29%3ArC%3Dk%2Cfill%28rC%2Crandom%2825%29%2C100%29%2Cc%3Dnew%20C1%2Cpush%28%29%2Ctranslate%28s%2Ce%29%2Cscale%28.14%2C.14%29%2Cc.s%28%29%2Cpop%28%29%3Bc1%3Dnew%20C2%28pCs%5BpC%5D%2C40%2C100%2C0%29%2Cpush%28%29%2Ctranslate%28250%2C500%29%2Crotate%283.14%29%2Cscale%28.55%2C1.25%29%2Cc1.s%28%29%2Cpop%28%29%2Cpush%28%29%2Ctranslate%28250%2C250%29%2Cc1.s%28%29%2Cpop%28%29%2CnoStroke%28%29%2Ce1%3Dnew%20C2%280%2C0%2C100%2C1%29%2Cpush%28%29%2Ctranslate%28200%2C200%29%2Cscale%28.33%29%2Ce1.s%28%29%2Cpop%28%29%2Ce2%3Dnew%20C2%280%2C0%2C100%2C1%29%2Cpush%28%29%2Cpush%28%29%2Ctranslate%28300%2C200%29%2Cscale%28eSs%5BeS%5D%29%2Crotate%28PI%29%2Ce2.s%28%29%2Cpop%28%29%2Cp1%3Dnew%20C2%28k%2C100%2C100%2C1%29%2Cpush%28%29%2Ctranslate%28200%2C200%2BeLs%5BeL%5D%29%2Cscale%28.1%29%2Cp1.s%28%29%2Cpop%28%29%2Cp2%3Dnew%20C2%28k%2C100%2C100%2C1%29%2Cpush%28%29%2Ctranslate%28300%2C200-eLs%5BeL%5D%29%2Cscale%28.1%29%2Crotate%28PI%29%2Cp2.s%28%29%2Cpop%28%29%3Bfor%28let%20s%3D200%3Bs%3C%3D300%3Bs%2B%2B%29sats%3Dmap%28noise%28xo%29%2C0%2C1%2C30%2C100%29%2Cfill%28k%2Csats%2C95%29%2Cr%3Dmap%28noise%28xo%29%2C0%2C1%2C.53%2C.77%29%2Cellipse%28s%2C500%2Ar%2C28%29%2Cxo%2B%3D.015%3BnoLoop%28%29%7Dclass%20C1%7Bs%28%29%7BbeginShape%28%29%3Bfor%28let%20s%3D0%3Bs%3CTWO_PI%3Bs%2B%3D.16%29%7Blet%20e%3Dmap%28cos%28s%29%2C-1%2C1%2C0%2CnMV%5BnM%5D%29%2Ct%3Dmap%28sin%28s%29%2C-1%2C1%2C0%2CnMV%5BnM%5D%29%2Cn%3Dmap%28noise%28e%2Ct%29%2C0%2C1%2C100%2C200%29%2Ca%3Dn%2Acos%28s%29%2Cp%3Dn%2Asin%28s%29%3Bvertex%28a%2Cp%29%2Ce%2B%3D.004%7DendShape%28%29%7D%7Dclass%20C2%7Bconstructor%28s%2Ce%2Ct%2Cn%29%7Bthis.h%3Ds%2Cthis.z%3De%2Cthis.l%3Dt%2Cthis.b%3Dn%7Ds%28%29%7BbeginShape%28%29%2CnoFill%28%29%3Bfor%28let%20s%3D0%3Bs%3CTWO_PI%3Bs%2B%3D.045%29%7Blet%20e%3Dmap%28sin%28s%29%2C-1%2C1%2C0%2CnMV%5BnM%5D%29%2Cn%3Dmap%28cos%28s%29%2C-1%2C1%2C0%2CnMV%5BnM%5D%29%2Ca%3Dmap%28noise%28n%2Ce%29%2C0%2C1%2C100%2C200%29%2Cp%3Da%2Acos%28s%29%2Co%3Da%2Asin%28s%29%3B0%3D%3Dthis.b%26%26%28stroke%28this.h%2Cthis.z%2Cthis.l-25%29%2CstrokeWeight%28tV%5Bt%5D%29%29%2Cvertex%28p%2Co%29%2CendShape%28%29%2Cpush%28%29%2Cstroke%28this.h%2Cthis.z%2Cthis.l%29%2CstrokeWeight%286%29%2Cline%28p%2B7.5%2Co%2B10%2C500%2FwP%2C500%2FhP%29%2Cpop%28%29%2Cn%2B%3D.04%2Ce%2B%3D.001%7DendShape%28%29%7D%7D%3C%2Fscript%3E%3C%2Fbody%3E%3C%2Fhtml%3E" ) ); return htmlString; }
12,998,923
[ 1, 2310, 358, 3982, 445, 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, 565, 445, 1651, 774, 4870, 12, 1080, 3778, 389, 2816, 16, 2254, 5034, 389, 2316, 548, 13, 203, 3639, 1071, 203, 3639, 1476, 203, 3639, 1135, 261, 1080, 3778, 13, 203, 565, 288, 203, 3639, 533, 3778, 1729, 780, 273, 533, 12, 203, 5411, 24126, 18, 3015, 4420, 329, 12, 203, 7734, 315, 892, 30, 955, 19, 2620, 15529, 23, 39, 2620, 9, 23, 41, 9, 23, 39, 1978, 9, 23, 41, 9, 23, 39, 4263, 9, 3462, 4816, 9, 23, 40, 9, 3787, 3113, 203, 7734, 293, 25, 2924, 1489, 16, 203, 7734, 2213, 3787, 9, 3462, 27423, 560, 9, 23, 40, 9, 3787, 3113, 203, 7734, 293, 25, 2924, 30669, 16, 203, 7734, 2213, 3787, 9, 3462, 14653, 10012, 9, 23, 40, 9, 3787, 19070, 9, 3787, 9, 23, 41, 9, 23, 39, 9, 22, 42, 4263, 9, 23, 41, 9, 23, 39, 9, 22, 42, 1978, 9, 23, 41, 9, 23, 39, 3432, 9, 23, 41, 9, 23, 39, 4263, 9, 23, 41, 1401, 9, 3462, 2316, 548, 9, 23, 40, 3113, 203, 7734, 1922, 6435, 1812, 9313, 18, 10492, 24899, 2316, 548, 3631, 203, 7734, 2213, 23, 38, 1401, 9, 3462, 2816, 9, 23, 40, 9, 3787, 3113, 203, 7734, 389, 2816, 16, 203, 7734, 2213, 3787, 9, 23, 38, 6, 203, 5411, 262, 203, 3639, 11272, 203, 203, 3639, 1729, 780, 273, 533, 12, 203, 5411, 24126, 18, 3015, 4420, 329, 12, 203, 7734, 1729, 780, 16, 203, 7734, 315, 25272, 9, 23, 40, 21, 9, 22, 39, 6427, 2 ]
/** *Submitted for verification at Etherscan.io on 2021-04-28 */ // File: node_modules\@openzeppelin\contracts\utils\EnumerableSet.sol // SPDX-License-Identifier: MIT 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)); } } // File: node_modules\@openzeppelin\contracts\utils\Address.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: node_modules\@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; } } // File: @openzeppelin\contracts\access\AccessControl.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context { using EnumerableSet for EnumerableSet.AddressSet; using Address for address; struct RoleData { EnumerableSet.AddressSet members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view returns (bool) { return _roles[role].members.contains(account); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view returns (uint256) { return _roles[role].members.length(); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view returns (address) { return _roles[role].members.at(index); } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant"); _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke"); _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, _roles[role].adminRole, adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (_roles[role].members.add(account)) { emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (_roles[role].members.remove(account)) { emit RoleRevoked(role, account, _msgSender()); } } } // File: node_modules\@openzeppelin\contracts\token\ERC20\IERC20.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: node_modules\@openzeppelin\contracts\math\SafeMath.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: @openzeppelin\contracts\token\ERC20\ERC20.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.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 guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // File: @openzeppelin\contracts\token\ERC20\ERC20Burnable.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.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 { uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance"); _approve(account, _msgSender(), decreasedAllowance); _burn(account, amount); } } // File: node_modules\@openzeppelin\contracts\utils\Pausable.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.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. */ contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor () internal { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!_paused, "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(_paused, "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // File: @openzeppelin\contracts\token\ERC20\ERC20Pausable.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.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: contracts\NuNetToken.sol pragma solidity ^0.6.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. */ contract NuNetToken is Context, AccessControl, ERC20Burnable, ERC20Pausable { bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); uint256 public constant MAX_SUPPLY = 1000000000 * 10**uint256(6); /** * @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) public ERC20(name, symbol) { _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); _setupRole(MINTER_ROLE, _msgSender()); _setupRole(PAUSER_ROLE, _msgSender()); // Setting Demcimal Places to 6 _setupDecimals(6); } /** * @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"); require(totalSupply().add(amount) <= MAX_SUPPLY, "Mint: Cannot mint more than initial supply"); _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); } }
* @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./
contract NuNetToken is Context, AccessControl, ERC20Burnable, ERC20Pausable { bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); uint256 public constant MAX_SUPPLY = 1000000000 * 10**uint256(6); constructor(string memory name, string memory symbol) public ERC20(name, symbol) { _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); _setupRole(MINTER_ROLE, _msgSender()); _setupRole(PAUSER_ROLE, _msgSender()); _setupDecimals(6); } function mint(address to, uint256 amount) public virtual { require(hasRole(MINTER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have minter role to mint"); require(totalSupply().add(amount) <= MAX_SUPPLY, "Mint: Cannot mint more than initial supply"); _mint(to, amount); } function pause() public virtual { require(hasRole(PAUSER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have pauser role to pause"); _pause(); } 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); } }
1,168,519
[ 1, 95, 654, 39, 3462, 97, 1147, 16, 6508, 30, 225, 300, 7123, 364, 366, 4665, 358, 18305, 261, 11662, 13, 3675, 2430, 225, 300, 279, 1131, 387, 2478, 716, 5360, 364, 1147, 312, 474, 310, 261, 17169, 13, 225, 300, 279, 6790, 1355, 2478, 716, 5360, 358, 2132, 777, 1147, 29375, 1220, 6835, 4692, 288, 16541, 97, 358, 2176, 4132, 329, 4186, 1450, 326, 3775, 4900, 300, 910, 358, 2097, 7323, 364, 3189, 18, 1021, 2236, 716, 5993, 383, 1900, 326, 6835, 903, 506, 17578, 326, 1131, 387, 471, 6790, 1355, 4900, 16, 487, 5492, 487, 326, 805, 3981, 2478, 16, 1492, 903, 2231, 518, 7936, 3937, 1131, 387, 471, 6790, 1355, 4900, 358, 1308, 9484, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 6835, 20123, 7308, 1345, 353, 1772, 16, 24349, 16, 4232, 39, 3462, 38, 321, 429, 16, 4232, 39, 3462, 16507, 16665, 288, 203, 565, 1731, 1578, 1071, 5381, 6989, 2560, 67, 16256, 273, 417, 24410, 581, 5034, 2932, 6236, 2560, 67, 16256, 8863, 203, 565, 1731, 1578, 1071, 5381, 15662, 4714, 67, 16256, 273, 417, 24410, 581, 5034, 2932, 4066, 4714, 67, 16256, 8863, 203, 203, 565, 2254, 5034, 1071, 5381, 4552, 67, 13272, 23893, 273, 15088, 3784, 380, 1728, 636, 11890, 5034, 12, 26, 1769, 203, 203, 203, 565, 3885, 12, 1080, 3778, 508, 16, 533, 3778, 3273, 13, 1071, 4232, 39, 3462, 12, 529, 16, 3273, 13, 288, 203, 3639, 389, 8401, 2996, 12, 5280, 67, 15468, 67, 16256, 16, 389, 3576, 12021, 10663, 203, 203, 3639, 389, 8401, 2996, 12, 6236, 2560, 67, 16256, 16, 389, 3576, 12021, 10663, 203, 3639, 389, 8401, 2996, 12, 4066, 4714, 67, 16256, 16, 389, 3576, 12021, 10663, 203, 203, 3639, 389, 8401, 31809, 12, 26, 1769, 203, 565, 289, 203, 203, 565, 445, 312, 474, 12, 2867, 358, 16, 2254, 5034, 3844, 13, 1071, 5024, 288, 203, 3639, 2583, 12, 5332, 2996, 12, 6236, 2560, 67, 16256, 16, 389, 3576, 12021, 1435, 3631, 315, 654, 39, 3462, 18385, 49, 2761, 16507, 1355, 30, 1297, 1240, 1131, 387, 2478, 358, 312, 474, 8863, 203, 3639, 2583, 12, 4963, 3088, 1283, 7675, 1289, 12, 8949, 13, 1648, 4552, 67, 13272, 23893, 16, 315, 49, 474, 30, 14143, 312, 474, 1898, 2353, 2172, 14467, 8863, 203, 3639, 2 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.6.10; pragma experimental ABIEncoderV2; import {IGelatoUserProxyFactory} from "./interfaces/IGelatoUserProxyFactory.sol"; import {Address} from "../../external/Address.sol"; import {GelatoUserProxy} from "./GelatoUserProxy.sol"; import {GelatoUserProxySet} from "../../libraries/GelatoUserProxySet.sol"; import {Action, Provider, Task} from "../../gelato_core/interfaces/IGelatoCore.sol"; contract GelatoUserProxyFactory is IGelatoUserProxyFactory { using Address for address payable; /// for oz's sendValue method using GelatoUserProxySet for GelatoUserProxySet.Set; address public immutable override gelatoCore; mapping(GelatoUserProxy => address) public override userByGelatoProxy; mapping(address => GelatoUserProxySet.Set) private _gelatoProxiesByUser; constructor(address _gelatoCore) public { gelatoCore = _gelatoCore; } // ==================== CREATE ======================================= function create() public payable override returns (GelatoUserProxy userProxy) { userProxy = new GelatoUserProxy{value: msg.value}(msg.sender, gelatoCore); _storeGelatoUserProxy(userProxy); } function createExecActions(Action[] calldata _actions) external payable override returns (GelatoUserProxy userProxy) { userProxy = create(); if (_actions.length != 0) _execActions(userProxy, _actions); } function createSubmitTasks( Provider calldata _provider, Task[] calldata _tasks, uint256[] calldata _expiryDates ) external payable override returns (GelatoUserProxy userProxy) { userProxy = create(); if (_tasks.length != 0) _submitTasks(userProxy, _provider, _tasks, _expiryDates); } function createExecActionsSubmitTasks( Action[] calldata _actions, Provider calldata _provider, Task[] calldata _tasks, uint256[] calldata _expiryDates ) external payable override returns(GelatoUserProxy userProxy) { userProxy = create(); if (_actions.length != 0) _execActions(userProxy, _actions); if (_tasks.length != 0) _submitTasks(userProxy, _provider, _tasks, _expiryDates); } function createExecActionsSubmitTaskCycle( Action[] calldata _actions, Provider calldata _provider, Task[] calldata _tasks, uint256 _expiryDate, uint256 _cycles ) external payable override returns(GelatoUserProxy userProxy) { userProxy = create(); if (_actions.length != 0) _execActions(userProxy, _actions); if (_tasks.length == 0) revert("GelatoUserProxyFactory.createExecActionsSubmitTaskCycle: 0 _tasks"); _submitTaskCycle(userProxy, _provider, _tasks, _expiryDate, _cycles); } function createExecActionsSubmitTaskChain( Action[] calldata _actions, Provider calldata _provider, Task[] calldata _tasks, uint256 _expiryDate, uint256 _sumOfRequestedTaskSubmits ) external payable override returns(GelatoUserProxy userProxy) { userProxy = create(); if (_actions.length != 0) _execActions(userProxy, _actions); if (_tasks.length == 0) revert("GelatoUserProxyFactory.createExecActionsSubmitTaskChain: 0 _tasks"); _submitTaskChain(userProxy, _provider, _tasks, _expiryDate, _sumOfRequestedTaskSubmits); } // ==================== CREATE 2 ======================================= function createTwo(uint256 _saltNonce) public payable override returns (GelatoUserProxy userProxy) { bytes32 salt = keccak256(abi.encode(msg.sender, _saltNonce)); userProxy = new GelatoUserProxy{salt: salt, value: msg.value}(msg.sender, gelatoCore); require( address(userProxy) == predictProxyAddress(msg.sender, _saltNonce), "GelatoUserProxyFactory.createTwo: wrong address prediction" ); _storeGelatoUserProxy(userProxy); } function createTwoExecActions(uint256 _saltNonce, Action[] calldata _actions) external payable override returns (GelatoUserProxy userProxy) { userProxy = createTwo(_saltNonce); if (_actions.length != 0) _execActions(userProxy, _actions); } function createTwoSubmitTasks( uint256 _saltNonce, // Submit Tasks Data Provider calldata _provider, Task[] calldata _tasks, uint256[] calldata _expiryDates ) external payable override returns (GelatoUserProxy userProxy) { userProxy = createTwo(_saltNonce); if (_tasks.length != 0) _submitTasks(userProxy, _provider, _tasks, _expiryDates); } // A standard _saltNonce can be used for deterministic shared address derivation function createTwoExecActionsSubmitTasks( uint256 _saltNonce, Action[] calldata _actions, // Submit Tasks Data Provider calldata _provider, Task[] calldata _tasks, uint256[] calldata _expiryDates ) external payable override returns(GelatoUserProxy userProxy) { userProxy = createTwo(_saltNonce); if (_actions.length != 0) _execActions(userProxy, _actions); if (_tasks.length != 0) _submitTasks(userProxy, _provider, _tasks, _expiryDates); } function createTwoExecActionsSubmitTaskCycle( uint256 _saltNonce, Action[] calldata _actions, // Submit TaskCycle Data Provider calldata _provider, Task[] calldata _tasks, uint256 _expiryDate, uint256 _cycles ) external payable override returns(GelatoUserProxy userProxy) { userProxy = createTwo(_saltNonce); if (_actions.length != 0) _execActions(userProxy, _actions); if (_tasks.length == 0) revert("GelatoUserProxyFactory.createTwoExecActionsSubmitTaskCycle: 0 _tasks"); _submitTaskCycle(userProxy, _provider, _tasks, _expiryDate, _cycles); } function createTwoExecActionsSubmitTaskChain( uint256 _saltNonce, Action[] calldata _actions, // Submit TaskChain Data Provider calldata _provider, Task[] calldata _tasks, uint256 _expiryDate, uint256 _sumOfRequestedTaskSubmits ) external payable override returns(GelatoUserProxy userProxy) { userProxy = createTwo(_saltNonce); if (_actions.length != 0) _execActions(userProxy, _actions); if (_tasks.length == 0) revert("GelatoUserProxyFactory.createTwoExecActionsSubmitTaskChain: 0 _tasks"); _submitTaskChain(userProxy, _provider, _tasks, _expiryDate, _sumOfRequestedTaskSubmits); } // ==================== GETTERS ======================================= function predictProxyAddress(address _user, uint256 _saltNonce) public view override returns(address) { // Standard Way of deriving salt bytes32 salt = keccak256(abi.encode(_user, _saltNonce)); // Derive undeployed userProxy address return address(uint(keccak256(abi.encodePacked( byte(0xff), address(this), salt, keccak256(abi.encodePacked(proxyCreationCode(), abi.encode(_user, gelatoCore))) )))); } function isGelatoUserProxy(address _proxy) external view override returns(bool) { return userByGelatoProxy[GelatoUserProxy(payable(_proxy))] != address(0); } function isGelatoProxyUser(address _user, GelatoUserProxy _userProxy) external view override returns(bool) { return _gelatoProxiesByUser[_user].contains(_userProxy); } function gelatoProxiesByUser(address _user) external view override returns(GelatoUserProxy[] memory) { return _gelatoProxiesByUser[_user].enumerate(); } function getGelatoUserProxyByIndex(address _user, uint256 _index) external view override returns(GelatoUserProxy) { return _gelatoProxiesByUser[_user].get(_index); } function proxyCreationCode() public pure override returns(bytes memory) { return type(GelatoUserProxy).creationCode; } // ==================== HELPERS ======================================= // store and emit LogCreation function _storeGelatoUserProxy(GelatoUserProxy _userProxy) private { _gelatoProxiesByUser[msg.sender].add(_userProxy); userByGelatoProxy[_userProxy] = msg.sender; emit LogCreation(msg.sender, _userProxy, msg.value); } function _execActions(GelatoUserProxy _userProxy, Action[] calldata _actions) private { try _userProxy.multiExecActions(_actions) { } catch Error(string memory err) { revert(string(abi.encodePacked("GelatoUserProxyFactory._execActions:", err))); } catch { revert("GelatoUserProxyFactory._execActions:undefined"); } } function _submitTasks( GelatoUserProxy _userProxy, // Submit Tasks Data Provider calldata _provider, Task[] calldata _tasks, uint256[] calldata _expiryDates ) private { try _userProxy.multiSubmitTasks(_provider, _tasks, _expiryDates) { } catch Error(string memory err) { revert(string(abi.encodePacked("GelatoUserProxyFactory._submitTasks:", err))); } catch { revert("GelatoUserProxyFactory._submitTasks:undefined"); } } function _submitTaskCycle( GelatoUserProxy _userProxy, // Submit TaskCyle Data Provider calldata _provider, Task[] calldata _tasks, uint256 _expiryDate, uint256 _cycles ) private { try _userProxy.submitTaskCycle(_provider, _tasks, _expiryDate, _cycles) { } catch Error(string memory err) { revert( string(abi.encodePacked("GelatoUserProxyFactory._submitTaskCycle:", err)) ); } catch { revert("GelatoUserProxyFactory._submitTaskCycle:undefined"); } } function _submitTaskChain( GelatoUserProxy _userProxy, // Submit TaskChain Data Provider calldata _provider, Task[] calldata _tasks, uint256 _expiryDate, uint256 _sumOfRequestedTaskSubmits ) private { try _userProxy.submitTaskChain( _provider, _tasks, _expiryDate, _sumOfRequestedTaskSubmits ) { } catch Error(string memory err) { revert( string(abi.encodePacked("GelatoUserProxyFactory._submitTaskChain:", err)) ); } catch { revert("GelatoUserProxyFactory._submitTaskChain:undefined"); } } }
==================== GETTERS ======================================= Standard Way of deriving salt Derive undeployed userProxy address
function predictProxyAddress(address _user, uint256 _saltNonce) public view override returns(address) { bytes32 salt = keccak256(abi.encode(_user, _saltNonce)); return address(uint(keccak256(abi.encodePacked( byte(0xff), address(this), salt, keccak256(abi.encodePacked(proxyCreationCode(), abi.encode(_user, gelatoCore))) )))); }
918,892
[ 1, 2429, 894, 17788, 1470, 11367, 422, 4428, 894, 33, 8263, 678, 528, 434, 4854, 9288, 4286, 14969, 688, 640, 12411, 329, 729, 3886, 1758, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 7810, 3886, 1887, 12, 2867, 389, 1355, 16, 2254, 5034, 389, 5759, 13611, 13, 203, 3639, 1071, 203, 3639, 1476, 203, 3639, 3849, 203, 3639, 1135, 12, 2867, 13, 203, 565, 288, 203, 3639, 1731, 1578, 4286, 273, 417, 24410, 581, 5034, 12, 21457, 18, 3015, 24899, 1355, 16, 389, 5759, 13611, 10019, 203, 203, 3639, 327, 1758, 12, 11890, 12, 79, 24410, 581, 5034, 12, 21457, 18, 3015, 4420, 329, 12, 203, 5411, 1160, 12, 20, 5297, 3631, 203, 5411, 1758, 12, 2211, 3631, 203, 5411, 4286, 16, 203, 5411, 417, 24410, 581, 5034, 12, 21457, 18, 3015, 4420, 329, 12, 5656, 9906, 1085, 9334, 24126, 18, 3015, 24899, 1355, 16, 314, 292, 31093, 4670, 20349, 203, 3639, 262, 3719, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/43114/0xF206f9ACBE69CA5d2166a36F22d5D8e10f2d836D/sources/CowBarn.sol
wolves take a 20% tax on all $avaMILK claimed
uint256 public constant MILK_UNSTAKE_TAX_PERCENTAGE = 30;
4,635,534
[ 1, 91, 355, 3324, 4862, 279, 4200, 9, 5320, 603, 777, 271, 1629, 49, 2627, 47, 7516, 329, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 2254, 5034, 1071, 5381, 490, 2627, 47, 67, 2124, 882, 37, 6859, 67, 56, 2501, 67, 3194, 19666, 2833, 273, 5196, 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 ]
pragma solidity 0.4.25; contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor () public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != owner); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title -Name Filter- v0.1.9 */ library NameFilter { /** * @dev filters name strings * -converts uppercase to lower case. * -makes sure it does not start/end with a space * -makes sure it does not contain multiple spaces in a row * -restricts characters to A-Z, a-z, 0-9, and space. * @return reprocessed string in bytes32 format */ function nameFilter(string _input) internal pure returns(bytes32) { bytes memory _temp = bytes(_input); uint256 _length = _temp.length; //sorry limited to 32 characters require (_length <= 32 && _length > 0, "string must be between 1 and 32 characters"); // make sure it doesnt start with or end with space require(_temp[0] != 0x20 && _temp[_length-1] != 0x20, "string cannot start or end with space"); // create a bool to track if we have a non number character bool _hasNonNumber; // convert & check for (uint256 i = 0; i < _length; i++) { // if its uppercase A-Z if (_temp[i] > 0x40 && _temp[i] < 0x5b) { // convert to lower case a-z _temp[i] = byte(uint(_temp[i]) + 32); // we have a non number if (_hasNonNumber == false) _hasNonNumber = true; } else { require ( // require character is a space _temp[i] == 0x20 || // OR lowercase a-z (_temp[i] > 0x60 && _temp[i] < 0x7b) || // or 0-9 (_temp[i] > 0x2f && _temp[i] < 0x3a), "string contains invalid characters" ); // make sure theres not 2x spaces in a row if (_temp[i] == 0x20) require( _temp[i+1] != 0x20, "string cannot contain consecutive spaces"); // see if we have a character other than a number if (_hasNonNumber == false && (_temp[i] < 0x30 || _temp[i] > 0x39)) _hasNonNumber = true; } } bytes32 _ret; assembly { _ret := mload(add(_temp, 32)) } return (_ret); } } /** * Math operations with safety checks */ /** * @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; } } contract CelebrityGame is Ownable { using SafeMath for *; using NameFilter for string; string constant public gameName = "Celebrity Game"; // fired whenever a card is created event LogNewCard(string name, uint256 id); // fired whenever a player is registered event LogNewPlayer(string name, uint256 id); //just for isStartEnable modifier bool private isStart = false; uint256 private roundId = 0; struct Card { bytes32 name; // card owner name uint256 fame; // The number of times CARDS were liked uint256 fameValue; // The charge for the current card to be liked once uint256 notorious; // The number of times CARDS were disliked uint256 notoriousValue; // The charge for the current card to be disliked once } struct CardForPlayer { uint256 likeCount; // The number of times the player likes it uint256 dislikeCount; // The number of times the player disliked it } struct CardWinner { bytes32 likeWinner; bytes32 dislikeWinner; } Card[] public cards; bytes32[] public players; mapping (uint256 => mapping (uint256 => mapping ( uint256 => CardForPlayer))) public playerCard; // returns cards of this player like or dislike by playerId and roundId and cardId mapping (uint256 => mapping (uint256 => CardWinner)) public cardWinnerMap; // (roundId => (cardId => winner)) returns winner by roundId and cardId mapping (uint256 => Card[]) public rounCardMap; // returns Card info by roundId mapping (bytes32 => uint256) private plyNameXId; // (playerName => Id) returns playerId by playerName mapping (bytes32 => uint256) private cardNameXId; // (cardName => Id) returns cardId by cardName mapping (bytes32 => bool) private cardIsReg; // (cardName => cardCount) returns cardCount by cardName,just for createCard function mapping (bytes32 => bool) private playerIsReg; // (playerName => isRegister) returns registerInfo by playerName, just for registerPlayer funciton mapping (uint256 => bool) private cardIdIsReg; // (cardId => card info) returns card info by cardId mapping (uint256 => bool) private playerIdIsReg; // (playerId => id) returns player index of players by playerId mapping (uint256 => uint256) private cardIdXSeq; mapping (uint256 => uint256) private playerIdXSeq; /** * @dev used to make sure no one can interact with contract until it has been started */ modifier isStartEnable { require(isStart == true); _; } /** * the contract precision is 1000 */ constructor() public { string[8] memory names= ["SatoshiNakamoto","CZ","HeYi","LiXiaolai","GuoHongcai","VitalikButerin","StarXu","ByteMaster"]; uint256[8] memory _ids = [uint256(183946248739),536269148721,762415028463,432184367532,398234673241,264398721023,464325189620,217546321806]; for (uint i = 0; i < 8; i++){ string memory _nameString = names[i]; uint256 _id = _ids[i]; bytes32 _name = _nameString.nameFilter(); require(cardIsReg[_name] == false); uint256 _seq = cards.push(Card(_name, 1, 1000, 1, 1000)) - 1; cardIdXSeq[_id] = _seq; cardNameXId[_name] = _id; cardIsReg[_name] = true; cardIdIsReg[_id] = true; } } /** * @dev use this function to create card. * - must pay some create fees. * - name must be unique * - max length of 32 characters long * @param _nameString owner desired name for card * @param _id card id * (this might cost a lot of gas) */ function createCard(string _nameString, uint256 _id) public onlyOwner() { require(keccak256(abi.encodePacked(_name)) != keccak256(abi.encodePacked(""))); bytes32 _name = _nameString.nameFilter(); require(cardIsReg[_name] == false); uint256 _seq = cards.push(Card(_name, 1, 1000, 1, 1000)) - 1; cardIdXSeq[_id] = _seq; cardNameXId[_name] = _id; cardIsReg[_name] = true; cardIdIsReg[_id] = true; emit LogNewCard(_nameString, _id); } /** * @dev use this function to register player. * - must pay some register fees. * - name must be unique * - name cannot be null * - max length of 32 characters long * @param _nameString team desired name for player * @param _id player id * (this might cost a lot of gas) */ function registerPlayer(string _nameString, uint256 _id) external { require(keccak256(abi.encodePacked(_name)) != keccak256(abi.encodePacked(""))); bytes32 _name = _nameString.nameFilter(); require(playerIsReg[_name] == false); uint256 _seq = players.push(_name) - 1; playerIdXSeq[_id] = _seq; plyNameXId[_name] = _id; playerIsReg[_name] = true; playerIdIsReg[_id] = true; emit LogNewPlayer(_nameString, _id); } /** * @dev this function for One player likes the CARD once. * @param _cardId must be returned when creating CARD * @param _playerId must be returned when registering player * (this might cost a lot of gas) */ function likeCelebrity(uint256 _cardId, uint256 _playerId) external isStartEnable { require(cardIdIsReg[_cardId] == true, "sorry create this card first"); require(playerIdIsReg[_playerId] == true, "sorry register the player name first"); Card storage queryCard = cards[cardIdXSeq[_cardId]]; queryCard.fame = queryCard.fame.add(1); queryCard.fameValue = queryCard.fameValue.add(queryCard.fameValue / 100*1000); playerCard[_playerId][roundId][_cardId].likeCount == (playerCard[_playerId][roundId][_cardId].likeCount).add(1); cardWinnerMap[roundId][_cardId].likeWinner = players[playerIdXSeq[_playerId]]; } /** * @dev this function for One player dislikes the CARD once. * @param _cardId must be returned when creating CARD * @param _playerId must be created when registering player * (this might cost a lot of gas) */ function dislikeCelebrity(uint256 _cardId, uint256 _playerId) external isStartEnable { require(cardIdIsReg[_cardId] == true, "sorry create this card first"); require(playerIdIsReg[_playerId] == true, "sorry register the player name first"); Card storage queryCard = cards[cardIdXSeq[_cardId]]; queryCard.notorious = queryCard.notorious.add(1); queryCard.notoriousValue = queryCard.notoriousValue.add(queryCard.notoriousValue / 100*1000); playerCard[_playerId][roundId][_cardId].dislikeCount == (playerCard[_playerId][roundId][_cardId].dislikeCount).add(1); cardWinnerMap[roundId][_cardId].dislikeWinner = players[playerIdXSeq[_playerId]]; } /** * @dev use this function to reset card properties. * - must be called when game is not started by team. * @param _id must be returned when creating CARD * (this might cost a lot of gas) */ function reset(uint256 _id) external onlyOwner() { require(isStart == false); Card storage queryCard = cards[cardIdXSeq[_id]]; queryCard.fame = 1; queryCard.fameValue = 1000; queryCard.notorious = 1; queryCard.notoriousValue = 1000; } /** * @dev use this function to start the game. * - must be called by owner. * (this might cost a lot of gas) */ function gameStart() external onlyOwner() { isStart = true; roundId = roundId.add(1); } /** * @dev use this function to end the game. Just for emergency control by owner * (this might cost a lot of gas) */ function gameEnd() external onlyOwner() { isStart = false; rounCardMap[roundId] = cards; } /** * @dev use this function to get CARDS count * @return Total all CARDS in the current game */ function getCardsCount() public view returns(uint256) { return cards.length; } /** * @dev use this function to get CARDS id by its name. * @param _nameString must be created when creating CARD * @return the card id */ function getCardId(string _nameString) public view returns(uint256) { bytes32 _name = _nameString.nameFilter(); require(cardIsReg[_name] == true, "sorry create this card first"); return cardNameXId[_name]; } /** * @dev use this function to get player id by the name. * @param _nameString must be created when creating CARD * @return the player id */ function getPlayerId(string _nameString) public view returns(uint256) { bytes32 _name = _nameString.nameFilter(); require(playerIsReg[_name] == true, "sorry register the player name first"); return plyNameXId[_name]; } /** * @dev use this function to get player bet count. * @param _playerName must be created when registering player * @param _roundId must be a game that has already started * @param _cardName the player id must be created when creating CARD * @return likeCount * @return dislikeCount */ function getPlayerBetCount(string _playerName, uint256 _roundId, string _cardName) public view returns(uint256 likeCount, uint256 dislikeCount) { bytes32 _cardNameByte = _cardName.nameFilter(); require(cardIsReg[_cardNameByte] == false); bytes32 _playerNameByte = _playerName.nameFilter(); require(playerIsReg[_playerNameByte] == false); return (playerCard[plyNameXId[_playerNameByte]][_roundId][cardNameXId[_cardNameByte]].likeCount, playerCard[plyNameXId[_playerNameByte]][_roundId][cardNameXId[_cardNameByte]].dislikeCount); } }
* @dev Allows the current owner to transfer control of the contract to a newOwner. @param newOwner The address to transfer ownership to./
function transferOwnership(address newOwner) public onlyOwner { require(newOwner != owner); emit OwnershipTransferred(owner, newOwner); owner = newOwner; }
12,614,143
[ 1, 19132, 326, 783, 3410, 358, 7412, 3325, 434, 326, 6835, 358, 279, 394, 5541, 18, 225, 394, 5541, 1021, 1758, 358, 7412, 23178, 358, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 7412, 5460, 12565, 12, 2867, 394, 5541, 13, 1071, 1338, 5541, 288, 203, 3639, 2583, 12, 2704, 5541, 480, 3410, 1769, 203, 3639, 3626, 14223, 9646, 5310, 1429, 4193, 12, 8443, 16, 394, 5541, 1769, 203, 3639, 3410, 273, 394, 5541, 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 ]
pragma solidity ^ 0.4.24; import "./ERC20.sol"; import "./Util.sol"; import "./List.sol"; import "./ERC20Token.sol"; import "./Ownable.sol"; import "./Vault.sol"; import "./CrowdsaleToken.sol"; import "./ERC721.sol"; import "./ERC721Token.sol"; import "./ERC777.sol"; import "./ERC777Token.sol"; contract SimpleOwnable { using SafeMath for uint256; using AddressUtils for address; address _owner; function owner() public view returns(address) { return _owner; } } contract SimpleNFT is SimpleOwnable { using SafeMath for uint256; using AddressUtils for address; function transfer(address _to) public returns(bool) { address sender = msg.sender; MiscOp.requireEx(_owner == sender); MiscOp.requireEx(_to != address(0)); _owner = _to; emit Transfer(msg.sender, _to); return true; } event Transfer(address indexed from, address indexed to); } contract ApprovableNFT is SimpleNFT { address allowed; event Approval(address indexed owner, address indexed spender); function transfer(address _to) public returns(bool) { allowed = 0x0; return super.transfer(_to); } function transferFrom( address _from, address _to ) public returns(bool) { address sender = msg.sender; MiscOp.requireEx(allowed == sender); MiscOp.requireEx(_owner == _from); MiscOp.requireEx(_to != 0x0); allowed = 0x0; _owner = _to; emit Transfer(_from, _to); return true; } function approve(address _spender) public returns(bool) { address sender = msg.sender; MiscOp.requireEx(_owner == sender); MiscOp.requireEx(_spender != address(0)); allowed = _spender; emit Approval(msg.sender, _spender); return true; } function approved() public view returns(address) { return allowed; } } contract SimpleFT { using SafeMath for uint256; using AddressUtils for address; mapping(address => uint256) balances; uint256 total; function totalSupply() public view returns(uint256) { return total; } function transfer(address _to, uint256 _value) public returns(bool) { MiscOp.requireEx(_value <= balances[msg.sender]); MiscOp.requireEx(_to != address(0)); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } function balanceOf(address _owner) public view returns(uint256) { return balances[_owner]; } event Transfer(address indexed from, address indexed to, uint256 value); } contract ApprovableFT is SimpleFT { mapping(address => mapping(address => uint256)) internal allowed; event Approval(address indexed owner, address indexed spender, uint256 value); function transferFrom( address _from, address _to, uint256 _value ) public returns(bool) { MiscOp.requireEx(_value <= balances[_from]); MiscOp.requireEx(_value <= allowed[_from][msg.sender]); MiscOp.requireEx(_to != address(0)); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } 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]; } } contract SimpleRecoverable { address recoverAgent; function agentRecoverNFT(address _to, address _asset) public returns(bool) { address sender = msg.sender; MiscOp.requireEx(sender == recoverAgent); MiscOp.requireEx(_asset != address(0)); MiscOp.requireEx(_to != address(0)); SimpleNFT(_asset).transfer(_to); emit RecoverNFT(sender, _to, _asset); return true; } function agentRecoverFT(address _to, address _asset, uint256 _value) public returns(bool) { address sender = msg.sender; MiscOp.requireEx(sender == recoverAgent); MiscOp.requireEx(_asset != address(0)); MiscOp.requireEx(_to != address(0)); SimpleFT(_asset).transfer(_to, _value); emit RecoverFT(sender, _to, _asset, _value); return true; } event RecoverFT(address indexed sender, address indexed to, address indexed asset, uint256 value); event RecoverNFT(address indexed sender, address indexed to, address indexed asset); } contract DebtRecoverable is SimpleRecoverable { function agentAcceptDebt(address _to, address _asset, uint256 _value) public returns(bool) { address sender = msg.sender; MiscOp.requireEx(sender == recoverAgent); MiscOp.requireEx(_asset != address(0)); MiscOp.requireEx(_to != address(0)); SimpleBondFT(_asset).acceptDebt(_to, _value); emit AcceptDebt(sender, _to, _asset, _value); return true; } event AcceptDebt(address indexed sender, address indexed to, address indexed asset, uint256 value); } contract AllowRecoverable is SimpleRecoverable { function agentAllow(address _spender, address _asset, uint256 _value) public returns(bool) { address sender = msg.sender; MiscOp.requireEx(sender == recoverAgent); MiscOp.requireEx(_asset != address(0)); MiscOp.requireEx(_spender != address(0)); ApprovableFT(_asset).approve(_spender, _value); emit Allow(sender, _spender, _asset, _value); return true; } event Allow(address indexed sender, address indexed to, address indexed asset, uint256 value); } contract EthRecoverable is SimpleRecoverable { function agentRecoverEth(address _to, uint256 _value) public returns(bool) { address sender = msg.sender; MiscOp.requireEx(sender == recoverAgent); MiscOp.requireEx(_to != address(0)); _to.transfer(_value); emit RecoverEth(sender, _to, _value); return true; } event RecoverEth(address indexed sender, address indexed to, uint256 value); } contract SimpleBondFT { using SafeMath for uint256; address mintAgent; SimpleFT currency; uint256 matureDate; uint256 bondTotal; mapping(address => int256) balances; function init( // used for constructor address _from, // debt, negative asset address _to, // bond, positive asset uint256 _value) internal { MiscOp.requireEx(_from != address(0)); MiscOp.requireEx(_to != address(0)); MiscOp.requireEx(_value > 0); _add(_to, int256(_value)); // inc first _add(_from, -int256(_value)); // dec second } function totalSupply() public view returns(uint256) { return bondTotal; } function transfer(address _to, uint256 _value) public returns(bool) { int256 svalue = int256(_value); MiscOp.requireEx(_to != address(0)); MiscOp.requireEx(balances[msg.sender] > 0); MiscOp.requireEx(svalue > 0); MiscOp.requireEx(balances[msg.sender] >= svalue); _add(_to, int256(_value)); // inc first _add(msg.sender, -int256(_value)); // dec second emit Transfer(msg.sender, _to, _value); return true; } function acceptDebt(address _to, uint256 _value) public returns(bool) { int256 svalue = int256(_value); MiscOp.requireEx(_to != address(0)); MiscOp.requireEx(svalue > 0); _add(_to, int256(_value)); // inc first _add(msg.sender, -int256(_value)); // dec second emit Transfer(msg.sender, _to, _value); return true; } function _add(address _to, int256 _value) internal returns(bool) { uint256 a = balances[_to] > 0 ? uint256(balances[_to]) : 0; balances[_to] += int256(_value); uint256 b = balances[_to] > 0 ? uint256(balances[_to]) : 0; bondTotal = bondTotal.add(b).sub(a); } function balanceOf(address _owner) public view returns(int256) { return balances[_owner]; } event Transfer(address indexed from, address indexed to, uint256 value); } contract ApprovableBondFT is SimpleBondFT { mapping(address => mapping(address => uint256)) internal allowed; mapping(address => mapping(address => uint256)) internal debtAllowed; event Approval(address indexed owner, address indexed spender, uint256 value); function transferFrom( address _from, address _to, uint256 _value ) public returns(bool) { int256 svalue = int256(_value); MiscOp.requireEx(_to != address(0)); MiscOp.requireEx(balances[_from] > 0); MiscOp.requireEx(svalue > 0); MiscOp.requireEx(balances[_from] >= svalue); _add(_to, int256(_value)); // inc first _add(_from, -int256(_value)); // dec second allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } // function debtTransferFrom( // address _from, // address _to, // uint256 _value // ) // public // returns(bool) // { // int256 svalue = int256(_value); // MiscOp.requireEx(_from != address(0)); // MiscOp.requireEx(_to != address(0)); // MiscOp.requireEx(svalue > 0); // _add(_from, int256(_value)); // inc first // _add(_to, -int256(_value)); // dec second // allowed[_to][msg.sender] = allowed[_to][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 debtApprove(address _spender, uint256 _value) public returns(bool) { // debtAllowed[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]; } } contract SimpleWallet is SimpleOwnable, SimpleRecoverable { } contract SimpleBond is ApprovableBondFT, SimpleRecoverable { } contract SimpleOption is ApprovableFT, SimpleRecoverable { } contract SimpleRightToken is // product and service token ApprovableFT, SimpleRecoverable { } contract SimpleServiceRightBond is ApprovableBondFT, SimpleRecoverable { } contract MintableServiceFT is ApprovableFT, SimpleRecoverable { } contract MintableServiceReceiptFT is ApprovableFT, SimpleRecoverable { } contract SaleCurrency is ApprovableFT, SimpleRecoverable { } contract SimpleSellerToken is ApprovableNFT, SimpleRecoverable { } contract SimpleBuyerToken is ApprovableNFT, SimpleRecoverable { } contract DebtBuyerToken is ApprovableNFT, DebtRecoverable { } contract ShoppingMarket { function transferFromFT( address _from, address _to, ApprovableFT token, uint256 _value) public { token.transferFrom(_from, _to, _value); } } contract SimpleIcoPreOption { 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; // Debenture debt bond struct ContractEntry { address id; uint256 productId; address seller; SimpleSellerToken sellerWorkingVault; SimpleSellerToken sellerFinalVault; ShoppingMarket market; SaleCurrency currency; SimpleOption optionToken; address targetToken; uint256 TokenPricePerGG; uint256 OptionPricePerGG; uint256 sellerAccount; uint256 buyerPrimary; } ContractEntry entry; uint256 constant GG = 10**18; function open() internal { entry.sellerWorkingVault = new SimpleSellerToken(); } function buyOption(address buyer, uint256 currencyAmount) internal { entry.market.transferFromFT(buyer, entry.sellerWorkingVault, entry.currency, currencyAmount); // refundable entry.sellerWorkingVault.agentRecoverFT(buyer, entry.optionToken, currencyAmount); } function refund(address buyer) internal { uint256 currencyAmount = entry.optionToken.balanceOf(buyer); entry.sellerWorkingVault.agentRecoverFT(buyer, entry.currency, currencyAmount); entry.market.transferFromFT(buyer, entry.sellerFinalVault, entry.optionToken, currencyAmount); } function executeOption(address buyer) internal { uint256 currencyAmount = entry.optionToken.balanceOf(buyer); uint256 tokenAmount = GG.mul(currencyAmount).div(entry.OptionPricePerGG); uint256 currencyAmount2 = tokenAmount.mul(entry.TokenPricePerGG).div(GG); entry.market.transferFromFT(buyer, entry.sellerFinalVault, entry.currency, currencyAmount2); entry.sellerWorkingVault.agentRecoverFT(buyer, entry.targetToken, tokenAmount); entry.sellerWorkingVault.agentRecoverFT(entry.sellerFinalVault, entry.currency, currencyAmount); entry.market.transferFromFT(buyer, entry.sellerFinalVault, entry.optionToken, currencyAmount); } function close() internal pure { } } contract LockedIcoSale { 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; // Debenture debt bond struct BuyerInfo { address lastOwner; uint256 currencyAmount; uint256 tokenAmount; } struct ContractEntry { address id; uint256 productId; address seller; SimpleSellerToken sellerInitialVault; SimpleSellerToken sellerWorkingVault; SimpleSellerToken sellerFinalVault; ShoppingMarket market; SaleCurrency currency; address targetToken; uint256 TokenPricePerGG; uint256 OptionPricePerGG; uint256 sellerAccount; uint256 buyerPrimary; // list_address.t nft; mapping(address => BuyerInfo) buyInfos; // SimpleBuyerToken -> BuyerInfo mapping(address => address) initialBuyers; // buyer -> SimpleBuyerToken } ContractEntry entry; uint256 constant GG = 10**18; function open() internal { entry.sellerInitialVault = new SimpleSellerToken(); entry.sellerWorkingVault = new SimpleSellerToken(); } function buyToken(address buyer, uint256 currencyAmount) internal { SimpleBuyerToken buyerVault = new SimpleBuyerToken(); uint256 tokenAmount = GG.mul(currencyAmount).div(entry.OptionPricePerGG); BuyerInfo memory bi = BuyerInfo({ lastOwner : buyer, currencyAmount : currencyAmount, tokenAmount : tokenAmount }); entry.buyInfos[address(buyerVault)] = bi; entry.market.transferFromFT(buyer, buyerVault, entry.currency, bi.currencyAmount); // refundable entry.sellerInitialVault.agentRecoverFT(entry.sellerWorkingVault, entry.targetToken, bi.tokenAmount); } function refund(address buyerVault) internal { SimpleBuyerToken bv = SimpleBuyerToken(buyerVault); address buyer = bv.owner(); BuyerInfo storage bi = entry.buyInfos[buyerVault]; bv.agentRecoverFT(buyer, entry.currency, bi.currencyAmount); entry.sellerWorkingVault.agentRecoverFT(entry.sellerFinalVault, entry.targetToken, bi.tokenAmount); } function finalize(address buyerVault) internal { SimpleBuyerToken bv = SimpleBuyerToken(buyerVault); address buyer = bv.owner(); BuyerInfo storage bi = entry.buyInfos[buyerVault]; bv.agentRecoverFT(entry.sellerFinalVault, entry.currency, bi.currencyAmount); entry.sellerWorkingVault.agentRecoverFT(buyer, entry.targetToken, bi.tokenAmount); } function close() internal pure { } } contract MarginBroke { 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; // Debenture debt bond struct BuyerInfo { address lastOwner; uint256 currencyAmount; uint256 tokenAmount; } struct ContractEntry { address id; uint256 productId; address seller; SimpleSellerToken sellerInitialVault; SimpleSellerToken sellerWorkingVault; SimpleSellerToken sellerFinalVault; ShoppingMarket market; SaleCurrency currency; SimpleBond bondToken; address targetToken; uint256 TokenPricePerGG; uint256 OptionPricePerGG; uint256 sellerAccount; uint256 buyerPrimary; mapping(address => BuyerInfo) buyInfos; // SimpleBuyerToken -> BuyerInfo mapping(address => address) initialBuyers; // buyer -> SimpleBuyerToken } ContractEntry entry; uint256 constant GG = 10**18; function open() internal { entry.sellerWorkingVault = new SimpleSellerToken(); } function borrow(address buyer, uint256 currencyAmount) internal { DebtBuyerToken buyerVault = new DebtBuyerToken(); uint256 tokenAmount = GG.mul(currencyAmount).div(entry.OptionPricePerGG); BuyerInfo memory bi = BuyerInfo({ lastOwner : buyer, currencyAmount : currencyAmount, tokenAmount : tokenAmount }); entry.buyInfos[address(buyerVault)] = bi; buyerVault.agentAcceptDebt(entry.sellerInitialVault, entry.currency, bi.currencyAmount); entry.sellerInitialVault.agentRecoverFT(buyerVault, entry.currency, currencyAmount); } function close() internal pure { } } contract SimpleIcoOption { 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; // Debenture debt bond struct ContractEntry { address id; uint256 productId; address seller; SimpleSellerToken sellerInitialVault; SimpleSellerToken sellerWorkingVault; SimpleSellerToken sellerFinalVault; ShoppingMarket market; SaleCurrency currency; SimpleOption optionToken; address targetToken; uint256 TokenPricePerGG; uint256 OptionPricePerGG; uint256 sellerAccount; uint256 buyerPrimary; } ContractEntry entry; uint256 constant GG = 10**18; function open() internal { entry.sellerWorkingVault = new SimpleSellerToken(); } function buyOption(address buyer, uint256 currencyAmount) internal { entry.market.transferFromFT(buyer, entry.sellerWorkingVault, entry.currency, currencyAmount); // refundable entry.sellerWorkingVault.agentRecoverFT(buyer, entry.optionToken, currencyAmount); } function executeOption(address buyer) internal { uint256 currencyAmount = entry.optionToken.balanceOf(buyer); uint256 tokenAmount = GG.mul(currencyAmount).div(entry.OptionPricePerGG); uint256 currencyAmount2 = tokenAmount.mul(entry.TokenPricePerGG).div(GG); entry.market.transferFromFT(buyer, entry.sellerFinalVault, entry.currency, currencyAmount2); entry.sellerWorkingVault.agentRecoverFT(buyer, entry.targetToken, tokenAmount); entry.sellerWorkingVault.agentRecoverFT(entry.sellerFinalVault, entry.currency, currencyAmount); entry.market.transferFromFT(buyer, entry.sellerFinalVault, entry.optionToken, currencyAmount); } function close() internal pure { } } contract SimpleIcoSale { 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; // Debenture debt bond struct BuyerInfo { // address buyer; SimpleBuyerToken buyerVault; uint256 currencyAmount; uint256 tokenAmount; } struct ContractEntry { address id; uint256 productId; address seller; SimpleSellerToken sellerInitialVault; SimpleSellerToken sellerWorkingVault; SimpleSellerToken sellerFinalVault; ShoppingMarket market; SaleCurrency currency; address targetToken; uint256 TokenPricePerGG; uint256 OptionPricePerGG; uint256 sellerAccount; uint256 buyerPrimary; list_address.t buyers; mapping(address => BuyerInfo) buyInfos; } ContractEntry entry; uint256 constant GG = 10**18; function open() internal { entry.sellerWorkingVault = new SimpleSellerToken(); } function buyToken(address buyer, uint256 currencyAmount) internal { // SimpleBuyerToken buyerVault = new SimpleBuyerToken(); uint256 tokenAmount = GG.mul(currencyAmount).div(entry.OptionPricePerGG); //TODO entry.market.transferFromFT(buyer, entry.sellerFinalVault, entry.currency, currencyAmount); entry.sellerWorkingVault.agentRecoverFT(buyer, entry.targetToken, tokenAmount); } function close() internal pure { } } contract SimpleLoan { 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; // Debenture debt bond struct BuyerInfo { // address buyer; SimpleBuyerToken buyerVault; uint256 currencyAmount; uint256 tokenAmount; } struct ContractEntry { address id; uint256 productId; address seller; SimpleSellerToken sellerInitialVault; SimpleSellerToken sellerWorkingVault; SimpleSellerToken sellerFinalVault; ShoppingMarket market; SaleCurrency currency; address targetToken; uint256 TokenPricePerGG; uint256 OptionPricePerGG; uint256 sellerAccount; uint256 buyerPrimary; list_address.t buyers; mapping(address => BuyerInfo) buyInfos; } ContractEntry entry; uint256 constant GG = 10**18; function open() internal { entry.sellerWorkingVault = new SimpleSellerToken(); } function buyToken(address buyer, uint256 currencyAmount) internal { // SimpleBuyerToken buyerVault = new SimpleBuyerToken(); uint256 tokenAmount = GG.mul(currencyAmount).div(entry.OptionPricePerGG); //TODO entry.market.transferFromFT(buyer, entry.sellerFinalVault, entry.currency, currencyAmount); entry.sellerWorkingVault.agentRecoverFT(buyer, entry.targetToken, tokenAmount); } function close() internal pure { } } contract SimpleSaleOne { using SafeMath for uint256; struct ContractEntry { // todo comment address id; uint256 productId; address initialxSeller; // the token owners can change address initialxBuyer; address seller; SimpleSellerToken sellerWorkingVault; address buyer; SimpleBuyerToken buyerVault; ShoppingMarket market; SaleCurrency currency; string title; string url; string description; uint256 sellerDiscount; uint256 sellerGuarantee; // penality bool sellerGuaranteeToBuyer; uint256 buyerPrimary; uint256 buyerGuarantee; // penality bool buyerGuaranteeToSeller; uint256 createTime; uint256 closeDeadlineTime; // open, OKClosed, cancel, CancelClosed // cancel action, 2x2 } ContractEntry entry; function buy() internal { // entry.buyer = msg.sender; entry.sellerWorkingVault = new SimpleSellerToken(); entry.buyerVault = new SimpleBuyerToken(); entry.market.transferFromFT(entry.seller, entry.sellerWorkingVault, entry.currency, entry.sellerDiscount + entry.sellerGuarantee); entry.market.transferFromFT(entry.buyer, entry.buyerVault, entry.currency, entry.buyerPrimary + entry.buyerGuarantee); } function okClose() internal { entry.sellerWorkingVault.agentRecoverFT(entry.seller, entry.currency, entry.sellerDiscount + entry.sellerGuarantee); entry.buyerVault.agentRecoverFT(entry.seller, entry.currency, entry.buyerPrimary + entry.buyerGuarantee); } function cancelByBuyer(bool requestGuarantee) internal { entry.sellerGuaranteeToBuyer = requestGuarantee; } function cancelBySeller(bool requestGuarantee) internal { entry.buyerGuaranteeToSeller = requestGuarantee; } function cancelClose() internal { entry.sellerWorkingVault.agentRecoverFT(entry.seller, entry.currency, entry.sellerDiscount); entry.sellerWorkingVault.agentRecoverFT( entry.sellerGuaranteeToBuyer ? entry.buyer : entry.seller, entry.currency, entry.sellerGuarantee); entry.buyerVault.agentRecoverFT(entry.buyer, entry.currency, entry.buyerPrimary); entry.buyerVault.agentRecoverFT( entry.buyerGuaranteeToSeller ? entry.seller : entry.buyer, entry.currency, entry.buyerGuarantee); } } contract DiscountStore is SimpleRecoverable { using SafeMath for uint256; } contract DiscountToken is SimpleRecoverable { using SafeMath for uint256; } contract SellerToken is SimpleRecoverable { using SafeMath for uint256; } contract BuyerServiceToken is SimpleRecoverable { using SafeMath for uint256; } library DiscountSchema { 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; struct Person { address user; string aliasName; string url; string contact; string description; uint256 createTime; uint256 upVote; uint256 downVote; } struct Product { uint256 id; address user; string title; string url; string description; uint256 sellerDiscount; uint256 sellerGuarantee; uint256 buyerPrimary; uint256 buyerGuarantee; uint256 createTime; uint256 daysBeforeClose; uint256 upVote; uint256 downVote; } struct OrderEntry { uint256 id; uint256 productId; address seller; // the token owners can change address buyer; string title; string url; string description; uint256 sellerWorkingVault; uint256 buyerVault; uint256 sellerDiscount; uint256 sellerGuarantee; uint256 buyerPrimary; uint256 buyerGuarantee; uint256 createTime; uint256 closeDeadlineTime; // open, OKClosed, cancel, CancelClosed // cancel action, 2x2 } struct OrderMessage { uint256 id; address seller; uint256 productId; uint256 orderId; address from; string description; } struct PersonInfo { mapping(address => Person) persons; list_address users; } struct ProductInfo { mapping(uint256 => Product) products; one_many_address_uint256.t userDic; // user <-> productId } struct OrderInfo { mapping(uint256 => OrderEntry) orders; one_many_address_uint256.t sellerDic; one_many_address_uint256.t buyerDic; // user <-> orderId } struct MessageInfo { mapping(uint256 => OrderMessage) messages; // messageId key one_many_address_uint256.t fromDic; one_many_address_uint256.t sellerMessageDic; one_many_address_uint256.t productDic; one_many_address_uint256.t orderDic; } struct OrderDb { PersonInfo persons; ProductInfo products; OrderInfo orders; MessageInfo messsages; } } // library TokenAddressLib // { // /* // asset has owner, owner can has asset // owner -> asset // no tokenId: // (POA, GCA, BCA) -> ... // FT <- ... // tokenId: // () -> ... // (FT/amount) <- ... // (NFT) <- ... // (FT/amount) <- ... -> ... // (NFT) <- ... -> ... // */ // enum AddressNodeType { // noTokenId_x_isOwner_x, // hasTokenId_x_isOwner_x, // noTokenId_POA_isOwner_notAsset, // noTokenId_GCA_isOwner_notAsset, // noTokenId_BCA_isOwner_notAsset, // noTokenId_FT_notOwner_isAsset, // hasTokenId_Owner_isOwner_notAsset, // hasTokenId_FT_notOwner_isAsset, // hasTokenId_FT_isOwner_isAsset, // hasTokenId_NFT_notOwner_isAsset, // hasTokenId_NFT_isOwner_isAsset // } // struct AddressNode { // uint256 id; // address addr; // uint256 tokenId; // AddressNodeType nodeType; // } // struct Owner { // AddressNode node; // } // struct Asset { // AddressNode node; // } // } // library DerivativeTokenLib // { // struct DerivativeDb { // uint256 nextId; // address myAddress; // // balances[asset] = owner // mapping(uint256 => uint256) ownership; // for NFT // mapping(uint256 => uint256) tokenApprovals; // // subTotal[asset] = subTotalSupply // mapping(uint256 => uint256) subTotal; // // balances[asset][owner] = amount // mapping(uint256 => mapping(uint256 => uint256)) balances; // for FT asset // mapping(address => uint256) anodes; // // inodes[tokenId] = nodeId // // mapping(uint256 => uint256) inodes; // mapping(address => mapping(uint256 => uint256)) nodes; // // balances[asset][owner][spender] = amount // mapping(uint256 => mapping(uint256 => mapping(uint256 => uint256))) allowed; // } // function approve( // DerivativeDb storage db, // TokenAddressLib.Owner sender, // TokenAddressLib.Owner _to, // TokenAddressLib.Asset assetNFT) // internal returns(bool success) // { // MiscOp.requireEx(db.ownership[assetNFT.node.id] == sender.node.id); // db.tokenApprovals[assetNFT.node.id] = _to.node.id; // return true; // } // function transferFrom( // DerivativeDb storage db, // TokenAddressLib.Owner _sender, // TokenAddressLib.Owner _from, // TokenAddressLib.Owner _to, // TokenAddressLib.Asset assetNFT // ) // internal returns(bool) // { // // require from approval // MiscOp.requireEx(db.ownership[assetNFT.node.id] == _from.node.id); // db.ownership[assetNFT.node.id] = _to.node.id; // return true; // } // function balanceOf( // DerivativeDb storage db, // TokenAddressLib.Owner owner, // TokenAddressLib.Asset assetFT) // internal view returns(uint256) // { // return db.balances[assetFT.node.id][owner.node.id]; // } // function totalSupply( // DerivativeDb storage db, // TokenAddressLib.Asset assetFT) // internal view returns(uint256) // { // return db.subTotal[assetFT.node.id]; // } // function approve( // DerivativeDb storage db, // TokenAddressLib.Owner sender, // TokenAddressLib.Owner _spender, // TokenAddressLib.Asset assetFT, uint256 _amount) // internal returns(bool success) // { // db.allowed[assetFT.node.id][sender.node.id][_spender.node.id] = _amount; // return true; // } // function transferFrom( // DerivativeDb storage db, // TokenAddressLib.Owner _sender, // TokenAddressLib.Owner _from, // TokenAddressLib.Owner _to, // TokenAddressLib.Asset assetFT, // uint256 amount // ) // internal returns(bool) // { // // require from approval // db.balances[assetFT.node.id][_to.node.id] += amount; // db.balances[assetFT.node.id][_from.node.id] -= amount; // return true; // } // function allowance( // DerivativeDb storage db, // TokenAddressLib.Owner sender, TokenAddressLib.Owner _spender, // TokenAddressLib.Asset assetFT) // internal view returns (uint256) // { // return db.allowed[assetFT.node.id][sender.node.id][_spender.node.id]; // } // function nextId( // DerivativeDb storage db) // internal returns(uint256) // { // return db.nextId++; // } // function lookupAddressNode( // DerivativeDb storage db, // address owner) // internal view returns(TokenAddressLib.AddressNode) // { // return TokenAddressLib.AddressNode({ // id: db.anodes[owner], // addr: owner, // tokenId: 0, // nodeType: TokenAddressLib.AddressNodeType.noTokenId_x_isOwner_x // }); // } // function ensureAddressNode( // DerivativeDb storage db, // address owner) // internal returns(TokenAddressLib.AddressNode) // { // if (db.anodes[owner] == 0x0) { // db.anodes[owner] = nextId(db); // } // return TokenAddressLib.AddressNode({ // id: db.anodes[owner], // addr: owner, // tokenId: 0, // nodeType: TokenAddressLib.AddressNodeType.noTokenId_x_isOwner_x // }); // } // function lookupAddressNode( // DerivativeDb storage db, // address owner, uint256 tokenId) // internal view returns(TokenAddressLib.AddressNode) // { // return TokenAddressLib.AddressNode({ // id: db.anodes[owner], // addr: owner, // tokenId: tokenId, // nodeType: TokenAddressLib.AddressNodeType.noTokenId_x_isOwner_x // }); // } // function ensureAddressNode( // DerivativeDb storage db, // address owner, uint256 tokenId) // internal returns(TokenAddressLib.AddressNode) // { // if (db.nodes[owner][tokenId] == 0x0) { // db.nodes[owner][tokenId] = nextId(db); // } // return TokenAddressLib.AddressNode({ // id: db.anodes[owner], // addr: owner, // tokenId: tokenId, // nodeType: TokenAddressLib.AddressNodeType.hasTokenId_x_isOwner_x // }); // } // } // contract DerivativeToken // { // using DerivativeTokenLib for DerivativeTokenLib.DerivativeDb; // DerivativeTokenLib.DerivativeDb db; // function transferFrom(address from, address to, uint256 tokenId) public returns(bool) { // TokenAddressLib.AddressNode memory senderAddressNode = db.ensureAddressNode(msg.sender); // TokenAddressLib.Owner memory senderUser = TokenAddressLib.Owner({node : senderAddressNode}); // TokenAddressLib.AddressNode memory fromAddressNode = db.ensureAddressNode(from); // TokenAddressLib.Owner memory fromUser = TokenAddressLib.Owner({node : fromAddressNode}); // TokenAddressLib.AddressNode memory toAddressNode = db.ensureAddressNode(to); // TokenAddressLib.Owner memory toUser = TokenAddressLib.Owner({node : toAddressNode}); // TokenAddressLib.AddressNode memory assetAddressNode = db.ensureAddressNode(address(this), tokenId); // TokenAddressLib.Asset memory asset = TokenAddressLib.Asset({node : assetAddressNode}); // return db.transferFrom(senderUser, fromUser, toUser, asset); // } // function approve(address spender, uint256 tokenId) public returns(bool) { // TokenAddressLib.AddressNode memory fromAddressNode = db.ensureAddressNode(msg.sender); // TokenAddressLib.Owner memory fromUser = TokenAddressLib.Owner({node : fromAddressNode}); // TokenAddressLib.AddressNode memory spenderAddressNode = db.ensureAddressNode(spender); // TokenAddressLib.Owner memory spenderUser = TokenAddressLib.Owner({node : spenderAddressNode}); // TokenAddressLib.AddressNode memory assetAddressNode = db.ensureAddressNode(address(this), tokenId); // TokenAddressLib.Asset memory asset = TokenAddressLib.Asset({node : assetAddressNode}); // return db.approve(fromUser, spenderUser, asset); // } // /** // */ // function totalSupply(uint256 tokenId) public view returns (uint256) { // TokenAddressLib.AddressNode memory assetAddressNode = db.lookupAddressNode(address(this), tokenId); // TokenAddressLib.Asset memory asset = TokenAddressLib.Asset({node : assetAddressNode}); // return db.totalSupply(asset); // } // function balanceOf(address who, uint256 tokenId) public view returns (uint256) { // TokenAddressLib.AddressNode memory node = db.lookupAddressNode(who); // TokenAddressLib.Owner memory user = TokenAddressLib.Owner({node : node}); // TokenAddressLib.AddressNode memory assetAddressNode = db.lookupAddressNode(address(this), tokenId); // TokenAddressLib.Asset memory asset = TokenAddressLib.Asset({node : assetAddressNode}); // return db.balanceOf(user, asset); // } // function transfer(address to, uint256 tokenId, uint256 value) public returns(bool) { // return transferFrom(msg.sender, to, tokenId, value); // } // event Transfer(address indexed from, address indexed to, uint256 value); // function allowance(address from, address spender, uint256 tokenId) public view returns (uint256) { // TokenAddressLib.AddressNode memory fromAddressNode = db.lookupAddressNode(from); // TokenAddressLib.Owner memory fromUser = TokenAddressLib.Owner({node : fromAddressNode}); // TokenAddressLib.AddressNode memory spenderAddressNode = db.lookupAddressNode(spender); // TokenAddressLib.Owner memory spenderUser = TokenAddressLib.Owner({node : spenderAddressNode}); // TokenAddressLib.AddressNode memory assetAddressNode = db.lookupAddressNode(address(this), tokenId); // TokenAddressLib.Asset memory asset = TokenAddressLib.Asset({node : assetAddressNode}); // return db.allowance(fromUser, spenderUser, asset); // } // function transferFrom(address from, address to, uint256 tokenId, uint256 value) public returns(bool) { // TokenAddressLib.AddressNode memory senderAddressNode = db.ensureAddressNode(msg.sender); // TokenAddressLib.Owner memory senderUser = TokenAddressLib.Owner({node : senderAddressNode}); // TokenAddressLib.AddressNode memory fromAddressNode = db.ensureAddressNode(from); // TokenAddressLib.Owner memory fromUser = TokenAddressLib.Owner({node : fromAddressNode}); // TokenAddressLib.AddressNode memory toAddressNode = db.ensureAddressNode(to); // TokenAddressLib.Owner memory toUser = TokenAddressLib.Owner({node : toAddressNode}); // TokenAddressLib.AddressNode memory assetAddressNode = db.ensureAddressNode(address(this), tokenId); // TokenAddressLib.Asset memory asset = TokenAddressLib.Asset({node : assetAddressNode}); // return db.transferFrom(senderUser, fromUser, toUser, asset, value); // } // function approve(address spender, uint256 tokenId, uint256 value) public returns(bool) { // TokenAddressLib.AddressNode memory fromAddressNode = db.ensureAddressNode(msg.sender); // TokenAddressLib.Owner memory fromUser = TokenAddressLib.Owner({node : fromAddressNode}); // TokenAddressLib.AddressNode memory spenderAddressNode = db.ensureAddressNode(spender); // TokenAddressLib.Owner memory spenderUser = TokenAddressLib.Owner({node : spenderAddressNode}); // TokenAddressLib.AddressNode memory assetAddressNode = db.ensureAddressNode(address(this), tokenId); // TokenAddressLib.Asset memory asset = TokenAddressLib.Asset({node : assetAddressNode}); // return db.approve(fromUser, spenderUser, asset, value); // } // event Approval(address indexed owner, address indexed spender, uint256 value); // } // library PrimaryTokenLib // { // struct PrimaryDb { // uint256 nextId; // address myAddress; // uint256 total; // // balances[owner] = amount // mapping(uint256 => uint256) balances; // for FT asset // mapping(address => uint256) anodes; // mapping(address => mapping(uint256 => uint256)) nodes; // // balances[owner][spender] = amount // mapping(uint256 => mapping(uint256 => uint256)) allowed; // } // function balanceOf( // PrimaryDb storage db, // TokenAddressLib.Owner owner) // internal view returns(uint256) // { // return db.balances[owner.node.id]; // } // function totalSupply( // PrimaryDb storage db) // internal view returns(uint256) // { // return db.total; // } // function transferFrom( // PrimaryDb storage db, // TokenAddressLib.Owner _sender, // TokenAddressLib.Owner _from, // TokenAddressLib.Owner _to, // uint256 amount // ) // internal returns(bool) // { // // require from approval // db.balances[_to.node.id] += amount; // db.balances[_from.node.id] -= amount; // return true; // } // function approve( // PrimaryDb storage db, // TokenAddressLib.Owner sender, TokenAddressLib.Owner _spender, uint256 _amount) // internal returns(bool success) // { // db.allowed[sender.node.id][_spender.node.id] = _amount; // return true; // } // function allowance( // PrimaryDb storage db, // TokenAddressLib.Owner sender, TokenAddressLib.Owner _spender) // internal view returns (uint256) // { // return db.allowed[sender.node.id][_spender.node.id]; // } // function nextId( // PrimaryDb storage db) // internal returns(uint256) // { // return db.nextId++; // } // function lookupAddressNode( // PrimaryDb storage db, // address owner) // internal view returns(TokenAddressLib.AddressNode) // { // return TokenAddressLib.AddressNode({ // id: db.anodes[owner], // addr: owner, // tokenId: 0, // nodeType: TokenAddressLib.AddressNodeType.noTokenId_x_isOwner_x // }); // } // function ensureAddressNode( // PrimaryDb storage db, // address owner) // internal returns(TokenAddressLib.AddressNode) // { // if (db.anodes[owner] == 0x0) { // db.anodes[owner] = nextId(db); // } // return TokenAddressLib.AddressNode({ // id: db.anodes[owner], // addr: owner, // tokenId: 0, // nodeType: TokenAddressLib.AddressNodeType.noTokenId_x_isOwner_x // }); // } // function ensureAddressNode( // PrimaryDb storage db, // address owner, uint256 tokenId) // internal returns(TokenAddressLib.AddressNode) // { // if (db.nodes[owner][tokenId] == 0x0) { // db.nodes[owner][tokenId] = nextId(db); // } // return TokenAddressLib.AddressNode({ // id: db.anodes[owner], // addr: owner, // tokenId: tokenId, // nodeType: TokenAddressLib.AddressNodeType.hasTokenId_x_isOwner_x // }); // } // } // contract PrimaryToken is // ERC20 // { // using PrimaryTokenLib for PrimaryTokenLib.PrimaryDb; // PrimaryTokenLib.PrimaryDb db; // function totalSupply() public view returns (uint256) { // return db.totalSupply(); // } // function balanceOf(address who) public view returns (uint256) { // TokenAddressLib.AddressNode memory node = db.lookupAddressNode(who); // TokenAddressLib.Owner memory user = TokenAddressLib.Owner({node : node}); // return db.balanceOf(user); // } // function transfer(address to, uint256 value) public returns(bool) { // return transferFrom(msg.sender, to, value); // } // event Transfer(address indexed from, address indexed to, uint256 value); // function allowance(address from, address spender) public view returns (uint256) { // TokenAddressLib.AddressNode memory fromAddressNode = db.lookupAddressNode(from); // TokenAddressLib.Owner memory fromUser = TokenAddressLib.Owner({node : fromAddressNode}); // TokenAddressLib.AddressNode memory spenderAddressNode = db.lookupAddressNode(spender); // TokenAddressLib.Owner memory spenderUser = TokenAddressLib.Owner({node : spenderAddressNode}); // return db.allowance(fromUser, spenderUser); // } // function transferFrom(address from, address to, uint256 value) public returns(bool) { // TokenAddressLib.AddressNode memory senderAddressNode = db.ensureAddressNode(msg.sender); // TokenAddressLib.Owner memory senderUser = TokenAddressLib.Owner({node : senderAddressNode}); // TokenAddressLib.AddressNode memory fromAddressNode = db.ensureAddressNode(from); // TokenAddressLib.Owner memory fromUser = TokenAddressLib.Owner({node : fromAddressNode}); // TokenAddressLib.AddressNode memory toAddressNode = db.ensureAddressNode(to); // TokenAddressLib.Owner memory toUser = TokenAddressLib.Owner({node : toAddressNode}); // return db.transferFrom(senderUser, fromUser, toUser, value); // } // function approve(address spender, uint256 value) public returns(bool) { // TokenAddressLib.AddressNode memory fromAddressNode = db.ensureAddressNode(msg.sender); // TokenAddressLib.Owner memory fromUser = TokenAddressLib.Owner({node : fromAddressNode}); // TokenAddressLib.AddressNode memory spenderAddressNode = db.ensureAddressNode(spender); // TokenAddressLib.Owner memory spenderUser = TokenAddressLib.Owner({node : spenderAddressNode}); // return db.approve(fromUser, spenderUser, value); // } // event Approval(address indexed owner, address indexed spender, uint256 value); // } // contract TokenHolder is // SupportsInterfaceWithLookup // { // function tokensToSend( // address operator, // address from, // address to, // uint256 amount, // bytes userData, // bytes operatorData // ) public {MiscOp.revertEx();} // function tokensReceived( // address operator, // address from, // address to, // uint256 amount, // bytes userData, // bytes operatorData // ) public {MiscOp.revertEx();} // function onERC721Received( // address _operator, // address _from, // uint256 _tokenId, // bytes _data // ) // public // returns(bytes4) {MiscOp.revertEx();} // function onERC721ChildrenReceived( // address _operator, // address _from, // uint256 _tokenId, // uint256 amount, // bytes _data // ) // public // returns(bytes4) {MiscOp.revertEx();} // } // contract Derco is // ERC721, ERC721Token // { // struct BuyerFuture { // uint256 id; // derivative id // address derco; // address disco; // } // } // library DiscountStoreOp // { // struct t { // uint256 nextId; // always > 0 // } // } /** Financial derivative coin ordco := discount + guarantee pasco := left + guarantee disco Crowdsale buy/mint disco Exchange exchange disco or pasco Store: deposit disco? create pasco mint spec buy pasco refund pasco? 10% founders 10% business 10% company 10% new employee 60% crowdsale */
Debenture debt bond
{ 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; struct BuyerInfo { address lastOwner; uint256 currencyAmount; uint256 tokenAmount; } struct ContractEntry { address id; uint256 productId; address seller; SimpleSellerToken sellerInitialVault; SimpleSellerToken sellerWorkingVault; SimpleSellerToken sellerFinalVault; ShoppingMarket market; SaleCurrency currency; address targetToken; uint256 TokenPricePerGG; uint256 OptionPricePerGG; uint256 sellerAccount; uint256 buyerPrimary; } ContractEntry entry; uint256 constant GG = 10**18; function open() internal { entry.sellerInitialVault = new SimpleSellerToken(); entry.sellerWorkingVault = new SimpleSellerToken(); } function buyToken(address buyer, uint256 currencyAmount) internal { SimpleBuyerToken buyerVault = new SimpleBuyerToken(); uint256 tokenAmount = GG.mul(currencyAmount).div(entry.OptionPricePerGG); BuyerInfo memory bi = BuyerInfo({ lastOwner : buyer, currencyAmount : currencyAmount, tokenAmount : tokenAmount }); entry.buyInfos[address(buyerVault)] = bi; entry.market.transferFromFT(buyer, buyerVault, entry.sellerInitialVault.agentRecoverFT(entry.sellerWorkingVault, entry.targetToken, bi.tokenAmount); } function buyToken(address buyer, uint256 currencyAmount) internal { SimpleBuyerToken buyerVault = new SimpleBuyerToken(); uint256 tokenAmount = GG.mul(currencyAmount).div(entry.OptionPricePerGG); BuyerInfo memory bi = BuyerInfo({ lastOwner : buyer, currencyAmount : currencyAmount, tokenAmount : tokenAmount }); entry.buyInfos[address(buyerVault)] = bi; entry.market.transferFromFT(buyer, buyerVault, entry.sellerInitialVault.agentRecoverFT(entry.sellerWorkingVault, entry.targetToken, bi.tokenAmount); } function refund(address buyerVault) internal { SimpleBuyerToken bv = SimpleBuyerToken(buyerVault); address buyer = bv.owner(); BuyerInfo storage bi = entry.buyInfos[buyerVault]; bv.agentRecoverFT(buyer, entry.currency, bi.currencyAmount); entry.sellerWorkingVault.agentRecoverFT(entry.sellerFinalVault, entry.targetToken, bi.tokenAmount); } function finalize(address buyerVault) internal { SimpleBuyerToken bv = SimpleBuyerToken(buyerVault); address buyer = bv.owner(); BuyerInfo storage bi = entry.buyInfos[buyerVault]; bv.agentRecoverFT(entry.sellerFinalVault, entry.currency, bi.currencyAmount); entry.sellerWorkingVault.agentRecoverFT(buyer, entry.targetToken, bi.tokenAmount); } function close() internal pure { } }
13,124,458
[ 1, 758, 70, 319, 594, 18202, 88, 8427, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 95, 203, 202, 9940, 14060, 10477, 364, 2254, 5034, 31, 203, 202, 9940, 312, 1098, 67, 2867, 364, 312, 1098, 67, 2867, 18, 88, 31, 203, 202, 9940, 312, 1098, 67, 11890, 5034, 364, 312, 1098, 67, 11890, 5034, 18, 88, 31, 203, 202, 9940, 666, 67, 2867, 364, 666, 67, 2867, 18, 88, 31, 203, 202, 9940, 666, 67, 11890, 5034, 364, 666, 67, 11890, 5034, 18, 88, 31, 203, 203, 203, 202, 1697, 605, 16213, 966, 288, 203, 202, 202, 2867, 1142, 5541, 31, 203, 202, 202, 11890, 5034, 5462, 6275, 31, 203, 202, 202, 11890, 5034, 1147, 6275, 31, 203, 1082, 203, 202, 97, 203, 202, 1697, 13456, 1622, 288, 203, 202, 202, 2867, 612, 31, 203, 202, 202, 11890, 5034, 23820, 31, 203, 203, 202, 202, 2867, 29804, 31, 203, 202, 202, 5784, 22050, 1345, 29804, 4435, 12003, 31, 203, 202, 202, 5784, 22050, 1345, 29804, 14836, 12003, 31, 203, 202, 202, 5784, 22050, 1345, 29804, 7951, 12003, 31, 203, 1082, 203, 203, 202, 202, 7189, 1382, 3882, 278, 13667, 31, 203, 202, 202, 30746, 7623, 5462, 31, 203, 203, 202, 202, 2867, 1018, 1345, 31, 203, 203, 202, 202, 11890, 5034, 3155, 5147, 2173, 19491, 31, 203, 202, 202, 11890, 5034, 2698, 5147, 2173, 19491, 31, 203, 203, 203, 202, 202, 11890, 5034, 29804, 3032, 31, 203, 203, 202, 202, 11890, 5034, 27037, 6793, 31, 203, 203, 202, 203, 203, 202, 97, 203, 202, 8924, 1622, 1241, 31, 203, 203, 202, 11890, 5034, 5381, 611, 43, 273, 1728, 636, 2 ]
//Address: 0x8f8e5e6515c3e6088c327257bdcf2c973b1530ad //Contract name: ValusCrowdsale //Balance: 0 Ether //Verification Date: 10/13/2017 //Transacion Count: 19 // CODE STARTS HERE pragma solidity ^0.4.17; contract owned { address public owner; function owned() { owner = msg.sender; } modifier onlyOwner { if (msg.sender != owner) throw; _; } function transferOwnership(address newOwner) onlyOwner { owner = newOwner; } } contract IValusToken { function mintTokens(address _to, uint256 _amount); function totalSupply() constant returns (uint256 totalSupply); } contract IERC20Token { function totalSupply() constant returns (uint256 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); } contract ValusCrowdsale is owned { uint256 public startBlock; uint256 public endBlock; uint256 public minEthToRaise; uint256 public maxEthToRaise; uint256 public totalEthRaised; address public multisigAddress; IValusToken valusTokenContract; uint256 nextFreeParticipantIndex; mapping (uint => address) participantIndex; mapping (address => uint256) participantContribution; bool crowdsaleHasStarted; bool softCapReached; bool hardCapReached; bool crowdsaleHasSucessfulyEnded; uint256 blocksInADay; bool ownerHasClaimedTokens; uint256 lastEthReturnIndex; mapping (address => bool) hasClaimedEthWhenFail; event CrowdsaleStarted(uint256 _blockNumber); event CrowdsaleSoftCapReached(uint256 _blockNumber); event CrowdsaleHardCapReached(uint256 _blockNumber); event CrowdsaleEndedSuccessfuly(uint256 _blockNumber, uint256 _amountRaised); event Crowdsale(uint256 _blockNumber, uint256 _ammountRaised); event ErrorSendingETH(address _from, uint256 _amount); function ValusCrowdsale(){ blocksInADay = 2950; startBlock = 4363310; endBlock = startBlock + blocksInADay * 29; minEthToRaise = 3030 * 10**18; maxEthToRaise = 30303 * 10**18; multisigAddress = 0x4e8FD5605028E12E1e7b1Fa60d437d310fa97Bb2; } // /* User accessible methods */ // function () payable{ if(msg.value == 0) throw; if (crowdsaleHasSucessfulyEnded || block.number > endBlock) throw; // Throw if the Crowdsale has ended if (!crowdsaleHasStarted){ // Check if this is the first Crowdsale transaction if (block.number >= startBlock){ // Check if the Crowdsale should start crowdsaleHasStarted = true; // Set that the Crowdsale has started CrowdsaleStarted(block.number); // Raise CrowdsaleStarted event } else{ throw; } } if (participantContribution[msg.sender] == 0){ // Check if the sender is a new user participantIndex[nextFreeParticipantIndex] = msg.sender; // Add a new user to the participant index nextFreeParticipantIndex += 1; } if (maxEthToRaise > (totalEthRaised + msg.value)){ // Check if the user sent too much ETH participantContribution[msg.sender] += msg.value; // Add contribution totalEthRaised += msg.value; // Add to total eth Raised valusTokenContract.mintTokens(msg.sender, getValusTokenIssuance(block.number, msg.value)); if (!softCapReached && totalEthRaised >= minEthToRaise){ // Check if the min treshold has been reached one time CrowdsaleSoftCapReached(block.number); // Raise CrowdsalesoftCapReached event softCapReached = true; // Set that the min treshold has been reached } }else{ // If user sent to much eth uint maxContribution = maxEthToRaise - totalEthRaised; // Calculate maximum contribution participantContribution[msg.sender] += maxContribution; // Add maximum contribution to account totalEthRaised += maxContribution; valusTokenContract.mintTokens(msg.sender, getValusTokenIssuance(block.number, maxContribution)); uint toReturn = msg.value - maxContribution; // Calculate how much should be returned crowdsaleHasSucessfulyEnded = true; // Set that Crowdsale has successfully ended CrowdsaleHardCapReached(block.number); hardCapReached = true; CrowdsaleEndedSuccessfuly(block.number, totalEthRaised); if(!msg.sender.send(toReturn)){ // Refund the balance that is over the cap ErrorSendingETH(msg.sender, toReturn); // Raise event for manual return if transaction throws } } } /* Users can claim ETH by themselves if they want to in case of ETH failure */ function claimEthIfFailed(){ if (block.number <= endBlock || totalEthRaised >= minEthToRaise) throw; // Check if Crowdsale has failed if (participantContribution[msg.sender] == 0) throw; // Check if user has participated if (hasClaimedEthWhenFail[msg.sender]) throw; // Check if this account has already claimed ETH uint256 ethContributed = participantContribution[msg.sender]; // Get participant ETH Contribution hasClaimedEthWhenFail[msg.sender] = true; if (!msg.sender.send(ethContributed)){ ErrorSendingETH(msg.sender, ethContributed); // Raise event if send failed, solve manually } } /* Owner can return eth for multiple users in one call */ function batchReturnEthIfFailed(uint256 _numberOfReturns) onlyOwner{ if (block.number < endBlock || totalEthRaised >= minEthToRaise) throw; // Check if Crowdsale failed address currentParticipantAddress; uint256 contribution; for (uint cnt = 0; cnt < _numberOfReturns; cnt++){ currentParticipantAddress = participantIndex[lastEthReturnIndex]; // Get next account if (currentParticipantAddress == 0x0) return; // Check if participants were reimbursed if (!hasClaimedEthWhenFail[currentParticipantAddress]) { // Check if user has manually recovered ETH contribution = participantContribution[currentParticipantAddress]; // Get accounts contribution hasClaimedEthWhenFail[msg.sender] = true; // Set that user got his ETH back if (!currentParticipantAddress.send(contribution)){ // Send fund back to account ErrorSendingETH(currentParticipantAddress, contribution); // Raise event if send failed, resolve manually } } lastEthReturnIndex += 1; } } /* Owner sets new address of escrow */ function changeMultisigAddress(address _newAddress) onlyOwner { multisigAddress = _newAddress; } /* Show how many participants was */ function participantCount() constant returns(uint){ return nextFreeParticipantIndex; } /* Owner can claim reserved tokens on the end of crowsale */ function claimTeamTokens(address _to) onlyOwner{ if (!crowdsaleHasSucessfulyEnded) throw; if (ownerHasClaimedTokens) throw; valusTokenContract.mintTokens(_to, valusTokenContract.totalSupply() * 49/51); /* 51% Crowdsale - 49% VALUS */ ownerHasClaimedTokens = true; } /* Set token contract where mints will be done (tokens will be issued) */ function setTokenContract(address _valusTokenContractAddress) onlyOwner { valusTokenContract = IValusToken(_valusTokenContractAddress); } function getValusTokenIssuance(uint256 _blockNumber, uint256 _ethSent) constant returns(uint){ if (_blockNumber >= startBlock && _blockNumber < startBlock + blocksInADay * 2) return _ethSent * 3882; if (_blockNumber >= startBlock + blocksInADay * 2 && _blockNumber < startBlock + blocksInADay * 7) return _ethSent * 3667; if (_blockNumber >= startBlock + blocksInADay * 7 && _blockNumber < startBlock + blocksInADay * 14) return _ethSent * 3511; if (_blockNumber >= startBlock + blocksInADay * 14 && _blockNumber < startBlock + blocksInADay * 21) return _ethSent * 3402; if (_blockNumber >= startBlock + blocksInADay * 21 ) return _ethSent * 3300; } /* Withdraw funds from contract */ function withdrawEther() onlyOwner{ if (this.balance == 0) throw; // Check if there is balance on the contract if (totalEthRaised < minEthToRaise) throw; // Check if minEthToRaise treshold is exceeded if(multisigAddress.send(this.balance)){} // Send the contract's balance to multisig address } function endCrowdsale() onlyOwner{ if (totalEthRaised < minEthToRaise) throw; if (block.number < endBlock) throw; crowdsaleHasSucessfulyEnded = true; CrowdsaleEndedSuccessfuly(block.number, totalEthRaised); } function salvageTokensFromContract(address _tokenAddress, address _to, uint _amount) onlyOwner{ IERC20Token(_tokenAddress).transfer(_to, _amount); } /* Getters */ function getVlsTokenAddress() constant returns(address _tokenAddress){ return address(valusTokenContract); } function crowdsaleInProgress() constant returns (bool answer){ return crowdsaleHasStarted && !crowdsaleHasSucessfulyEnded; } function participantContributionInEth(address _querryAddress) constant returns (uint256 answer){ return participantContribution[_querryAddress]; } /* Withdraw remaining balance to manually return where contract send has failed */ function withdrawRemainingBalanceForManualRecovery() onlyOwner{ if (this.balance == 0) throw; // Check if there is balance on the contract if (block.number < endBlock) throw; // Check if Crowdsale failed if (participantIndex[lastEthReturnIndex] != 0x0) throw; // Check if all the participants have been reimbursed if (multisigAddress.send(this.balance)){} // Send remainder so it can be manually processed } }
Check if Crowdsale failed
if (block.number < endBlock) throw;
6,431,254
[ 1, 1564, 309, 385, 492, 2377, 5349, 2535, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1377, 309, 261, 2629, 18, 2696, 411, 679, 1768, 13, 604, 31, 4766, 565, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/[email protected]/contracts/ownership/Ownable.sol'; import 'OpenZeppelin/[email protected]/contracts/math/SafeMath.sol'; import './BankConfig.sol'; import './GoblinConfig.sol'; interface InterestModel { /// @dev Return the interest rate per second, using 1e18 as denom. function getInterestRate(uint debt, uint floating) external view returns (uint); } contract TripleSlopeModel { using SafeMath for uint; /// @dev Return the interest rate per second, using 1e18 as denom. function getInterestRate(uint debt, uint floating) external pure returns (uint) { uint total = debt.add(floating); uint utilization = total == 0 ? 0 : debt.mul(100e18).div(total); if (utilization < 80e18) { // Less than 80% utilization - 0%-20% APY return utilization.mul(20e16).div(80e18) / 365 days; } else if (utilization < 90e18) { // Between 80% and 90% - 20% APY return uint(20e16) / 365 days; } else if (utilization < 100e18) { // Between 90% and 100% - 20%-200% APY return (20e16 + utilization.sub(90e18).mul(180e16).div(10e18)) / 365 days; } else { // Not possible, but just in case - 200% APY return uint(200e16) / 365 days; } } } contract ConfigurableInterestBankConfig is BankConfig, Ownable { /// The minimum BNB debt size per position. uint public minDebtSize; /// The portion of interests allocated to the reserve pool. uint public getReservePoolBps; /// The reward for successfully killing a position. uint public getKillBps; /// Mapping for goblin address to its configuration. mapping(address => GoblinConfig) public goblins; /// Interest rate model InterestModel public interestModel; constructor( uint _minDebtSize, uint _reservePoolBps, uint _killBps, InterestModel _interestModel ) public { setParams(_minDebtSize, _reservePoolBps, _killBps, _interestModel); } /// @dev Set all the basic parameters. Must only be called by the owner. /// @param _minDebtSize The new minimum debt size value. /// @param _reservePoolBps The new interests allocated to the reserve pool value. /// @param _killBps The new reward for killing a position value. /// @param _interestModel The new interest rate model contract. function setParams( uint _minDebtSize, uint _reservePoolBps, uint _killBps, InterestModel _interestModel ) public onlyOwner { minDebtSize = _minDebtSize; getReservePoolBps = _reservePoolBps; getKillBps = _killBps; interestModel = _interestModel; } /// @dev Set the configuration for the given goblins. Must only be called by the owner. function setGoblins(address[] calldata addrs, GoblinConfig[] calldata configs) external onlyOwner { require(addrs.length == configs.length, 'bad length'); for (uint idx = 0; idx < addrs.length; idx++) { goblins[addrs[idx]] = configs[idx]; } } /// @dev Return the interest rate per second, using 1e18 as denom. function getInterestRate(uint debt, uint floating) external view returns (uint) { return interestModel.getInterestRate(debt, floating); } /// @dev Return whether the given address is a goblin. function isGoblin(address goblin) external view returns (bool) { return address(goblins[goblin]) != address(0); } /// @dev Return whether the given goblin accepts more debt. Revert on non-goblin. function acceptDebt(address goblin) external view returns (bool) { return goblins[goblin].acceptDebt(goblin); } /// @dev Return the work factor for the goblin + BNB debt, using 1e4 as denom. Revert on non-goblin. function workFactor(address goblin, uint debt) external view returns (uint) { return goblins[goblin].workFactor(goblin, debt); } /// @dev Return the kill factor for the goblin + BNB debt, using 1e4 as denom. Revert on non-goblin. function killFactor(address goblin, uint debt) external view returns (uint) { return goblins[goblin].killFactor(goblin, debt); } }
@dev Set all the basic parameters. Must only be called by the owner. @param _minDebtSize The new minimum debt size value. @param _reservePoolBps The new interests allocated to the reserve pool value. @param _killBps The new reward for killing a position value. @param _interestModel The new interest rate model contract.
function setParams( uint _minDebtSize, uint _reservePoolBps, uint _killBps, InterestModel _interestModel ) public onlyOwner { minDebtSize = _minDebtSize; getReservePoolBps = _reservePoolBps; getKillBps = _killBps; interestModel = _interestModel; }
14,102,882
[ 1, 694, 777, 326, 5337, 1472, 18, 6753, 1338, 506, 2566, 635, 326, 3410, 18, 225, 389, 1154, 758, 23602, 1225, 1021, 394, 5224, 18202, 88, 963, 460, 18, 225, 389, 455, 6527, 2864, 38, 1121, 1021, 394, 16513, 87, 11977, 358, 326, 20501, 2845, 460, 18, 225, 389, 16418, 38, 1121, 1021, 394, 19890, 364, 417, 5789, 279, 1754, 460, 18, 225, 389, 2761, 395, 1488, 1021, 394, 16513, 4993, 938, 6835, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 225, 445, 31705, 12, 203, 565, 2254, 389, 1154, 758, 23602, 1225, 16, 203, 565, 2254, 389, 455, 6527, 2864, 38, 1121, 16, 203, 565, 2254, 389, 16418, 38, 1121, 16, 203, 565, 5294, 395, 1488, 389, 2761, 395, 1488, 203, 225, 262, 1071, 1338, 5541, 288, 203, 565, 1131, 758, 23602, 1225, 273, 389, 1154, 758, 23602, 1225, 31, 203, 565, 31792, 6527, 2864, 38, 1121, 273, 389, 455, 6527, 2864, 38, 1121, 31, 203, 565, 16566, 737, 38, 1121, 273, 389, 16418, 38, 1121, 31, 203, 565, 16513, 1488, 273, 389, 2761, 395, 1488, 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 ]
/** *Submitted for verification at Etherscan.io on 2022-03-02 */ // Sources flattened with hardhat v2.7.0 https://hardhat.org // File sol-temple/src/tokens/[email protected] pragma solidity >=0.8.0 <0.9.0; /* /* KEVIINNNNNNN /** * @title ERC721 * @notice A complete ERC721 implementation including metadata and enumerable * functions. Completely gas optimized and extensible. */ abstract contract ERC721 { /// @notice See {ERC721-Transfer}. event Transfer(address indexed _from, address indexed _to, uint256 indexed _tokenId); /// @notice See {ERC721-Approval}. event Approval(address indexed _owner, address indexed _approved, uint256 indexed _tokenId); /// @notice See {ERC721-ApprovalForAll}. event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved); /// @notice See {ERC721Metadata-name}. string public name; /// @notice See {ERC721Metadata-symbol}. string public symbol; /// @notice See {ERC721Enumerable-totalSupply}. uint256 public totalSupply; /// @notice Array of all owners. address[] private _owners; /// @notice Mapping of all balances. mapping(address => uint256) private _balanceOf; /// @notice Mapping from token Id to it's approved address. mapping(uint256 => address) private _tokenApprovals; /// @notice Mapping of approvals between owner and operator. mapping(address => mapping(address => bool)) private _isApprovedForAll; constructor(string memory name_, string memory symbol_) { name = name_; symbol = symbol_; } /// @notice See {ERC721-balanceOf}. function balanceOf(address account_) public view virtual returns (uint256) { require(account_ != address(0), "ERC721: balance query for the zero address"); return _balanceOf[account_]; } /// @notice See {ERC721-ownerOf}. function ownerOf(uint256 tokenId_) public view virtual returns (address) { require(_exists(tokenId_), "ERC721: query for nonexistent token"); address owner = _owners[tokenId_]; return owner; } /// @notice See {ERC721Metadata-tokenURI}. function tokenURI(uint256) public view virtual returns (string memory); /// @notice See {ERC721-approve}. function approve(address to_, uint256 tokenId_) public virtual { address owner = ownerOf(tokenId_); require(to_ != owner, "ERC721: approval to current owner"); require( msg.sender == owner || _isApprovedForAll[owner][msg.sender], "ERC721: caller is not owner nor approved for all" ); _approve(to_, tokenId_); } /// @notice See {ERC721-getApproved}. function getApproved(uint256 tokenId_) public view virtual returns (address) { require(_exists(tokenId_), "ERC721: query for nonexistent token"); return _tokenApprovals[tokenId_]; } /// @notice See {ERC721-setApprovalForAll}. function setApprovalForAll(address operator_, bool approved_) public virtual { _setApprovalForAll(msg.sender, operator_, approved_); } /// @notice See {ERC721-isApprovedForAll}. function isApprovedForAll(address account_, address operator_) public view virtual returns (bool) { return _isApprovedForAll[account_][operator_]; } /// @notice See {ERC721-transferFrom}. function transferFrom( address from_, address to_, uint256 tokenId_ ) public virtual { require(_isApprovedOrOwner(msg.sender, tokenId_), "ERC721: transfer caller is not owner nor approved"); _transfer(from_, to_, tokenId_); } /// @notice See {ERC721-safeTransferFrom}. function safeTransferFrom( address from_, address to_, uint256 tokenId_ ) public virtual { safeTransferFrom(from_, to_, tokenId_, ""); } /// @notice See {ERC721-safeTransferFrom}. function safeTransferFrom( address from_, address to_, uint256 tokenId_, bytes memory data_ ) public virtual { require(_isApprovedOrOwner(msg.sender, tokenId_), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from_, to_, tokenId_, data_); } /// @notice See {ERC721Enumerable.tokenOfOwnerByIndex}. function tokenOfOwnerByIndex(address account_, uint256 index_) public view returns (uint256 tokenId) { require(index_ < balanceOf(account_), "ERC721Enumerable: Index out of bounds"); uint256 count; for (uint256 i; i < _owners.length; ++i) { if (account_ == _owners[i]) { if (count == index_) return i; else count++; } } revert("ERC721Enumerable: Index out of bounds"); } /// @notice See {ERC721Enumerable.tokenByIndex}. function tokenByIndex(uint256 index_) public view virtual returns (uint256) { require(index_ < _owners.length, "ERC721Enumerable: Index out of bounds"); return index_; } /// @notice Returns a list of all token Ids owned by `owner`. function walletOfOwner(address account_) public view returns (uint256[] memory) { uint256 balance = balanceOf(account_); uint256[] memory ids = new uint256[](balance); for (uint256 i = 0; i < balance; i++) { ids[i] = tokenOfOwnerByIndex(account_, i); } return ids; } /** * @notice Safely transfers `tokenId_` token from `from_` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. */ function _safeTransfer( address from_, address to_, uint256 tokenId_, bytes memory data_ ) internal virtual { _transfer(from_, to_, tokenId_); _checkOnERC721Received(from_, to_, tokenId_, data_); } /// @notice Returns whether `tokenId_` exists. function _exists(uint256 tokenId_) internal view virtual returns (bool) { return tokenId_ < _owners.length && _owners[tokenId_] != address(0); } /// @notice Returns whether `spender_` is allowed to manage `tokenId`. function _isApprovedOrOwner(address spender_, uint256 tokenId_) internal view virtual returns (bool) { require(_exists(tokenId_), "ERC721: query for nonexistent token"); address owner = _owners[tokenId_]; return (spender_ == owner || getApproved(tokenId_) == spender_ || isApprovedForAll(owner, spender_)); } /// @notice Safely mints `tokenId_` and transfers it to `to`. function _safeMint(address to_, uint256 tokenId_) internal virtual { _safeMint(to_, tokenId_, ""); } /** * @notice Same as {_safeMint}, but with an additional `data_` parameter which is * forwarded in {ERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to_, uint256 tokenId_, bytes memory data_ ) internal virtual { _mint(to_, tokenId_); _checkOnERC721Received(address(0), to_, tokenId_, data_); } /// @notice Mints `tokenId_` and transfers it to `to_`. function _mint(address to_, uint256 tokenId_) internal virtual { require(!_exists(tokenId_), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to_, tokenId_); _owners.push(to_); totalSupply++; unchecked { _balanceOf[to_]++; } emit Transfer(address(0), to_, tokenId_); _afterTokenTransfer(address(0), to_, tokenId_); } /// @notice Destroys `tokenId`. The approval is cleared when the token is burned. function _burn(uint256 tokenId_) internal virtual { address owner = ownerOf(tokenId_); _beforeTokenTransfer(owner, address(0), tokenId_); // Clear approvals _approve(address(0), tokenId_); delete _owners[tokenId_]; totalSupply--; _balanceOf[owner]--; emit Transfer(owner, address(0), tokenId_); _afterTokenTransfer(owner, address(0), tokenId_); } /// @notice Transfers `tokenId_` from `from_` to `to`. function _transfer( address from_, address to_, uint256 tokenId_ ) internal virtual { require(_owners[tokenId_] == from_, "ERC721: transfer of token that is not own"); _beforeTokenTransfer(from_, to_, tokenId_); // Clear approvals from the previous owner _approve(address(0), tokenId_); _owners[tokenId_] = to_; unchecked { _balanceOf[from_]--; _balanceOf[to_]++; } emit Transfer(from_, to_, tokenId_); _afterTokenTransfer(from_, to_, tokenId_); } /// @notice Approve `to_` to operate on `tokenId_` function _approve(address to_, uint256 tokenId_) internal virtual { _tokenApprovals[tokenId_] = to_; emit Approval(_owners[tokenId_], to_, tokenId_); } /// @notice Approve `operator_` to operate on all of `account_` tokens. function _setApprovalForAll( address account_, address operator_, bool approved_ ) internal virtual { require(account_ != operator_, "ERC721: approve to caller"); _isApprovedForAll[account_][operator_] = approved_; emit ApprovalForAll(account_, operator_, approved_); } /// @notice ERC721Receiver callback checking and calling helper. function _checkOnERC721Received( address from_, address to_, uint256 tokenId_, bytes memory data_ ) private { if (to_.code.length > 0) { try IERC721Receiver(to_).onERC721Received(msg.sender, from_, tokenId_, data_) returns (bytes4 returned) { require(returned == 0x150b7a02, "ERC721: safe transfer to non ERC721Receiver implementation"); } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: safe transfer to non ERC721Receiver implementation"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } } /// @notice Hook that is called before any token transfer. function _beforeTokenTransfer( address from_, address to_, uint256 tokenId_ ) internal virtual {} /// @notice Hook that is called after any token transfer. function _afterTokenTransfer( address from_, address to_, uint256 tokenId_ ) internal virtual {} /// @notice See {IERC165-supportsInterface}. function supportsInterface(bytes4 interfaceId_) public view virtual returns (bool) { return interfaceId_ == 0x80ac58cd || // ERC721 interfaceId_ == 0x5b5e139f || // ERC721Metadata interfaceId_ == 0x780e9d63 || // ERC721Enumerable interfaceId_ == 0x01ffc9a7; // ERC165 } } interface IERC721Receiver { function onERC721Received( address operator, address from, uint256 tokenId, bytes memory data ) external returns (bytes4); } // File sol-temple/src/utils/[email protected] pragma solidity >=0.8.0 <0.9.0; /** * @title Auth * @notice Just a simple authing system. */ abstract contract Auth { /// @notice Emitted when the ownership is transfered. event OwnershipTransfered(address indexed from, address indexed to); /// @notice Contract's owner address. address public owner; /// @notice A simple modifier just to check whether the sender is the owner. modifier onlyOwner() { require(msg.sender == owner, "Auth: sender is not the owner"); _; } constructor() { _transferOwnership(msg.sender); } /// @notice Set the owner address to `owner_`. function transferOwnership(address owner_) public onlyOwner { require(owner != owner_, "Auth: transfering ownership to current owner"); _transferOwnership(owner_); } /// @notice Set the owner address to `owner_`. Does not require anything function _transferOwnership(address owner_) internal { address oldOwner = owner; owner = owner_; emit OwnershipTransfered(oldOwner, owner_); } } // 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/token/ERC20/[email protected] // OpenZeppelin Contracts v4.4.1 (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); } // 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/token/ERC721/[email protected] // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface 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/ERC1155/[email protected] // 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 contracts/KevinZuki.sol // SPDX-License-Identifier: MIT pragma solidity 0.8.11; contract KevinZuki is Auth, ERC721 { using Strings for uint256; /// @notice Max supply. uint256 public constant SUPPLY_MAX = 1100; /// @notice Max amount per claim. uint256 public constant SUPPLY_PER_TX = 5; /// @notice 0 = CLOSED, 1 = PUBLIC, 2 = WHITELIST. uint256 public saleState; /// @notice OpenSea proxy registry. address public opensea = 0xa5409ec958C83C3f309868babACA7c86DCB077c1; /// @notice LooksRare marketplace transfer manager. address public looksrare = 0xf42aa99F011A1fA7CDA90E5E98b277E306BcA83e; /// @notice Check if marketplaces pre-approve is enabled. bool public marketplacesApproved = true; /// @notice Unrevelead URI. string public unrevealedURI; /// @notice Metadata base URI. string public baseURI; /// @notice Metadata base file extension. string public baseExtension; constructor(string memory newUnrevealedURI) ERC721("KevinZuki", "KevZuki") { unrevealedURI = newUnrevealedURI; } /// @notice Claim one or more tokens. function mint(uint256 amount) external payable { uint256 supply = totalSupply; require(supply + amount <= SUPPLY_MAX, "Max supply exceeded"); if (msg.sender != owner) { require(saleState == 1, "Public sale is not open"); require(amount > 0 && amount <= SUPPLY_PER_TX, "Invalid claim amount"); if (supply <= 333) require(msg.value == 0, "Invalid ether amount"); else require(msg.value == amount * 0.01 ether, "Invalid ether amount"); } for (uint256 i = 0; i < amount; i++) _safeMint(msg.sender, supply++); } /// @notice See {IERC721-tokenURI}. function tokenURI(uint256 id) public view override returns (string memory) { require(_exists(id), "ERC721Metadata: query for nonexisting token"); if (bytes(unrevealedURI).length > 0) return unrevealedURI; return string(abi.encodePacked(baseURI, id.toString(), baseExtension)); } /// @notice Set baseURI to `newBaseURI`. function setBaseURI(string memory newBaseURI, string memory newBaseExtension) external onlyOwner { baseURI = newBaseURI; baseExtension = newBaseExtension; delete unrevealedURI; } /// @notice Set unrevealedURI to `newUnrevealedURI`. function setUnrevealedURI(string memory newUnrevealedURI) external onlyOwner { unrevealedURI = newUnrevealedURI; } /// @notice Set saleState to `newSaleState`. function setSaleState(uint256 newSaleState) external onlyOwner { saleState = newSaleState; } /// @notice Set opensea to `newOpensea`. function setOpensea(address newOpensea) external onlyOwner { opensea = newOpensea; } /// @notice Set looksrare to `newLooksrare`. function setLooksrare(address newLooksrare) external onlyOwner { looksrare = newLooksrare; } /// @notice Toggle pre-approve feature state for sender. function toggleMarketplacesApproved() external onlyOwner { marketplacesApproved = !marketplacesApproved; } /// @notice Withdraw `value` of ether to the sender. function withdraw(address payable to, uint256 amount) external onlyOwner { to.transfer(amount); } /// @notice Withdraw `value` of `token` to the sender. function withdrawERC20(IERC20 token, uint256 value) external onlyOwner { token.transfer(msg.sender, value); } /// @notice Withdraw `id` of `token` to the sender. function withdrawERC721(IERC721 token, uint256 id) external onlyOwner { token.safeTransferFrom(address(this), msg.sender, id); } /// @notice Withdraw `id` with `value` from `token` to the sender. function withdrawERC1155( IERC1155 token, uint256 id, uint256 value ) external onlyOwner { token.safeTransferFrom(address(this), msg.sender, id, value, ""); } /// @dev Modified for opensea and looksrare pre-approve so users can make truly gasless sales. function isApprovedForAll(address owner, address operator) public view override returns (bool) { if (!marketplacesApproved) return super.isApprovedForAll(owner, operator); return operator == address(ProxyRegistry(opensea).proxies(owner)) || operator == looksrare || super.isApprovedForAll(owner, operator); } } contract OwnableDelegateProxy {} contract ProxyRegistry { mapping(address => OwnableDelegateProxy) public proxies; }
@notice Safely mints `tokenId_` and transfers it to `to`.
function _safeMint(address to_, uint256 tokenId_) internal virtual { _safeMint(to_, tokenId_, ""); }
1,994,573
[ 1, 26946, 2357, 312, 28142, 1375, 2316, 548, 67, 68, 471, 29375, 518, 358, 1375, 869, 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 ]
[ 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, 4626, 49, 474, 12, 2867, 358, 67, 16, 2254, 5034, 1147, 548, 67, 13, 2713, 5024, 288, 203, 565, 389, 4626, 49, 474, 12, 869, 67, 16, 1147, 548, 67, 16, 1408, 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 ]
pragma solidity ^0.5.0; interface ConflictResolutionInterface { function minHouseStake(uint activeGames) external view returns(uint); function maxBalance() external view returns(int); function conflictEndFine() external pure returns(int); function isValidBet(uint8 _gameType, uint _betNum, uint _betValue) external view returns(bool); function endGameConflict( uint8 _gameType, uint _betNum, uint _betValue, int _balance, uint _stake, bytes32 _serverSeed, bytes32 _userSeed ) external view returns(int); function serverForceGameEnd( uint8 gameType, uint _betNum, uint _betValue, int _balance, uint _stake, bytes32 _serverSeed, bytes32 _userSeed, uint _endInitiatedTime ) external view returns(int); function userForceGameEnd( uint8 _gameType, uint _betNum, uint _betValue, int _balance, uint _stake, uint _endInitiatedTime ) external view returns(int); } library MathUtil { /** * @dev Returns the absolute value of _val. * @param _val value * @return The absolute value of _val. */ function abs(int _val) internal pure returns(uint) { if (_val < 0) { return uint(-_val); } else { return uint(_val); } } /** * @dev Calculate maximum. */ function max(uint _val1, uint _val2) internal pure returns(uint) { return _val1 >= _val2 ? _val1 : _val2; } /** * @dev Calculate minimum. */ function min(uint _val1, uint _val2) internal pure returns(uint) { return _val1 <= _val2 ? _val1 : _val2; } } library SafeCast { /** * Cast unsigned a to signed a. */ function castToInt(uint a) internal pure returns(int) { assert(a < (1 << 255)); return int(a); } /** * Cast signed a to unsigned a. */ function castToUint(int a) internal pure returns(uint) { assert(a >= 0); return uint(a); } } library SafeMath { /** * @dev Multiplies two unsigned integers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Multiplies two signed integers, throws on overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } int256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two unsigned integers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Integer division of two signed integers, truncating the quotient. */ function div(int256 a, int256 b) internal pure returns (int256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // Overflow only happens when the smallest negative int is multiplied by -1. int256 INT256_MIN = int256((uint256(1) << 255)); assert(a != INT256_MIN || b != - 1); return a / b; } /** * @dev Subtracts two unsigned integers, 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 Subtracts two signed integers, throws on overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; assert((b >= 0 && c <= a) || (b < 0 && c > a)); return c; } /** * @dev Adds two unsigned integers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } /** * @dev Adds two signed integers, throws on overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; assert((b >= 0 && c >= a) || (b < 0 && c < a)); return c; } } interface GameInterface { function maxBet(uint _num, uint _bankRoll) external view returns(uint); function resultNumber(bytes32 _serverSeed, bytes32 _userSeed, uint _num) external view returns(uint); function userProfit(uint _num, uint _betValue, uint _resultNum) external view returns(int); function maxUserProfit(uint _num, uint _betValue) external view returns(int); } contract Games { using SafeMath for int; using SafeMath for uint; mapping (uint => GameInterface) public games; /** * @dev constructor * @param gameContracts addresses of different game implementations. */ constructor(address[] memory gameContracts) public { for (uint i = 0; i < gameContracts.length; i++) { // set first GameInterface to 0 0 => start with i + 1 games[i + 1] = GameInterface(gameContracts[i]); } } /** * @dev Returns the max allowed bet for a specific game. * @param _gameType game identifier. * @param _num game specific bet number. * @param _bankRoll bank roll size. * @return max allowed bet. */ function maxBet(uint8 _gameType, uint _num, uint _bankRoll) public view returns(uint) { uint maxBetVal = getGameImplementation(_gameType).maxBet(_num, _bankRoll); return maxBetVal.add(5e14).div(1e15).mul(1e15); // round to multiple of 0.001 Ether } /** * @dev Calculates the result of the bet. * @param _gameType game identifier. * @param _serverSeed server seed. * @param _userSeed user seed. * @param _num game specific bet number. * @return result number. */ function resultNumber(uint8 _gameType, bytes32 _serverSeed, bytes32 _userSeed, uint _num) public view returns(uint) { return getGameImplementation(_gameType).resultNumber(_serverSeed, _userSeed, _num); } /** * @dev Calculates the user profit for the bet. * @param _gameType game identifier. * @param _num game specific bet number. * @param _betValue bet value. * @param _resultNum bet result. * @return user profit. */ function userProfit(uint8 _gameType, uint _num, uint _betValue, uint _resultNum) public view returns(int) { uint betValue = _betValue / 1e9; // convert to gwei int res = getGameImplementation(_gameType).userProfit(_num, betValue, _resultNum); return res.mul(1e9); // convert to wei } /** * @dev Calculates the maximal posible user profit for the given bet. * @param _gameType game identifier. * @param _num game specific bet number e.g. 0 or 1 for RollADice. * @param _betValue bet value. * @return max user profit. */ function maxUserProfit(uint8 _gameType, uint _num, uint _betValue) public view returns(int) { uint betValue = _betValue / 1e9; // convert to gwei int res = getGameImplementation(_gameType).maxUserProfit(_num, betValue); return res.mul(1e9); // convert to wei } /** * @dev Returns the game implementation contract for the given game type. * @param _gameType game identifier. * @return game implementation contract. */ function getGameImplementation(uint8 _gameType) private view returns(GameInterface) { require(games[_gameType] != GameInterface(0), "Invalid game type"); return games[_gameType]; } } contract ConflictResolution is ConflictResolutionInterface, Games { using SafeCast for int; using SafeCast for uint; using SafeMath for int; using SafeMath for uint; uint public constant SERVER_TIMEOUT = 6 hours; uint public constant USER_TIMEOUT = 6 hours; uint public constant MIN_BET_VALUE = 1e13; /// min 0.00001 ether bet uint public constant MIN_BANKROLL = 40e18; int public constant NOT_ENDED_FINE = 1e15; /// 0.001 ether int public constant CONFLICT_END_FINE = 1e15; /// 0.001 ether int public constant MAX_BALANCE = int(MIN_BANKROLL / 2); modifier onlyValidBet(uint8 _gameType, uint _betNum, uint _betValue) { require(isValidBet(_gameType, _betNum, _betValue), "inv bet"); _; } modifier onlyValidBalance(int _balance, uint _gameStake) { require(-_gameStake.castToInt() <= _balance && _balance <= MAX_BALANCE, "inv balance"); _; } /** * @dev constructor * @param games the games specific contracts. */ constructor(address[] memory games) Games(games) public { // Nothing to do } /** * @return Conflict end fine. */ function conflictEndFine() public pure returns(int) { return CONFLICT_END_FINE; } /** * @return Max balance. */ function maxBalance() public view returns(int) { return MAX_BALANCE; } /** * Calculate minimum needed house stake. */ function minHouseStake(uint activeGames) public view returns(uint) { return MathUtil.min(activeGames, 1) * MIN_BANKROLL; } /** * @dev Check if bet is valid. * @param _gameType Game type. * @param _betNum Number of bet. * @param _betValue Value of bet. * @return True if bet is valid false otherwise. */ function isValidBet(uint8 _gameType, uint _betNum, uint _betValue) public view returns(bool) { bool validMinBetValue = MIN_BET_VALUE <= _betValue; bool validMaxBetValue = _betValue <= Games.maxBet(_gameType, _betNum, MIN_BANKROLL); return validMinBetValue && validMaxBetValue; } /** * @dev Calculates game result and returns new balance. * @param _gameType Type of game. * @param _betNum Bet number. * @param _betValue Value of bet. * @param _balance Current balance. * @param _serverSeed Server's seed of current round. * @param _userSeed User's seed of current round. * @return New game session balance. */ function endGameConflict( uint8 _gameType, uint _betNum, uint _betValue, int _balance, uint _stake, bytes32 _serverSeed, bytes32 _userSeed ) public view onlyValidBet(_gameType, _betNum, _betValue) onlyValidBalance(_balance, _stake) returns(int) { require(_serverSeed != 0 && _userSeed != 0, "inv seeds"); int newBalance = processBet(_gameType, _betNum, _betValue, _balance, _serverSeed, _userSeed); // user need to pay a fee when conflict ended. // this ensures a malicious, rich user can not just generate game sessions and then wait // for us to end the game session and then confirm the session status, so // we would have to pay a high gas fee without profit. newBalance = newBalance.sub(CONFLICT_END_FINE); // do not allow balance below user stake int stake = _stake.castToInt(); if (newBalance < -stake) { newBalance = -stake; } return newBalance; } /** * @dev Force end of game if user does not respond. Only possible after a time period. * to give the user a chance to respond. * @param _gameType Game type. * @param _betNum Bet number. * @param _betValue Bet value. * @param _balance Current balance. * @param _stake User stake. * @param _endInitiatedTime Time server initiated end. * @return New game session balance. */ function serverForceGameEnd( uint8 _gameType, uint _betNum, uint _betValue, int _balance, uint _stake, bytes32 _serverSeed, bytes32 _userSeed, uint _endInitiatedTime ) public view onlyValidBalance(_balance, _stake) returns(int) { require(_endInitiatedTime + SERVER_TIMEOUT <= block.timestamp, "too low timeout"); require((_gameType == 0 && _betNum == 0 && _betValue == 0 && _balance == 0) || isValidBet(_gameType, _betNum, _betValue), "inv bet"); // if no bet was placed (cancelActiveGame) set new balance to 0 int newBalance = 0; // a bet was placed calculate new balance if (_gameType != 0) { newBalance = processBet(_gameType, _betNum, _betValue, _balance, _serverSeed, _userSeed); } // penalize user as he didn't end game newBalance = newBalance.sub(NOT_ENDED_FINE); // do not allow balance below user stake int stake = _stake.castToInt(); if (newBalance < -stake) { newBalance = -stake; } return newBalance; } /** * @dev Force end of game if server does not respond. Only possible after a time period * to give the server a chance to respond. * @param _gameType Game type. * @param _betNum Bet number. * @param _betValue Value of bet. * @param _balance Current balance. * @param _endInitiatedTime Time server initiated end. * @return New game session balance. */ function userForceGameEnd( uint8 _gameType, uint _betNum, uint _betValue, int _balance, uint _stake, uint _endInitiatedTime ) public view onlyValidBalance(_balance, _stake) returns(int) { require(_endInitiatedTime + USER_TIMEOUT <= block.timestamp, "too low timeout"); require((_gameType == 0 && _betNum == 0 && _betValue == 0 && _balance == 0) || isValidBet(_gameType, _betNum, _betValue), "inv bet"); int profit = 0; if (_gameType == 0 && _betNum == 0 && _betValue == 0 && _balance == 0) { // user cancelled game without playing profit = 0; } else { profit = Games.maxUserProfit(_gameType, _betNum, _betValue); } // penalize server as it didn't end game profit = profit.add(NOT_ENDED_FINE); return _balance.add(profit); } /** * @dev Calculate new balance after executing bet. * @param _gameType game type. * @param _betNum Bet Number. * @param _betValue Value of bet. * @param _balance Current balance. * @param _serverSeed Server's seed * @param _userSeed User's seed * return new balance. */ function processBet( uint8 _gameType, uint _betNum, uint _betValue, int _balance, bytes32 _serverSeed, bytes32 _userSeed ) public view returns (int) { uint resNum = Games.resultNumber(_gameType, _serverSeed, _userSeed, _betNum); int profit = Games.userProfit(_gameType, _betNum, _betValue, resNum); return _balance.add(profit); } }
penalize server as it didn't end game
profit = profit.add(NOT_ENDED_FINE);
943,185
[ 1, 1907, 287, 554, 1438, 487, 518, 10242, 1404, 679, 7920, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 450, 7216, 273, 450, 7216, 18, 1289, 12, 4400, 67, 22088, 67, 42, 3740, 1769, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC20.sol"; import "./ERC721.sol"; import "./utils/Ownable.sol"; import "./utils/NameUtils.sol"; import "./utils/ReentrancyGuard.sol"; import "./utils/Base64.sol"; import "./chainlink/VRFConsumerBase.sol"; /** * @title The Greats Contract (Codenamed: Canary) * @dev Extends OpenZeppelin's ERC721 implementation */ contract Canary is ERC721, Ownable, ReentrancyGuard, VRFConsumerBase { using Strings for uint256; using Address for address; // Global variables // Constants /// @dev Invariant: MAX_SUPPLY to be an even number uint256 public constant MAX_SUPPLY = 4608; uint256 public constant RESERVE_PRICE = 3 * (10 ** 18); uint256 public constant STEEP_CURVE_PERIOD = 86400; uint256 public constant GENERAL_CURVE_PERIOD = 7 * 86400; uint256 public constant NAME_CHANGE_PRICE = 100000 * (10 ** 18); uint16[18] public DEVMINT_METADATA_INDICES = [5, 618, 814, 2291, 2342, 2410, 3140, 4035, 4372, 4499, 1818, 111, 1274, 2331, 2885, 3369, 4268, 4589]; // Artist Attestation Metadata string public constant ARTIST_ATTESTATION_METADATA = "ipfs://QmVeJyaLh44i2VsePHbwHaQT89SetXGKstZrjx38sjKGhL"; // Metadata Variables /** * @dev There is a predetermined sequence of metadata that 1-1 corresponds to the index on IPFS and Arweave directories * Our randomization mechanism works by assigning the token ID with a certain metadata index in a randomized fashion */ string public imageIPFSURIPrefix = "ipfs://QmWWMp4Srk6CC9nuGw7fJz6BfxNw7xT7QBHTtxFVRjQTzU/"; string public imageArweaveURIPrefix = "ar://placeholder/"; string public galleryIPFSURIPrefix = "ipfs://QmRv3YCXRYx3v36btcKGnuAXKFqjiWQPW7bGUHWKb9GWGv/"; string public physicalSpecificationsIPFSURIPrefix = "ipfs://QmNSsUw8Z3H5z2FroCwVVZ32vye9RF3QJKejiFLEnn4pik/"; mapping(uint256 => bool) public metadataAssigned; mapping(uint256 => uint256) public tokenIdToMetadataIndex; // Sale variables uint256 public immutable STEEP_CURVE_STARTING_PRICE; uint256 public immutable GENERAL_CURVE_STARTING_PRICE; uint256 public immutable HASHMASKS_DISCOUNT; address public immutable HASHMASKS_ADDRESS; uint256 public SALE_START; bool public salePaused = false; uint256 public FINAL_SETTLEMENT_PRICE = 0; uint256 public SETTLEMENT_PRICE_SET_TIMESTAMP = 0; mapping(address => uint256) public addressToBidExcludingDiscount; // Chainlink and Randomization mapping(bytes32 => uint256) public requestIdToFirstMintIdInBatch; bytes32 internal keyHash; uint256 internal fee; uint256[MAX_SUPPLY] internal indices; uint256 internal indicesAssigned = 0; // Naming address public immutable NCT_ADDRESS; mapping(uint256 => string) public tokenName; mapping(string => bool) private nameReserved; /// @dev The era and subera traits are determined based on the index number of the original metadata sequence uint256[7] public eraStartIndices = [0, 6, 814, 1847, 2540, 3518, 4372]; /// @notice Name of the Eras in the same order as eraStartIndices string[7] public eraNames = ["High Renaissance", "Post-Impressionism", "Surrealism", "Cubism", "Pop Art", "Factory Art", "Beltracchi"]; uint256[33] public subEraStartIndices = [ 0, 1, 6, 270, 440, 610, 814, 1847, 2291, 2321, 2342, 2362, 2410, 2539, 2540, 2790, 3040, 3140, 3240, 3518, 3668, 3828, 3956, 4212, 4372, 4410, 4481, 4510, 4537, 4574, 4581, 4594, 4605 ]; /// @notice Name of the Eras in the same order as eraStartIndices string[33] public subEraNames = [ "Rebirth", "Umbra", "Starry", "Wheatfield", "Olive Trees", "The Room", "The Gambit of Salvator Mundi in the Desert Ocean", "Synthetic Vantage", "Synthetic Limited", "Mephisto Voodoo", "Mephisto Plague", "Mephisto Nimbus", "Analytical", "Foundation", "Nubian", "Light", "Moon", "Vietnam", "Far East", "The Guru", "Unicolor", "Duality", "Solitude", "Angelic", "Storming of Jerusalem", "The Witches", "Sieben Schalen der Apokalypse", "Feathers", "Comet", "Gold", "Angel's Hymn", "Fallen Angels", "Crimson Angel" ]; /// Events event NameChange(uint256 indexed tokenId, string newName); event MetadataAssigned(uint256 indexed tokenId, uint256 indexed metadataIndex); event Mint(uint256 indexed tokenId, uint256 price); event RequestedRandomness(bytes32 requestId); constructor( string memory name, string memory symbol, uint256 steepCurveStartingPrice, uint256 generalCurveStartingPrice, address nctAddress, address hashmasksAddress, uint256 hashmasksDiscount, address vrfCoordinator, address linkToken, uint256 chainlinkFee, bytes32 chainlinkKeyHash ) VRFConsumerBase( vrfCoordinator, // VRF Coordinator linkToken // LINK Token ) ERC721(name, symbol) { require(RESERVE_PRICE > hashmasksDiscount, "Reserve price must be higher than the discount"); require(steepCurveStartingPrice > generalCurveStartingPrice, "steepCurveStartingPrice is invalid"); require(generalCurveStartingPrice > RESERVE_PRICE, "generalCurveStartingPrice is invalid"); STEEP_CURVE_STARTING_PRICE = steepCurveStartingPrice; GENERAL_CURVE_STARTING_PRICE = generalCurveStartingPrice; NCT_ADDRESS = nctAddress; HASHMASKS_ADDRESS = hashmasksAddress; HASHMASKS_DISCOUNT = hashmasksDiscount; // Chainlink keyHash = chainlinkKeyHash; fee = chainlinkFee; } // Public Functions /** * @notice Calculates the current bid price * @dev There are basically two price curves. The steep price curve drops from STEEP_CURVE_STARTING_PRICE TO * GENERAL_CURVE_STARTING_PRICE in STEEP_CURVE_PERIOD time. After that period, the other curve immediately starts * and drops from GENERAL_CURVE_STARTING_PRICE to RESERVE_PRICE in GENERAL_CURVE_PERIOD time * @return Current bid price including any discount * @return Current bid price which doesn't include any discount (Ordinary bid price) */ function getCurrentBidPriceDetails() public view returns (uint256, uint256) { uint256 elapsed = block.timestamp - SALE_START; uint256 ordinaryPrice = 0; if (elapsed >= STEEP_CURVE_PERIOD + GENERAL_CURVE_PERIOD) { ordinaryPrice = RESERVE_PRICE; } else { if (elapsed < STEEP_CURVE_PERIOD) { uint256 priceDrop = ((STEEP_CURVE_STARTING_PRICE - GENERAL_CURVE_STARTING_PRICE) * elapsed) / STEEP_CURVE_PERIOD; ordinaryPrice = max(GENERAL_CURVE_STARTING_PRICE, STEEP_CURVE_STARTING_PRICE - priceDrop); } else { // STEEP_CURVE_PERIOD is subtracted from elapsed to account for the former curve period uint256 priceDrop = ((GENERAL_CURVE_STARTING_PRICE - RESERVE_PRICE) * (elapsed - STEEP_CURVE_PERIOD)) / GENERAL_CURVE_PERIOD; ordinaryPrice = max(RESERVE_PRICE, GENERAL_CURVE_STARTING_PRICE - priceDrop); } } uint256 discount = 0; if (ERC721(HASHMASKS_ADDRESS).balanceOf(msg.sender) > 0) { discount = HASHMASKS_DISCOUNT; } // If the discount is greater than or equal to the ordinary price if (discount >= ordinaryPrice) { return (0, ordinaryPrice); } else { return (ordinaryPrice - discount, ordinaryPrice); } } /// @notice Returns integer that represents the era corresponding to the tokenId function getTokenEra(uint256 tokenId) public view returns (uint256) { require(_exists(tokenId), "Token ID does not exist"); require(metadataAssigned[tokenId], "Metadata is not assigned to the token yet"); uint256 metadataIndex = tokenIdToMetadataIndex[tokenId]; for (uint256 i = eraStartIndices.length - 1; i >= 0; i--) { if (metadataIndex >= eraStartIndices[i]) { return i; } } } /// @notice Returns the era name corresponding to the tokenId function getTokenEraName(uint256 tokenId) public view returns (string memory) { uint256 tokenEra = getTokenEra(tokenId); return eraNames[tokenEra]; } /// @notice Returns integer that represents the sub era corresponding to the tokenId function getTokenSubEra(uint256 tokenId) public view returns (uint256) { require(_exists(tokenId), "Token ID does not exist"); require(metadataAssigned[tokenId], "Metadata is not assigned to the token yet"); uint256 metadataIndex = tokenIdToMetadataIndex[tokenId]; for (uint256 i = subEraStartIndices.length - 1; i >= 0; i--) { if (metadataIndex >= subEraStartIndices[i]) { return i; } } } /// @notice Returns the sub era name corresponding to the tokenId function getTokenSubEraName(uint256 tokenId) public view returns (string memory) { uint256 tokenSubEra = getTokenSubEra(tokenId); return subEraNames[tokenSubEra]; } /// @inheritdoc ERC721 /// @notice Returns Base64 encoded JSON metadata for the given tokenId function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); require(metadataAssigned[tokenId], "Metadata is not assigned to the token yet"); string memory namePostfix = '"'; if (bytes(tokenName[tokenId]).length != 0) { namePostfix = string(abi.encodePacked(': ', tokenName[tokenId], '"')); } // Block scoping to avoid stack too deep error bytes memory uriPartsOfMetadata; { uriPartsOfMetadata = abi.encodePacked( ', "image": "', string(abi.encodePacked(baseURI(), tokenIdToMetadataIndex[tokenId].toString(), '.jpeg')), '", "image_arweave_uri": "', string( abi.encodePacked( imageArweaveURIPrefix, tokenIdToMetadataIndex[tokenId].toString(), '.jpeg' ) ), '", "gallery_glb_uri": "', string(abi.encodePacked(galleryIPFSURIPrefix, getTokenEra(tokenId).toString(), '.glb')) ); } return string( abi.encodePacked( "data:application/json;base64,", Base64.encode( abi.encodePacked( '{"name": "Mundi #', tokenId.toString(), namePostfix, ', "description": "The Greats Collection", "attributes": [{ "trait_type": "Era", "value": "', getTokenEraName(tokenId), '"}, { "trait_type": "Sub Era", "value": "', getTokenSubEraName(tokenId), '"}], "physical_specifications_uri": "', string(abi.encodePacked(physicalSpecificationsIPFSURIPrefix, getTokenSubEra(tokenId).toString(), '.json"')), uriPartsOfMetadata, '" }' ) ) ) ); } /// @inheritdoc ERC721 function baseURI() public view virtual override returns (string memory) { return imageIPFSURIPrefix; } /// @notice Returns if the name has been reserved already (Case insensitive) function isNameReserved(string memory name) public view returns (bool) { return nameReserved[NameUtils.toLower(name)]; } // External Functions /// @notice Mints initial tokens for the purpose of auctioning off function devMint() external onlyOwner { require(totalSupply() < DEVMINT_METADATA_INDICES.length, "Dev minting already done"); require(SALE_START == 0, "Sale has already started"); for (uint256 i = 0; i < DEVMINT_METADATA_INDICES.length; i++) { uint256 mintIndex = MAX_SUPPLY - i - 1; _safeMint(msg.sender, mintIndex); emit Mint(mintIndex, 0); assignMetadataIndexToTokenId(mintIndex, assignIndexWithSeed(DEVMINT_METADATA_INDICES[i])); } // Even number post condition (For Chainlink batching consistency) require(totalSupply() % 2 == 0, "Dev mint number must be even"); } /* * @notice Mints a token for a bid at the current price. * A portion of the bid may be refunded based on the final settlement price * @dev Minted token is revealed (assigned metadata) after the chainlink callback (Done in batches of two) * Known: There would be a reveal delay of next token mint + Chainlink callback time if the token id is even * Smart contracts are prevented from minting */ function mint() external payable nonReentrant { require(msg.sender == tx.origin, "Minter cannot be a contract"); require(totalSupply() < MAX_SUPPLY, "Sale ended"); require(addressToBidExcludingDiscount[msg.sender] == 0, "Only one token mintable per address if RESERVE_PRICE is not reached"); require(SALE_START != 0 && block.timestamp >= SALE_START, "Sale has not started"); require(!salePaused, "Sale is paused"); // Transfer any remaining Ether back to the minter (uint256 currentBidPrice, uint256 nonDiscountedBidPrice) = getCurrentBidPriceDetails(); require(msg.value >= currentBidPrice, "Insufficient funds"); uint256 mintIndex = totalSupply() - DEVMINT_METADATA_INDICES.length; // Offset for dev mints _safeMint(msg.sender, mintIndex); if (totalSupply() % 2 == 0) { require(LINK.balanceOf(address(this)) >= fee, "Not enough LINK - fill contract"); bytes32 requestId = requestRandomness(keyHash, fee); requestIdToFirstMintIdInBatch[requestId] = mintIndex - 1; emit RequestedRandomness(requestId); } emit Mint(mintIndex, currentBidPrice); if (FINAL_SETTLEMENT_PRICE == 0) { // Set final settlement price if it's last mint or if the price curve period has ended if (totalSupply() == MAX_SUPPLY || nonDiscountedBidPrice == RESERVE_PRICE) { FINAL_SETTLEMENT_PRICE = nonDiscountedBidPrice; SETTLEMENT_PRICE_SET_TIMESTAMP = block.timestamp; } else { // It's only considered a bid if the final settlement price is not reached addressToBidExcludingDiscount[msg.sender] = nonDiscountedBidPrice; } } // Return back the remaining Ether if (msg.value > currentBidPrice) { payable(msg.sender).transfer(msg.value - currentBidPrice); } } /// @notice Change name of the given token ID. Cannot be re-named /// @dev The caller needs to have given sufficient allowance on NCT to this contract function changeName(uint256 tokenId, string memory name) external nonReentrant { address owner = ownerOf(tokenId); require(_msgSender() == owner, "ERC721: caller is not the owner"); require(NameUtils.validateName(name) == true, "Not a valid new name"); require(bytes(tokenName[tokenId]).length == 0, "Token ID is already named"); require(isNameReserved(name) == false, "Name is already reserved"); IERC20(NCT_ADDRESS).transferFrom(msg.sender, address(this), NAME_CHANGE_PRICE); tokenName[tokenId] = name; nameReserved[NameUtils.toLower(name)] = true; IERC20(NCT_ADDRESS).burn(NAME_CHANGE_PRICE); emit NameChange(tokenId, name); } /// @notice Refund the difference between the bid by the given address and the settlement price function refundDifferenceToBidders(address[] memory bidderAddresses) external nonReentrant { require(FINAL_SETTLEMENT_PRICE > 0, "Settlement price not set"); for (uint256 i = 0; i < bidderAddresses.length; i++) { uint256 bidAmountExcludingDiscount = addressToBidExcludingDiscount[bidderAddresses[i]]; if (bidAmountExcludingDiscount != 0) { addressToBidExcludingDiscount[bidderAddresses[i]] = 0; payable(bidderAddresses[i]).transfer( bidAmountExcludingDiscount - FINAL_SETTLEMENT_PRICE ); } } } /* * @dev Withdraw ether from this contract (Callable by owner) * 3 days grace period for anyone to be able to refund difference to the bidders as a way to minimize trust in the contract owner. * Callable 3 days after the settlement price is set or 3 days after the general curve period ends */ function withdraw() external onlyOwner { require( (SETTLEMENT_PRICE_SET_TIMESTAMP != 0 && block.timestamp > SETTLEMENT_PRICE_SET_TIMESTAMP + 3 days) || (block.timestamp > SALE_START + STEEP_CURVE_PERIOD + GENERAL_CURVE_PERIOD + 3 days), "Atleast 3 days must pass after settlement price is set or after the general curve period ends" ); uint256 balance = address(this).balance; payable(msg.sender).transfer(balance); } /// @notice saleStartTimestamp param is ignored if sale start timestamp is already set /// @dev Starts / resumes / pauses the sale based on the state (Callable by owner) function toggleSale(uint256 saleStartTimestamp) external onlyOwner { require(totalSupply() < MAX_SUPPLY, "Sale has ended"); if (SALE_START == 0) { require(saleStartTimestamp >= block.timestamp, "saleStartTimestamp is in the past"); SALE_START = saleStartTimestamp; } else { salePaused = !salePaused; } } /// @dev Metadata will be frozen once ownership of the contract is renounced function changeURIs( string memory imageURI, string memory imageArweaveURI, string memory galleryURI, string memory physicalSpecsURI ) external onlyOwner { imageIPFSURIPrefix = imageURI; imageArweaveURIPrefix = imageArweaveURI; galleryIPFSURIPrefix = galleryURI; physicalSpecificationsIPFSURIPrefix = physicalSpecsURI; } // Internal Functions /// @dev Callback function used by VRF Coordinator. Assigns metadata to the tokens in a batch of two function fulfillRandomness(bytes32 requestId, uint256 randomness) internal override { uint256 firstMintIdInBatch = requestIdToFirstMintIdInBatch[requestId]; uint256[2] memory mintIdsToAssign = [firstMintIdInBatch, firstMintIdInBatch + 1]; for (uint256 i = 0; i < mintIdsToAssign.length; i++) { require(metadataAssigned[mintIdsToAssign[i]] == false, "Metadata already assigned"); uint256 metadataIndex = assignIndexWithSeed( uint256(keccak256(abi.encode(randomness, i))) ); assignMetadataIndexToTokenId(mintIdsToAssign[i], metadataIndex); } } /// @dev Assigns metadata index to token id function assignMetadataIndexToTokenId(uint256 tokenId, uint256 metadataIndex) internal { tokenIdToMetadataIndex[tokenId] = metadataIndex; metadataAssigned[tokenId] = true; emit MetadataAssigned(tokenId, metadataIndex); } /// @dev Generates a random index using the seed and stores it in a mapping for 0(1) complexity in case of repetition function assignIndexWithSeed(uint256 seed) internal returns (uint256) { uint256 totalSize = MAX_SUPPLY - indicesAssigned; uint256 index = seed % totalSize; // Credits to Meebits for the following snippet uint256 value = 0; if (indices[index] != 0) { value = indices[index]; } else { value = index; } // Move last value to selected position if (indices[totalSize - 1] == 0) { // 2 -> indices[2] = 999. indices[1] = 999 // Array position not initialized, so use position indices[index] = totalSize - 1; } else { // Array position holds a value so use that indices[index] = indices[totalSize - 1]; } indicesAssigned++; return value; } /** * @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; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _ALPHABET = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _ALPHABET[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } pragma solidity ^0.8.0; import "./Context.sol"; contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of utils functions related to on-chain naming */ library NameUtils { /** * @dev Check if the name string is valid (Alphanumeric and spaces without leading or trailing space) */ function validateName(string memory str) internal pure returns (bool){ bytes memory b = bytes(str); if(b.length < 1) return false; if(b.length > 25) return false; // Cannot be longer than 25 characters if(b[0] == 0x20) return false; // Leading space if (b[b.length - 1] == 0x20) return false; // Trailing space bytes1 lastChar = b[0]; for(uint i; i<b.length; i++){ bytes1 char = b[i]; if (char == 0x20 && lastChar == 0x20) return false; // Cannot contain continous spaces if( !(char >= 0x30 && char <= 0x39) && //9-0 !(char >= 0x41 && char <= 0x5A) && //A-Z !(char >= 0x61 && char <= 0x7A) && //a-z !(char == 0x20) //space ) return false; lastChar = char; } return true; } /** * @dev Converts the string to lowercase */ function toLower(string memory str) internal pure returns (string memory){ bytes memory bStr = bytes(str); bytes memory bLower = new bytes(bStr.length); for (uint i = 0; i < bStr.length; i++) { // Uppercase character if ((uint8(bStr[i]) >= 65) && (uint8(bStr[i]) <= 90)) { bLower[i] = bytes1(uint8(bStr[i]) + 32); } else { bLower[i] = bStr[i]; } } return string(bLower); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev 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]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./EnumerableSet.sol"; /** * @dev Library for managing an enumerable variant of Solidity's * https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`] * type. * * Maps have the following properties: * * - Entries are added, removed, and checked for existence in constant time * (O(1)). * - Entries are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableMap for EnumerableMap.UintToAddressMap; * * // Declare a set state variable * EnumerableMap.UintToAddressMap private myMap; * } * ``` * * As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are * supported. */ library EnumerableMap { using EnumerableSet for EnumerableSet.Bytes32Set; // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Map type with // bytes32 keys and values. // The Map implementation uses private functions, and user-facing // implementations (such as Uint256ToAddressMap) are just wrappers around // the underlying Map. // This means that we can only create new EnumerableMaps for types that fit // in bytes32. struct Map { // Storage of keys EnumerableSet.Bytes32Set _keys; mapping(bytes32 => bytes32) _values; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function _set( Map storage map, bytes32 key, bytes32 value ) private returns (bool) { map._values[key] = value; return map._keys.add(key); } /** * @dev Removes a key-value pair from a map. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function _remove(Map storage map, bytes32 key) private returns (bool) { delete map._values[key]; return map._keys.remove(key); } /** * @dev Returns true if the key is in the map. O(1). */ function _contains(Map storage map, bytes32 key) private view returns (bool) { return map._keys.contains(key); } /** * @dev Returns the number of key-value pairs in the map. O(1). */ function _length(Map storage map) private view returns (uint256) { return map._keys.length(); } /** * @dev Returns the key-value pair stored at position `index` in the map. O(1). * * Note that there are no guarantees on the ordering of entries inside the * array, and it may change when more entries are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) { bytes32 key = map._keys.at(index); return (key, map._values[key]); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. */ function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) { bytes32 value = map._values[key]; if (value == bytes32(0)) { return (_contains(map, key), bytes32(0)); } else { return (true, value); } } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function _get(Map storage map, bytes32 key) private view returns (bytes32) { bytes32 value = map._values[key]; require(value != 0 || _contains(map, key), "EnumerableMap: nonexistent key"); return value; } /** * @dev Same as {_get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {_tryGet}. */ function _get( Map storage map, bytes32 key, string memory errorMessage ) private view returns (bytes32) { bytes32 value = map._values[key]; require(value != 0 || _contains(map, key), errorMessage); return value; } // UintToAddressMap struct UintToAddressMap { Map _inner; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function set( UintToAddressMap storage map, uint256 key, address value ) internal returns (bool) { return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) { return _remove(map._inner, bytes32(key)); } /** * @dev Returns true if the key is in the map. O(1). */ function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) { return _contains(map._inner, bytes32(key)); } /** * @dev Returns the number of elements in the map. O(1). */ function length(UintToAddressMap storage map) internal view returns (uint256) { return _length(map._inner); } /** * @dev Returns the element stored at position `index` in the set. O(1). * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) { (bytes32 key, bytes32 value) = _at(map._inner, index); return (uint256(key), address(uint160(uint256(value)))); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. * * _Available since v3.4._ */ function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) { (bool success, bytes32 value) = _tryGet(map._inner, bytes32(key)); return (success, address(uint160(uint256(value)))); } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function get(UintToAddressMap storage map, uint256 key) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key))))); } /** * @dev Same as {get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryGet}. */ function get( UintToAddressMap storage map, uint256 key, string memory errorMessage ) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage)))); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @title Base64 /// @author Brecht Devos - <[email protected]> /// @notice Provides functions for encoding/decoding base64 library Base64 { string internal constant TABLE_ENCODE = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; bytes internal constant TABLE_DECODE = hex"0000000000000000000000000000000000000000000000000000000000000000" hex"00000000000000000000003e0000003f3435363738393a3b3c3d000000000000" hex"00000102030405060708090a0b0c0d0e0f101112131415161718190000000000" hex"001a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132330000000000"; function encode(bytes memory data) internal pure returns (string memory) { if (data.length == 0) return ''; // load the table into memory string memory table = TABLE_ENCODE; // multiply by 4/3 rounded up uint256 encodedLen = 4 * ((data.length + 2) / 3); // add some extra buffer at the end required for the writing string memory result = new string(encodedLen + 32); assembly { // set the actual output length mstore(result, encodedLen) // prepare the lookup table let tablePtr := add(table, 1) // input ptr let dataPtr := data let endPtr := add(dataPtr, mload(data)) // result ptr, jump over length let resultPtr := add(result, 32) // run over the input, 3 bytes at a time for {} lt(dataPtr, endPtr) {} { // read 3 bytes dataPtr := add(dataPtr, 3) let input := mload(dataPtr) // write 4 characters mstore8(resultPtr, mload(add(tablePtr, and(shr(18, input), 0x3F)))) resultPtr := add(resultPtr, 1) mstore8(resultPtr, mload(add(tablePtr, and(shr(12, input), 0x3F)))) resultPtr := add(resultPtr, 1) mstore8(resultPtr, mload(add(tablePtr, and(shr( 6, input), 0x3F)))) resultPtr := add(resultPtr, 1) mstore8(resultPtr, mload(add(tablePtr, and( input, 0x3F)))) resultPtr := add(resultPtr, 1) } // padding with '=' switch mod(mload(data), 3) case 1 { mstore(sub(resultPtr, 2), shl(240, 0x3d3d)) } case 2 { mstore(sub(resultPtr, 1), shl(248, 0x3d)) } } return result; } function decode(string memory _data) internal pure returns (bytes memory) { bytes memory data = bytes(_data); if (data.length == 0) return new bytes(0); require(data.length % 4 == 0, "invalid base64 decoder input"); // load the table into memory bytes memory table = TABLE_DECODE; // every 4 characters represent 3 bytes uint256 decodedLen = (data.length / 4) * 3; // add some extra buffer at the end required for the writing bytes memory result = new bytes(decodedLen + 32); assembly { // padding with '=' let lastBytes := mload(add(data, mload(data))) if eq(and(lastBytes, 0xFF), 0x3d) { decodedLen := sub(decodedLen, 1) if eq(and(lastBytes, 0xFFFF), 0x3d3d) { decodedLen := sub(decodedLen, 1) } } // set the actual output length mstore(result, decodedLen) // prepare the lookup table let tablePtr := add(table, 1) // input ptr let dataPtr := data let endPtr := add(dataPtr, mload(data)) // result ptr, jump over length let resultPtr := add(result, 32) // run over the input, 4 characters at a time for {} lt(dataPtr, endPtr) {} { // read 4 characters dataPtr := add(dataPtr, 4) let input := mload(dataPtr) // write 3 bytes let output := add( add( shl(18, and(mload(add(tablePtr, and(shr(24, input), 0xFF))), 0xFF)), shl(12, and(mload(add(tablePtr, and(shr(16, input), 0xFF))), 0xFF))), add( shl( 6, and(mload(add(tablePtr, and(shr( 8, input), 0xFF))), 0xFF)), and(mload(add(tablePtr, and( input , 0xFF))), 0xFF) ) ) mstore(resultPtr, shl(232, output)) resultPtr := add(resultPtr, 3) } } return result; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) private pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; contract VRFRequestIDBase { /** * @notice returns the seed which is actually input to the VRF coordinator * * @dev To prevent repetition of VRF output due to repetition of the * @dev user-supplied seed, that seed is combined in a hash with the * @dev user-specific nonce, and the address of the consuming contract. The * @dev risk of repetition is mostly mitigated by inclusion of a blockhash in * @dev the final seed, but the nonce does protect against repetition in * @dev requests which are included in a single block. * * @param _userSeed VRF seed input provided by user * @param _requester Address of the requesting contract * @param _nonce User-specific nonce at the time of the request */ function makeVRFInputSeed(bytes32 _keyHash, uint256 _userSeed, address _requester, uint256 _nonce) internal pure returns (uint256) { return uint256(keccak256(abi.encode(_keyHash, _userSeed, _requester, _nonce))); } /** * @notice Returns the id for this request * @param _keyHash The serviceAgreement ID to be used for this request * @param _vRFInputSeed The seed to be passed directly to the VRF * @return The id for this request * * @dev Note that _vRFInputSeed is not the seed passed by the consuming * @dev contract, but the one generated by makeVRFInputSeed */ function makeRequestId( bytes32 _keyHash, uint256 _vRFInputSeed) internal pure returns (bytes32) { return keccak256(abi.encodePacked(_keyHash, _vRFInputSeed)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./SafeMathChainlink.sol"; import "./LinkTokenInterface.sol"; import "./VRFRequestIDBase.sol"; /** **************************************************************************** * @notice Interface for contracts using VRF randomness * ***************************************************************************** * @dev PURPOSE * * @dev Reggie the Random Oracle (not his real job) wants to provide randomness * @dev to Vera the verifier in such a way that Vera can be sure he's not * @dev making his output up to suit himself. Reggie provides Vera a public key * @dev to which he knows the secret key. Each time Vera provides a seed to * @dev Reggie, he gives back a value which is computed completely * @dev deterministically from the seed and the secret key. * * @dev Reggie provides a proof by which Vera can verify that the output was * @dev correctly computed once Reggie tells it to her, but without that proof, * @dev the output is indistinguishable to her from a uniform random sample * @dev from the output space. * * @dev The purpose of this contract is to make it easy for unrelated contracts * @dev to talk to Vera the verifier about the work Reggie is doing, to provide * @dev simple access to a verifiable source of randomness. * ***************************************************************************** * @dev USAGE * * @dev Calling contracts must inherit from VRFConsumerBase, and can * @dev initialize VRFConsumerBase's attributes in their constructor as * @dev shown: * * @dev contract VRFConsumer { * @dev constuctor(<other arguments>, address _vrfCoordinator, address _link) * @dev VRFConsumerBase(_vrfCoordinator, _link) public { * @dev <initialization with other arguments goes here> * @dev } * @dev } * * @dev The oracle will have given you an ID for the VRF keypair they have * @dev committed to (let's call it keyHash), and have told you the minimum LINK * @dev price for VRF service. Make sure your contract has sufficient LINK, and * @dev call requestRandomness(keyHash, fee, seed), where seed is the input you * @dev want to generate randomness from. * * @dev Once the VRFCoordinator has received and validated the oracle's response * @dev to your request, it will call your contract's fulfillRandomness method. * * @dev The randomness argument to fulfillRandomness is the actual random value * @dev generated from your seed. * * @dev The requestId argument is generated from the keyHash and the seed by * @dev makeRequestId(keyHash, seed). If your contract could have concurrent * @dev requests open, you can use the requestId to track which seed is * @dev associated with which randomness. See VRFRequestIDBase.sol for more * @dev details. (See "SECURITY CONSIDERATIONS" for principles to keep in mind, * @dev if your contract could have multiple requests in flight simultaneously.) * * @dev Colliding `requestId`s are cryptographically impossible as long as seeds * @dev differ. (Which is critical to making unpredictable randomness! See the * @dev next section.) * * ***************************************************************************** * @dev SECURITY CONSIDERATIONS * * @dev A method with the ability to call your fulfillRandomness method directly * @dev could spoof a VRF response with any random value, so it's critical that * @dev it cannot be directly called by anything other than this base contract * @dev (specifically, by the VRFConsumerBase.rawFulfillRandomness method). * * @dev For your users to trust that your contract's random behavior is free * @dev from malicious interference, it's best if you can write it so that all * @dev behaviors implied by a VRF response are executed *during* your * @dev fulfillRandomness method. If your contract must store the response (or * @dev anything derived from it) and use it later, you must ensure that any * @dev user-significant behavior which depends on that stored value cannot be * @dev manipulated by a subsequent VRF request. * * @dev Similarly, both miners and the VRF oracle itself have some influence * @dev over the order in which VRF responses appear on the blockchain, so if * @dev your contract could have multiple VRF requests in flight simultaneously, * @dev you must ensure that the order in which the VRF responses arrive cannot * @dev be used to manipulate your contract's user-significant behavior. * * @dev Since the ultimate input to the VRF is mixed with the block hash of the * @dev block in which the request is made, user-provided seeds have no impact * @dev on its economic security properties. They are only included for API * @dev compatability with previous versions of this contract. * * @dev Since the block hash of the block which contains the requestRandomness * @dev call is mixed into the input to the VRF *last*, a sufficiently powerful * @dev miner could, in principle, fork the blockchain to evict the block * @dev containing the request, forcing the request to be included in a * @dev different block with a different hash, and therefore a different input * @dev to the VRF. However, such an attack would incur a substantial economic * @dev cost. This cost scales with the number of blocks the VRF oracle waits * @dev until it calls responds to a request. */ abstract contract VRFConsumerBase is VRFRequestIDBase { using SafeMathChainlink for uint256; /** * @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 constant private 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].add(1); return makeRequestId(_keyHash, vRFSeed); } LinkTokenInterface immutable internal LINK; address immutable private vrfCoordinator; // Nonces for each VRF key from which randomness has been requested. // // Must stay in sync with VRFCoordinator[_keyHash][this] mapping(bytes32 /* keyHash */ => uint256 /* nonce */) private nonces; /** * @param _vrfCoordinator address of VRFCoordinator contract * @param _link address of LINK token contract * * @dev https://docs.chain.link/docs/link-token-contracts */ constructor(address _vrfCoordinator, address _link) { vrfCoordinator = _vrfCoordinator; LINK = LinkTokenInterface(_link); } // rawFulfillRandomness is called by VRFCoordinator when it receives a valid VRF // proof. rawFulfillRandomness then calls fulfillRandomness, after validating // the origin of the call function rawFulfillRandomness(bytes32 requestId, uint256 randomness) external { require(msg.sender == vrfCoordinator, "Only VRFCoordinator can fulfill"); fulfillRandomness(requestId, randomness); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @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 SafeMathChainlink { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, "SafeMath: division by zero"); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, "SafeMath: modulo by zero"); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface LinkTokenInterface { function allowance(address owner, address spender) external view returns (uint256 remaining); function approve(address spender, uint256 value) external returns (bool success); function balanceOf(address owner) external view returns (uint256 balance); function decimals() external view returns (uint8 decimalPlaces); function decreaseApproval(address spender, uint256 addedValue) external returns (bool success); function increaseApproval(address spender, uint256 subtractedValue) external; function name() external view returns (string memory tokenName); function symbol() external view returns (string memory tokenSymbol); function totalSupply() external view returns (uint256 totalTokensIssued); function transfer(address to, uint256 value) external returns (bool success); function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool success); function transferFrom(address from, address to, uint256 value) external returns (bool success); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./utils/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @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); /** * TODO: Add comment */ function burn(uint256 burnQuantity) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./utils/Context.sol"; import "./IERC721.sol"; import "./IERC721Metadata.sol"; import "./IERC721Enumerable.sol"; import "./IERC721Receiver.sol"; import "./utils/ERC165.sol"; import "./utils/Address.sol"; import "./utils/EnumerableSet.sol"; import "./utils/EnumerableMap.sol"; import "./utils/Strings.sol"; /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using Address for address; using EnumerableSet for EnumerableSet.UintSet; using EnumerableMap for EnumerableMap.UintToAddressMap; using Strings for uint256; // Mapping from holder address to their (enumerable) set of owned tokens mapping (address => EnumerableSet.UintSet) private _holderTokens; // Enumerable mapping from token ids to their owners EnumerableMap.UintToAddressMap private _tokenOwners; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; // Token name string private _name; // Token symbol string private _symbol; // Optional mapping for token URIs mapping (uint256 => string) private _tokenURIs; // Base URI string private _baseURI; /** * @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 || 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), "ERC721: balance query for the zero address"); return _holderTokens[owner].length(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token"); } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; string memory base = baseURI(); // If there is no base URI, return the token URI. if (bytes(base).length == 0) { return _tokenURI; } // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(base, _tokenURI)); } // If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI. return string(abi.encodePacked(base, tokenId.toString())); } /** * @dev Returns the base URI set via {_setBaseURI}. This will be * automatically added as a prefix in {tokenURI} to each token's URI, or * to the token ID if no specific URI is set for that token ID. */ function baseURI() public view virtual returns (string memory) { return _baseURI; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { return _holderTokens[owner].at(index); } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { // _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds return _tokenOwners.length(); } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { (uint256 tokenId, ) = _tokenOwners.at(index); return tokenId; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require(_msgSender() == owner || ERC721.isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom(address from, address to, uint256 tokenId) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _tokenOwners.contains(tokenId); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || ERC721.isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: d* * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual { _mint(to, tokenId); require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); // internal owner _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); // Clear metadata (if any) if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } _holderTokens[owner].remove(tokenId); _tokenOwners.remove(tokenId); emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer(address from, address to, uint256 tokenId) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); // internal owner require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _holderTokens[from].remove(tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(from, to, tokenId); } /** * @dev Sets `_tokenURI` as the tokenURI of `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } /** * @dev Internal function to set the base URI for all token IDs. It is * automatically added as a prefix to the value returned in {tokenURI}, * or to the token ID if {tokenURI} is empty. */ function _setBaseURI(string memory baseURI_) internal virtual { _baseURI = baseURI_; } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { // solhint-disable-next-line no-inline-assembly assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } function _approve(address to, uint256 tokenId) private { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); // internal owner } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { } }
@notice Returns if the name has been reserved already (Case insensitive)
function isNameReserved(string memory name) public view returns (bool) { return nameReserved[NameUtils.toLower(name)]; }
9,976,505
[ 1, 1356, 309, 326, 508, 711, 2118, 8735, 1818, 261, 2449, 17904, 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 ]
[ 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, 30430, 10435, 12, 1080, 3778, 508, 13, 1071, 1476, 1135, 261, 6430, 13, 288, 203, 3639, 327, 508, 10435, 63, 461, 1989, 18, 869, 4070, 12, 529, 13, 15533, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity 0.8.4; import {ERC721Full} from "../../.openzeppelin/0.8/token/ERC721/ERC721Full.sol"; import {Counters} from "../../.openzeppelin/0.8/drafts/Counters.sol"; import {IERC721} from "../../.openzeppelin/0.8/token/ERC721/IERC721.sol"; import {Address} from "../../.openzeppelin/0.8/utils/Address.sol"; import {Bytes32} from "../../lib/Bytes32.sol"; import {Adminable} from "../../lib/Adminable.sol"; import {Initializable} from "../../lib/Initializable.sol"; import {DefiPassportStorage} from "./DefiPassportStorage.sol"; import {ISapphirePassportScores} from "../../sapphire/ISapphirePassportScores.sol"; import {SapphireTypes} from "../../sapphire/SapphireTypes.sol"; contract DefiPassport is ERC721Full, Adminable, DefiPassportStorage, Initializable { /* ========== Libraries ========== */ using Counters for Counters.Counter; using Address for address; using Bytes32 for bytes32; /* ========== Events ========== */ event BaseURISet(string _baseURI); event ApprovedSkinStatusChanged( address _skin, uint256 _skinTokenId, bool _status ); event ApprovedSkinsStatusesChanged( SkinAndTokenIdStatusRecord[] _skinsRecords ); event DefaultSkinStatusChanged( address _skin, bool _status ); event DefaultActiveSkinChanged( address _skin, uint256 _skinTokenId ); event ActiveSkinSet( uint256 _tokenId, SkinRecord _skinRecord ); event SkinManagerSet(address _skinManager); event WhitelistSkinSet(address _skin, bool _status); /* ========== Public variables ========== */ string public override baseURI; /** * @dev Deprecated. Including this because this is a proxy implementation. */ bytes32 private _proofProtocol; /* ========== Modifier ========== */ modifier onlySkinManager () { require( msg.sender == skinManager, "DefiPassport: caller is not skin manager" ); _; } /* ========== Restricted Functions ========== */ function init( string calldata name_, string calldata symbol_, address _skinManager ) external onlyAdmin initializer { _name = name_; _symbol = symbol_; skinManager = _skinManager; } /** * @dev Sets the base URI that is appended as a prefix to the * token URI. */ function setBaseURI( string calldata _baseURI ) external onlyAdmin { baseURI = _baseURI; emit BaseURISet(_baseURI); } /** * @dev Sets the address of the skin manager role * * @param _skinManager The new skin manager */ function setSkinManager( address _skinManager ) external onlyAdmin { require ( _skinManager != skinManager, "DefiPassport: the same skin manager is already set" ); skinManager = _skinManager; emit SkinManagerSet(skinManager); } /** * @notice Registers/unregisters a default skin * * @param _skin Address of the skin NFT * @param _status Wether or not it should be considered as a default * skin or not */ function setDefaultSkin( address _skin, bool _status ) external onlySkinManager { if (!_status) { require( defaultActiveSkin.skin != _skin, "Defi Passport: cannot unregister the default active skin" ); } require( defaultSkins[_skin] != _status, "DefiPassport: skin already has the same status" ); require( _skin.isContract(), "DefiPassport: the given skin is not a contract" ); require ( IERC721(_skin).ownerOf(1) != address(0), "DefiPassport: default skin must at least have tokenId eq 1" ); if (defaultActiveSkin.skin == address(0)) { defaultActiveSkin = SkinRecord(address(0), _skin, 1); } defaultSkins[_skin] = _status; emit DefaultSkinStatusChanged(_skin, _status); } /** * @dev Set the default active skin, which will be used instead of * unavailable user's active one * @notice Skin should be used as default one (with setDefaultSkin function) * * @param _skin Address of the skin NFT * @param _skinTokenId The NFT token ID */ function setDefaultActiveSkin( address _skin, uint256 _skinTokenId ) external onlySkinManager { require( defaultSkins[_skin], "DefiPassport: the given skin is not registered as a default" ); require( defaultActiveSkin.skin != _skin || defaultActiveSkin.skinTokenId != _skinTokenId, "DefiPassport: the skin is already set as default active" ); defaultActiveSkin = SkinRecord(address(0), _skin, _skinTokenId); emit DefaultActiveSkinChanged(_skin, _skinTokenId); } /** * @notice Approves a passport skin. * Only callable by the skin manager */ function setApprovedSkin( address _skin, uint256 _skinTokenId, bool _status ) external onlySkinManager { approvedSkins[_skin][_skinTokenId] = _status; emit ApprovedSkinStatusChanged(_skin, _skinTokenId, _status); } /** * @notice Sets the approved status for all skin contracts and their * token IDs passed into this function. */ function setApprovedSkins( SkinAndTokenIdStatusRecord[] memory _skinsToApprove ) public onlySkinManager { for (uint256 i = 0; i < _skinsToApprove.length; i++) { TokenIdStatus[] memory tokensAndStatuses = _skinsToApprove[i].skinTokenIdStatuses; for (uint256 j = 0; j < tokensAndStatuses.length; j ++) { TokenIdStatus memory tokenStatusPair = tokensAndStatuses[j]; approvedSkins[_skinsToApprove[i].skin][tokenStatusPair.tokenId] = tokenStatusPair.status; } } emit ApprovedSkinsStatusesChanged(_skinsToApprove); } /** * @notice Adds or removes a skin contract to the whitelist. * The Defi Passport considers all skins minted by whitelisted contracts * to be valid skins for applying them on to the passport. * The user applying the skins must still be their owner though. */ function setWhitelistedSkin( address _skinContract, bool _status ) external onlySkinManager { require ( _skinContract.isContract(), "DefiPassport: address is not a contract" ); require ( whitelistedSkins[_skinContract] != _status, "DefiPassport: the skin already has the same whitelist status" ); whitelistedSkins[_skinContract] = _status; emit WhitelistSkinSet(_skinContract, _status); } /* ========== Public Functions ========== */ /** * @notice Mints a DeFi passport to the address specified by `_to`. Note: * - The `_passportSkin` must be an approved or default skin. * - The token URI will be composed by <baseURI> + `_to`, * without the "0x" in front * * @param _to The receiver of the defi passport * @param _passportSkin The address of the skin NFT to be applied to the passport * @param _skinTokenId The ID of the passport skin NFT, owned by the receiver */ function mint( address _to, address _passportSkin, uint256 _skinTokenId ) external returns (uint256) { require ( isSkinAvailable(_to, _passportSkin, _skinTokenId), "DefiPassport: invalid skin" ); // A user cannot have two passports require( balanceOf(_to) == 0, "DefiPassport: user already has a defi passport" ); _tokenIds.increment(); uint256 newTokenId = _tokenIds.current(); _mint(_to, newTokenId); _setActiveSkin(newTokenId, SkinRecord(_to, _passportSkin, _skinTokenId)); return newTokenId; } /** * @notice Changes the passport skin of the caller's passport * * @param _skin The contract address to the skin NFT * @param _skinTokenId The ID of the skin NFT */ function setActiveSkin( address _skin, uint256 _skinTokenId ) external { require( balanceOf(msg.sender) > 0, "DefiPassport: caller has no passport" ); require( isSkinAvailable(msg.sender, _skin, _skinTokenId), "DefiPassport: invalid skin" ); uint256 tokenId = tokenOfOwnerByIndex(msg.sender, 0); _setActiveSkin(tokenId, SkinRecord(msg.sender, _skin, _skinTokenId)); } function approve( address, uint256 ) public pure override { revert("DefiPassport: defi passports are not transferrable"); } function setApprovalForAll( address, bool ) public pure override { revert("DefiPassport: defi passports are not transferrable"); } function safeTransferFrom( address, address, uint256 ) public pure override { revert("DefiPassport: defi passports are not transferrable"); } function safeTransferFrom( address, address, uint256, bytes memory ) public pure override { revert("DefiPassport: defi passports are not transferrable"); } function transferFrom( address, address, uint256 ) public pure override { revert("DefiPassport: defi passports are not transferrable"); } /* ========== Public View Functions ========== */ function name() external override view returns (string memory) { return _name; } function symbol() external override view returns (string memory) { return _symbol; } /** * @notice Returns whether a certain skin can be applied to the specified * user's passport. * * @param _user The user for whom to check * @param _skinContract The address of the skin NFT * @param _skinTokenId The NFT token ID */ function isSkinAvailable( address _user, address _skinContract, uint256 _skinTokenId ) public view returns (bool) { if (defaultSkins[_skinContract]) { return IERC721(_skinContract).ownerOf(_skinTokenId) != address(0); } else if ( whitelistedSkins[_skinContract] || approvedSkins[_skinContract][_skinTokenId] ) { return _isSkinOwner(_user, _skinContract, _skinTokenId); } return false; } /** * @notice Returns the active skin of the given passport ID * * @param _tokenId Passport ID */ function getActiveSkin( uint256 _tokenId ) public view returns (SkinRecord memory) { SkinRecord memory _activeSkin = _activeSkins[_tokenId]; if (isSkinAvailable(_activeSkin.owner, _activeSkin.skin, _activeSkin.skinTokenId)) { return _activeSkin; } else { return defaultActiveSkin; } } /** * @dev Returns the URI for a given token ID. May return an empty string. * * Reverts if the token ID does not exist. */ function tokenURI( uint256 tokenId ) public view override returns (string memory) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); address owner = ownerOf(tokenId); return string(abi.encodePacked(baseURI, "0x", _toAsciiString(owner))); } /* ========== Private Functions ========== */ /** * @dev Converts the given address to string. Used when minting new * passports. */ function _toAsciiString( address _address ) private pure returns (string memory) { bytes memory s = new bytes(40); for (uint i = 0; i < 20; i++) { bytes1 b = bytes1(uint8(uint(uint160(_address)) / (2**(8*(19 - i))))); bytes1 hi = bytes1(uint8(b) / 16); bytes1 lo = bytes1(uint8(b) - 16 * uint8(hi)); s[2*i] = _char(hi); s[2*i+1] = _char(lo); } return string(s); } function _char( bytes1 b ) private pure returns (bytes1 c) { if (uint8(b) < 10) return bytes1(uint8(b) + 0x30); else return bytes1(uint8(b) + 0x57); } /** * @dev Ensures that the user is the owner of the skin NFT */ function _isSkinOwner( address _user, address _skin, uint256 _tokenId ) internal view returns (bool) { /** * It is not sure if the skin contract implements the ERC721 or ERC1155 standard, * so we must do the check. */ bytes memory payload = abi.encodeWithSignature("ownerOf(uint256)", _tokenId); (bool success, bytes memory returnData) = _skin.staticcall(payload); if (success) { (address owner) = abi.decode(returnData, (address)); return owner == _user; } else { // The skin contract might be an ERC1155 (like OpenSea) payload = abi.encodeWithSignature("balanceOf(address,uint256)", _user, _tokenId); (success, returnData) = _skin.staticcall(payload); if (success) { (uint256 balance) = abi.decode(returnData, (uint256)); return balance > 0; } } return false; } function _setActiveSkin( uint256 _tokenId, SkinRecord memory _skinRecord ) private { SkinRecord memory currentSkin = _activeSkins[_tokenId]; require( currentSkin.skin != _skinRecord.skin || currentSkin.skinTokenId != _skinRecord.skinTokenId, "DefiPassport: the same skin is already active" ); _activeSkins[_tokenId] = _skinRecord; emit ActiveSkinSet(_tokenId, _skinRecord); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.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 { function _transferFrom( address from, address to, uint256 tokenId ) internal override(ERC721, ERC721Enumerable) { ERC721Enumerable._transferFrom(from, to, tokenId); } function _mint( address to, uint256 tokenId ) internal override(ERC721, ERC721Enumerable) { ERC721Enumerable._mint(to, tokenId); } function _burn( address owner, uint256 tokenId ) internal override(ERC721, ERC721Enumerable, ERC721Metadata) { // Burn implementation of Metadata ERC721._burn(owner, tokenId); ERC721Metadata._burn(owner, tokenId); ERC721Enumerable._burn(owner, tokenId); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../math/SafeMath.sol"; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` * Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the {SafeMath} * overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never * directly accessed. */ library Counters { using SafeMath for uint256; struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { // The {SafeMath} overflow check can be skipped here, see the comment at the top counter._value += 1; } function decrement(Counter storage counter) internal { counter._value = counter._value.sub(1); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; 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 memory data) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // 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]. * * _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-low-level-calls (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.4; library Bytes32 { function toString( bytes32 _bytes ) internal pure returns (string memory) { uint8 i = 0; while (i < 32 && _bytes[i] != 0) { i++; } bytes memory bytesArray = new bytes(i); for (i = 0; i < 32 && _bytes[i] != 0; i++) { bytesArray[i] = _bytes[i]; } return string(bytesArray); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; import { Storage } from "./Storage.sol"; /** * @title Adminable * @author dYdX * * @dev EIP-1967 Proxy Admin contract. */ contract Adminable { /** * @dev Storage slot with the admin of the contract. * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1. */ bytes32 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; /** * @dev Modifier to check whether the `msg.sender` is the admin. * If it is, it will run the function. Otherwise, it will revert. */ modifier onlyAdmin() { require( msg.sender == getAdmin(), "Adminable: caller is not admin" ); _; } /** * @return The EIP-1967 proxy admin */ function getAdmin() public view returns (address) { return address(uint160(uint256(Storage.load(ADMIN_SLOT)))); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.4; /** * @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. * * Taken from OpenZeppelin */ contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } // SPDX-License-Identifier: MIT pragma solidity 0.8.4; import {Counters} from "../../.openzeppelin/0.8/drafts/Counters.sol"; import {ISapphirePassportScores} from "../../sapphire/ISapphirePassportScores.sol"; contract DefiPassportStorage { /* ========== Structs ========== */ struct SkinRecord { address owner; address skin; uint256 skinTokenId; } struct TokenIdStatus { uint256 tokenId; bool status; } struct SkinAndTokenIdStatusRecord { address skin; TokenIdStatus[] skinTokenIdStatuses; } // Made these internal because the getters override these variables (because this is an upgrade) string internal _name; string internal _symbol; /** * @notice The credit score contract used by the passport */ ISapphirePassportScores private passportScoresContract; /* ========== Public Variables ========== */ /** * @notice Records the whitelisted skins. All tokens minted by these contracts * will be considered valid to apply on the passport, given they are * owned by the caller. */ mapping (address => bool) public whitelistedSkins; /** * @notice Records the approved skins of the passport */ mapping (address => mapping (uint256 => bool)) public approvedSkins; /** * @notice Records the default skins */ mapping (address => bool) public defaultSkins; /** * @notice Records the default skins */ SkinRecord public defaultActiveSkin; /** * @notice The skin manager appointed by the admin, who can * approve and revoke passport skins */ address public skinManager; /* ========== Internal Variables ========== */ /** * @notice Maps a passport (tokenId) to its active skin NFT */ mapping (uint256 => SkinRecord) internal _activeSkins; Counters.Counter internal _tokenIds; } // SPDX-License-Identifier: MIT pragma solidity 0.8.4; import {SapphireTypes} from "./SapphireTypes.sol"; interface ISapphirePassportScores { function updateMerkleRoot(bytes32 newRoot) external; function setMerkleRootUpdater(address merkleRootUpdater) external; /** * Reverts if proof is invalid */ function verify(SapphireTypes.ScoreProof calldata proof) external view returns(bool); function setMerkleRootDelay(uint256 delay) external; function setPause(bool status) external; } // SPDX-License-Identifier: MIT pragma solidity 0.8.4; library SapphireTypes { struct ScoreProof { address account; bytes32 protocol; uint256 score; bytes32[] merkleProof; } struct Vault { uint256 collateralAmount; uint256 borrowedAmount; } struct RootInfo { bytes32 merkleRoot; uint256 timestamp; } enum Operation { Deposit, Withdraw, Borrow, Repay, Liquidate } struct Action { uint256 amount; Operation operation; address userToLiquidate; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.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; /** * @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 override 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 override 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 override virtual { 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 override 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 override virtual { 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 override 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 override virtual { //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 override virtual { 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 override virtual { 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 virtual { 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 virtual { 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 virtual { 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 is an internal detail of the `ERC721` contract and its use 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; } // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = to.call(abi.encodeWithSelector( IERC721Receiver(to).onERC721Received.selector, _msgSender(), from, tokenId, _data )); if (!success) { if (returndata.length > 0) { // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert("ERC721: transfer to non ERC721Receiver implementer"); } } else { bytes4 retval = abi.decode(returndata, (bytes4)); 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 (_tokenApprovals[tokenId] != address(0)) { _tokenApprovals[tokenId] = address(0); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.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 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 override 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 override 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 override 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 override virtual { 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 override virtual { 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 override virtual { _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 - 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 _ownedTokens[from].pop(); // 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 - 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.pop(); _allTokensIndex[tokenId] = 0; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.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; // Base URI string private _baseURI; // 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 Gets the token name. * @return string representing the token name */ function name() external override virtual view returns (string memory) { return _name; } /** * @dev Gets the token symbol. * @return string representing the token symbol */ function symbol() external override virtual view returns (string memory) { return _symbol; } /** * @dev Returns the URI for a given token ID. May return an empty string. * * If the token's URI is non-empty and a base URI was set (via * {_setBaseURI}), it will be added to the token ID's URI as a prefix. * * Reverts if the token ID does not exist. */ function tokenURI(uint256 tokenId) external override virtual view returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; // Even if there is a base URI, it is only appended to non-empty token-specific URIs if (bytes(_tokenURI).length == 0) { return ""; } else { // abi.encodePacked is being used to concatenate strings return string(abi.encodePacked(_baseURI, _tokenURI)); } } /** * @dev Internal function to set the token URI for a given token. * * Reverts if the token ID does not exist. * * TIP: if all token IDs share a prefix (e.g. if your URIs look like * `http://api.myproject.com/token/<id>`), use {_setBaseURI} to store * it and save gas. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal { require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } /** * @dev Internal function to set the base URI for all token IDs. It is * automatically added as a prefix to the value returned in {tokenURI}. * * _Available since v2.5.0._ */ function _setBaseURI(string memory baseURI_) internal { _baseURI = baseURI_; } /** * @dev Returns the base URI set via {_setBaseURI}. This will be * automatically added as a preffix in {tokenURI} to each token's URI, when * they are non-empty. * * _Available since v2.5.0._ */ function baseURI() external virtual view returns (string memory) { return _baseURI; } /** * @dev Internal function to burn a specific token. * Reverts if the token does not exist. * Deprecated, use _burn(uint256) instead. * @param tokenId uint256 ID of the token being burned by the msg.sender */ function _burn(address, uint256 tokenId) internal override virtual { // Clear metadata (if any) if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with 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 returns (address) { 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; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @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) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, 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; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ abstract contract ERC165 is IERC165 { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; constructor () { // 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 override 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; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { function totalSupply() external view returns (uint256); function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { function name() external view returns (string memory); function symbol() external view returns (string memory); function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; library Storage { /** * @dev Performs an SLOAD and returns the data in the slot. */ function load( bytes32 slot ) internal view returns (bytes32) { bytes32 result; /* solhint-disable-next-line no-inline-assembly */ assembly { result := sload(slot) } return result; } /** * @dev Performs an SSTORE to save the value to the slot. */ function store( bytes32 slot, bytes32 value ) internal { /* solhint-disable-next-line no-inline-assembly */ assembly { sstore(slot, value) } } }
* @notice Approves a passport skin. Only callable by the skin manager/
function setApprovedSkin( address _skin, uint256 _skinTokenId, bool _status ) external onlySkinManager { approvedSkins[_skin][_skinTokenId] = _status; emit ApprovedSkinStatusChanged(_skin, _skinTokenId, _status); }
11,896,549
[ 1, 12053, 3324, 279, 1342, 655, 18705, 18, 540, 5098, 4140, 635, 326, 18705, 3301, 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, 444, 31639, 26827, 12, 203, 3639, 1758, 389, 7771, 267, 16, 203, 3639, 2254, 5034, 389, 7771, 267, 1345, 548, 16, 203, 3639, 1426, 389, 2327, 203, 565, 262, 203, 3639, 3903, 203, 3639, 1338, 26827, 1318, 203, 565, 288, 203, 3639, 20412, 5925, 2679, 63, 67, 7771, 267, 6362, 67, 7771, 267, 1345, 548, 65, 273, 389, 2327, 31, 203, 203, 3639, 3626, 1716, 685, 2155, 26827, 1482, 5033, 24899, 7771, 267, 16, 389, 7771, 267, 1345, 548, 16, 389, 2327, 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 ]
./full_match/4/0xF5B2583eE01378EA847e6a5861091b4eC68A1860/sources/contracts/1_Storage.sol
* @title Storage @dev Store & retrieve value in a variable/
contract DogecoinGold { uint256 number; function store(uint256 num) public { number = num; } function retrieve() public view returns (uint256){ return number; } }
12,303,300
[ 1, 3245, 225, 4994, 473, 4614, 460, 316, 279, 2190, 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, 16351, 463, 717, 557, 885, 43, 1673, 288, 203, 203, 565, 2254, 5034, 1300, 31, 203, 203, 203, 565, 445, 1707, 12, 11890, 5034, 818, 13, 1071, 288, 203, 3639, 1300, 273, 818, 31, 203, 565, 289, 203, 203, 565, 445, 4614, 1435, 1071, 1476, 1135, 261, 11890, 5034, 15329, 203, 3639, 327, 1300, 31, 203, 565, 289, 203, 97, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity 0.8.7; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/security/Pausable.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; contract Auction is Ownable, Pausable { using Counters for Counters.Counter; uint256 public immutable minimumUnitPrice; uint256 public immutable minimumBidIncrement; uint256 public immutable unitPriceStepSize; uint256 public immutable minimumQuantity; uint256 public immutable maximumQuantity; uint256 public immutable numberOfAuctions; uint256 public immutable itemsPerDay; address payable public immutable beneficiaryAddress; Counters.Counter private _auctionIDCounter; Counters.Counter private _bidPlacedCounter; bool private _allowWithdrawals; event AuctionStarted(uint256 auctionID); event AuctionEnded(uint256 auctionID); event BidPlaced(uint256 indexed auctionID, address indexed bidder, uint256 bidIndex, uint256 unitPrice, uint256 quantity); event WinnerSelected(uint256 indexed auctionID, address indexed bidder, uint256 unitPrice, uint256 quantity); event BidderRefunded(address indexed bidder, uint256 refundAmount); struct Bid { uint256 unitPrice; uint256 quantity; } struct AuctionStatus { bool started; bool ended; } // auctionID => auction status tracker mapping (uint256 => AuctionStatus) private _auctionStatus; // bidder address => current bid mapping (address => Bid) private _bids; // auctionID => remainingItemsPerAuction mapping (uint256 => uint256) private _remainingItemsPerAuction; // Ownership is immediately transferred to contractOwner. // Beneficiary address cannot be changed after deployment. constructor( address _contractOwner, address payable _beneficiaryAddress, uint256 _minimumUnitPrice, uint256 _minimumBidIncrement, uint256 _unitPriceStepSize, uint256 _minimumQuantity, uint256 _maximumQuantity, uint256 _numberOfAuctions, uint256 _itemsPerDay ) { beneficiaryAddress = _beneficiaryAddress; transferOwnership(_contractOwner); minimumUnitPrice = _minimumUnitPrice; minimumBidIncrement = _minimumBidIncrement; unitPriceStepSize = _unitPriceStepSize; minimumQuantity = _minimumQuantity; maximumQuantity = _maximumQuantity; numberOfAuctions = _numberOfAuctions; itemsPerDay = _itemsPerDay; // Set up the _remainingItemsPerAuction tracker. for(uint256 i = 0; i < _numberOfAuctions; i++) { _remainingItemsPerAuction[i] = _itemsPerDay; } pause(); } modifier whenAuctionActive() { require(!currentAuctionStatus().ended, "Auction has already ended."); require(currentAuctionStatus().started, "Auction hasn't started yet."); _; } modifier whenPreAuction() { require(!currentAuctionStatus().ended, "Auction has already ended."); require(!currentAuctionStatus().started, "Auction has already started."); _; } modifier whenAuctionEnded() { require(currentAuctionStatus().ended, "Auction hasn't ended yet."); require(currentAuctionStatus().started, "Auction hasn't started yet."); _; } function pause() public onlyOwner { _pause(); } function unpause() public onlyOwner { _unpause(); } function setAllowWithdrawals(bool allowWithdrawals_) public onlyOwner { _allowWithdrawals = allowWithdrawals_; } function getAllowWithdrawals() public view returns (bool) { return _allowWithdrawals; } function auctionStatus(uint256 _auctionID) public view returns (AuctionStatus memory) { return _auctionStatus[_auctionID]; } function currentAuctionStatus() public view returns (AuctionStatus memory) { return _auctionStatus[getCurrentAuctionID()]; } // Returns the balance currently held in this contract. function contractBalance() external view returns (uint256) { return address(this).balance; } function bidsPlacedCount() external view returns (uint256) { return _bidPlacedCounter.current(); } function getCurrentAuctionID() public view returns (uint) { return _auctionIDCounter.current(); } function incrementAuctionID() public onlyOwner whenPaused whenAuctionEnded { _auctionIDCounter.increment(); require(_auctionIDCounter.current() < numberOfAuctions, "Max number of auctions reached."); } // this function should only ever be used if something goes wrong, so it doesn't have the whenAuctionEnded modifier function decrementAuctionID() public onlyOwner whenPaused { _auctionIDCounter.decrement(); } function startAuction() external onlyOwner whenPreAuction { uint256 currentAuctionID = getCurrentAuctionID(); _auctionStatus[currentAuctionID].started = true; if (paused()) { unpause(); } emit AuctionStarted(currentAuctionID); } function endAuction() external onlyOwner whenAuctionActive { uint256 currentAuctionID = getCurrentAuctionID(); _auctionStatus[currentAuctionID].ended = true; if (!paused()) { pause(); } emit AuctionEnded(currentAuctionID); } function getBid(address bidder) external view returns (Bid memory) { return _bids[bidder]; } function getRemainingItemsForAuction(uint256 auctionID) external view returns (uint256) { require(auctionID < numberOfAuctions, "Invalid auctionID."); return _remainingItemsPerAuction[auctionID]; } // Requires a sorted list of winners. You can submit the winners in any batch size you want, but order matters. function selectWinners(address[] calldata bidders) external onlyOwner whenPaused whenAuctionEnded { uint256 auctionID = getCurrentAuctionID(); // Iterate over each winning address until we reach the end of the winners list or we deplete _remainingItemsPerAuction for this auctionID. for(uint256 i = 0; i < bidders.length; i++) { address bidder = bidders[i]; uint256 bidUnitPrice = _bids[bidder].unitPrice; uint256 bidQuantity = _bids[bidder].quantity; // Skip bidders whose bid quantity or unit price is already 0. if (bidUnitPrice == 0 || bidQuantity == 0) { continue; } if (_remainingItemsPerAuction[auctionID] == bidQuantity) { // STOP: _remainingItemsPerAuction has been depleted, and the quantity for this bid made us hit 0 exactly. _bids[bidder] = Bid(0,0); emit WinnerSelected(auctionID, bidder, bidUnitPrice, bidQuantity); _remainingItemsPerAuction[auctionID] = 0; break; } else if (_remainingItemsPerAuction[auctionID] < bidQuantity) { // STOP: _remainingItemsPerAuction has been depleted, and the quantity for this bid made us go negative (quantity too high to give the bidder all they asked for) emit WinnerSelected(auctionID, bidder, bidUnitPrice, _remainingItemsPerAuction[auctionID]); // Don't set unitPrice to 0 here as there is still at least 1 quantity remaining. // Must set _remainingItemsPerAuction to 0 AFTER this. _bids[bidder].quantity -= _remainingItemsPerAuction[auctionID]; _remainingItemsPerAuction[auctionID] = 0; break; } else { // CONTINUE: _remainingItemsPerAuction hasn't been depleted yet... _bids[bidder] = Bid(0,0); emit WinnerSelected(auctionID, bidder, bidUnitPrice, bidQuantity); _remainingItemsPerAuction[auctionID] -= bidQuantity; } } } // Refunds losing bidders from the contract's balance. function refundBidders(address payable[] calldata bidders) external onlyOwner whenPaused whenAuctionEnded { uint256 totalRefundAmount = 0; for(uint256 i = 0; i < bidders.length; i++) { address payable bidder = bidders[i]; uint256 refundAmount = _bids[bidder].unitPrice * _bids[bidder].quantity; // Skip bidders who aren't entitled to a refund. if (refundAmount == 0) { continue; } _bids[bidder] = Bid(0,0); (bool success, ) = bidder.call{ value: refundAmount }(""); require(success, "Transfer failed."); totalRefundAmount += refundAmount; emit BidderRefunded(bidder, refundAmount); } } function withdrawContractBalance() external onlyOwner { (bool success, ) = beneficiaryAddress.call{value: address(this).balance}(""); require(success, "Transfer failed."); } // Note: this function allows claiming refunds even before the winners are selected. It's up to the owner to only allow withdrawals when appropriate. // It's also the responsbility of the owner to keep enough ether in the contract for refunds. function claimRefund() external whenPaused whenAuctionEnded { // This must be the final auction. require(getCurrentAuctionID() == (numberOfAuctions - 1), "Withdrawals allowed after final auction has ended."); // Withdrawals must not be paused. require(_allowWithdrawals, "Withdrawals are not allowed right now."); uint256 refundAmount = _bids[msg.sender].unitPrice * _bids[msg.sender].quantity; require(refundAmount > 0, "Refund amount is 0."); _bids[msg.sender] = Bid(0,0); (bool success, ) = msg.sender.call{ value: refundAmount }(""); require(success, "Transfer failed."); emit BidderRefunded(msg.sender, refundAmount); } // When a bidder places a bid or updates their existing bid, they will use this function. // - total value can never be lowered // - unit price can never be lowered // - quantity can be raised or lowered, but only if unit price is raised to meet or exceed previous total price function placeBid(uint256 quantity, uint256 unitPrice) external payable whenNotPaused whenAuctionActive { // If the bidder is increasing their bid, the amount being added must be greater than or equal to the minimum bid increment. if (msg.value > 0 && msg.value < minimumBidIncrement) { revert("Bid lower than minimum bid increment."); } // Cache initial bid values. uint256 initialUnitPrice = _bids[msg.sender].unitPrice; uint256 initialQuantity = _bids[msg.sender].quantity; uint256 initialTotalValue = initialUnitPrice * initialQuantity; // Cache final bid values. uint256 finalUnitPrice = unitPrice; uint256 finalQuantity = quantity; uint256 finalTotalValue = initialTotalValue + msg.value; // Don't allow bids with a unit price scale smaller than unitPriceStepSize. // For example, allow 1.01 or 111.01 but don't allow 1.011. require(finalUnitPrice % unitPriceStepSize == 0, "Unit price step too small."); // Reject bids that don't have a quantity within the valid range. require(finalQuantity >= minimumQuantity, "Quantity too low."); require(finalQuantity <= maximumQuantity, "Quantity too high."); // Total value can never be lowered. require(finalTotalValue >= initialTotalValue, "Total value can't be lowered."); // Unit price can never be lowered. // Quantity can be raised or lowered, but it can only be lowered if the unit price is raised to meet or exceed the initial total value. Ensuring the the unit price is never lowered takes care of this. require(finalUnitPrice >= initialUnitPrice, "Unit price can't be lowered."); // Ensure the new totalValue equals quantity * the unit price that was given in this txn exactly. This is important to prevent rounding errors later when returning ether. require(finalQuantity * finalUnitPrice == finalTotalValue, "Quantity * Unit Price != Total Value"); // Unit price must be greater than or equal to the minimumUnitPrice. require(finalUnitPrice >= minimumUnitPrice, "Bid unit price too low."); // Something must be changing from the initial bid for this new bid to be valid. if (initialUnitPrice == finalUnitPrice && initialQuantity == finalQuantity) { revert("This bid doesn't change anything."); } // Update the bidder's bid. _bids[msg.sender].unitPrice = finalUnitPrice; _bids[msg.sender].quantity = finalQuantity; emit BidPlaced(_auctionIDCounter.current(), msg.sender, _bidPlacedCounter.current(), finalUnitPrice, finalQuantity); // Increment after emitting the BidPlaced event because counter is 0-indexed. _bidPlacedCounter.increment(); } // Handles receiving ether to the contract. // Reject all direct payments to the contract except from beneficiary and owner. // Bids must be placed using the placeBid function. receive() external payable { require(msg.value > 0, "No ether was sent."); require(msg.sender == beneficiaryAddress || msg.sender == owner(), "Only owner or beneficiary can fund contract."); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library Counters { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor() { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } }
Ensure the new totalValue equals quantity * the unit price that was given in this txn exactly. This is important to prevent rounding errors later when returning ether.
require(finalQuantity * finalUnitPrice == finalTotalValue, "Quantity * Unit Price != Total Value");
411,813
[ 1, 12512, 326, 394, 2078, 620, 1606, 10457, 225, 326, 2836, 6205, 716, 1703, 864, 316, 333, 7827, 8950, 18, 1220, 353, 10802, 358, 5309, 13885, 1334, 5137, 1347, 5785, 225, 2437, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2583, 12, 6385, 12035, 380, 727, 2802, 5147, 422, 727, 5269, 620, 16, 315, 12035, 380, 8380, 20137, 480, 10710, 1445, 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 ]
/** * This is the offical code for Cyn-Coin * Official Website: https://www.cyn-c.io/ * Discord: https://discord.gg/qP6rhnNW * Twitter: @CyncNft * Opensea- http://opensea.io/CYN-C * Telegram- http://t.me/CYNCommunity * This code was originally written as Safetoken by: 0f0crypto <[email protected]> * discord: https://discord.gg/zn86MDCQc * * SPDX-License-Identifier: MIT */ pragma solidity ^0.8.4; /** * Tokenomics: * Redistribution 2% * Community Fund 1% * Project Fund 1% */ 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 IERC20Metadata is IERC20 { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); } abstract contract Context { function _msgSender() internal view virtual returns (address) {return msg.sender;} function _msgData() internal view virtual returns (bytes calldata) {this; return msg.data;} } library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) {return a + b;} function sub(uint256 a, uint256 b) internal pure returns (uint256) {return a - b;} function mul(uint256 a, uint256 b) internal pure returns (uint256) {return a * b;} function div(uint256 a, uint256 b) internal pure returns (uint256) {return a / b;} function mod(uint256 a, uint256 b) internal pure returns (uint256) {return a % b;} function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } } library Address { function isContract(address account) internal view returns (bool) { uint256 size; assembly { size := extcodesize(account) } return size > 0;} function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance");(bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } function functionCall(address target, bytes memory data) internal returns (bytes memory) {return functionCall(target, data, "Address: low-level call failed");} function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {return functionCallWithValue(target, data, 0, errorMessage);} function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {return functionCallWithValue(target, data, value, "Address: low-level call with value failed");} function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { if (returndata.length > 0) { assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else {revert(errorMessage);} } } } abstract contract Ownable is Context { address private _owner; address private _previousOwner; uint256 private _lockTime; bool private _renounced; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } function owner() public view returns (address) { return _owner; } modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); _renounced = true; } 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 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, "Only the previous owner can unlock onwership"); require(_renounced == false, "Cannot unlock renounced ownership"); require(block.timestamp > _lockTime , "The contract is still locked"); emit OwnershipTransferred(_owner, _previousOwner); _owner = _previousOwner; } } abstract contract Manageable is Context { address private _manager; event ManagementTransferred(address indexed previousManager, address indexed newManager); constructor(){ address msgSender = _msgSender(); _manager = msgSender; emit ManagementTransferred(address(0), msgSender); } function manager() public view returns(address){ return _manager; } modifier onlyManager(){ require(_manager == _msgSender(), "Manageable: caller is not the manager"); _; } function transferManagement(address newManager) external virtual onlyManager { emit ManagementTransferred(_manager, newManager); _manager = newManager; } } interface IPancakeV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function createPair(address tokenA, address tokenB) external returns (address pair); } interface IPancakeV2Router { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } abstract contract Tokenomics { using SafeMath for uint256; // --------------------- Token Settings ------------------- // string internal constant NAME = "CYN-COIN"; string internal constant SYMBOL = "CYNC"; uint16 internal constant FEES_DIVISOR = 10**3; uint8 internal constant DECIMALS = 18; uint256 internal constant ZEROES = 10**DECIMALS; uint256 private constant MAX = ~uint256(0); uint256 internal constant TOTAL_SUPPLY = 100000000000 * ZEROES; // 100B Total Supply uint256 internal _reflectedSupply = (MAX - (MAX % TOTAL_SUPPLY)); uint256 internal constant maxTransactionAmount = TOTAL_SUPPLY / 100; // 1% of the total supply per transaction uint256 internal constant maxWalletBalance = TOTAL_SUPPLY / 20; // 5% of the total supply per wallet (20/100=5%) uint256 internal constant numberOfTokensToSwapToLiquidity = TOTAL_SUPPLY / 1000; // not being used. // --------------------- Fees Settings ------------------- // //address internal projectFund = 0xCF14cAA1aFb0464b3e9BB0Fd652b01fC59388fCC; //Multi-sig Project Fund test //address internal communityWallet = 0x863bBFf526DD5ec0e77AB7eB959a2FbC9910CB98; //Multi-sig Community Fund test address internal projectFund = 0xCa5284C60aF1c65507bE8d597b213666C3a7551F; //Multi-sig Project Fund address internal communityWallet = 0xE057D9f2b4d39793DBe92dA241b8A33ad9a6dD46; //Multi-sig Community Fund address internal burnAddress = 0x0000000000000000000000000000000662607015; //(Planck's constant) This burn address is only here for potenital future manual burning. enum FeeType { Antiwhale, Burn, Liquidity, Rfi, External, ExternalToETH } struct Fee { FeeType name; uint256 value; address recipient; uint256 total; } Fee[] internal fees; uint256 internal sumOfFees; constructor() { _addFees(); } function _addFee(FeeType name, uint256 value, address recipient) private { fees.push( Fee(name, value, recipient, 0 ) ); sumOfFees += value; } function _addFees() private { /** * Tokenomics: * Project Fund 1% * Redistribution 2% * Community Wallet 1% */ _addFee(FeeType.Rfi, 20, address(this) ); _addFee(FeeType.Burn, 0, burnAddress ); // not being used _addFee(FeeType.Liquidity, 0, address(this) ); // not being used _addFee(FeeType.External, 10, projectFund ); _addFee(FeeType.External, 10, communityWallet ); } function _getFeesCount() internal view returns (uint256){ return fees.length; } function _getFeeStruct(uint256 index) private view returns(Fee storage){ require( index >= 0 && index < fees.length, "FeesSettings._getFeeStruct: Fee index out of bounds"); return fees[index]; } function _getFee(uint256 index) internal view returns (FeeType, uint256, address, uint256){ Fee memory fee = _getFeeStruct(index); return ( fee.name, fee.value, fee.recipient, fee.total ); } function _addFeeCollectedAmount(uint256 index, uint256 amount) internal { Fee storage fee = _getFeeStruct(index); fee.total = fee.total.add(amount); } // function getCollectedFeeTotal(uint256 index) external view returns (uint256){ function getCollectedFeeTotal(uint256 index) internal view returns (uint256){ Fee memory fee = _getFeeStruct(index); return fee.total; } } abstract contract Presaleable is Manageable { bool internal isInPresale; function setPreseableEnabled(bool value) external onlyManager { isInPresale = value; } } abstract contract BaseRfiToken is IERC20, IERC20Metadata, Ownable, Presaleable, Tokenomics { using SafeMath for uint256; using Address for address; mapping (address => uint256) internal _reflectedBalances; mapping (address => uint256) internal _balances; mapping (address => mapping (address => uint256)) internal _allowances; mapping (address => bool) internal _isExcludedFromFee; mapping (address => bool) internal _isExcludedFromRewards; address[] private _excluded; constructor(){ _reflectedBalances[owner()] = _reflectedSupply; // exclude owner,Multi-sig wallets and this contract from fee _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; _isExcludedFromFee[communityWallet] = true; //multi-sig wallet for community Fund _isExcludedFromFee[projectFund] = true; // multi-sig wallet for project fund // exclude the owner, multi-sig wallets and this contract from rewards _exclude(owner()); _exclude(communityWallet); _exclude(projectFund); _exclude(address(this)); emit Transfer(address(0), owner(), TOTAL_SUPPLY); } /** Functions required by IERC20Metadat **/ function name() external pure override returns (string memory) { return NAME; } function symbol() external pure override returns (string memory) { return SYMBOL; } function decimals() external pure override returns (uint8) { return DECIMALS; } /** Functions required by IERC20Metadat - END **/ /** Functions required by IERC20 **/ function totalSupply() external pure override returns (uint256) { return TOTAL_SUPPLY; } function balanceOf(address account) public view override returns (uint256){ if (_isExcludedFromRewards[account]) return _balances[account]; return tokenFromReflection(_reflectedBalances[account]); } function transfer(address recipient, uint256 amount) external override returns (bool){ _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) external view override returns (uint256){ return _allowances[owner][spender]; } function approve(address spender, uint256 amount) external override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) external override returns (bool){ _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** Functions required by IERC20 - END **/ function burn(uint256 amount) external { address sender = _msgSender(); require(sender != address(0), "BaseRfiToken: burn from the zero address"); require(sender != address(burnAddress), "BaseRfiToken: burn from the burn address"); uint256 balance = balanceOf(sender); require(balance >= amount, "BaseRfiToken: burn amount exceeds balance"); uint256 reflectedAmount = amount.mul(_getCurrentRate()); // remove the amount from the sender's balance first _reflectedBalances[sender] = _reflectedBalances[sender].sub(reflectedAmount); if (_isExcludedFromRewards[sender]) _balances[sender] = _balances[sender].sub(amount); _burnTokens( sender, amount, reflectedAmount ); } /** * @dev "Soft" burns the specified amount of tokens by sending them * to the burn address */ function _burnTokens(address sender, uint256 tBurn, uint256 rBurn) internal { /** * @dev Do not reduce _totalSupply and/or _reflectedSupply. (soft) burning by sending * tokens to the burn address (which should be excluded from rewards) is sufficient * in RFI */ _reflectedBalances[burnAddress] = _reflectedBalances[burnAddress].add(rBurn); if (_isExcludedFromRewards[burnAddress]) _balances[burnAddress] = _balances[burnAddress].add(tBurn); /** * @dev Emit the event so that the burn address balance is updated (on bscscan) */ emit Transfer(sender, burnAddress, tBurn); } 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) external view returns (bool) { return _isExcludedFromRewards[account]; } /** * @dev Calculates and returns the reflected amount for the given amount with or without * the transfer fees (deductTransferFee true/false) */ function reflectionFromToken(uint256 tAmount, bool deductTransferFee) external view returns(uint256) { require(tAmount <= TOTAL_SUPPLY, "Amount must be less than supply"); if (!deductTransferFee) { (uint256 rAmount,,,,) = _getValues(tAmount,0); return rAmount; } else { (,uint256 rTransferAmount,,,) = _getValues(tAmount,_getSumOfFees(_msgSender(), tAmount)); return rTransferAmount; } } /** * @dev Calculates and returns the amount of tokens corresponding to the given reflected amount. */ function tokenFromReflection(uint256 rAmount) internal view returns(uint256) { require(rAmount <= _reflectedSupply, "Amount must be less than total reflections"); uint256 currentRate = _getCurrentRate(); return rAmount.div(currentRate); } function excludeFromReward(address account) external onlyOwner() { require(!_isExcludedFromRewards[account], "Account is not included"); require(_excluded.length < 10, "Cannot exclude more than 10 accounts"); _exclude(account); } function _exclude(address account) internal { if(_reflectedBalances[account] > 0) { _balances[account] = tokenFromReflection(_reflectedBalances[account]); } _isExcludedFromRewards[account] = true; _excluded.push(account); } function includeInReward(address account) external onlyOwner() { require(_isExcludedFromRewards[account], "Account is not excluded"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _balances[account] = 0; _isExcludedFromRewards[account] = false; _excluded.pop(); break; } } } function setExcludedFromFee(address account, bool value) external onlyOwner { _isExcludedFromFee[account] = value; } function isExcludedFromFee(address account) public view returns(bool) { return _isExcludedFromFee[account]; } function _approve(address owner, address spender, uint256 amount) internal { require(owner != address(0), "BaseRfiToken: approve from the zero address"); require(spender != address(0), "BaseRfiToken: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** */ function _isUnlimitedSender(address account) internal view returns(bool){ // the owner and multi-sig wallets are excluded: return (account == owner() || account == communityWallet || account == projectFund ); } /** */ function _isUnlimitedRecipient(address account) internal view returns(bool){ // the owner and community fund wallet should be a white-listed recipient // and anyone should be able to burn as many tokens as they wish. return (account == owner() || account == burnAddress || account == communityWallet|| account == projectFund); } function _transfer(address sender, address recipient, uint256 amount) private { require(sender != address(0), "BaseRfiToken: transfer from the zero address"); require(recipient != address(0), "BaseRfiToken: transfer to the zero address"); require(sender != address(burnAddress), "BaseRfiToken: transfer from the burn address"); require(amount > 0, "Transfer amount must be greater than zero"); // indicates whether or not feee should be deducted from the transfer bool takeFee = true; if ( isInPresale ){ takeFee = false; } else { /** * Check the amount is within the max allowed limit as long as a * unlimited sender/recepient is not involved in the transaction */ if ( amount > maxTransactionAmount && !_isUnlimitedSender(sender) && !_isUnlimitedRecipient(recipient) ){ revert("Transfer amount exceeds the maxTxAmount."); } if ( maxWalletBalance > 0 && !_isUnlimitedSender(sender) && !_isUnlimitedRecipient(recipient) && !_isV2Pair(recipient) ){ uint256 recipientBalance = balanceOf(recipient); require(recipientBalance + amount <= maxWalletBalance, "New balance would exceed the maxWalletBalance"); } } // if any account belongs to _isExcludedFromFee account then remove the fee if(_isExcludedFromFee[sender] || _isExcludedFromFee[recipient]){ takeFee = false; } _beforeTokenTransfer(sender, recipient, amount, takeFee); _transferTokens(sender, recipient, amount, takeFee); } function _transferTokens(address sender, address recipient, uint256 amount, bool takeFee) private { uint256 sumOfFees = _getSumOfFees(sender, amount); if ( !takeFee ){ sumOfFees = 0; } (uint256 rAmount, uint256 rTransferAmount, uint256 tAmount, uint256 tTransferAmount, uint256 currentRate ) = _getValues(amount, sumOfFees); /** * Sender's and Recipient's reflected balances must be always updated regardless of * whether they are excluded from rewards or not. */ _reflectedBalances[sender] = _reflectedBalances[sender].sub(rAmount); _reflectedBalances[recipient] = _reflectedBalances[recipient].add(rTransferAmount); /** * Update the true/nominal balances for excluded accounts */ if (_isExcludedFromRewards[sender]){ _balances[sender] = _balances[sender].sub(tAmount); } if (_isExcludedFromRewards[recipient] ){ _balances[recipient] = _balances[recipient].add(tTransferAmount); } _takeFees( amount, currentRate, sumOfFees ); emit Transfer(sender, recipient, tTransferAmount); } function _takeFees(uint256 amount, uint256 currentRate, uint256 sumOfFees ) private { if ( sumOfFees > 0 && !isInPresale ){ _takeTransactionFees(amount, currentRate); } } function _getValues(uint256 tAmount, uint256 feesSum) internal view returns (uint256, uint256, uint256, uint256, uint256) { uint256 tTotalFees = tAmount.mul(feesSum).div(FEES_DIVISOR); uint256 tTransferAmount = tAmount.sub(tTotalFees); uint256 currentRate = _getCurrentRate(); uint256 rAmount = tAmount.mul(currentRate); uint256 rTotalFees = tTotalFees.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rTotalFees); return (rAmount, rTransferAmount, tAmount, tTransferAmount, currentRate); } function _getCurrentRate() internal view returns(uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() internal view returns(uint256, uint256) { uint256 rSupply = _reflectedSupply; uint256 tSupply = TOTAL_SUPPLY; for (uint256 i = 0; i < _excluded.length; i++) { if (_reflectedBalances[_excluded[i]] > rSupply || _balances[_excluded[i]] > tSupply) return (_reflectedSupply, TOTAL_SUPPLY); rSupply = rSupply.sub(_reflectedBalances[_excluded[i]]); tSupply = tSupply.sub(_balances[_excluded[i]]); } if (tSupply == 0 || rSupply < _reflectedSupply.div(TOTAL_SUPPLY)) return (_reflectedSupply, TOTAL_SUPPLY); return (rSupply, tSupply); } /** * @dev Hook that is called before any transfer of tokens. */ function _beforeTokenTransfer(address sender, address recipient, uint256 amount, bool takeFee) internal virtual; function _getSumOfFees(address sender, uint256 amount) internal view virtual returns (uint256); function _isV2Pair(address account) internal view virtual returns(bool); function _redistribute(uint256 amount, uint256 currentRate, uint256 fee, uint256 index) internal { uint256 tFee = amount.mul(fee).div(FEES_DIVISOR); uint256 rFee = tFee.mul(currentRate); _reflectedSupply = _reflectedSupply.sub(rFee); _addFeeCollectedAmount(index, tFee); } /** * @dev Hook that is called before the `Transfer` event is emitted if fees are enabled for the transfer */ function _takeTransactionFees(uint256 amount, uint256 currentRate) internal virtual; } abstract contract Liquifier is Ownable, Manageable { using SafeMath for uint256; uint256 private withdrawableBalance; enum Env {Testnet, MainnetV1, MainnetV2} Env private _env; address private _mainnetRouterV1Address = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; // just a place holder address private _mainnetRouterV2Address = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; // just a place holder address private _testnetRouterAddress = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; // being used - all addresses are using the routerV2 of Uniswap // PancakeSwap Testnet = https://pancake.kiemtienonline360.com/ //address private _testnetRouterAddress = 0x9Ac64Cc6e4415144C455BD8E4837Fea55603e5c3; IPancakeV2Router internal _router; address internal _pair; bool private inSwapAndLiquify; bool private swapAndLiquifyEnabled = true; uint256 private maxTransactionAmount; uint256 private numberOfTokensToSwapToLiquidity; modifier lockTheSwap { inSwapAndLiquify = true; _; inSwapAndLiquify = false; } event RouterSet(address indexed router); event SwapAndLiquify(uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiquidity); event SwapAndLiquifyEnabledUpdated(bool enabled); event LiquidityAdded(uint256 tokenAmountSent, uint256 ethAmountSent, uint256 liquidity); receive() external payable {} function initializeLiquiditySwapper(Env env, uint256 maxTx, uint256 liquifyAmount) internal { _env = env; if (_env == Env.MainnetV1){ _setRouterAddress(_mainnetRouterV1Address); } else if (_env == Env.MainnetV2){ _setRouterAddress(_mainnetRouterV2Address); } else /*(_env == Env.Testnet)*/{ _setRouterAddress(_testnetRouterAddress); } maxTransactionAmount = maxTx; numberOfTokensToSwapToLiquidity = liquifyAmount; } /** * NOTE: passing the `contractTokenBalance` here is preferred to creating `balanceOfDelegate` */ function liquify(uint256 contractTokenBalance, address sender) internal { if (contractTokenBalance >= maxTransactionAmount) contractTokenBalance = maxTransactionAmount; bool isOverRequiredTokenBalance = ( contractTokenBalance >= numberOfTokensToSwapToLiquidity ); if ( isOverRequiredTokenBalance && swapAndLiquifyEnabled && !inSwapAndLiquify && (sender != _pair) ){ // TODO check if the `(sender != _pair)` is necessary because that basically // stops swap and liquify for all "buy" transactions _swapAndLiquify(contractTokenBalance); } } function _setRouterAddress(address router) private { IPancakeV2Router _newPancakeRouter = IPancakeV2Router(router); _pair = IPancakeV2Factory(_newPancakeRouter.factory()).createPair(address(this), _newPancakeRouter.WETH()); _router = _newPancakeRouter; emit RouterSet(router); } function _swapAndLiquify(uint256 amount) private lockTheSwap { // split the contract balance into halves uint256 half = amount.div(2); uint256 otherHalf = amount.sub(half); uint256 initialBalance = address(this).balance; // swap tokens for ETH _swapTokensForEth(half); // <- this breaks the ETH -> HATE swap when swap+liquify is triggered // how much ETH did we just swap into? uint256 newBalance = address(this).balance.sub(initialBalance); // add liquidity to uniswap _addLiquidity(otherHalf, newBalance); emit SwapAndLiquify(half, newBalance, otherHalf); } 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] = _router.WETH(); _approveDelegate(address(this), address(_router), tokenAmount); // make the swap _router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, // The minimum amount of output tokens that must be received for the transaction not to revert. // 0 = accept any amount (slippage is inevitable) 0, path, address(this), block.timestamp ); } function _addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { // approve token transfer to cover all possible scenarios _approveDelegate(address(this), address(_router), tokenAmount); // add tahe liquidity (uint256 tokenAmountSent, uint256 ethAmountSent, uint256 liquidity) = _router.addLiquidityETH{value: ethAmount}( address(this), tokenAmount, // Bounds the extent to which the WETH/token price can go up before the transaction reverts. // Must be <= amountTokenDesired; 0 = accept any amount (slippage is inevitable) 0, // Bounds the extent to which the token/WETH price can go up before the transaction reverts. // 0 = accept any amount (slippage is inevitable) 0, // this is a centralized risk if the owner's account is ever compromised (see Certik SSL-04) owner(), block.timestamp ); withdrawableBalance = address(this).balance; emit LiquidityAdded(tokenAmountSent, ethAmountSent, liquidity); } /** * @dev Sets the uniswapV2 pair (router & factory) for swapping and liquifying tokens */ function setRouterAddress(address router) external onlyManager() { _setRouterAddress(router); } /** * @dev Sends the swap and liquify flag to the provided value. If set to `false` tokens collected in the contract will * NOT be converted into liquidity. */ function setSwapAndLiquifyEnabled(bool enabled) external onlyManager { swapAndLiquifyEnabled = enabled; emit SwapAndLiquifyEnabledUpdated(swapAndLiquifyEnabled); } function withdrawLockedEth(address payable recipient) external onlyManager(){ require(recipient != address(0), "Cannot withdraw the ETH balance to the zero address"); require(withdrawableBalance > 0, "The ETH balance must be greater than 0"); // prevent re-entrancy attacks uint256 amount = withdrawableBalance; withdrawableBalance = 0; recipient.transfer(amount); } /** * @dev Use this delegate instead of having (unnecessarily) extend `BaseRfiToken` to gained access * to the `_approve` function. */ function _approveDelegate(address owner, address spender, uint256 amount) internal virtual; } ////////////////////////////////////////////////////////////////////////// abstract contract Antiwhale is Tokenomics { function _getAntiwhaleFees(uint256, uint256) internal view returns (uint256){ return sumOfFees; } } ////////////////////////////////////////////////////////////////////////// abstract contract CynCoin is BaseRfiToken, Liquifier, Antiwhale { using SafeMath for uint256; // constructor(string memory _name, string memory _symbol, uint8 _decimals){ constructor(Env _env){ initializeLiquiditySwapper(_env, maxTransactionAmount, numberOfTokensToSwapToLiquidity); // exclude the pair address from rewards - we don't want to redistribute // tx fees to these two; redistribution is only for holders, dah! _exclude(_pair); _exclude(burnAddress); } function _isV2Pair(address account) internal view override returns(bool){ return (account == _pair); } function _getSumOfFees(address sender, uint256 amount) internal view override returns (uint256){ return _getAntiwhaleFees(balanceOf(sender), amount); } // function _beforeTokenTransfer(address sender, address recipient, uint256 amount, bool takeFee) internal override { function _beforeTokenTransfer(address sender, address , uint256 , bool ) internal override { if ( !isInPresale ){ uint256 contractTokenBalance = balanceOf(address(this)); liquify( contractTokenBalance, sender ); } } function _takeTransactionFees(uint256 amount, uint256 currentRate) internal override { if( isInPresale ){ return; } uint256 feesCount = _getFeesCount(); for (uint256 index = 0; index < feesCount; index++ ){ (FeeType name, uint256 value, address recipient,) = _getFee(index); // no need to check value < 0 as the value is uint (i.e. from 0 to 2^256-1) if ( value == 0 ) continue; if ( name == FeeType.Rfi ){ _redistribute( amount, currentRate, value, index ); } else if ( name == FeeType.Burn ){ _burn( amount, currentRate, value, index ); } else if ( name == FeeType.Antiwhale){ // TODO } else if ( name == FeeType.ExternalToETH){ _takeFeeToETH( amount, currentRate, value, recipient, index ); } else { _takeFee( amount, currentRate, value, recipient, index ); } } } function _burn(uint256 amount, uint256 currentRate, uint256 fee, uint256 index) private { uint256 tBurn = amount.mul(fee).div(FEES_DIVISOR); uint256 rBurn = tBurn.mul(currentRate); _burnTokens(address(this), tBurn, rBurn); _addFeeCollectedAmount(index, tBurn); } function _takeFee(uint256 amount, uint256 currentRate, uint256 fee, address recipient, uint256 index) private { uint256 tAmount = amount.mul(fee).div(FEES_DIVISOR); uint256 rAmount = tAmount.mul(currentRate); _reflectedBalances[recipient] = _reflectedBalances[recipient].add(rAmount); if(_isExcludedFromRewards[recipient]) _balances[recipient] = _balances[recipient].add(tAmount); _addFeeCollectedAmount(index, tAmount); } function _takeFeeToETH(uint256 amount, uint256 currentRate, uint256 fee, address recipient, uint256 index) private { _takeFee(amount, currentRate, fee, recipient, index); } function _approveDelegate(address owner, address spender, uint256 amount) internal override { _approve(owner, spender, amount); } } contract CynCoinV1 is CynCoin{ constructor() CynCoin(Env.MainnetV2){ // pre-approve the initial liquidity supply (to safe a bit of time) _approve(owner(),address(_router), ~uint256(0)); } }
if any account belongs to _isExcludedFromFee account then remove the fee
if(_isExcludedFromFee[sender] || _isExcludedFromFee[recipient]){ takeFee = false; }
923,587
[ 1, 430, 1281, 2236, 11081, 358, 389, 291, 16461, 1265, 14667, 2236, 1508, 1206, 326, 14036, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 3639, 309, 24899, 291, 16461, 1265, 14667, 63, 15330, 65, 747, 389, 291, 16461, 1265, 14667, 63, 20367, 5717, 95, 4862, 14667, 273, 629, 31, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.24; // File: openzeppelin-solidity/contracts/token/ERC20/IERC20.sol /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); event Transfer( address indexed from, address indexed to, uint256 value ); event Approval( address indexed owner, address indexed spender, uint256 value ); } // File: openzeppelin-solidity/contracts/math/SafeMath.sol /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring '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: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { function safeTransfer( IERC20 token, address to, uint256 value ) internal { require(token.transfer(to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { require(token.transferFrom(from, to, value)); } function safeApprove( IERC20 token, address spender, uint256 value ) internal { require(token.approve(spender, value)); } } // File: openzeppelin-solidity/contracts/crowdsale/Crowdsale.sol /** * @title Crowdsale * @dev Crowdsale is a base contract for managing a token crowdsale, * allowing investors to purchase tokens with ether. This contract implements * such functionality in its most fundamental form and can be extended to provide additional * functionality and/or custom behavior. * The external interface represents the basic interface for purchasing tokens, and conform * the base architecture for crowdsales. They are *not* intended to be modified / overridden. * The internal interface conforms the extensible and modifiable surface of crowdsales. Override * the methods to add functionality. Consider using 'super' where appropriate to concatenate * behavior. */ contract Crowdsale { using SafeMath for uint256; using SafeERC20 for IERC20; // The token being sold IERC20 private _token; // Address where funds are collected address private _wallet; // How many token units a buyer gets per wei. // The rate is the conversion between wei and the smallest and indivisible token unit. // So, if you are using a rate of 1 with a ERC20Detailed token with 3 decimals called TOK // 1 wei will give you 1 unit, or 0.001 TOK. uint256 private _rate; // Amount of wei raised uint256 private _weiRaised; /** * Event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokensPurchased( address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount ); /** * @param rate Number of token units a buyer gets per wei * @dev The rate is the conversion between wei and the smallest and indivisible * token unit. So, if you are using a rate of 1 with a ERC20Detailed token * with 3 decimals called TOK, 1 wei will give you 1 unit, or 0.001 TOK. * @param wallet Address where collected funds will be forwarded to * @param token Address of the token being sold */ constructor(uint256 rate, address wallet, IERC20 token) public { require(rate > 0); require(wallet != address(0)); require(token != address(0)); _rate = rate; _wallet = wallet; _token = token; } // ----------------------------------------- // Crowdsale external interface // ----------------------------------------- /** * @dev fallback function ***DO NOT OVERRIDE*** */ function () external payable { buyTokens(msg.sender); } /** * @return the token being sold. */ function token() public view returns(IERC20) { return _token; } /** * @return the address where funds are collected. */ function wallet() public view returns(address) { return _wallet; } /** * @return the number of token units a buyer gets per wei. */ function rate() public view returns(uint256) { return _rate; } /** * @return the mount of wei raised. */ function weiRaised() public view returns (uint256) { return _weiRaised; } /** * @dev low level token purchase ***DO NOT OVERRIDE*** * @param beneficiary Address performing the token purchase */ function buyTokens(address beneficiary) public payable { uint256 weiAmount = msg.value; _preValidatePurchase(beneficiary, weiAmount); // calculate token amount to be created uint256 tokens = _getTokenAmount(weiAmount); // update state _weiRaised = _weiRaised.add(weiAmount); _processPurchase(beneficiary, tokens); emit TokensPurchased( msg.sender, beneficiary, weiAmount, tokens ); _updatePurchasingState(beneficiary, weiAmount); _forwardFunds(); _postValidatePurchase(beneficiary, weiAmount); } // ----------------------------------------- // Internal interface (extensible) // ----------------------------------------- /** * @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. Use `super` in contracts that inherit from Crowdsale to extend their validations. * Example from CappedCrowdsale.sol's _preValidatePurchase method: * super._preValidatePurchase(beneficiary, weiAmount); * require(weiRaised().add(weiAmount) <= cap); * @param beneficiary Address performing the token purchase * @param weiAmount Value in wei involved in the purchase */ function _preValidatePurchase( address beneficiary, uint256 weiAmount ) internal { require(beneficiary != address(0)); require(weiAmount != 0); } /** * @dev Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid conditions are not met. * @param beneficiary Address performing the token purchase * @param weiAmount Value in wei involved in the purchase */ function _postValidatePurchase( address beneficiary, uint256 weiAmount ) internal { // optional override } /** * @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends its tokens. * @param beneficiary Address performing the token purchase * @param tokenAmount Number of tokens to be emitted */ function _deliverTokens( address beneficiary, uint256 tokenAmount ) internal { _token.safeTransfer(beneficiary, tokenAmount); } /** * @dev Executed when a purchase has been validated and is ready to be executed. Not necessarily emits/sends tokens. * @param beneficiary Address receiving the tokens * @param tokenAmount Number of tokens to be purchased */ function _processPurchase( address beneficiary, uint256 tokenAmount ) internal { _deliverTokens(beneficiary, tokenAmount); } /** * @dev Override for extensions that require an internal state to check for validity (current user contributions, etc.) * @param beneficiary Address receiving the tokens * @param weiAmount Value in wei involved in the purchase */ function _updatePurchasingState( address beneficiary, uint256 weiAmount ) internal { // optional override } /** * @dev Override to extend the way in which ether is converted to tokens. * @param weiAmount Value in wei to be converted into tokens * @return Number of tokens that can be purchased with the specified _weiAmount */ function _getTokenAmount(uint256 weiAmount) internal view returns (uint256) { return weiAmount.mul(_rate); } /** * @dev Determines how ETH is stored/forwarded on purchases. */ function _forwardFunds() internal { _wallet.transfer(msg.value); } } // File: openzeppelin-solidity/contracts/crowdsale/validation/TimedCrowdsale.sol /** * @title TimedCrowdsale * @dev Crowdsale accepting contributions only within a time frame. */ contract TimedCrowdsale is Crowdsale { using SafeMath for uint256; uint256 private _openingTime; uint256 private _closingTime; /** * @dev Reverts if not in crowdsale time range. */ modifier onlyWhileOpen { require(isOpen()); _; } /** * @dev Constructor, takes crowdsale opening and closing times. * @param openingTime Crowdsale opening time * @param closingTime Crowdsale closing time */ constructor(uint256 openingTime, uint256 closingTime) public { // solium-disable-next-line security/no-block-members require(openingTime >= block.timestamp); require(closingTime >= openingTime); _openingTime = openingTime; _closingTime = closingTime; } /** * @return the crowdsale opening time. */ function openingTime() public view returns(uint256) { return _openingTime; } /** * @return the crowdsale closing time. */ function closingTime() public view returns(uint256) { return _closingTime; } /** * @return true if the crowdsale is open, false otherwise. */ function isOpen() public view returns (bool) { // solium-disable-next-line security/no-block-members return block.timestamp >= _openingTime && block.timestamp <= _closingTime; } /** * @dev Checks whether the period in which the crowdsale is open has already elapsed. * @return Whether crowdsale period has elapsed */ function hasClosed() public view returns (bool) { // solium-disable-next-line security/no-block-members return block.timestamp > _closingTime; } /** * @dev Extend parent behavior requiring to be within contributing period * @param beneficiary Token purchaser * @param weiAmount Amount of wei contributed */ function _preValidatePurchase( address beneficiary, uint256 weiAmount ) internal onlyWhileOpen { super._preValidatePurchase(beneficiary, weiAmount); } } // File: openzeppelin-solidity/contracts/crowdsale/distribution/PostDeliveryCrowdsale.sol /** * @title PostDeliveryCrowdsale * @dev Crowdsale that locks tokens from withdrawal until it ends. */ contract PostDeliveryCrowdsale is TimedCrowdsale { using SafeMath for uint256; mapping(address => uint256) private _balances; /** * @dev Withdraw tokens only after crowdsale ends. * @param beneficiary Whose tokens will be withdrawn. */ function withdrawTokens(address beneficiary) public { require(hasClosed()); uint256 amount = _balances[beneficiary]; require(amount > 0); _balances[beneficiary] = 0; _deliverTokens(beneficiary, amount); } /** * @return the balance of an account. */ function balanceOf(address account) public view returns(uint256) { return _balances[account]; } /** * @dev Overrides parent by storing balances instead of issuing tokens right away. * @param beneficiary Token purchaser * @param tokenAmount Amount of tokens purchased */ function _processPurchase( address beneficiary, uint256 tokenAmount ) internal { _balances[beneficiary] = _balances[beneficiary].add(tokenAmount); } } // File: openzeppelin-solidity/contracts/crowdsale/distribution/FinalizableCrowdsale.sol /** * @title FinalizableCrowdsale * @dev Extension of Crowdsale with a one-off finalization action, where one * can do extra work after finishing. */ contract FinalizableCrowdsale is TimedCrowdsale { using SafeMath for uint256; bool private _finalized = false; event CrowdsaleFinalized(); /** * @return true if the crowdsale is finalized, false otherwise. */ function finalized() public view returns (bool) { return _finalized; } /** * @dev Must be called after crowdsale ends, to do some extra finalization * work. Calls the contract's finalization function. */ function finalize() public { require(!_finalized); require(hasClosed()); _finalization(); emit CrowdsaleFinalized(); _finalized = true; } /** * @dev Can be overridden to add finalization logic. The overriding function * should call super._finalization() to ensure the chain of finalization is * executed entirely. */ function _finalization() internal { } } // File: openzeppelin-solidity/contracts/ownership/Ownable.sol /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address 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. */ constructor() public { _owner = msg.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; } } // File: contracts/Whitelist.sol contract Whitelist is Ownable { mapping (address => bool) private whitelistedAddresses; mapping (address => bool) private admins; modifier onlyIfWhitelisted(address _addr) { require(whitelistedAddresses[_addr] == true, "Address not on the whitelist!"); _; } modifier onlyAdmins() { require(admins[msg.sender] == true || isOwner(), "Not an admin!"); _; } function addAdmin(address _addr) external onlyOwner { admins[_addr] = true; } function removeAdmin(address _addr) external onlyOwner { admins[_addr] = false; } function isAdmin(address _addr) public view returns(bool) { return admins[_addr]; } function addAddressToWhitelist(address _addr) public onlyAdmins { whitelistedAddresses[_addr] = true; } function whitelist(address _addr) public view returns(bool) { return whitelistedAddresses[_addr]; } function addAddressesToWhitelist(address[] _addrs) public onlyAdmins { for (uint256 i = 0; i < _addrs.length; i++) { addAddressToWhitelist(_addrs[i]); } } function removeAddressFromWhitelist(address _addr) public onlyAdmins { whitelistedAddresses[_addr] = false; } function removeAddressesFromWhitelist(address[] _addrs) public onlyAdmins { for (uint256 i = 0; i < _addrs.length; i++) { removeAddressFromWhitelist(_addrs[i]); } } } // File: contracts/ClarityCrowdsale.sol contract ClarityCrowdsale is Crowdsale, TimedCrowdsale, PostDeliveryCrowdsale, FinalizableCrowdsale, Whitelist { address private advisorWallet; // forward all phase one funds here uint256 private phaseOneRate; // rate for phase one uint256 private phaseTwoRate; // rate for phase teo uint256 private phaseOneTokens = 10000000 * 10**18; // tokens available in phase one uint256 private phaseTwoTokens = 30000000 * 10**18; // tokens available in phase two mapping (address => address) referrals; // Keep track of referrals for bonuses modifier onlyFounders() { require(msg.sender == super.wallet() || isOwner(), "Not a founder!"); _; } constructor( uint256 _phaseOneRate, uint256 _phaseTwoRate, address _advisorWallet, address _founderWallet, uint256 _openingTime, uint256 _closingTime, IERC20 _token ) Crowdsale(_phaseTwoRate, _founderWallet, _token) TimedCrowdsale(_openingTime, _closingTime) public { advisorWallet = _advisorWallet; phaseOneRate = _phaseOneRate; phaseTwoRate = _phaseTwoRate; } // overridden from Crowdsale parent contract function _getTokenAmount(uint256 weiAmount) internal view returns (uint256) { if (phaseOneTokens > 0) { uint256 tokens = weiAmount.mul(phaseOneRate); if (tokens > phaseOneTokens) { uint256 weiRemaining = tokens.sub(phaseOneTokens).div(phaseOneRate); tokens = phaseOneTokens.add(super._getTokenAmount(weiRemaining)); } return tokens; } return super._getTokenAmount(weiAmount); } // overridden from Crowdsale parent contract function _forwardFunds() internal { uint256 tokens; if (phaseOneTokens > 0) { tokens = msg.value.mul(phaseOneRate); if (tokens > phaseOneTokens) { uint256 weiRemaining = tokens.sub(phaseOneTokens).div(phaseOneRate); phaseOneTokens = 0; advisorWallet.transfer(msg.value.sub(weiRemaining)); tokens = weiRemaining.mul(phaseTwoRate); phaseTwoTokens = phaseTwoTokens.sub(tokens); super.wallet().transfer(weiRemaining); } else { phaseOneTokens = phaseOneTokens.sub(tokens); advisorWallet.transfer(msg.value); } return; } tokens = msg.value.mul(phaseTwoRate); phaseTwoTokens = phaseTwoTokens.sub(tokens); super._forwardFunds(); } // overridden from Crowdsale parent contract function _preValidatePurchase( address beneficiary, uint256 weiAmount ) internal onlyIfWhitelisted(beneficiary) { require(tokensLeft() >= _getTokenAmount(weiAmount), "Insufficient number of tokens to complete purchase!"); super._preValidatePurchase(beneficiary, weiAmount); } // overridden from Crowdsale parent contract function _finalization() internal onlyFounders { super.token().safeTransfer(super.wallet(), tokensLeft()); super._finalization(); } function tokensLeft() public view returns (uint256) { return phaseOneTokens + phaseTwoTokens; } function addReferral(address beneficiary, address referrer) external onlyAdmins onlyIfWhitelisted(referrer) onlyIfWhitelisted(beneficiary) { referrals[beneficiary] = referrer; } // overridden from Crowdsale parent contract function _processPurchase( address beneficiary, uint256 tokenAmount ) internal { if (referrals[beneficiary] != 0) { uint256 tokensAvailable = tokensLeft().sub(tokenAmount); uint256 bonus = tokenAmount.mul(15).div(100); if (bonus >= tokensAvailable) { bonus = tokensAvailable; phaseTwoTokens = phaseTwoTokens.sub(tokensAvailable); } else { phaseTwoTokens = phaseTwoTokens.sub(bonus); } if (bonus > 0) { super._processPurchase(referrals[beneficiary], bonus); } } super._processPurchase(beneficiary, tokenAmount); } }
rate for phase teo
uint256 private phaseTwoRate;
5,532,117
[ 1, 5141, 364, 6855, 268, 4361, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 2254, 5034, 3238, 6855, 11710, 4727, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.9; // ____ _ _ ____ ____ __ ___ __ ____ ____ _ _ // (_ _)/ )( \( __) / ___) / \ / __)( )( __)(_ _)( \/ ) // )( ) __ ( ) _) \___ \( O )( (__ )( ) _) )( ) / // (__) \_)(_/(____) (____/ \__/ \___)(__)(____) (__) (__/ // import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/interfaces/IERC721Receiver.sol"; import "@openzeppelin/contracts/interfaces/IERC2981.sol"; import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; // Society membership is captured in this contract. // // It is an NFT (ERC721) with a few custom enhancements: // // 1. Captcha Scheme // We use a captcha scheme to prevent bots from minting. // #isProbablyHuman() - matches a captcha signature signed elsewhere // // 2. Money-back Warranty // We promise your money back if we don't get enough members: // #withdraw() - locks the money unless there are >=2000 members // #refundFull(), - these return your money during refunding // #refundKeepArt() and they're enabled automatically after time has elapsed // // (see "Refund Warranty Process" below for more details) // // 3. Minting Limits // A single wallet may only mint 2 memberships. // // 4. Founding Team // During contract construction, we mint 7 memberships, // one for each member of the founding team and the first artist. // // 5. Member Migration // This contract is an improved edition of an earlier membership contract. // Early token holders can migrate into this and receive an additional token // for their continued loyalty. // // 6. Gold/Standard Tokens // The first 2,000 memberships will get a Gold token, these are // identified by having an ID number 1-2000. // // 7. Limited Sales Window // After the Feb. 18 sales deadline one of two things will happen: // - if there are <2,000 members, then refunds are enabled and the society winds down. // - if there are 2,000+ members, then membership is capped to the number already sold. // // Refund Warranty Process // // If 2,000+ memberships are sold by Feb 18 there are no refunds. // But if less than 2,000 are sold by Feb 18, then the refund // implementation operates within three phases: // // Phase 1: Jan 18 - Feb 18 // After contract creation, until the sales deadline or >2,000 sold, // all minting fees remain locked in the contract. // - The Society's #withdraw() is disabled // - Member's #refund...() are also disabled // // Phase 2: Feb 18 - Mar 18 // After the sales deadline (if <2,000 sold), until the refund deadline, // Members may claim a #refund...() for the sale price. // - The Society's #withdraw() is still disabled // - Member's #refund...() are now enabled // // Phase 3: after Mar 18 // After the refund deadline, Members can no longer claim a #refund...() // and The Society can #withdraw() any unrefunded fees. // - The Society's #withdraw() is enabled // - Member's #refund...() are disabled contract SocietyMember is ERC721, IERC2981, IERC721Receiver, Ownable, ReentrancyGuard { using ECDSA for bytes32; // This indicates what mode this contract is operating in. // See #updateMode() for implementation enum Mode { // Happy path: SellingPreThreshold, // before sales deadline < 2,000 sold SellingPostThreshold, // > 2,000 sold, < 5,000 sold SoldOut, // 5,000 sold (or 2,000+ sold after sales deadline) // Sad path: Refunding, // < 2,000 sold, after sales deadline before refund deadline ClosingAfterRefundPeriod // < 2,000 sold, after refund deadline } // This is the sale price of each membership. uint256 public constant SALE_PRICE = 0.15 ether; // This is the price of individual pieces of art. // NOTE: we only use this if people opt for partial refund. uint256 public constant ART_PRICE = 0.1 ether; // A single wallet may only mint 2 memberships. uint256 public constant MINTS_PER_WALLET = 2; // There can be only 5,000 members (2,000 gold). // However many memberships have been sold at the sales deadline, // that number becomes the new maximum total member count. uint256 public MAXIMUM_TOTAL_MEMBER_COUNT; uint256 public immutable MAXIMUM_GOLD_MEMBER_COUNT; // When members rollover a token from the original membership contract // they will receive 3 memberships. They receive 2 memberships immediately // and then receive a 3rd when the sales threshold is reached. // For each membership token, members also receives a piece of artwork. // This records where to send the token post-threshold. mapping(uint16 => address) private pendingTransfers; // Emitted when `tokenId` token is minted and pending transfer to `to`. event PendingTransfer(address indexed to, uint256 indexed tokenId); // This records the migrated token so the old refund can be claimed. mapping(uint16 => uint16) private pendingRefundTokens; // The old member contract is used to verify migration. IOldMember private oldMemberK; // There need to be 2,000 members to proceed. // NOTE: permanently fixed upon contract creation uint256 public immutable ENOUGH_MEMBERS_TO_PROCEED; // Sales must exceed 2,000 members for the Society to proceed. // If we fail to get 2,000 members then the first #refund() request // after this time will start refunding. // See note re "Refund Warrant Process" for more details. // NOTE: permanently fixed upon contract creation uint256 public immutable SALES_DEADLINE; // timestamp in seconds // If we fail to get 2,000 members then Members have until // this time to claim their #refund() // See note re "Refund Warrant Process" for more details. // NOTE: permanently fixed upon contract creation uint256 public immutable REFUND_DEADLINE; // timestamp in seconds // During contract construction, we mint 7 tokens, // one for each member of the founding team and the first artist. // NOTE: permanently fixed upon contract creation uint256 private immutable FOUNDING_TEAM_COUNT; // This indicates the current mode (selling, refunding etc) Mode public mode; // We generate the next token ID by incrementing these counters. // Gold tokens have an ID <= 2,000. uint16 private goldIds; // 1 - 2000 uint16 private standardIds; // 2001 - 5000 // This tracks mint counts to help limit mints per wallet. mapping(address => uint8) private mintCountsByAddress; // This tracks gold token count per owner. mapping(address => uint16) private goldBalances; // Minting membership includes an item from the initial art collection. IInitialArtSale private artSale; // This contains the base URI (e.g. "https://example.com/tokens/") // that is used to produce a URI for the metadata about // each token (e.g. "https://example.com/tokens/1234") string private baseURI; // For exchanges that support ERC2981, this sets our royalty rate. // NOTE: whereas "percent" is /100, this uses "per mille" which is /1000 uint256 private royaltyPerMille; // To combat bots, minting requests include a captcha signed elsewhere. // To verify the captcha, we compare its signature with this signer. address private captchaSigner; // To enable gas-free listings on OpenSea we integrate with the proxy registry. address private openSeaProxyRegistry; // The Society can disable gas-free listings in case OpenSea is compromised. bool private isOpenSeaProxyEnabled = true; struct Config { address[] foundingTeam; uint256 maximumTotalMemberCount; uint256 maximumGoldMemberCount; uint256 enoughMembersToProceed; uint256 salesDeadline; uint256 refundDeadline; uint256 royaltyPerMille; address captchaSigner; address openSeaProxyRegistry; IOldMember oldMemberK; } constructor(Config memory config) ERC721("Collector", "COLLECTOR") { require( config.enoughMembersToProceed <= config.maximumTotalMemberCount ); require( config.maximumGoldMemberCount <= config.maximumTotalMemberCount ); require(config.salesDeadline <= config.refundDeadline); MAXIMUM_TOTAL_MEMBER_COUNT = config.maximumTotalMemberCount; MAXIMUM_GOLD_MEMBER_COUNT = config.maximumGoldMemberCount; ENOUGH_MEMBERS_TO_PROCEED = config.enoughMembersToProceed; SALES_DEADLINE = config.salesDeadline; REFUND_DEADLINE = config.refundDeadline; royaltyPerMille = config.royaltyPerMille; captchaSigner = config.captchaSigner; openSeaProxyRegistry = config.openSeaProxyRegistry; oldMemberK = config.oldMemberK; mode = Mode.SellingPreThreshold; // Grant the founding team the first 7 tokens. FOUNDING_TEAM_COUNT = config.foundingTeam.length; for (uint256 i = 0; i < config.foundingTeam.length; i++) { _mint(config.foundingTeam[i], generateTokenId()); // NOTE: the accompanying art is minted later when we #setInitialArtSale(). } } // // Public Read Methods // // See how many memberships have been minted by the specified wallet. // NOTE: this is not the same as ownership function getMintCountByAddress(address minter_) external view returns (uint8) { return mintCountsByAddress[minter_]; } // How many gold tokens have been issued. function goldSupply() external view returns (uint256) { return goldIds; } // Returns the number of gold tokens held by `owner`. function goldBalanceOf(address owner) external view returns (uint256) { return goldBalances[owner]; } // // Public Write Methods // // This mints membership tokens to the sender. // Each token also includes a mint of artwork from the current collection. // It requires a `captcha` which is used to verify that // the sender is probably human and came here via our web flow. function mint(bytes memory captcha, uint8 numberOfTokens) external payable nonReentrant { require(numberOfTokens > 0, "missing number of tokens to mint"); updateMode(); require( mode == Mode.SellingPreThreshold || mode == Mode.SellingPostThreshold, "minting is not available" ); require( memberCount() + numberOfTokens <= MAXIMUM_TOTAL_MEMBER_COUNT, "not enough memberships remaining" ); require( msg.value == SALE_PRICE * numberOfTokens, "incorrect ETH payment amount" ); require(isProbablyHuman(captcha, msg.sender), "you seem like a robot"); uint8 mintCount = mintCountsByAddress[msg.sender]; require( mintCount + numberOfTokens <= MINTS_PER_WALLET, "you can only mint two memberships per wallet" ); mintCountsByAddress[msg.sender] = mintCount + numberOfTokens; for (uint256 i = 0; i < numberOfTokens; i++) { mintWithArt(msg.sender, generateTokenId()); } } // This mints 3 memberships for the user when they migrate the old token. // The first 2 memberships are transferred immediately along with 2 art pieces. // The 3rd token is marked as pending until reaching the sales threshold. function migrateMint(uint256[] memory oldTokenIds) external nonReentrant { updateMode(); require( mode == Mode.SellingPreThreshold || mode == Mode.SellingPostThreshold, "minting is not available" ); require( memberCount() + 3 * oldTokenIds.length <= MAXIMUM_TOTAL_MEMBER_COUNT, "not enough memberships remaining" ); require(oldTokenIds.length < 4, "migrating too many in a single call"); for (uint256 i = 0; i < oldTokenIds.length; i++) { uint256 oldTokenId = oldTokenIds[i]; require( oldTokenId > FOUNDING_TEAM_COUNT, "founding team tokens cannot migrate" ); // The first 2 tokens transfer immediately. oldMemberK.transferFrom(msg.sender, address(this), oldTokenId); mintFromOldWithArt(oldTokenId, msg.sender, generateTokenId()); mintFromOldWithArt(oldTokenId, msg.sender, generateTokenId()); // And we mint the 3rd token and record where it should eventually go. // It is transferred upon reaching the sales threshold. See #claimPending() uint256 pendingTokenId = generateTokenId(); _mint(address(this), pendingTokenId); pendingTransfers[uint16(pendingTokenId)] = msg.sender; emit PendingTransfer(msg.sender, pendingTokenId); } } // After reaching the sales threshold, this transfers the // pending 3rd token for migrated members. function claimPending(uint256[] memory tokenIds) external nonReentrant { updateMode(); require( mode == Mode.SellingPostThreshold || mode == Mode.SoldOut, "token remains pending until post-threshold" ); require(tokenIds.length < 8, "claiming too many in a single call"); for (uint256 i = 0; i < tokenIds.length; i++) { uint256 tokenId = tokenIds[i]; address to = pendingTransfers[uint16(tokenId)]; require(to != address(0), "token is not pending transfer"); pendingTransfers[uint16(tokenId)] = address(0); _transfer(address(this), to, tokenId); artSale.mintTo(to); } } // // Refund Options // If we fail to get >2,000 members members can call these to receive their ETH back. // During a refund, the member can decide what to do with the artwork they received during mint: // // refundFull: a member returns both their membership and the artwork they received. // The member receives a full refund (.15E). // // refundKeepArt: a member returns their membership but keeps the artwork. // The member receives the full price minus the art price (.15E - .1E = .05E) // // This lets a member return both their membership and the artwork they received. // The member receives a full refund (.15E). // NOTE: to receive the full refund, the member does NOT retain the artwork. // NOTE: after the sales deadline this is enabled automatically. function refundFull(uint256 memberTokenId, uint256 artTokenId) external nonReentrant { require( ownerOf(memberTokenId) == msg.sender, "only the owner may claim a refund" ); require( memberTokenId > FOUNDING_TEAM_COUNT, "founding team tokens do not get a refund" ); updateMode(); require(mode == Mode.Refunding, "refunding is not available"); claimAnyOldRefunds(memberTokenId); artSale.transferFrom(msg.sender, address(this), artTokenId); _burn(memberTokenId); payable(msg.sender).transfer(SALE_PRICE); } // This lets a member returns their membership but keeps the artwork. // The member receives the full price minus the art price (.15E - .1E = .05E) // NOTE: the amount refunded is reduced by the price of the artwork. // NOTE: after the sales deadline this is enabled automatically. function refundKeepArt(uint256 memberTokenId) external nonReentrant { require( ownerOf(memberTokenId) == msg.sender, "only the owner may claim a refund" ); require( memberTokenId > FOUNDING_TEAM_COUNT, "founding team tokens do not get a refund" ); updateMode(); require(mode == Mode.Refunding, "refunding is not available"); claimAnyOldRefunds(memberTokenId); _burn(memberTokenId); payable(msg.sender).transfer(SALE_PRICE - ART_PRICE); } // // Admin Methods // // This allows the Society to withdraw funds from the treasury. // NOTE: this is locked until there are at least 2,000 members. function withdraw() external onlyOwner { updateMode(); require( mode == Mode.SellingPostThreshold || mode == Mode.SoldOut || mode == Mode.ClosingAfterRefundPeriod, "locked until there are enough members (or after refund period)" ); uint256 balance = address(this).balance; payable(msg.sender).transfer(balance); } // This allows the Society to withdraw any received ERC20 tokens. // NOTE: This method exists to avoid the sad scenario where someone // accidentally sends tokens to this address and the tokens get stuck. function withdrawERC20Tokens(IERC20 token) external onlyOwner { uint256 balance = token.balanceOf(address(this)); token.transfer(msg.sender, balance); } // This allows the Society to withdraw any received ERC721 tokens. // NOTE: This method locks to secure old memberships used for refunds. // NOTE: This method also exists to avoid the sad scenario where someone // accidentally sends tokens to this address and the tokens get stuck. function withdrawERC721Token(IERC721 token, uint256 tokenId) external onlyOwner { updateMode(); require( mode == Mode.SellingPostThreshold || mode == Mode.SoldOut || mode == Mode.ClosingAfterRefundPeriod, "locked until there are enough members (or after refund period)" ); token.transferFrom(address(this), msg.sender, tokenId); } // The society can update the baseURI for metadata. // e.g. if there is a hosting change function setBaseURI(string memory uri) external onlyOwner { baseURI = uri; } // The society can update the ERC2981 royalty rate. // NOTE: whereas "percent" is /100, this uses "per mille" which is /1000 function setRoyalty(uint256 _royaltyPerMille) external onlyOwner { royaltyPerMille = _royaltyPerMille; } // The society can set the initial art sale. function setInitialArtSale(IInitialArtSale _artSale) external onlyOwner { require( address(artSale) == address(0), "initial art sale already specified" ); artSale = _artSale; // The art to accompany the founding team's memberships (#1..#7) can now be minted. for (uint256 i = 0; i < FOUNDING_TEAM_COUNT; i++) { artSale.mintTo(ownerOf(i + 1)); } } // The society can update the signer of the captcha used to secure #mint(). function setCaptchaSigner(address _captchaSigner) external onlyOwner { captchaSigner = _captchaSigner; } // The society can disable gas-less listings for security in case OpenSea is compromised. function setOpenSeaProxyEnabled(bool isEnabled) external onlyOwner { isOpenSeaProxyEnabled = isEnabled; } // // Interface Override Methods // // The membership contract can receive ETH deposits. receive() external payable {} // The membership contract can receive ERC721 tokens. // See IERC721Receiver function onERC721Received( address, address, uint256, bytes calldata ) public virtual override returns (bytes4) { return this.onERC721Received.selector; } // This hooks into the ERC721 implementation // it is used by `tokenURI(..)` to produce the full thing. function _baseURI() internal view override returns (string memory) { return baseURI; } /// /// IERC2981 Implementation /// /** * @dev See {IERC2981-royaltyInfo}. * This exposes the ERC2981 royalty rate. */ function royaltyInfo(uint256 tokenId, uint256 salePrice) external view returns (address receiver, uint256 royaltyAmount) { require(_exists(tokenId), "not a valid token"); return (owner(), (salePrice * royaltyPerMille) / 1000); } /// /// IERC721Enumerable Implementation (partial) /// NOTE: to reduce gas costs, we don't implement tokenOfOwnerByIndex() /// /** * @dev See {IERC721Enumerable-totalSupply}. * Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256) { return memberCount(); } /** * @dev See {IERC721Enumerable-tokenByIndex}. * 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) { if (_index >= goldIds) { _index = MAXIMUM_GOLD_MEMBER_COUNT + (goldIds - _index); } require(_exists(_index + 1), "bad token index"); return _index + 1; } // This hooks into transfers to track gold balances. function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { if (tokenId > MAXIMUM_GOLD_MEMBER_COUNT) { // We only do the extra bookkeeping // when a gold token is being transferred. return; } if (from != address(0)) { goldBalances[from] -= 1; } if (to != address(0)) { goldBalances[to] += 1; } } // This hooks into approvals to allow gas-free listings on OpenSea. function isApprovedForAll(address owner, address operator) public view override returns (bool) { if (isOpenSeaProxyEnabled) { ProxyRegistry registry = ProxyRegistry(openSeaProxyRegistry); if (address(registry.proxies(owner)) == operator) { return true; } } return super.isApprovedForAll(owner, operator); } /// /// IERC165 Implementation /// /** * @dev See {IERC165-supportsInterface}. * This implements ERC165 which announces our other supported interfaces: * - ERC2981 (royalty info) */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { if (interfaceId == type(IERC2981).interfaceId) { return true; } // NOTE: we don't include IERC721Enumerable // because ours is only a partial implementation. return super.supportsInterface(interfaceId); } // // Private Helper Methods // // This tries to prevent robots from minting a membership. // The `captcha` contains a signature (generated via web captcha flow) // that was made using the Society's private key. // // This method checks the signature to see: // - if it was signed by the Society's key and // - if it was for the current msg.sender function isProbablyHuman(bytes memory captcha, address sender) private view returns (bool) { // First we recreate the same message that was originally signed. // This is equivalent to how we created it elsewhere: // message = ethers.utils.solidityKeccak256( // ["string", "address"], // ["member", sender]); bytes32 message = keccak256(abi.encodePacked("member", sender)); // Now we can see who actually signed it address signer = message.toEthSignedMessageHash().recover(captcha); // And finally check if the signer was us! return signer == captchaSigner; } // This updates the current mode based on the member count and the time. // The contract calls this before any use of the current mode. // See "Refund Warranty Process" above for more details. function updateMode() private { if (mode == Mode.SoldOut) { // After selling out, the mode cannot change. return; } uint256 count = memberCount(); // After the sales deadline, the total supply is fixed to the number sold. if ( block.timestamp >= SALES_DEADLINE && count >= ENOUGH_MEMBERS_TO_PROCEED ) { MAXIMUM_TOTAL_MEMBER_COUNT = count; } // Update the mode based on the sales count and time. if (count >= MAXIMUM_TOTAL_MEMBER_COUNT) { mode = Mode.SoldOut; } else if (count >= ENOUGH_MEMBERS_TO_PROCEED) { mode = Mode.SellingPostThreshold; } else { // count < enoughMembersToProceed // When there are not enough members to proceed // then the mode depends on the time. if (block.timestamp < SALES_DEADLINE) { // Before sales deadline mode = Mode.SellingPreThreshold; } else if (block.timestamp < REFUND_DEADLINE) { // After sales deadline, before refund deadline mode = Mode.Refunding; } else { // block.timestamp >= refundDeadline // After the refund deadline mode = Mode.ClosingAfterRefundPeriod; } } } // Create the next token ID to be used. // This is complicated because we shuffle between two ID ranges: // 1-2000 -> gold // 2001-5000 -> standard // So if there are gold remaining then we use the gold IDs. // Otherwise we use the standard IDs. function generateTokenId() private returns (uint256) { if (goldIds < MAXIMUM_GOLD_MEMBER_COUNT) { goldIds += 1; return goldIds; } standardIds += 1; return standardIds + MAXIMUM_GOLD_MEMBER_COUNT; } // Compute the total member count. function memberCount() private view returns (uint256) { return goldIds + standardIds; } // This claims any old pending refund to cover the refund of this `memberTokenId`. function claimAnyOldRefunds(uint256 memberTokenId) private { uint16 oldMemberTokenId = pendingRefundTokens[uint16(memberTokenId)]; if (oldMemberTokenId != 0) { try oldMemberK.refund(oldMemberTokenId) {} catch (bytes memory) {} } } // This actually mints `memberTokenId` to `to` along with a piece of artwork. function mintWithArt(address to, uint256 memberTokenId) private { _safeMint(to, memberTokenId); artSale.mintTo(to); } // This actually mints `memberTokenId` to `to` along with a piece of artwork. // It also associates the minted `memberTokenId` with a pending refund for `oldMemberTokenId` function mintFromOldWithArt( uint256 oldMemberTokenId, address to, uint256 memberTokenId ) private { pendingRefundTokens[uint16(memberTokenId)] = uint16(oldMemberTokenId); mintWithArt(to, memberTokenId); } } // This is the interface to the old membership contract. interface IOldMember is IERC721 { // This allows the membership contract to claim the refund for migrated tokens. function refund(uint256 tokenId) external; } // This is the interface to the ongoing art sale. interface IInitialArtSale is IERC721 { // This allows the membership contract to mint artwork to a new member. function mintTo(address to) external payable; } // These types define our interface to the OpenSea proxy registry. // We use these to support gas-free listings. contract OwnableDelegateProxy { } contract ProxyRegistry { mapping(address => OwnableDelegateProxy) public proxies; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../token/ERC721/IERC721Receiver.sol"; // SPDX-License-Identifier: 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); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { enum RecoverError { NoError, InvalidSignature, InvalidSignatureLength, InvalidSignatureS, InvalidSignatureV } function _throwError(RecoverError error) private pure { if (error == RecoverError.NoError) { return; // no error: do nothing } else if (error == RecoverError.InvalidSignature) { revert("ECDSA: invalid signature"); } else if (error == RecoverError.InvalidSignatureLength) { revert("ECDSA: invalid signature length"); } else if (error == RecoverError.InvalidSignatureS) { revert("ECDSA: invalid signature 's' value"); } else if (error == RecoverError.InvalidSignatureV) { revert("ECDSA: invalid signature 'v' value"); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature` or error string. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. * * Documentation for signature generation: * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js] * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers] * * _Available since v4.3._ */ function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) { // Check the signature length // - case 65: r,s,v signature (standard) // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._ if (signature.length == 65) { bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return tryRecover(hash, v, r, s); } else if (signature.length == 64) { bytes32 r; bytes32 vs; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) vs := mload(add(signature, 0x40)) } return tryRecover(hash, r, vs); } else { return (address(0), RecoverError.InvalidSignatureLength); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, signature); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately. * * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures] * * _Available since v4.3._ */ function tryRecover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address, RecoverError) { bytes32 s; uint8 v; assembly { s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) v := add(shr(255, vs), 27) } return tryRecover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately. * * _Available since v4.2._ */ function recover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, r, vs); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `v`, * `r` and `s` signature fields separately. * * _Available since v4.3._ */ function tryRecover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address, RecoverError) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return (address(0), RecoverError.InvalidSignatureS); } if (v != 27 && v != 28) { return (address(0), RecoverError.InvalidSignatureV); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); if (signer == address(0)) { return (address(0), RecoverError.InvalidSignature); } return (signer, RecoverError.NoError); } /** * @dev Overload of {ECDSA-recover} that receives the `v`, * `r` and `s` signature fields separately. */ function recover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, v, r, s); _throwError(error); return recovered; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } /** * @dev Returns an Ethereum Signed Typed Data, created from a * `domainSeparator` and a `structHash`. This produces hash corresponding * to the one signed with the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] * JSON-RPC method as part of EIP-712. * * See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/introspection/IERC165.sol";
How many gold tokens have been issued.
function goldSupply() external view returns (uint256) { return goldIds; }
13,491,980
[ 1, 44, 543, 4906, 20465, 2430, 1240, 2118, 16865, 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, 20465, 3088, 1283, 1435, 3903, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 20465, 2673, 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 ]
./partial_match/11155111/0x9598CDF255589C86F5ef6ff7A96Ce87D8E04F9e0/sources/src/Bridge.sol
Set the minting fee @param fee_ New minting fee @dev Only addresses with ADMIN_ROLE can call this
function setFee(uint256 fee_) public onlyRole(ADMIN_ROLE) { fee = fee_; }
3,533,257
[ 1, 694, 326, 312, 474, 310, 14036, 225, 14036, 67, 1166, 312, 474, 310, 14036, 225, 5098, 6138, 598, 25969, 67, 16256, 848, 745, 333, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 444, 14667, 12, 11890, 5034, 14036, 67, 13, 1071, 1338, 2996, 12, 15468, 67, 16256, 13, 288, 203, 3639, 14036, 273, 14036, 67, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/3/0x133547ee5274CF42eF01Dd3bca7a01ac6f9a6BbF/sources/browser/BCP.sol
(commitmentID-17)
commitments.push(Commitment(4, uint32(now + 60 days), 500 szabo, uint64(12*gwei), 0x0));
14,246,056
[ 1, 12, 7371, 475, 734, 17, 4033, 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, 3639, 3294, 1346, 18, 6206, 12, 5580, 475, 12, 24, 16, 2254, 1578, 12, 3338, 397, 4752, 4681, 3631, 6604, 11262, 378, 83, 16, 2254, 1105, 12, 2138, 14, 75, 1814, 77, 3631, 374, 92, 20, 10019, 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 ]
./full_match/5/0xF5f1648C7c93EDF0a5A82689eb4C793245BE481c/sources/contracts/test.sol
Calculate total giveaway amountCheck conditionsCheck token price Generate random addresses
function startGiveaway() external { require(giveawayIndex == 0, "Giveaway already started"); uint256 totalAmount = _giveawayAmount * _giveawayDuration; require(totalAmount < (_totalSupply * 1) / 100, "Giveaway exceeds 1% of liquidity"); require(totalAmount < (_totalSupply * 3) / 100, "Giveaway exceeds 3% of token buyback amount"); require(getPrice() < 50 ether, "Token price is not less than $50"); _giveawayWallet = 0xAf142c957dfdB0023f99f4D7b6B7651cfF4ee954; for (uint256 i = 0; i < _giveawayDuration; i++) { address[] memory addresses = new address[](5); for (uint256 j = 0; j < 5; j++) { addresses[j] = address(uint160(uint256(keccak256(abi.encodePacked(giveawayIndex, i, j))))); } giveawayAddresses[giveawayIndex] = addresses; giveawayIndex++; } }
1,860,610
[ 1, 8695, 2078, 8492, 26718, 3844, 1564, 4636, 1564, 1147, 6205, 6654, 2744, 6138, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 787, 43, 688, 26718, 1435, 3903, 225, 288, 203, 1377, 2583, 12, 75, 688, 26718, 1016, 422, 374, 16, 315, 43, 688, 26718, 1818, 5746, 8863, 203, 203, 1377, 2254, 5034, 2078, 6275, 273, 389, 75, 688, 26718, 6275, 380, 389, 75, 688, 26718, 5326, 31, 203, 203, 1377, 2583, 12, 4963, 6275, 411, 261, 67, 4963, 3088, 1283, 380, 404, 13, 342, 2130, 16, 315, 43, 688, 26718, 14399, 404, 9, 434, 4501, 372, 24237, 8863, 203, 1377, 2583, 12, 4963, 6275, 411, 261, 67, 4963, 3088, 1283, 380, 890, 13, 342, 2130, 16, 315, 43, 688, 26718, 14399, 890, 9, 434, 1147, 30143, 823, 3844, 8863, 203, 203, 1377, 2583, 12, 588, 5147, 1435, 411, 6437, 225, 2437, 16, 315, 1345, 6205, 353, 486, 5242, 2353, 271, 3361, 8863, 203, 203, 377, 389, 75, 688, 26718, 16936, 273, 374, 92, 12664, 29126, 71, 8778, 27, 2180, 72, 38, 713, 4366, 74, 2733, 74, 24, 40, 27, 70, 26, 38, 6669, 10593, 8522, 42, 24, 1340, 29, 6564, 31, 203, 203, 3639, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 389, 75, 688, 26718, 5326, 31, 277, 27245, 288, 203, 5411, 1758, 8526, 3778, 6138, 273, 394, 1758, 8526, 12, 25, 1769, 203, 5411, 364, 261, 11890, 5034, 525, 273, 374, 31, 525, 411, 1381, 31, 525, 27245, 288, 203, 7734, 6138, 63, 78, 65, 273, 1758, 12, 11890, 16874, 12, 11890, 5034, 12, 79, 24410, 581, 5034, 12, 21457, 18, 3015, 4420, 329, 12, 75, 688, 26718, 1016, 2 ]
// File: @openzeppelin\contracts\token\ERC20\IERC20.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: node_modules\@openzeppelin\contracts\math\SafeMath.sol pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: node_modules\@openzeppelin\contracts\utils\Address.sol pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin\contracts\token\ERC20\SafeERC20.sol pragma solidity ^0.6.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File: @openzeppelin\contracts\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)); } } // File: node_modules\@openzeppelin\contracts\GSN\Context.sol pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin\contracts\access\Ownable.sol pragma solidity ^0.6.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: @openzeppelin\contracts\token\ERC20\ERC20.sol pragma solidity ^0.6.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 guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // File: contracts\ZEUSToken.sol pragma solidity 0.6.12; // ZEUSToken with Governance. contract ZEUSToken is ERC20("ZEUSV2Token", "ZEUSV2"), Ownable { /// @notice Creates `_amount` token to `_to`. Must only be called by the owner (MasterChef). function mint(address _to, uint256 _amount) public onlyOwner { _mint(_to, _amount); _moveDelegates(address(0), _delegates[_to], _amount); } function burn(address _from, uint256 _amount) public onlyOwner { _burn(_from, _amount); } // Copied and modified from YAM code: // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol // Which is copied and modified from COMPOUND: // https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol /// @notice A record of each accounts delegate mapping (address => address) internal _delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint256 votes; } /// @notice A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @notice A record of states for signing / validating signatures mapping (address => uint) public nonces; /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegator The address to get delegatee for */ function delegates(address delegator) external view returns (address) { return _delegates[delegator]; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) external { return _delegate(msg.sender, delegatee); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig( address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s ) 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), "ZEUSV2::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "ZEUSV2::delegateBySig: invalid nonce"); require(now <= expiry, "ZEUSV2::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint256) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint blockNumber) external view returns (uint256) { require(blockNumber < block.number, "ZEUSV2::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = _delegates[delegator]; uint256 delegatorBalance = balanceOf(delegator); // balance of underlying ZEUSs (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 uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld.sub(amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { // increase new representative uint32 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes ) internal { uint32 blockNumber = safe32(block.number, "ZEUSV2::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function getChainId() internal pure returns (uint) { uint256 chainId; assembly { chainId := chainid() } return chainId; } } // File: contracts\zeusmain.sol pragma solidity 0.6.12; interface IMigratorChef { // Perform LP token migration from legacy UniswapV2 to ZEUSSwap. // Take the current LP token address and return the new LP token address. // Migrator should have full access to the caller's LP token. // Return the new LP token address. // // XXX Migrator must have allowance access to UniswapV2 LP tokens. // ZEUSSwap must mint EXACTLY the same amount of ZEUSSwap LP tokens or // else something bad will happen. Traditional UniswapV2 does not // do that so be careful! function migrate(IERC20 token) external returns (IERC20); } // ZEUSMain is the master of ZEUS. He can make ZEUS and he is a fair guy. // // Note that it's ownable and the owner wields tremendous power. The ownership // will be transferred to a governance smart contract once ZEUS is sufficiently // distributed and the community can show to govern itself. // // Have fun reading it. Hopefully it's bug-free. God bless. contract ZEUSMain is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of ZEUSs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accZEUSPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accZEUSPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. bool bChange; // if true锛宎llocPoint changed by bool bLock; // if true锛宼he pool be locked bool bDepositFee; // uint256 depositMount; // uint256 changeMount; // uint256 allocPoint; // How many allocation points assigned to this pool. ZEUSs to distribute per block. uint256 lastRewardBlock; // Last block number that ZEUSs distribution occurs. uint256 accZEUSPerShare; // Accumulated ZEUSs per share, times 1e12. See below. } struct AreaInfo { uint256 totalAllocPoint; uint256 rate; } // The ZEUS TOKEN! ZEUSToken public zeus; ZEUSToken public zeusOld; // Dev address. address public devaddr; // min per block mint uint256 public minPerBlock; // ZEUS tokens created per block. uint256 public zeusPerBlock; uint256 public halfPeriod; uint256 public lockPeriods; // lock periods // The migrator contract. It has a lot of power. Can only be set through governance (owner). IMigratorChef public migrator; // Info of each pool. //PoolInfo[] public poolInfo; mapping (uint256 => PoolInfo[]) public poolInfo; // Info of each user that stakes LP tokens. //mapping (uint256 => mapping (address => UserInfo)) public userInfo; mapping (uint256 => 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; AreaInfo[] public areaInfo; uint256 public totalRate = 0; // The block number when ZEUS mining starts. uint256 public startBlock; uint256 public permitExpired; event Deposit(address indexed user, uint256 indexed aid, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed aid, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed aid, uint256 indexed pid, uint256 amount); constructor( ZEUSToken _zeus, ZEUSToken _zeusOld, address _devaddr, uint256 _zeusPerBlock, uint256 _startBlock, uint256 _minPerBlock, uint256 _halfPeriod, uint256 _lockPeriods, uint256 _permitExpired ) public { zeus = _zeus; zeusOld = _zeusOld; devaddr = _devaddr; zeusPerBlock = _zeusPerBlock; minPerBlock = _minPerBlock; startBlock = _startBlock; halfPeriod = _halfPeriod; lockPeriods = _lockPeriods; permitExpired = _permitExpired; } function buyBackToken(address payable buybackaddr) public onlyOwner { require(buybackaddr != address(0), "buy back is addr 0"); buybackaddr.transfer(address(this).balance); } function areaLength() external view returns (uint256) { return areaInfo.length; } function poolLength(uint256 _aid) external view returns (uint256) { return poolInfo[_aid].length; } function addArea(uint256 _rate, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdateAreas(); } totalRate = totalRate.add(_rate); areaInfo.push(AreaInfo({ totalAllocPoint: 0, rate: _rate })); } // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add(uint256 _aid, uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate, bool _bChange, uint256 _changeMount, bool _bLock, bool _bDepositFee, uint256 _depositFee) public onlyOwner { if (_withUpdate) { massUpdatePools(_aid); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; areaInfo[_aid].totalAllocPoint = areaInfo[_aid].totalAllocPoint.add(_allocPoint); poolInfo[_aid].push(PoolInfo({ lpToken: _lpToken, bChange: _bChange, bLock: _bLock, bDepositFee: _bDepositFee, depositMount: _depositFee, changeMount: _changeMount, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accZEUSPerShare: 0 })); } function setArea(uint256 _aid, uint256 _rate, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdateAreas(); } totalRate = totalRate.sub(areaInfo[_aid].rate).add(_rate); areaInfo[_aid].rate = _rate; } // Update the given pool's zeus allocation point. Can only be called by the owner. function set(uint256 _aid, uint256 _pid, uint256 _allocPoint, bool _withUpdate, bool _bChange, uint256 _changeMount, bool _bLock, bool _bDepositFee, uint256 _depositFee) public onlyOwner { if (_withUpdate) { massUpdatePools(_aid); } areaInfo[_aid].totalAllocPoint = areaInfo[_aid].totalAllocPoint.sub(poolInfo[_aid][_pid].allocPoint).add(_allocPoint); poolInfo[_aid][_pid].allocPoint = _allocPoint; poolInfo[_aid][_pid].bChange = _bChange; poolInfo[_aid][_pid].bLock = _bLock; poolInfo[_aid][_pid].changeMount = _changeMount; poolInfo[_aid][_pid].bDepositFee = _bDepositFee; poolInfo[_aid][_pid].depositMount = _depositFee; } // Set the migrator contract. Can only be called by the owner. function setMigrator(IMigratorChef _migrator) public onlyOwner { migrator = _migrator; } // Migrate lp token to another lp contract. Can be called by anyone. We trust that migrator contract is good. function migrate(uint256 _aid, uint256 _pid) public { require(address(migrator) != address(0), "migrate: no migrator"); PoolInfo storage pool = poolInfo[_aid][_pid]; IERC20 lpToken = pool.lpToken; uint256 bal = lpToken.balanceOf(address(this)); lpToken.safeApprove(address(migrator), bal); IERC20 newLpToken = migrator.migrate(lpToken); require(bal == newLpToken.balanceOf(address(this)), "migrate: bad"); pool.lpToken = newLpToken; } // Reduce by 50% per halfPeriod blocks. function getBlockReward(uint256 number) public view returns (uint256) { if (number < startBlock){ return 0; } uint256 mintBlocks = number.sub(startBlock); uint256 exp = mintBlocks.div(halfPeriod); if (exp == 0) return 100000000000000000000; if (exp == 1) return 80000000000000000000; if (exp == 2) return 60000000000000000000; if (exp == 3) return 40000000000000000000; if (exp == 4) return 20000000000000000000; if (exp == 5) return 10000000000000000000; if (exp == 6) return 8000000000000000000; if (exp == 7) return 6000000000000000000; if (exp == 8) return 4000000000000000000; if (exp == 9) return 2000000000000000000; if (exp >= 10) return 1000000000000000000; // uint256 blockReward = zeusPerBlock.mul(5 ** exp).div(10 ** exp); // blockReward = blockReward > minPerBlock ? blockReward : minPerBlock; // if(blockReward > 0 && blockReward <= htcPerBlock){ // return blockReward; // } return 0; } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { if(_from < startBlock){ _from = startBlock; } if(_from >= _to){ return 0; } uint256 blockReward1 = getBlockReward(_from); uint256 blockReward2 = getBlockReward(_to); uint256 blockGap = _to.sub(_from); if(blockReward1 != blockReward2){ uint256 blocks2 = _to.mod(halfPeriod); if (blockGap < blocks2) { return 0; } uint256 blocks1 = blockGap > blocks2 ? blockGap.sub(blocks2): 0; return blocks1.mul(blockReward1).add(blocks2.mul(blockReward2)); } return blockGap.mul(blockReward1); } // View function to see pending ZEUSs on frontend. function pendingZEUS(uint256 _aid, uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_aid][_pid]; UserInfo storage user = userInfo[_aid][_pid][_user]; uint256 accZEUSPerShare = pool.accZEUSPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 ZEUSReward = multiplier.mul(pool.allocPoint).div(areaInfo[_aid].totalAllocPoint); accZEUSPerShare = accZEUSPerShare.add((ZEUSReward.mul(1e12).div(lpSupply)).mul(areaInfo[_aid].rate).div(totalRate)); } return user.amount.mul(accZEUSPerShare).div(1e12).sub(user.rewardDebt); } function massUpdateAreas() public { uint256 length = areaInfo.length; for (uint256 aid = 0; aid < length; ++aid) { massUpdatePools(aid); } } // Update reward variables for all pools. Be careful of gas spending! function massUpdatePools(uint256 _aid) public { uint256 length = poolInfo[_aid].length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(_aid, pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _aid, uint256 _pid) public { PoolInfo storage pool = poolInfo[_aid][_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); if (multiplier == 0) return; uint256 zeusReward = multiplier.mul(pool.allocPoint).div(areaInfo[_aid].totalAllocPoint).mul(areaInfo[_aid].rate).div(totalRate); zeus.mint(devaddr, zeusReward.div(20)); zeus.mint(address(this), zeusReward); pool.accZEUSPerShare = pool.accZEUSPerShare.add((zeusReward.mul(1e12).div(lpSupply))); pool.lastRewardBlock = block.number; } // Deposit LP tokens to ZEUSMain for ZEUS allocation. function deposit(uint256 _aid, uint256 _pid, uint256 _amount) payable public { PoolInfo storage pool = poolInfo[_aid][_pid]; UserInfo storage user = userInfo[_aid][_pid][msg.sender]; if (_amount > 0){ require((pool.bDepositFee == false) || (pool.bDepositFee == true && msg.value == pool.depositMount), "deposit: not enough"); } updatePool(_aid, _pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accZEUSPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeZEUSTransfer(msg.sender, pending); } } else { if (pool.bChange == true) { pool.allocPoint += pool.changeMount; areaInfo[_aid].totalAllocPoint += pool.changeMount; } } if(_amount > 0) { pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); } user.rewardDebt = user.amount.mul(pool.accZEUSPerShare).div(1e12); emit Deposit(msg.sender, _aid, _pid, _amount); } // Withdraw LP tokens from ZEUSMain. function withdraw(uint256 _aid, uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_aid][_pid]; UserInfo storage user = userInfo[_aid][_pid][msg.sender]; require((pool.bLock == false) || (pool.bLock && (block.number >= (startBlock.add(lockPeriods)))), "withdraw: pool lock"); require(user.amount >= _amount, "withdraw: not good"); updatePool(_aid, _pid); uint256 pending = user.amount.mul(pool.accZEUSPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeZEUSTransfer(msg.sender, pending); } if(_amount > 0) { user.amount = user.amount.sub(_amount); pool.lpToken.safeTransfer(address(msg.sender), _amount); } if (user.amount == 0) { if (pool.bChange == true) { uint256 changenum = pool.allocPoint > pool.changeMount ? pool.changeMount : 0; pool.allocPoint = pool.allocPoint.sub(changenum); areaInfo[_aid].totalAllocPoint = areaInfo[_aid].totalAllocPoint.sub(changenum); } } user.rewardDebt = user.amount.mul(pool.accZEUSPerShare).div(1e12); emit Withdraw(msg.sender, _aid, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _aid, uint256 _pid) public { PoolInfo storage pool = poolInfo[_aid][_pid]; UserInfo storage user = userInfo[_aid][_pid][msg.sender]; require((pool.bLock == false) || (pool.bLock && (block.number >= (startBlock.add(lockPeriods)))), "withdraw: pool lock"); pool.lpToken.safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, _aid, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; if (pool.bChange == true) { uint256 changenum = pool.allocPoint > pool.changeMount ? pool.changeMount : 0; pool.allocPoint = pool.allocPoint.sub(changenum); areaInfo[_aid].totalAllocPoint = areaInfo[_aid].totalAllocPoint.sub(changenum); } } function exchangeZeusV2(uint256 _amount) public { require(_amount > 0, "exchange: not good"); zeusOld.transferFrom(address(msg.sender), address(this), _amount); zeus.mint(address(msg.sender), _amount); } function setPollInfo(uint256 _aid, uint256 _pid, uint256 _lastRewardBlock, uint256 _accZEUSPerShare) public onlyOwner { require(block.number < (permitExpired + startBlock), "setPoolInfo: expired"); PoolInfo storage pool = poolInfo[_aid][_pid]; pool.lastRewardBlock = _lastRewardBlock; pool.accZEUSPerShare = _accZEUSPerShare; } function setUserInfo(uint256 _aid, uint256 _pid, address _useraddr, uint256 _amount, uint256 _rewardDebt) public onlyOwner { require(block.number < (permitExpired + startBlock), "setUserInfo: expired"); UserInfo storage user = userInfo[_aid][_pid][_useraddr]; user.amount = _amount; user.rewardDebt = _rewardDebt; } function safeBurn(address _from, uint256 _amount) public onlyOwner { require(_amount > 0, "burn: not good"); zeus.burn(_from, _amount); } function transferTokenOwnerShip(address _newowner) public onlyOwner{ zeus.transferOwnership(_newowner); } // Safe ZEUS transfer function, just in case if rounding error causes pool to not have enough ZEUSs. function safeZEUSTransfer(address _to, uint256 _amount) internal { uint256 ZEUSBal = zeus.balanceOf(address(this)); if (_amount > ZEUSBal) { zeus.transfer(_to, ZEUSBal); } else { zeus.transfer(_to, _amount); } } // Update dev address by the previous dev. function dev(address _devaddr) public { require(msg.sender == devaddr, "dev: wut?"); devaddr = _devaddr; } }
ZEUSToken with Governance.
contract ZEUSToken is ERC20("ZEUSV2Token", "ZEUSV2"), Ownable { function mint(address _to, uint256 _amount) public onlyOwner { _mint(_to, _amount); _moveDelegates(address(0), _delegates[_to], _amount); } function burn(address _from, uint256 _amount) public onlyOwner { _burn(_from, _amount); } mapping (address => address) internal _delegates; struct Checkpoint { uint32 fromBlock; uint256 votes; } mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; mapping (address => uint32) public numCheckpoints; bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); mapping (address => uint) public nonces; event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); function delegates(address delegator) external view returns (address) { return _delegates[delegator]; } function delegate(address delegatee) external { return _delegate(msg.sender, delegatee); } 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), "ZEUSV2::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "ZEUSV2::delegateBySig: invalid nonce"); require(now <= expiry, "ZEUSV2::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } function getCurrentVotes(address account) external view returns (uint256) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } function getPriorVotes(address account, uint blockNumber) external view returns (uint256) { require(blockNumber < block.number, "ZEUSV2::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; lower = center; upper = center - 1; } } return checkpoints[account][lower].votes; } function getPriorVotes(address account, uint blockNumber) external view returns (uint256) { require(blockNumber < block.number, "ZEUSV2::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; lower = center; upper = center - 1; } } return checkpoints[account][lower].votes; } function getPriorVotes(address account, uint blockNumber) external view returns (uint256) { require(blockNumber < block.number, "ZEUSV2::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; lower = center; upper = center - 1; } } return checkpoints[account][lower].votes; } function getPriorVotes(address account, uint blockNumber) external view returns (uint256) { require(blockNumber < block.number, "ZEUSV2::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; lower = center; upper = center - 1; } } return checkpoints[account][lower].votes; } function getPriorVotes(address account, uint blockNumber) external view returns (uint256) { require(blockNumber < block.number, "ZEUSV2::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; lower = center; upper = center - 1; } } return checkpoints[account][lower].votes; } function getPriorVotes(address account, uint blockNumber) external view returns (uint256) { require(blockNumber < block.number, "ZEUSV2::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; lower = center; upper = center - 1; } } return checkpoints[account][lower].votes; } } else if (cp.fromBlock < blockNumber) { } else { function _delegate(address delegator, address delegatee) internal { address currentDelegate = _delegates[delegator]; _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)) { uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld.sub(amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { uint32 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld.sub(amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { uint32 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld.sub(amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { uint32 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld.sub(amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { uint32 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes ) internal { uint32 blockNumber = safe32(block.number, "ZEUSV2::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes ) internal { uint32 blockNumber = safe32(block.number, "ZEUSV2::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } } else { function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function getChainId() internal pure returns (uint) { uint256 chainId; return chainId; } assembly { chainId := chainid() } }
509,549
[ 1, 3794, 5996, 969, 598, 611, 1643, 82, 1359, 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, 16351, 2285, 41, 5996, 969, 353, 4232, 39, 3462, 2932, 3794, 3378, 58, 22, 1345, 3113, 315, 3794, 3378, 58, 22, 6, 3631, 14223, 6914, 288, 203, 203, 565, 445, 312, 474, 12, 2867, 389, 869, 16, 2254, 5034, 389, 8949, 13, 1071, 1338, 5541, 288, 203, 3639, 389, 81, 474, 24899, 869, 16, 389, 8949, 1769, 203, 3639, 389, 8501, 15608, 815, 12, 2867, 12, 20, 3631, 389, 3771, 1332, 815, 63, 67, 869, 6487, 389, 8949, 1769, 203, 565, 289, 203, 203, 565, 445, 18305, 12, 2867, 389, 2080, 16, 2254, 5034, 389, 8949, 13, 1071, 1338, 5541, 288, 203, 3639, 389, 70, 321, 24899, 2080, 16, 389, 8949, 1769, 203, 565, 289, 203, 203, 203, 203, 565, 2874, 261, 2867, 516, 1758, 13, 2713, 389, 3771, 1332, 815, 31, 203, 565, 1958, 25569, 288, 203, 3639, 2254, 1578, 628, 1768, 31, 203, 3639, 2254, 5034, 19588, 31, 203, 565, 289, 203, 203, 203, 203, 203, 203, 203, 203, 203, 565, 2874, 261, 2867, 516, 2874, 261, 11890, 1578, 516, 25569, 3719, 1071, 26402, 31, 203, 565, 2874, 261, 2867, 516, 2254, 1578, 13, 1071, 818, 1564, 4139, 31, 203, 565, 1731, 1578, 1071, 5381, 27025, 67, 2399, 15920, 273, 417, 24410, 581, 5034, 2932, 41, 2579, 27, 2138, 3748, 12, 1080, 508, 16, 11890, 5034, 2687, 548, 16, 2867, 3929, 310, 8924, 2225, 1769, 203, 565, 1731, 1578, 1071, 5381, 2030, 19384, 2689, 67, 2399, 15920, 273, 417, 24410, 581, 5034, 2932, 26945, 12, 2867, 7152, 73, 16, 11890, 5034, 7448, 2 ]
pragma solidity ^0.4.24; import "./Owned.sol"; import "./SGDz.sol"; import "./StashFactory.sol"; import "./Bank.sol"; contract Payment is Owned {// Regulator node (MAS) should be the owner /* pseudo-public */ function releasePmt(bytes32 _txRef) atState(AgentState.Normal) { /* require(pmtProved(_txRef)); */ require(globalGridlockQueue[_txRef].state == GridlockState.Active || globalGridlockQueue[_txRef].state == GridlockState.Inactive); delete globalGridlockQueue[_txRef]; globalGridlockQueueDepth--; globalGridlockQueue[_txRef].state = GridlockState.Released; removeByValue('gridlockQueue', _txRef); } /* @pseudo-public */ // need to orchestrate the adding to the global gridlockqueue function addToGlobalQueue(bytes32 _txRef) atState(AgentState.Normal) { globalGridlockQueueDepth++; globalGridlockQueue[_txRef].state = GridlockState.Active; globalGridlockQueue[_txRef].receiverVote = true; if (globalGridlockQueueDepth >= maxQueueDepth) nextState(); if (isReceiver(_txRef)) enqueue(_txRef, payments[_txRef].express); } event Time(uint remainingTime); /* @pseudo-public Determine the resolve sequence, and broadcast gridlocked payments to receivers */ function lineUp() atState(AgentState.Lineopen) //isStashOwner(_stashName) { if (lineOpenTime == 0) {lineOpenTime = now;} resolveSequence.push(msg.sender); done[bank.getStash(msg.sender)] = false; Time(lineOpenTime + timeout - now); if (resolveSequence.length == sf.getStashNameCount()) nextState(); } function isParticipating(bytes32 _stashName) internal returns (bool) { for (uint i = 0; i < resolveSequence.length; i++) { if (bank.getStash(resolveSequence[i]) == _stashName) return true; } return false; } /* for testing */ event Hash(bytes32 hash, bytes32 a); function doHash(uint256 _a) { bytes32 result = keccak256(_a); Hash(result, bytes32(_a)); } function doHashBytes(bytes32 _a) { bytes32 result = keccak256(_a); Hash(result, _a); } function doHashBytes2(bytes32 _a, bytes32 _b) { bytes32 result = keccak256(_a, _b); Hash(result, _a); } event Answer(bool a); event Num(uint n); function verify() { bytes32 key = 'R1231'; Answer(payments[key].txRef == bytes32('')); Num(uint(- 1)); } event Array(bytes32[] a); bytes32[] array; function emitArray(bytes32 a, bytes32 b) { array.push(a); array.push(b); Array(array); } function bytesArrayInput(bytes32[] _input) { Array(_input); } /* @pseudo-public THIS METHOD WILL BREAK THE PSEUDO-PUBLIC STATES. However you should still make a pseudo-public call as we want to update PaymentAgent's state on all the nodes. You'll need to call syncPseudoPublicStates after calling this method to sync up the pseudo-public states. */ event Sync(bytes32[] inactivatedPmtRefs, bytes32[] doneStashes, bytes32[] notDoneStashes); function doResolveRound() timedTransitions atState(AgentState.Resolving) isYourTurn returns (bool _didResolution) { lastResolveTime = now; bytes32 currentStash = bank.getStash(resolveSequence[current]); if (!checkOwnedStash(currentStash)) {return false;} if (currentStash != bank.centralBank() && isCentralBankNode()) {return false;} for (uint i = 0; i < gridlockQueue.length; i++) { Pmt inflow = payments[gridlockQueue[i]]; GridlockedPmt g_inflow = globalGridlockQueue[inflow.txRef]; /* to be changed */ /* deactivate inflows from non-participant*/ if (!isParticipating(inflow.sender) && g_inflow.state == GridlockState.Active) { g_inflow.state = GridlockState.Inactive; sf.updatePosition(inflow.receiver, inflow.sender, inflow.amount); // Stash(stashRegistry[inflow.sender]).inc_position(inflow.amount); // Stash(stashRegistry[inflow.receiver]).dec_position(inflow.amount); } } /* Bilateral EAF2 */ inactivatedPmtRefs.length = 0; for (uint j = gridlockQueue.length - 1; j >= 0; j--) {// reverse chronological order if (sf.getPosition(currentStash) >= 0) break; // LSM liquidity partition Pmt pmt = payments[gridlockQueue[j]]; GridlockedPmt g_pmt = globalGridlockQueue[pmt.txRef]; /* to be changed */ /* vote on your outflows */ if (pmt.sender == currentStash && g_pmt.state == GridlockState.Active) { g_pmt.state = GridlockState.Inactive; inactivatedPmtRefs.push(pmt.txRef); sf.updatePosition(pmt.receiver, pmt.sender, pmt.amount); // Stash(stashRegistry[pmt.sender]).inc_position(pmt.amount); // Stash(stashRegistry[pmt.receiver]).dec_position(pmt.amount); done[pmt.receiver] = false; } } done[currentStash] = true; /* emit sync info */ doneStashes.length = 0; notDoneStashes.length = 0; for (uint k = 0; k < resolveSequence.length; k++) { bytes32 stashName = bank.getStash(resolveSequence[k]); if (done[stashName]) doneStashes.push(stashName); else notDoneStashes.push(stashName); } Sync(inactivatedPmtRefs, doneStashes, notDoneStashes); committed = true; return true; } function allDone() internal returns (bool) { bool alldone = true; for (uint i = 0; i < resolveSequence.length; i++) { if (!done[bank.getStash(resolveSequence[i])]) { alldone = false; break; } } return alldone; } function receiverInactivate(bytes32 _txRef) private returns (bool _isReceiver) { for (uint i = 0; i < gridlockQueue.length; i++) { Pmt pmt = payments[gridlockQueue[i]]; if (pmt.txRef == _txRef) { if (!checkOwnedStash(pmt.receiver)) return false; sf.updatePosition(pmt.receiver, pmt.sender, pmt.amount); return true; } } } event AllDone(bool allDone, uint current); /* @pseudo-public */ function syncPseudoPublicStates(bytes32[] _inactivatedPmtRefs, bytes32[] _doneStashes, bytes32[] _notDoneStashes) atState(AgentState.Resolving) isYourTurn hasCommitted(_inactivatedPmtRefs, _doneStashes, _notDoneStashes) { /* syncing global queue */ globalGridlockQueueDepth += _inactivatedPmtRefs.length; for (uint i = 0; i < _inactivatedPmtRefs.length; i++) { globalGridlockQueue[_inactivatedPmtRefs[i]].state = GridlockState.Inactive; receiverInactivate(_inactivatedPmtRefs[i]); } /* syncing done mapping */ for (uint j = 0; j < _doneStashes.length; j++) { done[_doneStashes[j]] = true; } for (uint k = 0; k < _notDoneStashes.length; k++) { done[_notDoneStashes[k]] = false; } /* if everyone is done, enter netting phase, else pass on to the next participant */ bool alldone = allDone(); current++; if (current == resolveSequence.length) current = 0; AllDone(alldone, current); if (alldone == true) nextState(); } /* @pseudo-public */ //update private balance , update zcontract first then local balance, used at the end of the // LSM process only. event Deadlock(); function settle() atState(AgentState.Settling) { /* netting by doing net balance movement */ sf.netting(msg.sender); /* 1. confirm and dequeue active gridlocked payments 2. reactivate inactive gridlocked payments and update position accordingly */ uint beforeSettleGridlockCount = gridlockQueue.length; uint numGridlockedPmts = 0; for (uint j = 0; j < gridlockQueue.length; j++) { /* require(pmtProved(gridlockQueue[j])); */ Pmt pmt = payments[gridlockQueue[j]]; GridlockedPmt g_pmt = globalGridlockQueue[pmt.txRef]; /* to be changed */ if (g_pmt.state == GridlockState.Active) { g_pmt.state = GridlockState.Released; // Changed pmt.state = PmtState.Confirmed; } else if (g_pmt.state == GridlockState.Inactive) {// reactivate inactive pmts g_pmt.state = GridlockState.Active; sf.updatePosition(pmt.sender, pmt.receiver, pmt.amount); gridlockQueue[numGridlockedPmts] = pmt.txRef; numGridlockedPmts++; } else if (g_pmt.state == GridlockState.Onhold) { gridlockQueue[numGridlockedPmts] = pmt.txRef; numGridlockedPmts++; } } if (beforeSettleGridlockCount == numGridlockedPmts) { Deadlock(); /* maxQueueDepth += 5; // prevent recursive gridlock */ } else if (isNettingParticipant()) { bank.updateCurrentSalt2NettingSalt(); } gridlockQueue.length = numGridlockedPmts; nextState(); } // current resolve round leader can stop the LSM if timeout function moveOn() atState(AgentState.Settling) isYourTurn { require(now >= resolveEndTime + proofTimeout); nextState(); } function pmtProved(bytes32 _txRef) external view returns (bool) { return sgdz.proofCompleted(_txRef); } /* @private for: [sender, receiver, (MAS)] */ function confirmPmt(bytes32 _txRef) atState(AgentState.Normal) onlyReceiver(_txRef) { //comment out to get it to work /* require(pmtProved(_txRef)); */ sf.transfer(payments[_txRef].sender, payments[_txRef].receiver, payments[_txRef].amount, msg.sender); payments[_txRef].state = PmtState.Confirmed; bank.updateCurrentSalt(payments[_txRef].salt); } // UBIN-61 /////////////////////////////////////////////////// // @pseudo-public == privateFor: [everyone] // ---------------------------------------------------------- // UBIN-61 [Quorum] Cancel unsettled outgoing payment instruction - Laks // ---------------------------------------------------------- function cancelPmtFromGlobalQueue(bytes32 _txRef) atState(AgentState.Normal) //onlySender(_txRef) { require(globalGridlockQueue[_txRef].state != GridlockState.Cancelled); if (globalGridlockQueue[_txRef].state != GridlockState.Onhold) { globalGridlockQueueDepth--; delete globalGridlockQueue[_txRef]; } globalGridlockQueue[_txRef].state = GridlockState.Cancelled; } //anything other than agent state Normal will get rejected // @privateFor: [receiver, (optional MAS)] // call this after cancelPmtFromGlobalQueue function cancelPmt(bytes32 _txRef) atState(AgentState.Normal) onlySender(_txRef) { if (bank.isSuspended(payments[_txRef].sender)) { bank.emitStatusCode(600); return; } require((payments[_txRef].state == PmtState.Pending) || (payments[_txRef].state == PmtState.Onhold)); require(globalGridlockQueue[_txRef].state != GridlockState.Cancelled); bool changePosition = false; if (payments[_txRef].state == PmtState.Pending) changePosition = true; if (payments[_txRef].state == PmtState.Onhold) removeByValue('onholdPmts', _txRef); payments[_txRef].state = PmtState.Cancelled; //if high priority, decrement express count if (payments[_txRef].express == 1) { expressCount--; } //remove item from gridlock array removeByValue('gridlockQueue', _txRef); // instead of doing this, we have compress the cancelled item in settle() if (changePosition) updatePosition(_txRef, true); // if (success) Status(_txRef,true); //inactivationTracker++; Status(_txRef, true); } // --------------------------------------------------------------------------- // UBIN-62 - Put unsettled outgoing payment instruction on hold - Laks // @pseudo-public // --------------------------------------------------------------------------- function holdPmtFromGlobalQueue(bytes32 _txRef) atState(AgentState.Normal) //onlySender(_txRef) { require((globalGridlockQueue[_txRef].state != GridlockState.Onhold) && (globalGridlockQueue[_txRef].state != GridlockState.Cancelled)); GridlockedPmt g_pmt = globalGridlockQueue[_txRef]; g_pmt.state = GridlockState.Onhold; globalGridlockQueueDepth--; } // --------------------------------------------------------------------------- // UBIN-62 - Put unsettled outgoing payment instruction on hold - Laks // @privateFor: [receiver, (optional MAS)] // --------------------------------------------------------------------------- event Status(bytes32 txRef, bool holdStatus); function holdPmt(bytes32 _txRef) atState(AgentState.Normal) onlySender(_txRef) { if (bank.isSuspended(payments[_txRef].sender)) { bank.emitStatusCode(700); return; } require(payments[_txRef].state == PmtState.Pending); require(globalGridlockQueue[_txRef].state != GridlockState.Onhold); payments[_txRef].state = PmtState.Onhold; onholdPmts.push(_txRef); updatePosition(_txRef, true); removeByValue('gridlockQueue', _txRef); if (payments[_txRef].state == PmtState.Onhold) { //inactivationTracker++; Status(_txRef, true); } else Status(_txRef, false); // Debug message - bank.getStash(msg.sender) is empty leading to onlySender to fail - Laks } // --------------------------------------------------------------------------- // UBIN-63 - Reactivate unsettled payment instruction that is on hold - Laks // @privateFor: [receiver, (optional MAS)] // --------------------------------------------------------------------------- function unholdPmt(bytes32 _txRef) atState(AgentState.Normal) onlySender(_txRef) { if (bank.isSuspended(payments[_txRef].sender)) { bank.emitStatusCode(800); return; } require(payments[_txRef].state == PmtState.Onhold); require(globalGridlockQueue[_txRef].state == GridlockState.Onhold); payments[_txRef].state = PmtState.Pending; removeByValue('onholdPmts', _txRef); enqueue(_txRef, payments[_txRef].express); updatePosition(_txRef, false); if (payments[_txRef].state == PmtState.Pending) { //inactivationTracker--; Status(_txRef, false); } else Status(_txRef, true); } // --------------------------------------------------------------------------- // UBIN-63 - Reactivate unsettled payment instruction that is on hold - Laks // @pseudo-public // called after unholdPmt // --------------------------------------------------------------------------- function unholdPmtFromGlobalQueue(bytes32 _txRef) atState(AgentState.Normal) //onlySender(_txRef) { //remove item from globalGridlockQueue require(globalGridlockQueue[_txRef].state == GridlockState.Onhold); GridlockedPmt g_pmt = globalGridlockQueue[_txRef]; g_pmt.state = GridlockState.Active; globalGridlockQueueDepth++; } function updatePosition(bytes32 _txRef, bool reverse) internal { if (reverse) { sf.updatePosition(payments[_txRef].receiver, payments[_txRef].sender, payments[_txRef].amount); } else { sf.updatePosition(payments[_txRef].sender, payments[_txRef].receiver, payments[_txRef].amount); } } function getLineLength() view returns (uint) { return resolveSequence.length; } function getIsPaymentActive(bytes32 _txRef) external view returns (bool) { GridlockedPmt g_pmt = globalGridlockQueue[_txRef]; /* to be changed */ if (g_pmt.state == GridlockState.Active) { return true; } else { return false; } } // ---------------------------------------------------------- // ---------------------------------------------------------- function IndexOf(bytes32[] values, bytes32 value) returns (uint) { uint i; bool found = true; for (i = 0; i < values.length; i++) { if (values[i] == value) { found = true; break; } } if (found) return i; else return 99999999; } // ------------------------------ // Implementation of UBIN-60 - Laks // ------------------------------ function updatePriority(bytes32 _txRef, int _express) { var (i,found) = ArrayIndexOf(pmtIdx, _txRef); if (!found) { bank.emitStatusCode(300); return; } if (bank.isSuspended(payments[_txRef].sender)) { bank.emitStatusCode(400); return; } require(payments[_txRef].express != _express); // no update when the priority level is the same if (payments[_txRef].express == 0) { expressCount++; } else if (payments[_txRef].express == 1) { expressCount--; } payments[_txRef].express = _express; updateGridlockQueue(_txRef); } // ----------------------------------------------------- // TO DO - To be refactored into a common untils - Laks // ----------------------------------------------------- function ArrayIndexOf(bytes32[] values, bytes32 value) view internal returns (uint, bool) { bool found = false; uint i; for (i = 0; i < values.length; i++) { if (values[i] == value) { found = true; break; } } if (found) return (i, found); else return (0, found); } // ------------------------------------ // Keep the gridlock queue sorted by 1. priority level 2. timestamp // Might need a more generic quick sort function in future // Assumes that the gridlockqueue is already sorted before the current txn // ------------------------------------ function updateGridlockQueue(bytes32 _txRef){ uint tstamp = payments[_txRef].timestamp; uint i; bytes32 curTxRef; uint curTstamp; int curExpress; var (index, found) = ArrayIndexOf(gridlockQueue, _txRef); uint j = index; if (payments[_txRef].express == 1) { // shift the txn to the left if (index == 0) return; for (i = index - 1; int(i) >= 0; i--) {// rather painful discovery that uint i>=0 doesn't work :( - Jay curTxRef = gridlockQueue[i]; curTstamp = payments[curTxRef].timestamp; curExpress = payments[curTxRef].express; if (curExpress == 0 || tstamp < curTstamp) { gridlockQueue[i] = _txRef; gridlockQueue[j] = curTxRef; j--; } } } else { // shift the txn to the right if (index == gridlockQueue.length - 1) return; for (i = index + 1; i <= gridlockQueue.length - 1; i++) { curTxRef = gridlockQueue[i]; curTstamp = payments[curTxRef].timestamp; curExpress = payments[curTxRef].express; if (curExpress == 1 || tstamp > curTstamp) { gridlockQueue[i] = _txRef; gridlockQueue[j] = curTxRef; j++; } } } } // ------------------------------------ // ------------------------------------ // Removes the given value in an array // Refactored to use ArrayIndexOf - Laks // ------------------------------------ function removeByValue(bytes32 arrayName, bytes32 value) internal returns (bool) { bytes32[] array; //TODO use a mapping? if (arrayName == 'onholdPmts') { array = onholdPmts; } else if (arrayName == 'gridlockQueue') { array = gridlockQueue; if (payments[value].express == 1) expressCount--; } else { return false; } var (index, found) = ArrayIndexOf(array, value); if (found) { for (uint i = index; i < array.length - 1; i++) { array[i] = array[i + 1]; } delete array[array.length - 1]; array.length--; return true; } return false; } }
shift the txn to the left
if (payments[_txRef].express == 1) { if (index == 0) return; curTxRef = gridlockQueue[i]; curTstamp = payments[curTxRef].timestamp; curExpress = payments[curTxRef].express; if (curExpress == 0 || tstamp < curTstamp) { gridlockQueue[i] = _txRef; gridlockQueue[j] = curTxRef; j--; } }
12,707,866
[ 1, 4012, 326, 7827, 358, 326, 2002, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 309, 261, 10239, 1346, 63, 67, 978, 1957, 8009, 338, 1028, 422, 404, 13, 288, 203, 5411, 309, 261, 1615, 422, 374, 13, 327, 31, 203, 7734, 662, 4188, 1957, 273, 3068, 739, 3183, 63, 77, 15533, 203, 7734, 662, 56, 14317, 273, 25754, 63, 1397, 4188, 1957, 8009, 5508, 31, 203, 7734, 662, 424, 1028, 273, 25754, 63, 1397, 4188, 1957, 8009, 338, 1028, 31, 203, 7734, 309, 261, 1397, 424, 1028, 422, 374, 747, 268, 14317, 411, 662, 56, 14317, 13, 288, 203, 10792, 3068, 739, 3183, 63, 77, 65, 273, 389, 978, 1957, 31, 203, 10792, 3068, 739, 3183, 63, 78, 65, 273, 662, 4188, 1957, 31, 203, 10792, 525, 413, 31, 203, 7734, 289, 203, 5411, 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 ]
./full_match/1/0x9Ac6c3c4dC3fD3e976d37e1FBc43e13C239FD8c9/sources/contracts/strategies/stakedao/CurveStakeDaoStratBase.sol
* @dev Returns true if withdraw success and false if fail. Withdraw failed when user removingCrvLps < requiredCrvLPs (wrong minAmounts) @return Returns true if withdraw success and false if fail. @param withdrawer - address of user that deposit funds @param userRatioOfCrvLps - user's Ratio of ZLP for withdraw @param tokenAmounts - array of amounts stablecoins that user want minimum receive/
function calcWithdrawOneCoin(uint256 sharesAmount, uint128 tokenIndex) external view virtual returns (uint256 tokenAmount); function calcSharesAmount(uint256[3] memory tokenAmounts, bool isDeposit) external view virtual returns (uint256 sharesAmount); function withdraw( address withdrawer, uint256[3] memory tokenAmounts, WithdrawalType withdrawalType, uint128 tokenIndex ) external virtual onlyZunami returns (bool) { require(userRatioOfCrvLps > 0 && userRatioOfCrvLps <= 1e18, 'Wrong lp Ratio'); (bool success, uint256 removingCrvLps, uint256[] memory tokenAmountsDynamic) = calcCrvLps( withdrawalType, userRatioOfCrvLps, tokenAmounts, tokenIndex ); if (!success) { return false; } uint256[] memory prevBalances = new uint256[](3); for (uint256 i = 0; i < 3; i++) { prevBalances[i] = _config.tokens[i].balanceOf(address(this)) - ((i == feeTokenId) ? managementFees : 0); } vault.withdraw(removingCrvLps); removeCrvLps(removingCrvLps, tokenAmountsDynamic, withdrawalType, tokenAmounts, tokenIndex); transferAllTokensOut(withdrawer, prevBalances); return true; }
9,754,757
[ 1, 1356, 638, 309, 598, 9446, 2216, 471, 629, 309, 2321, 18, 3423, 9446, 2535, 1347, 729, 9427, 39, 4962, 48, 1121, 411, 1931, 39, 4962, 14461, 87, 261, 21530, 1131, 6275, 87, 13, 327, 2860, 638, 309, 598, 9446, 2216, 471, 629, 309, 2321, 18, 225, 598, 9446, 264, 300, 1758, 434, 729, 716, 443, 1724, 284, 19156, 225, 729, 8541, 951, 39, 4962, 48, 1121, 300, 729, 1807, 534, 4197, 434, 2285, 14461, 364, 598, 9446, 225, 1147, 6275, 87, 300, 225, 526, 434, 30980, 14114, 71, 9896, 716, 729, 2545, 5224, 6798, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 7029, 1190, 9446, 3335, 27055, 12, 11890, 5034, 24123, 6275, 16, 2254, 10392, 1147, 1016, 13, 203, 3639, 3903, 203, 3639, 1476, 203, 3639, 5024, 203, 3639, 1135, 261, 11890, 5034, 1147, 6275, 1769, 203, 203, 565, 445, 7029, 24051, 6275, 12, 11890, 5034, 63, 23, 65, 3778, 1147, 6275, 87, 16, 1426, 353, 758, 1724, 13, 203, 3639, 3903, 203, 3639, 1476, 203, 3639, 5024, 203, 3639, 1135, 261, 11890, 5034, 24123, 6275, 1769, 203, 203, 565, 445, 598, 9446, 12, 203, 3639, 1758, 598, 9446, 264, 16, 203, 3639, 2254, 5034, 63, 23, 65, 3778, 1147, 6275, 87, 16, 203, 3639, 3423, 9446, 287, 559, 598, 9446, 287, 559, 16, 203, 3639, 2254, 10392, 1147, 1016, 203, 565, 262, 3903, 5024, 1338, 62, 318, 26223, 1135, 261, 6430, 13, 288, 203, 3639, 2583, 12, 1355, 8541, 951, 39, 4962, 48, 1121, 405, 374, 597, 729, 8541, 951, 39, 4962, 48, 1121, 1648, 404, 73, 2643, 16, 296, 13634, 12423, 534, 4197, 8284, 203, 3639, 261, 6430, 2216, 16, 2254, 5034, 9427, 39, 4962, 48, 1121, 16, 2254, 5034, 8526, 3778, 1147, 6275, 87, 9791, 13, 273, 7029, 39, 4962, 48, 1121, 12, 203, 5411, 598, 9446, 287, 559, 16, 203, 5411, 729, 8541, 951, 39, 4962, 48, 1121, 16, 203, 5411, 1147, 6275, 87, 16, 203, 5411, 1147, 1016, 203, 3639, 11272, 203, 203, 3639, 309, 16051, 4768, 13, 288, 203, 5411, 327, 629, 31, 203, 3639, 289, 203, 203, 3639, 2254, 5034, 8526, 3778, 2807, 38, 26488, 273, 394, 2 ]
/** *Submitted for verification at Etherscan.io on 2021-03-30 */ pragma solidity ^0.4.24; contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } contract Ownable { /* Define owner of the type address */ address owner; /** * Modifiers partially define a function and allow you to augment other functions. * The rest of the function continues at _; */ modifier onlyOwner { require(msg.sender == owner); _; } /* This function is executed at initialization and sets the owner of the contract */ constructor() public { owner = msg.sender; } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } /** * @title Template token that can be purchased * @dev World's smallest crowd sale */ contract HashLipsToken is ERC20Basic, Ownable { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; string public constant name = "HashLips"; string public constant symbol = "HLPS"; uint8 public constant decimals = 18; // 18 is the most common number of decimal places constructor() public { balances[0xde3b22caaad25e65c839c2a3d852d665669edd5c] = 500000000000000000000000000; balances[0xc1B368E83147309eEb030e453bBc97Ffb19927B1] = 500000000000000000000000000; } /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @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) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } /** * @dev This sells 1000 tokens in exchange for 1 ether */ function () public payable { uint256 amount = msg.value.mul(100000); balances[msg.sender] = balances[msg.sender].add(amount); totalSupply_ = totalSupply_.add(amount); owner.transfer(msg.value); emit Transfer(0x0, msg.sender, amount); } }
* @dev Gets the balance of the specified address. @param _owner The address to query the the balance of. @return An uint256 representing the amount owned by the passed address./
function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; }
6,552,466
[ 1, 3002, 326, 11013, 434, 326, 1269, 1758, 18, 225, 389, 8443, 1021, 1758, 358, 843, 326, 326, 11013, 434, 18, 327, 1922, 2254, 5034, 5123, 326, 3844, 16199, 635, 326, 2275, 1758, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 11013, 951, 12, 2867, 389, 8443, 13, 1071, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 565, 327, 324, 26488, 63, 67, 8443, 15533, 203, 225, 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 ]
./partial_match/1/0xC7e63B18dEDF226b1C1a7A436953a63c518bd442/sources/ENSRegistry.sol
* @dev Transfers ownership of a subnode keccak256(node, label) to a new address. May only be called by the owner of the parent node. @param _node The parent node. @param _label The hash of the label specifying the subnode. @param _owner The address of the new owner./
function setSubnodeOwner(bytes32 _node, bytes32 _label, address _owner) public authorised(_node) returns(bytes32) { bytes32 subnode = keccak256(abi.encodePacked(_node, _label)); _setOwner(subnode, _owner); emit NewOwner(_node, _label, _owner); return subnode; }
4,141,563
[ 1, 1429, 18881, 23178, 434, 279, 28300, 417, 24410, 581, 5034, 12, 2159, 16, 1433, 13, 358, 279, 394, 1758, 18, 16734, 1338, 506, 2566, 635, 326, 3410, 434, 326, 982, 756, 18, 225, 389, 2159, 1021, 982, 756, 18, 225, 389, 1925, 1021, 1651, 434, 326, 1433, 13664, 326, 28300, 18, 225, 389, 8443, 1021, 1758, 434, 326, 394, 3410, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 19942, 2159, 5541, 12, 3890, 1578, 389, 2159, 16, 1731, 1578, 389, 1925, 16, 1758, 389, 8443, 13, 1071, 2869, 5918, 24899, 2159, 13, 1135, 12, 3890, 1578, 13, 288, 203, 3639, 1731, 1578, 28300, 273, 417, 24410, 581, 5034, 12, 21457, 18, 3015, 4420, 329, 24899, 2159, 16, 389, 1925, 10019, 203, 3639, 389, 542, 5541, 12, 1717, 2159, 16, 389, 8443, 1769, 203, 3639, 3626, 1166, 5541, 24899, 2159, 16, 389, 1925, 16, 389, 8443, 1769, 203, 3639, 327, 28300, 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 ]
./full_match/43114/0x9042bFa5281C8362C81B8abf87654c0ffBe25ec4/sources/contracts/joe/bjoe2.sol
use by default 300,000 gas to process auto-claiming dividends exlcude from fees and max transaction amount store addresses that a automatic market maker pairs. Any transfer *to* these addresses could be subject to a maximum transfer amount
contract DoUKnoEsen5 is ERC20, Ownable { using SafeMath for uint256; IJoeRouter02 public uniswapV2Router; address public uniswapV2Pair; bool private swapping; JOEDividendTracker public dividendTracker; address public deadWallet = 0x000000000000000000000000000000000000dEaD; uint256 public swapTokensAtAmount = 1000000 * (10**18); mapping(address => bool) public _isBlacklisted; uint256 public JOERewardsFee = 9; uint256 public liquidityFee = 3; uint256 public marketingFee = 3; uint256 public totalFees = JOERewardsFee.add(liquidityFee).add(marketingFee); address public _marketingWalletAddress = 0x809669dF982d77180Ae0573A4c6d3Fe2B8D092B3; uint256 public gasForProcessing = 300000; mapping (address => bool) private _isExcludedFromFees; mapping (address => bool) public automatedMarketMakerPairs; event UpdateDividendTracker(address indexed newAddress, address indexed oldAddress); event UpdateUniswapV2Router(address indexed newAddress, address indexed oldAddress); event ExcludeFromFees(address indexed account, bool isExcluded); event ExcludeMultipleAccountsFromFees(address[] accounts, bool isExcluded); event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value); event LiquidityWalletUpdated(address indexed newLiquidityWallet, address indexed oldLiquidityWallet); event GasForProcessingUpdated(uint256 indexed newValue, uint256 indexed oldValue); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiqudity ); event SendDividends( uint256 tokensSwapped, uint256 amount ); event ProcessedDividendTracker( uint256 iterations, uint256 claims, uint256 lastProcessedIndex, bool indexed automatic, uint256 gas, address indexed processor ); pragma solidity ^0.6.2; constructor() public ERC20("DoUKnoEsen5", "DUKE5") { dividendTracker = new JOEDividendTracker(); IJoeRouter02 _uniswapV2Router = IJoeRouter02(0x60aE616a2155Ee3d9A68541Ba4544862310933d4); address _uniswapV2Pair = IJoeFactory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WAVAX()); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = _uniswapV2Pair; _setAutomatedMarketMakerPair(_uniswapV2Pair, true); dividendTracker.excludeFromDividends(address(dividendTracker)); dividendTracker.excludeFromDividends(address(this)); dividendTracker.excludeFromDividends(owner()); dividendTracker.excludeFromDividends(deadWallet); dividendTracker.excludeFromDividends(address(_uniswapV2Router)); excludeFromFees(owner(), true); excludeFromFees(_marketingWalletAddress, true); excludeFromFees(address(this), true); _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again _mint(owner(), 100000000000 * (10**18)); } receive() external payable { } function updateDividendTracker(address newAddress) public onlyOwner { require(newAddress != address(dividendTracker), "JOE: The dividend tracker already has that address"); JOEDividendTracker newDividendTracker = JOEDividendTracker(payable(newAddress)); require(newDividendTracker.owner() == address(this), "JOE: The new dividend tracker must be owned by the JOE token contract"); newDividendTracker.excludeFromDividends(address(newDividendTracker)); newDividendTracker.excludeFromDividends(address(this)); newDividendTracker.excludeFromDividends(owner()); newDividendTracker.excludeFromDividends(address(uniswapV2Router)); emit UpdateDividendTracker(newAddress, address(dividendTracker)); dividendTracker = newDividendTracker; } function updateUniswapV2Router(address newAddress) public onlyOwner { require(newAddress != address(uniswapV2Router), "JOE: The router already has that address"); emit UpdateUniswapV2Router(newAddress, address(uniswapV2Router)); uniswapV2Router = IJoeRouter02(newAddress); address _uniswapV2Pair = IJoeFactory(uniswapV2Router.factory()) .createPair(address(this), uniswapV2Router.WAVAX()); uniswapV2Pair = _uniswapV2Pair; } function excludeFromFees(address account, bool excluded) public onlyOwner { require(_isExcludedFromFees[account] != excluded, "JOE: Account is already the value of 'excluded'"); _isExcludedFromFees[account] = excluded; emit ExcludeFromFees(account, excluded); } function excludeMultipleAccountsFromFees(address[] calldata accounts, bool excluded) public onlyOwner { for(uint256 i = 0; i < accounts.length; i++) { _isExcludedFromFees[accounts[i]] = excluded; } emit ExcludeMultipleAccountsFromFees(accounts, excluded); } function excludeMultipleAccountsFromFees(address[] calldata accounts, bool excluded) public onlyOwner { for(uint256 i = 0; i < accounts.length; i++) { _isExcludedFromFees[accounts[i]] = excluded; } emit ExcludeMultipleAccountsFromFees(accounts, excluded); } function setMarketingWallet(address payable wallet) external onlyOwner{ _marketingWalletAddress = wallet; } function setJOERewardsFee(uint256 value) external onlyOwner{ JOERewardsFee = value; totalFees = JOERewardsFee.add(liquidityFee).add(marketingFee); } function setLiquiditFee(uint256 value) external onlyOwner{ liquidityFee = value; totalFees = JOERewardsFee.add(liquidityFee).add(marketingFee); } function setMarketingFee(uint256 value) external onlyOwner{ marketingFee = value; totalFees = JOERewardsFee.add(liquidityFee).add(marketingFee); } function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner { require(pair != uniswapV2Pair, "JOE: The Joe pair cannot be removed from automatedMarketMakerPairs"); _setAutomatedMarketMakerPair(pair, value); } function blacklistAddress(address account, bool value) external onlyOwner{ _isBlacklisted[account] = value; } function _setAutomatedMarketMakerPair(address pair, bool value) private { require(automatedMarketMakerPairs[pair] != value, "JOE: Automated market maker pair is already set to that value"); automatedMarketMakerPairs[pair] = value; if(value) { dividendTracker.excludeFromDividends(pair); } emit SetAutomatedMarketMakerPair(pair, value); } function _setAutomatedMarketMakerPair(address pair, bool value) private { require(automatedMarketMakerPairs[pair] != value, "JOE: Automated market maker pair is already set to that value"); automatedMarketMakerPairs[pair] = value; if(value) { dividendTracker.excludeFromDividends(pair); } emit SetAutomatedMarketMakerPair(pair, value); } function updateGasForProcessing(uint256 newValue) public onlyOwner { require(newValue >= 200000 && newValue <= 500000, "JOE: gasForProcessing must be between 200,000 and 500,000"); require(newValue != gasForProcessing, "JOE: Cannot update gasForProcessing to same value"); emit GasForProcessingUpdated(newValue, gasForProcessing); gasForProcessing = newValue; } function updateClaimWait(uint256 claimWait) external onlyOwner { dividendTracker.updateClaimWait(claimWait); } function getClaimWait() external view returns(uint256) { return dividendTracker.claimWait(); } function getTotalDividendsDistributed() external view returns (uint256) { return dividendTracker.totalDividendsDistributed(); } function isExcludedFromFees(address account) public view returns(bool) { return _isExcludedFromFees[account]; } function withdrawableDividendOf(address account) public view returns(uint256) { return dividendTracker.withdrawableDividendOf(account); } function dividendTokenBalanceOf(address account) public view returns (uint256) { return dividendTracker.balanceOf(account); } function excludeFromDividends(address account) external onlyOwner{ dividendTracker.excludeFromDividends(account); } function getAccountDividendsInfo(address account) external view returns ( address, int256, int256, uint256, uint256, uint256, uint256, uint256) { return dividendTracker.getAccount(account); } function getAccountDividendsInfoAtIndex(uint256 index) external view returns ( address, int256, int256, uint256, uint256, uint256, uint256, uint256) { return dividendTracker.getAccountAtIndex(index); } function processDividendTracker(uint256 gas) external { (uint256 iterations, uint256 claims, uint256 lastProcessedIndex) = dividendTracker.process(gas); emit ProcessedDividendTracker(iterations, claims, lastProcessedIndex, false, gas, tx.origin); } function claim() external { dividendTracker.processAccount(msg.sender, false); } function getLastProcessedIndex() external view returns(uint256) { return dividendTracker.getLastProcessedIndex(); } function getNumberOfDividendTokenHolders() external view returns(uint256) { return dividendTracker.getNumberOfTokenHolders(); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_isBlacklisted[from] && !_isBlacklisted[to], 'Blacklisted address'); if(amount == 0) { super._transfer(from, to, 0); return; } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && !swapping && !automatedMarketMakerPairs[from] && from != owner() && to != owner() ) { swapping = true; uint256 marketingTokens = contractTokenBalance.mul(marketingFee).div(totalFees); swapAndSendToFee(marketingTokens); uint256 swapTokens = contractTokenBalance.mul(liquidityFee).div(totalFees); swapAndLiquify(swapTokens); uint256 sellTokens = balanceOf(address(this)); swapAndSendDividends(sellTokens); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } if(takeFee) { uint256 fees = amount.mul(totalFees).div(100); if(automatedMarketMakerPairs[to]){ fees += amount.mul(1).div(100); } amount = amount.sub(fees); super._transfer(from, address(this), fees); } super._transfer(from, to, amount); if(!swapping) { uint256 gas = gasForProcessing; try dividendTracker.process(gas) returns (uint256 iterations, uint256 claims, uint256 lastProcessedIndex) { emit ProcessedDividendTracker(iterations, claims, lastProcessedIndex, true, gas, tx.origin); } catch { } } } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_isBlacklisted[from] && !_isBlacklisted[to], 'Blacklisted address'); if(amount == 0) { super._transfer(from, to, 0); return; } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && !swapping && !automatedMarketMakerPairs[from] && from != owner() && to != owner() ) { swapping = true; uint256 marketingTokens = contractTokenBalance.mul(marketingFee).div(totalFees); swapAndSendToFee(marketingTokens); uint256 swapTokens = contractTokenBalance.mul(liquidityFee).div(totalFees); swapAndLiquify(swapTokens); uint256 sellTokens = balanceOf(address(this)); swapAndSendDividends(sellTokens); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } if(takeFee) { uint256 fees = amount.mul(totalFees).div(100); if(automatedMarketMakerPairs[to]){ fees += amount.mul(1).div(100); } amount = amount.sub(fees); super._transfer(from, address(this), fees); } super._transfer(from, to, amount); if(!swapping) { uint256 gas = gasForProcessing; try dividendTracker.process(gas) returns (uint256 iterations, uint256 claims, uint256 lastProcessedIndex) { emit ProcessedDividendTracker(iterations, claims, lastProcessedIndex, true, gas, tx.origin); } catch { } } } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_isBlacklisted[from] && !_isBlacklisted[to], 'Blacklisted address'); if(amount == 0) { super._transfer(from, to, 0); return; } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && !swapping && !automatedMarketMakerPairs[from] && from != owner() && to != owner() ) { swapping = true; uint256 marketingTokens = contractTokenBalance.mul(marketingFee).div(totalFees); swapAndSendToFee(marketingTokens); uint256 swapTokens = contractTokenBalance.mul(liquidityFee).div(totalFees); swapAndLiquify(swapTokens); uint256 sellTokens = balanceOf(address(this)); swapAndSendDividends(sellTokens); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } if(takeFee) { uint256 fees = amount.mul(totalFees).div(100); if(automatedMarketMakerPairs[to]){ fees += amount.mul(1).div(100); } amount = amount.sub(fees); super._transfer(from, address(this), fees); } super._transfer(from, to, amount); if(!swapping) { uint256 gas = gasForProcessing; try dividendTracker.process(gas) returns (uint256 iterations, uint256 claims, uint256 lastProcessedIndex) { emit ProcessedDividendTracker(iterations, claims, lastProcessedIndex, true, gas, tx.origin); } catch { } } } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_isBlacklisted[from] && !_isBlacklisted[to], 'Blacklisted address'); if(amount == 0) { super._transfer(from, to, 0); return; } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && !swapping && !automatedMarketMakerPairs[from] && from != owner() && to != owner() ) { swapping = true; uint256 marketingTokens = contractTokenBalance.mul(marketingFee).div(totalFees); swapAndSendToFee(marketingTokens); uint256 swapTokens = contractTokenBalance.mul(liquidityFee).div(totalFees); swapAndLiquify(swapTokens); uint256 sellTokens = balanceOf(address(this)); swapAndSendDividends(sellTokens); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } if(takeFee) { uint256 fees = amount.mul(totalFees).div(100); if(automatedMarketMakerPairs[to]){ fees += amount.mul(1).div(100); } amount = amount.sub(fees); super._transfer(from, address(this), fees); } super._transfer(from, to, amount); if(!swapping) { uint256 gas = gasForProcessing; try dividendTracker.process(gas) returns (uint256 iterations, uint256 claims, uint256 lastProcessedIndex) { emit ProcessedDividendTracker(iterations, claims, lastProcessedIndex, true, gas, tx.origin); } catch { } } } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_isBlacklisted[from] && !_isBlacklisted[to], 'Blacklisted address'); if(amount == 0) { super._transfer(from, to, 0); return; } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && !swapping && !automatedMarketMakerPairs[from] && from != owner() && to != owner() ) { swapping = true; uint256 marketingTokens = contractTokenBalance.mul(marketingFee).div(totalFees); swapAndSendToFee(marketingTokens); uint256 swapTokens = contractTokenBalance.mul(liquidityFee).div(totalFees); swapAndLiquify(swapTokens); uint256 sellTokens = balanceOf(address(this)); swapAndSendDividends(sellTokens); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } if(takeFee) { uint256 fees = amount.mul(totalFees).div(100); if(automatedMarketMakerPairs[to]){ fees += amount.mul(1).div(100); } amount = amount.sub(fees); super._transfer(from, address(this), fees); } super._transfer(from, to, amount); if(!swapping) { uint256 gas = gasForProcessing; try dividendTracker.process(gas) returns (uint256 iterations, uint256 claims, uint256 lastProcessedIndex) { emit ProcessedDividendTracker(iterations, claims, lastProcessedIndex, true, gas, tx.origin); } catch { } } } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_isBlacklisted[from] && !_isBlacklisted[to], 'Blacklisted address'); if(amount == 0) { super._transfer(from, to, 0); return; } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && !swapping && !automatedMarketMakerPairs[from] && from != owner() && to != owner() ) { swapping = true; uint256 marketingTokens = contractTokenBalance.mul(marketingFee).div(totalFees); swapAndSendToFee(marketingTokens); uint256 swapTokens = contractTokenBalance.mul(liquidityFee).div(totalFees); swapAndLiquify(swapTokens); uint256 sellTokens = balanceOf(address(this)); swapAndSendDividends(sellTokens); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } if(takeFee) { uint256 fees = amount.mul(totalFees).div(100); if(automatedMarketMakerPairs[to]){ fees += amount.mul(1).div(100); } amount = amount.sub(fees); super._transfer(from, address(this), fees); } super._transfer(from, to, amount); if(!swapping) { uint256 gas = gasForProcessing; try dividendTracker.process(gas) returns (uint256 iterations, uint256 claims, uint256 lastProcessedIndex) { emit ProcessedDividendTracker(iterations, claims, lastProcessedIndex, true, gas, tx.origin); } catch { } } } try dividendTracker.setBalance(payable(from), balanceOf(from)) {} catch {} try dividendTracker.setBalance(payable(to), balanceOf(to)) {} catch {} function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_isBlacklisted[from] && !_isBlacklisted[to], 'Blacklisted address'); if(amount == 0) { super._transfer(from, to, 0); return; } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && !swapping && !automatedMarketMakerPairs[from] && from != owner() && to != owner() ) { swapping = true; uint256 marketingTokens = contractTokenBalance.mul(marketingFee).div(totalFees); swapAndSendToFee(marketingTokens); uint256 swapTokens = contractTokenBalance.mul(liquidityFee).div(totalFees); swapAndLiquify(swapTokens); uint256 sellTokens = balanceOf(address(this)); swapAndSendDividends(sellTokens); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } if(takeFee) { uint256 fees = amount.mul(totalFees).div(100); if(automatedMarketMakerPairs[to]){ fees += amount.mul(1).div(100); } amount = amount.sub(fees); super._transfer(from, address(this), fees); } super._transfer(from, to, amount); if(!swapping) { uint256 gas = gasForProcessing; try dividendTracker.process(gas) returns (uint256 iterations, uint256 claims, uint256 lastProcessedIndex) { emit ProcessedDividendTracker(iterations, claims, lastProcessedIndex, true, gas, tx.origin); } catch { } } } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_isBlacklisted[from] && !_isBlacklisted[to], 'Blacklisted address'); if(amount == 0) { super._transfer(from, to, 0); return; } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && !swapping && !automatedMarketMakerPairs[from] && from != owner() && to != owner() ) { swapping = true; uint256 marketingTokens = contractTokenBalance.mul(marketingFee).div(totalFees); swapAndSendToFee(marketingTokens); uint256 swapTokens = contractTokenBalance.mul(liquidityFee).div(totalFees); swapAndLiquify(swapTokens); uint256 sellTokens = balanceOf(address(this)); swapAndSendDividends(sellTokens); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } if(takeFee) { uint256 fees = amount.mul(totalFees).div(100); if(automatedMarketMakerPairs[to]){ fees += amount.mul(1).div(100); } amount = amount.sub(fees); super._transfer(from, address(this), fees); } super._transfer(from, to, amount); if(!swapping) { uint256 gas = gasForProcessing; try dividendTracker.process(gas) returns (uint256 iterations, uint256 claims, uint256 lastProcessedIndex) { emit ProcessedDividendTracker(iterations, claims, lastProcessedIndex, true, gas, tx.origin); } catch { } } } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_isBlacklisted[from] && !_isBlacklisted[to], 'Blacklisted address'); if(amount == 0) { super._transfer(from, to, 0); return; } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && !swapping && !automatedMarketMakerPairs[from] && from != owner() && to != owner() ) { swapping = true; uint256 marketingTokens = contractTokenBalance.mul(marketingFee).div(totalFees); swapAndSendToFee(marketingTokens); uint256 swapTokens = contractTokenBalance.mul(liquidityFee).div(totalFees); swapAndLiquify(swapTokens); uint256 sellTokens = balanceOf(address(this)); swapAndSendDividends(sellTokens); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } if(takeFee) { uint256 fees = amount.mul(totalFees).div(100); if(automatedMarketMakerPairs[to]){ fees += amount.mul(1).div(100); } amount = amount.sub(fees); super._transfer(from, address(this), fees); } super._transfer(from, to, amount); if(!swapping) { uint256 gas = gasForProcessing; try dividendTracker.process(gas) returns (uint256 iterations, uint256 claims, uint256 lastProcessedIndex) { emit ProcessedDividendTracker(iterations, claims, lastProcessedIndex, true, gas, tx.origin); } catch { } } } function swapAndSendToFee(uint256 tokens) private { uint256 initialJOEBalance = IERC20(JOE).balanceOf(address(this)); swapTokensForJOE(tokens); uint256 newBalance = (IERC20(JOE).balanceOf(address(this))).sub(initialJOEBalance); IERC20(JOE).transfer(_marketingWalletAddress, newBalance); } function swapAndLiquify(uint256 tokens) private { uint256 half = tokens.div(2); uint256 otherHalf = tokens.sub(half); uint256 initialBalance = address(this).balance; uint256 newBalance = address(this).balance.sub(initialBalance); addLiquidity(otherHalf, newBalance); emit SwapAndLiquify(half, newBalance, otherHalf); } function swapTokensForAVAX(uint256 tokenAmount) private { address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WAVAX(); _approve(address(this), address(uniswapV2Router), tokenAmount); uniswapV2Router.swapExactTokensForAVAXSupportingFeeOnTransferTokens( tokenAmount, path, address(this), block.timestamp ); } function swapTokensForJOE(uint256 tokenAmount) private { address[] memory path = new address[](3); path[0] = address(this); path[1] = uniswapV2Router.WAVAX(); path[2] = JOE; _approve(address(this), address(uniswapV2Router), tokenAmount); uniswapV2Router.swapExactTokensForTokensSupportingFeeOnTransferTokens( tokenAmount, 0, path, address(this), block.timestamp ); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { _approve(address(this), address(uniswapV2Router), tokenAmount); address(this), tokenAmount, address(0), block.timestamp ); } uniswapV2Router.addLiquidityAVAX{value: ethAmount}( function swapAndSendDividends(uint256 tokens) private{ swapTokensForJOE(tokens); uint256 dividends = IERC20(JOE).balanceOf(address(this)); bool success = IERC20(JOE).transfer(address(dividendTracker), dividends); if (success) { dividendTracker.distributeJOEDividends(dividends); emit SendDividends(tokens, dividends); } } function swapAndSendDividends(uint256 tokens) private{ swapTokensForJOE(tokens); uint256 dividends = IERC20(JOE).balanceOf(address(this)); bool success = IERC20(JOE).transfer(address(dividendTracker), dividends); if (success) { dividendTracker.distributeJOEDividends(dividends); emit SendDividends(tokens, dividends); } } }
4,588,281
[ 1, 1202, 635, 805, 11631, 16, 3784, 16189, 358, 1207, 3656, 17, 14784, 310, 3739, 350, 5839, 431, 17704, 1317, 628, 1656, 281, 471, 943, 2492, 3844, 1707, 6138, 716, 279, 5859, 13667, 312, 6388, 5574, 18, 5502, 7412, 358, 4259, 6138, 3377, 506, 3221, 358, 279, 4207, 7412, 3844, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 2256, 57, 47, 2135, 6705, 275, 25, 353, 4232, 39, 3462, 16, 14223, 6914, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 203, 565, 467, 46, 15548, 8259, 3103, 1071, 640, 291, 91, 438, 58, 22, 8259, 31, 203, 565, 1758, 1071, 225, 640, 291, 91, 438, 58, 22, 4154, 31, 203, 203, 565, 1426, 3238, 7720, 1382, 31, 203, 203, 565, 804, 51, 2056, 427, 26746, 8135, 1071, 31945, 8135, 31, 203, 203, 565, 1758, 1071, 8363, 16936, 273, 374, 92, 12648, 12648, 12648, 12648, 2787, 72, 41, 69, 40, 31, 203, 203, 203, 565, 2254, 5034, 1071, 7720, 5157, 861, 6275, 273, 15088, 380, 261, 2163, 636, 2643, 1769, 203, 377, 203, 565, 2874, 12, 2867, 516, 1426, 13, 1071, 389, 291, 13155, 18647, 31, 203, 203, 565, 2254, 5034, 1071, 804, 51, 654, 359, 14727, 14667, 273, 2468, 31, 203, 565, 2254, 5034, 1071, 4501, 372, 24237, 14667, 273, 890, 31, 203, 565, 2254, 5034, 1071, 13667, 310, 14667, 273, 890, 31, 203, 565, 2254, 5034, 1071, 2078, 2954, 281, 273, 804, 51, 654, 359, 14727, 14667, 18, 1289, 12, 549, 372, 24237, 14667, 2934, 1289, 12, 3355, 21747, 14667, 1769, 203, 203, 565, 1758, 1071, 389, 3355, 21747, 16936, 1887, 273, 374, 92, 3672, 29, 6028, 29, 72, 42, 10689, 22, 72, 4700, 18278, 37, 73, 6260, 9036, 37, 24, 71, 26, 72, 23, 2954, 22, 38, 28, 40, 5908, 22, 38, 23, 31, 203, 203, 565, 2254, 5034, 1071, 16189, 1290, 7798, 273, 890, 11706, 2 ]
./full_match/1/0x8aF6A2BF9f824A68cD21A45f9F58877733235A55/sources/src/TheChainMinter.sol
escrow = initEscrow;
) EIP712("THE_CHAIN", THE_CHAIN_VERSION) { THE_CHAIN = initChain; SELLER = initSeller; for (uint256 i; i < initSigners.length; i++) { signers[initSigners[i]] = true; } }
3,126,131
[ 1, 742, 492, 273, 1208, 6412, 492, 31, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 202, 13, 512, 2579, 27, 2138, 2932, 24644, 67, 1792, 6964, 3113, 12786, 67, 1792, 6964, 67, 5757, 13, 288, 203, 202, 202, 24644, 67, 1792, 6964, 273, 1208, 3893, 31, 203, 203, 202, 202, 1090, 4503, 654, 273, 1208, 22050, 31, 203, 203, 203, 202, 202, 1884, 261, 11890, 5034, 277, 31, 277, 411, 1208, 2766, 414, 18, 2469, 31, 277, 27245, 288, 203, 1082, 202, 2977, 414, 63, 2738, 2766, 414, 63, 77, 13563, 273, 638, 31, 203, 202, 202, 97, 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 ]
pragma solidity ^0.5.0; // Import key libraries for Ownable and SafeMath // import "../installed_contracts/zeppelin/contracts/math/SafeMath.sol"; // import "installed_contracts/zeppelin/contracts/ownership/Ownable.sol"; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior wwwin 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; } } // This contract setup the owner. // This contract provides inheritance to the main contract. contract FromParent { address payable public owner; address payable public beneficiary = address(0); // Set beneficiary to null constructor() public { // Set at start of deployment owner = msg.sender; // Set the owner of contract } } // This is the Donations contract // The contract does the following: // 1. Initilizes the contract with a donation limit to be collected and a beneficiary. Similar to gofund me. // 2. Users donate to the contract. Donation must be at least 1 ether. // 3. Track donations until the donation limit has been reached, or terminate if at least 10% has been collected // 4. Send 90% of the donations to the beneficiary // 5. Owner gets 10% of the contract dopnation // This contract inherits from the FromParent contract. contract Donations is FromParent { using SafeMath for uint; mapping (address => uint) private balances; // Track the donate amount from the user bool private hasBeneficiary = false; // Set no beneficiary selected bool private isAtLimit = false; // Set default for reaching donation limit flag bool private stopped = false; // Set default circuit breaker/ emergency stop flag bool private lock = false; // Safeguard against reentrancy string public emergencyTxt = 'Emergency circuit breaker is NOT ACTIVE'; // Track emergency circuit breaker status string public lockTxt = 'Lock is NOT ACTIVE'; // Track lock status uint public targetAmt; // Track donation limit to be sought uint public donationAmt; // Track current donation so far. uint public oldDonationAmt; // Track donation amount before withdraw payout uint public oldBalance; // Track the balance before withdraw payout uint public newBalance; // Track the balance after withdraw payout uint private round_expired; // Track time to expire round uint private escrowAmt; // Track the escrow amount from the beneficiary uint private beneficiaryAmt; // Track the beneficiary amount from the total donations uint private ownerAmt; // Track the owner amount from the total donations uint private duration; // Set the valid duration for a round of fundraising // Setup modifier for only owner modifier isAdmin() { require(msg.sender == owner); _; } // Setup modifier for Beneficiary modifier hasNoBeneficiary() { require(hasBeneficiary == false, 'Beneficiary has already been setup.'); _; } // Setup modifier for circuit breaker / Emergency stop flag to control control modifier notInEmergency { require(stopped == false, 'Emergency stop is active.'); _; } // Setup modifier for circuit breaker / Emergency stop flag to control control modifier isInEmergency { require(stopped == true, 'Emergency stop is not active.'); _; } // Returns the address of the Beneficiary event LogSetBeneficiary( address accountAddress ); event LogRefresh( bool refresh ); // The constructor set up default values for the contract constructor() public { targetAmt = 0; // Set donaiion target limit to zero donationAmt = 0; // Set donation to zero isAtLimit = false; // Set donation flag as false lock = false; // Set default lock state as false duration = 604800; // Set default fundraising time duration in 7 days in seconds (604800) from now } // Setup fallback to protect contract function() external payable { revert(); } // This is a data view function and can be removed at completion. // function showIntValues() public view returns (uint, uint, uint, bool, bool, bool, bool) { // return (address(this).balance, targetAmt, donationAmt, isAtLimit, lock, stopped, hasBeneficiary); // } // This function set the donation amount and the beneficiary // These actions can only be define by the owner // The beneficiary must commit to pay at least 10% of the proposed amount to be raised before the conbtract can accept the funding request function setDonationAndBeneficiary(uint _targetAmt) hasNoBeneficiary notInEmergency public payable returns (bool) { require(msg.sender != owner, 'Owner cannot be beneficiary.'); // Owner cannot be a beneficiary require(_targetAmt > 0, 'Donation limit must be greater than zero.'); require(msg.value > _targetAmt.div(10), 'Escrow amount must be greater than 10% of the amount to be raised.'); require(msg.value < _targetAmt, 'Escrow amount must be less than the amount to be raised.'); hasBeneficiary = true; // Accepts beneficiary for the contract and prevent recalling of the function escrowAmt = msg.value; // Seup the escrow amount targetAmt = _targetAmt; // Setup the donation limit beneficiary = msg.sender; // Setup the beneficiary oldDonationAmt = 0; // Set to zero oldBalance = 0; // Set to zero newBalance = address(this).balance; // Update current contract balance round_expired = now; // set round expiration to start with current time. round_expired = round_expired.add(duration); // Add Duration to round expiration time. } // This function accepts donations from Users // The function also checks if the fundraising has expired and limit has not been reached function sendDonations() notInEmergency public payable returns (bool) { require(round_expired != 0, 'Must have active fundraising.'); // Check if active fundraising exists require(hasBeneficiary == true, 'Beneficiary has not been defined.'); // Donation must have a beneficiary require(isAtLimit == false, 'Donation limit has been reached.'); // Limit has not been reached require(msg.sender != owner, 'Owner cannot be a participant.'); // Owner cannot be a participant require(msg.sender != beneficiary, 'Beneficiary cannot be a participant.'); // Beneficiary cannot be a participant balances[msg.sender] = balances[msg.sender].add(msg.value); // Track the donated amt from the user. donationAmt = donationAmt.add(msg.value); // Track the current donations newBalance = address(this).balance; // Update current contract balance // Check if fundraising time has not reached limit if (now <= round_expired) { // Check if donation limit has been reached if (donationAmt >= targetAmt) { isAtLimit = true; // Set donation flag as having reach the target oldDonationAmt = donationAmt; // Set the old donation amount - Use for testing oldBalance = address(this).balance; // Set the before withdraw balance - Use for testing withdrawDonations(); // Call withdraw to faciliate payments. } else { isAtLimit = false; // Set donation flag as not having reach the target } } else { // Time has expired and limit has not been reached. // owner.transfer(address(this).balance); // time has expired, end fundraising and transfer escrow to owner. round_expired = 0; // Clear time isAtLimit = true; // Forced Set donation flag as having reach the target oldDonationAmt = donationAmt; // Set the old donation amount - Use for testing oldBalance = address(this).balance; // Set the before withdraw balance - Use for testing withdrawDonations(); // Call withdraw to faciliate payments. } } // This function withdraws for the beneficiary and owner // Set global lock to prevent reentrancy // Compute payments to beneficiary and owner // Send to beneficiary and owner // implicitly set the transfer to prevent a reentrancy attack // Set payout flag to prevent reentrancy. function withdrawDonations() notInEmergency public payable { require (isAtLimit == true, 'Has not reached donation limit.'); // must be at donation limit require(!lock); // Must not already in locked state - This uses a MUTEX lock lock = true; // Force locked state to prevent reenterancy ownerAmt = donationAmt.div(10); // Calculate the owner portion => 10% beneficiaryAmt = donationAmt.sub(ownerAmt); // Calculate the beneficiary payment => 90% beneficiaryAmt = beneficiaryAmt.add(escrowAmt); // Calculate the beneficiary payment adjusted for escrow payment beneficiary.transfer(beneficiaryAmt); // Transfer the beneficiary amount to beneficiary owner.transfer(ownerAmt); // Transfer the owner amount to owner newBalance = address(this).balance; // Set the after withddraw balance - Use for testing lock = false; // Clear Locked state hasBeneficiary = false; // Wait for new beneficiary donationAmt = 0; // Clear to zero and waits for new beneficiary targetAmt = 0; // Clear to zero and waits for new beneficiary beneficiaryAmt = 0; // Set to zero ownerAmt = 0; // Set to zero isAtLimit = false; // Set to false beneficiary = address(0); // Clear beneficiary } // Add function that restricts stopping a contract to be based on another action function toggleContractActive() isAdmin public { stopped = !stopped; // Set the cirbuit breaker switch if (stopped) { emergencyTxt = 'Emergency circuit breaker is ACTIVE'; } else { emergencyTxt = 'Emergency circuit breaker is NOT ACTIVE'; } } // This function unlocks the lock for withdraws, just in case the contract is bugged function unlockLock() isAdmin isInEmergency public payable { lock = !lock; // Set the lock if (lock) { lockTxt = 'Lock is ACTIVE'; } else { lockTxt = 'Lock is NOT ACTIVE'; } } // This function ends collections and send contract value to owner function endDonations() isAdmin isInEmergency public payable { selfdestruct(owner); // End contract and send any remaining funds to owner } }
Forced Set donation flag as having reach the target
isAtLimit = true;
15,787,632
[ 1, 1290, 3263, 1000, 2727, 367, 2982, 487, 7999, 9287, 326, 1018, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 5411, 353, 861, 3039, 273, 638, 31, 1377, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/137/0x7cf2E30cA99410c03eed4B29e8909BbC0A0D60bC/sources/Users/rachel/dev/goodghosting/goodghosting-smart-contracts/contracts/GoodGhosting.sol
payment for first segment
_transferDaiToContract();
3,745,815
[ 1, 9261, 364, 1122, 3267, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 3639, 389, 13866, 40, 10658, 774, 8924, 5621, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: AGPL-3.0-only pragma solidity >=0.8.4; /* 30Web3 ERC721, Enumerable, Ownable, Adminlist Core is ERC721 library from Solmate by @transmissions11, modified to support Open Zeppelin Enumerable extension and hooks. Lilownable by @m1guelpf. Adminlist based on a branch of Open Zeppelin ownership branch from 2018. ERC721 Solmate: https://github.com/Rari-Capital/solmate/blob/main/src/tokens/ERC721.sol OZ Enumerable: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v4.4.2/contracts/token/ERC721/extensions/ERC721Enumerable.sol Lilownable: https://github.com/m1guelpf/erc721-drop/blob/main/src/LilOwnable.sol Adminlist: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/025c9bdcde412e65a307e4985151e7c023fd3870/contracts/ownership/Whitelist.sol @author kethic, xavier, larkef */ /// ---------------------------------------------------------------------------- /// Imports /// ---------------------------------------------------------------------------- import "./ERC721_Solmate_Hooked.sol"; import "./LilOwnable.sol"; import "./Adminlist.sol"; // Thank you tangert // https://gist.github.com/tangert/1eceaf04f2877d84fb0e10681b39d7e3#file-renderer-sol import "./Renderer.sol"; import "@openzeppelin/contracts/interfaces/IERC20.sol"; /// ---------------------------------------------------------------------------- /// Enums and Structs /// ---------------------------------------------------------------------------- /// ---------------------------------------------------------------------------- /// Errors /// ---------------------------------------------------------------------------- error InvalidToken(); error IndexOutOfBounds(); error TransferFailed(); error NoReentrancy(); contract NFT30Web3 is ERC721, LilOwnable, Adminlist, Renderer { /// ------------------------------------------------------------------------ /// Events /// ------------------------------------------------------------------------ /// ------------------------------------------------------------------------ /// Variables /// ------------------------------------------------------------------------ uint256 private currentToken; string public cohort; mapping(uint256 => string) idToCohort; uint8 private _mutex = 1; /// ------------------------------------------------------------------------ /// Modifiers /// ------------------------------------------------------------------------ modifier isValidToken(uint256 id) { if(ownerOf[id] == address(0)) revert InvalidToken(); _; } modifier mutex() { if(_mutex == 2) revert NoReentrancy(); _mutex = 2; _; _mutex = 1; } /// ------------------------------------------------------------------------ /// Functions /// ------------------------------------------------------------------------ constructor( address[] memory _adminlist, string memory _cohort ) ERC721 ( "30Web3 Graduates", "30Web3" ) { // Deployer has Admin Rights _setupAdmin(msg.sender); // Add the other Admins uint16 length = uint16(_adminlist.length); for(uint16 i=0; i < length; i = uncheckedInc(i)) { _setupAdmin(_adminlist[i]); } setCohort(_cohort); } function setCohort( string memory _cohort ) public onlyAdmin { cohort = _cohort; } function mint( address _target ) external payable onlyAdmin mutex { _mint(address(_target), currentToken); idToCohort[currentToken] = cohort; currentToken++; } function tokenURI( uint256 id ) public view override isValidToken(id) returns (string memory) { string memory svgString = _render(id, idToCohort[id]); return buildSvg("30Web3", "Congratulations on your successful completion of 30Web3!", svgString); } function contractURI() public pure returns (string memory) { return "data:application/json;base64,eyJuYW1lIjoiMzBXZWIzIEdyYWR1YXRlcyIsImRlc2NyaXB0aW9uIjoiMzAgZGF5cyBvZiBXZWIzIGlzIGFuIG9wcG9ydHVuaXR5IHRvIHdvcmsgd2l0aCB5b3VyIHBlZXJzLCBzaGlwIGEgcHJvamVjdCwgYW5kIGdhaW4gaGFuZHMtb24gV2ViMyBleHBlcmllbmNlIGluIHNtYWxsLCBjb2xsYWJvcmF0aXZlLCBmb2N1c2VkIGNvaG9ydHMuIFRoZXNlIHRva2VucyBjb21tZW1vcmF0ZSB0aGUgZ3JhZHVhdGVzIGZyb20gZWFjaCBjb2hvcnQuIiwiaW1hZ2UiOiAiZGF0YTppbWFnZS9zdmcreG1sO2Jhc2U2NCxQSE4yWnlCM2FXUjBhRDBpTlRSd2VDSWdhR1ZwWjJoMFBTSTBNSEI0SWlCMmFXVjNRbTk0UFNJd0lEQWdNelkySURJMk5pSWdabWxzYkQwaWJtOXVaU0lnZUcxc2JuTTlJbWgwZEhBNkx5OTNkM2N1ZHpNdWIzSm5Mekl3TURBdmMzWm5JajQ4Wld4c2FYQnpaU0JqZUQwaU1UTXlJaUJqZVQwaU1UTXpMalVpSUhKNFBTSXhNeklpSUhKNVBTSXhNekl1TlNJZ1ptbHNiRDBpSTBaR01EQTJSaUkrUEM5bGJHeHBjSE5sUGp4bklITjBlV3hsUFNKdGFYZ3RZbXhsYm1RdGJXOWtaVG9nWTI5c2IzSXRaRzlrWjJVN0lqNDhaV3hzYVhCelpTQmplRDBpTWpNMElpQmplVDBpTVRNeUxqVWlJSEo0UFNJeE16SWlJSEo1UFNJeE16SXVOU0lnWm1sc2JEMGlkMmhwZEdVaVBqd3ZaV3hzYVhCelpUNDhMMmMrUEhCaGRHZ2dabWxzYkMxeWRXeGxQU0psZG1WdWIyUmtJaUJqYkdsd0xYSjFiR1U5SW1WMlpXNXZaR1FpSUdROUlrMHhPREV1T0RFeUlERXdMamMxT0RkRE1qTXdMakF5TWlBek1DNDBPVEl5SURJMk5DQTNPQzR3TVRNeElESTJOQ0F4TXpNdU5VTXlOalFnTVRnNExqQTNNU0F5TXpFdU1UTTFJREl6TkM0NU16Y2dNVGcwTGpFNE9DQXlOVFV1TWpReFF6RXpOUzQ1TnpnZ01qTTFMalV3T0NBeE1ESWdNVGczTGprNE55QXhNRElnTVRNeUxqVkRNVEF5SURjM0xqa3lPVElnTVRNMExqZzJOU0F6TVM0d05qTTFJREU0TVM0NE1USWdNVEF1TnpVNE4xb2lJR1pwYkd3OUlpTkdSakF3UmtZaVBqd3ZjR0YwYUQ0OFkybHlZMnhsSUdONFBTSXhPRE1pSUdONVBTSXhNeklpSUhJOUlqZ3hJaUJtYVd4c1BTSWpPRFF6T1VWRUlqNDhMMk5wY21Oc1pUNDhjR0YwYUNCa1BTSk5NVFF3TGpneE5pQXhORE11T0RnNFF6RTBNQzQ0TVRZZ01UUTNMalF5T1NBeE16a3VPVFl6SURFMU1DNHdNVEVnTVRNNExqSTFOaUF4TlRFdU5qTXlRekV6Tmk0MU5Ea2dNVFV6TGpJeE1TQXhNek11TnpjMklERTFOQ0F4TWprdU9UTTJJREUxTkVneE1qRXVOelEwVmpFME9TNHlTREV6TUM0MU1USkRNVE15TGpFek15QXhORGt1TWlBeE16TXVNekk0SURFME9DNDRNemNnTVRNMExqQTVOaUF4TkRndU1URXlRekV6TkM0NE5qUWdNVFEzTGpNME5DQXhNelV1TWpRNElERTBOaTR4TkRrZ01UTTFMakkwT0NBeE5EUXVOVEk0VmpFek55NDVNelpETVRNMUxqSTBPQ0F4TXpZdU5USTRJREV6TkM0NE1qRWdNVE0xTGpReE9TQXhNek11T1RZNElERXpOQzQyTURoRE1UTXpMakV4TlNBeE16TXVOelUxSURFek1TNDVPRFFnTVRNekxqTXlPQ0F4TXpBdU5UYzJJREV6TXk0ek1qaElNVEl6TGpjeU9GWXhNamd1TlRJNFNERXlPUzQ1TXpaRE1UTXhMakkxT1NBeE1qZ3VOVEk0SURFek1pNHpOamdnTVRJNExqRXdNU0F4TXpNdU1qWTBJREV5Tnk0eU5EaERNVE0wTGpFMklERXlOaTR6T1RVZ01UTTBMall3T0NBeE1qVXVNalkwSURFek5DNDJNRGdnTVRJekxqZzFObFl4TVRndU5qQTRRekV6TkM0Mk1EZ2dNVEUyTGprNE55QXhNelF1TWpJMElERXhOUzQ0TVRNZ01UTXpMalExTmlBeE1UVXVNRGc0UXpFek1pNDNNekVnTVRFMExqTTJNeUF4TXpFdU5UVTNJREV4TkNBeE1qa3VPVE0ySURFeE5FZ3hNakV1TnpRMFZqRXdPUzR5U0RFeU9TNHhOamhETVRNeUxqYzVOU0F4TURrdU1pQXhNelV1TlRJMUlERXhNQzR3TVRFZ01UTTNMak0ySURFeE1TNDJNekpETVRNNUxqSXpOeUF4TVRNdU1qRXhJREUwTUM0eE56WWdNVEUxTGpjeU9DQXhOREF1TVRjMklERXhPUzR4T0RSV01USXpMakl4TmtNeE5EQXVNVGMySURFeU5pNDFNREVnTVRNNUxqQXdNeUF4TWpndU9UYzJJREV6Tmk0Mk5UWWdNVE13TGpZMFF6RXpPUzQwTWprZ01UTXlMakUzTmlBeE5EQXVPREUySURFek5DNDRJREUwTUM0NE1UWWdNVE00TGpVeE1sWXhORE11T0RnNFdrMHhOemN1TWpNMUlERTBNeTR4TWtNeE56Y3VNak0xSURFME5pNDJOakVnTVRjMkxqSTFNeUF4TkRrdU16Y3hJREUzTkM0eU9URWdNVFV4TGpJME9FTXhOekl1TXpjeElERTFNeTR3T0RNZ01UWTVMamMyT0NBeE5UUWdNVFkyTGpRNE15QXhOVFJJTVRZMUxqSXdNME14TmpFdU9URTNJREUxTkNBeE5Ua3VNamt6SURFMU15NHdPRE1nTVRVM0xqTXpNU0F4TlRFdU1qUTRRekUxTlM0ME1URWdNVFE1TGpNM01TQXhOVFF1TkRVeElERTBOaTQyTmpFZ01UVTBMalExTVNBeE5ETXVNVEpXTVRJd0xqQTRRekUxTkM0ME5URWdNVEUyTGpRNU5pQXhOVFV1TkRFeElERXhNeTQzT0RjZ01UVTNMak16TVNBeE1URXVPVFV5UXpFMU9TNHlOVEVnTVRFd0xqRXhOeUF4TmpFdU9EYzFJREV3T1M0eUlERTJOUzR5TURNZ01UQTVMakpJTVRZMkxqUTRNME14TmprdU9ERXhJREV3T1M0eUlERTNNaTQwTXpVZ01URXdMakV4TnlBeE56UXVNelUxSURFeE1TNDVOVEpETVRjMkxqSTNOU0F4TVRNdU56ZzNJREUzTnk0eU16VWdNVEUyTGpRNU5pQXhOemN1TWpNMUlERXlNQzR3T0ZZeE5ETXVNVEphVFRFM01TNDNPVFVnTVRFNExqZzJORU14TnpFdU56azFJREV4Tnk0MU5ERWdNVGN4TGpJNE15QXhNVFl1TkRFeElERTNNQzR5TlRrZ01URTFMalEzTWtNeE5qa3VNamMzSURFeE5DNDBPVEVnTVRZNExqQXhPU0F4TVRRZ01UWTJMalE0TXlBeE1UUklNVFkxTGpJd00wTXhOak11TmpZM0lERXhOQ0F4TmpJdU16ZzNJREV4TkM0ME9URWdNVFl4TGpNMk15QXhNVFV1TkRjeVF6RTJNQzR6T0RFZ01URTJMalF4TVNBeE5Ua3VPRGt4SURFeE55NDFOREVnTVRVNUxqZzVNU0F4TVRndU9EWTBWakV6Tmk0eU1EaE1NVGN4TGpjNU5TQXhNVGd1T0RZMFdrMHhOVGt1T0RreElERTBOQzR6TXpaRE1UVTVMamc1TVNBeE5EVXVOalU1SURFMk1DNHpPREVnTVRRMkxqZ3hNU0F4TmpFdU16WXpJREUwTnk0M09USkRNVFl5TGpNNE55QXhORGd1TnpNeElERTJNeTQyTmpjZ01UUTVMaklnTVRZMUxqSXdNeUF4TkRrdU1rZ3hOall1TkRnelF6RTJPQzR3TVRrZ01UUTVMaklnTVRZNUxqSTNOeUF4TkRndU56TXhJREUzTUM0eU5Ua2dNVFEzTGpjNU1rTXhOekV1TWpneklERTBOaTQ0TVRFZ01UY3hMamM1TlNBeE5EVXVOalU1SURFM01TNDNPVFVnTVRRMExqTXpObFl4TWpjdU1EVTJUREUxT1M0NE9URWdNVFEwTGpNek5scE5NakF3TGpJM055QXhNelV1T0RJMFRERTVOaTR5TkRVZ01UVTBTREU0T0M0MU5qVk1NVGcyTGpNNE9TQXhNRGt1TWtneE9URXVNVEkxVERFNU15NHdORFVnTVRRNUxqSk1NVGs0TGpNMU55QXhNamd1TURoSU1qQXlMak15TlV3eU1EY3VOelkxSURFME9TNHlUREl3T1M0M05Ea2dNVEE1TGpKSU1qRTBMakUyTlV3eU1URXVPVGc1SURFMU5FZ3lNRE11T1RJMVRESXdNQzR5TnpjZ01UTTFMamd5TkZwTk1qUTBMalV3TkNBeE5ETXVPRGc0UXpJME5DNDFNRFFnTVRRM0xqUXlPU0F5TkRNdU5qVWdNVFV3TGpBeE1TQXlOREV1T1RRMElERTFNUzQyTXpKRE1qUXdMakl6TnlBeE5UTXVNakV4SURJek55NDBOalFnTVRVMElESXpNeTQyTWpRZ01UVTBTREl5TlM0ME16SldNVFE1TGpKSU1qTTBMakpETWpNMUxqZ3lNU0F4TkRrdU1pQXlNemN1TURFMklERTBPQzQ0TXpjZ01qTTNMamM0TkNBeE5EZ3VNVEV5UXpJek9DNDFOVElnTVRRM0xqTTBOQ0F5TXpndU9UTTJJREUwTmk0eE5Ea2dNak00TGprek5pQXhORFF1TlRJNFZqRXpOeTQ1TXpaRE1qTTRMamt6TmlBeE16WXVOVEk0SURJek9DNDFNRGtnTVRNMUxqUXhPU0F5TXpjdU5qVTJJREV6TkM0Mk1EaERNak0yTGpnd01pQXhNek11TnpVMUlESXpOUzQyTnpJZ01UTXpMak15T0NBeU16UXVNalkwSURFek15NHpNamhJTWpJM0xqUXhObFl4TWpndU5USTRTREl6TXk0Mk1qUkRNak0wTGprME5pQXhNamd1TlRJNElESXpOaTR3TlRZZ01USTRMakV3TVNBeU16WXVPVFV5SURFeU55NHlORGhETWpNM0xqZzBPQ0F4TWpZdU16azFJREl6T0M0eU9UWWdNVEkxTGpJMk5DQXlNemd1TWprMklERXlNeTQ0TlRaV01URTRMall3T0VNeU16Z3VNamsySURFeE5pNDVPRGNnTWpNM0xqa3hNaUF4TVRVdU9ERXpJREl6Tnk0eE5EUWdNVEUxTGpBNE9FTXlNell1TkRFNElERXhOQzR6TmpNZ01qTTFMakkwTlNBeE1UUWdNak16TGpZeU5DQXhNVFJJTWpJMUxqUXpNbFl4TURrdU1rZ3lNekl1T0RVMlF6SXpOaTQwT0RJZ01UQTVMaklnTWpNNUxqSXhNeUF4TVRBdU1ERXhJREkwTVM0d05EZ2dNVEV4TGpZek1rTXlOREl1T1RJMUlERXhNeTR5TVRFZ01qUXpMamcyTkNBeE1UVXVOekk0SURJME15NDROalFnTVRFNUxqRTRORll4TWpNdU1qRTJRekkwTXk0NE5qUWdNVEkyTGpVd01TQXlOREl1TmprZ01USTRMamszTmlBeU5EQXVNelEwSURFek1DNDJORU15TkRNdU1URTNJREV6TWk0eE56WWdNalEwTGpVd05DQXhNelF1T0NBeU5EUXVOVEEwSURFek9DNDFNVEpXTVRRekxqZzRPRm9pSUdacGJHdzlJbmRvYVhSbElqNDhMM0JoZEdnK1BDOXpkbWMrIiwiZXh0ZXJuYWxfbGluayI6Imh0dHBzOi8vdHdpdHRlci5jb20vd3NseXZoIiwiZmVlX3JlY2lwaWVudCI6IjB4NjNjYWI2OTE4OWRCYTJmMTU0NGEyNWM4QzE5YjQzMDlmNDE1YzhBQSIsInNlbGxlcl9mZWVfYmFzaXNfcG9pbnRzIjowfQ=="; } function withdraw() public onlyAdmin { uint256 balance = address(this).balance; payable(msg.sender).transfer(balance); } function withdrawTokens( IERC20 token ) public onlyAdmin { uint256 balance = token.balanceOf(address(this)); token.transfer(msg.sender, balance); } /// ------------------------------------------------------------------------ /// ERC721Enumerable Variables /// ------------------------------------------------------------------------ // 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; /// ------------------------------------------------------------------------ /// ERC721Enumerable Functions /// ------------------------------------------------------------------------ function tokenOfOwnerByIndex( address owner, uint256 index ) public view returns (uint256) { if(index >= ERC721.balanceOf[owner]) revert IndexOutOfBounds(); return _ownedTokens[owner][index]; } function totalSupply() public view returns (uint256) { return _allTokens.length; } function tokenByIndex( uint256 index ) public view returns (uint256) { if(index >= totalSupply()) revert IndexOutOfBounds(); return _allTokens[index]; } function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } function _addTokenToOwnerEnumeration( address to, uint256 tokenId ) private { uint256 length = ERC721.balanceOf[to]; _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } function _addTokenToAllTokensEnumeration( uint256 tokenId ) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } function _removeTokenFromOwnerEnumeration( address from, uint256 tokenId ) private { uint256 lastTokenIndex = ERC721.balanceOf[from] - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _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 } delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; 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 delete _allTokensIndex[tokenId]; _allTokens.pop(); } /// ------------------------------------------------------------------------ /// ERC165 /// ------------------------------------------------------------------------ function supportsInterface(bytes4 interfaceId) public pure override(ERC721, LilOwnable) returns (bool) { return interfaceId == 0x01ffc9a7 || // ERC165 Interface ID for ERC165 interfaceId == 0x7f5828d0 || // ERC165 Interface ID for ERC173 interfaceId == 0x80ac58cd || // ERC165 Interface ID for ERC721 interfaceId == 0x5b5e139f || // ERC165 Interface ID for ERC721Metadata interfaceId == 0x780e9d63; // ERC165 Interface ID for ERC721Enumerable } /// ------------------------------------------------------------------------ /// Utility Functions /// ------------------------------------------------------------------------ //https://ethereum.stackexchange.com/questions/8346/convert-address-to-string function toAsciiString( address x ) internal pure returns (string memory) { bytes memory s = new bytes(40); for (uint256 i = 0; i < 20; i++) { bytes1 b = bytes1(uint8(uint256(uint160(x)) / (2**(8 * (19 - i))))); bytes1 hi = bytes1(uint8(b) / 16); bytes1 lo = bytes1(uint8(b) - 16 * uint8(hi)); s[2 * i] = char(hi); s[2 * i + 1] = char(lo); } return string(s); } function buildSvg( string memory nftName, string memory nftDescription, string memory svgString ) public pure returns (string memory) { string memory imgEncoded = Base64.encode(bytes(svgString)); string memory imgURI = string( abi.encodePacked("data:image/svg+xml;base64,", imgEncoded) ); string memory nftJson = string( abi.encodePacked( '{"name": "', nftName, '", "description": "', nftDescription, '", "image": "', imgURI, '"}' ) ); string memory nftEncoded = Base64.encode(bytes(nftJson)); string memory finalURI = string( abi.encodePacked("data:application/json;base64,", nftEncoded) ); return finalURI; } function char( bytes1 b ) internal pure returns (bytes1 c) { if (uint8(b) < 10) return bytes1(uint8(b) + 0x30); else return bytes1(uint8(b) + 0x57); } // https://gist.github.com/hrkrshnn/ee8fabd532058307229d65dcd5836ddc#the-increment-in-for-loop-post-condition-can-be-made-unchecked function uncheckedInc( uint16 i ) internal pure returns (uint16) { unchecked { return i + 1; } } } /// ---------------------------------------------------------------------------- /// External Contracts /// ---------------------------------------------------------------------------- // Primes NFT //https://etherscan.io/address/0xBDA937F5C5f4eFB2261b6FcD25A71A1C350FdF20#code#L1507 library Base64 { string internal constant TABLE_ENCODE = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; function encode(bytes memory data) internal pure returns (string memory) { if (data.length == 0) return ""; // load the table into memory string memory table = TABLE_ENCODE; // multiply by 4/3 rounded up uint256 encodedLen = 4 * ((data.length + 2) / 3); // add some extra buffer at the end required for the writing string memory result = new string(encodedLen + 32); assembly { // set the actual output length mstore(result, encodedLen) // prepare the lookup table let tablePtr := add(table, 1) // input ptr let dataPtr := data let endPtr := add(dataPtr, mload(data)) // result ptr, jump over length let resultPtr := add(result, 32) // run over the input, 3 bytes at a time for { } lt(dataPtr, endPtr) { } { // read 3 bytes dataPtr := add(dataPtr, 3) let input := mload(dataPtr) // write 4 characters mstore8( resultPtr, mload(add(tablePtr, and(shr(18, input), 0x3F))) ) resultPtr := add(resultPtr, 1) mstore8( resultPtr, mload(add(tablePtr, and(shr(12, input), 0x3F))) ) resultPtr := add(resultPtr, 1) mstore8( resultPtr, mload(add(tablePtr, and(shr(6, input), 0x3F))) ) resultPtr := add(resultPtr, 1) mstore8(resultPtr, mload(add(tablePtr, and(input, 0x3F)))) resultPtr := add(resultPtr, 1) } // padding with '=' switch mod(mload(data), 3) case 1 { mstore(sub(resultPtr, 2), shl(240, 0x3d3d)) } case 2 { mstore(sub(resultPtr, 1), shl(248, 0x3d)) } } return result; } }
------------------------------------------------------------------------ Events ------------------------------------------------------------------------ ------------------------------------------------------------------------ Variables ------------------------------------------------------------------------ ------------------------------------------------------------------------ Modifiers ------------------------------------------------------------------------
modifier isValidToken(uint256 id) { if(ownerOf[id] == address(0)) revert InvalidToken(); _; }
978,779
[ 1, 29461, 9043, 8879, 17082, 8879, 17082, 23536, 8879, 17082, 8879, 17082, 3431, 3383, 8879, 17082, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 9606, 4908, 1345, 12, 11890, 5034, 612, 13, 288, 203, 3639, 309, 12, 8443, 951, 63, 350, 65, 422, 1758, 12, 20, 3719, 15226, 1962, 1345, 5621, 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 ]
pragma solidity ^0.4.18; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; Unpause(); } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** * @title Pausable token * * @dev StandardToken modified with pausable transfers. **/ contract PausableToken is StandardToken, Pausable { function transfer(address _to, uint256 _value) public whenNotPaused returns (bool) { return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool) { return super.transferFrom(_from, _to, _value); } function approve(address _spender, uint256 _value) public whenNotPaused returns (bool) { return super.approve(_spender, _value); } function increaseApproval(address _spender, uint _addedValue) public whenNotPaused returns (bool success) { return super.increaseApproval(_spender, _addedValue); } function decreaseApproval(address _spender, uint _subtractedValue) public whenNotPaused returns (bool success) { return super.decreaseApproval(_spender, _subtractedValue); } } contract EthixToken is PausableToken { string public constant name = "EthixToken"; string public constant symbol = "ETHIX"; uint8 public constant decimals = 18; uint256 public constant INITIAL_SUPPLY = 100000000 * (10 ** uint256(decimals)); uint256 public totalSupply; /** * @dev Constructor that gives msg.sender all of existing tokens. */ function EthixToken() public { totalSupply = INITIAL_SUPPLY; balances[owner] = totalSupply; Transfer(0x0, owner, INITIAL_SUPPLY); } } /** * @title TokenDistributionStrategy * @dev Base abstract contract defining methods that control token distribution */ contract TokenDistributionStrategy { using SafeMath for uint256; CompositeCrowdsale crowdsale; uint256 rate; modifier onlyCrowdsale() { require(msg.sender == address(crowdsale)); _; } function TokenDistributionStrategy(uint256 _rate) { require(_rate > 0); rate = _rate; } function initializeDistribution(CompositeCrowdsale _crowdsale) { require(crowdsale == address(0)); require(_crowdsale != address(0)); crowdsale = _crowdsale; } function returnUnsoldTokens(address _wallet) onlyCrowdsale { } function whitelistRegisteredAmount(address beneficiary) view returns (uint256 amount) { } function distributeTokens(address beneficiary, uint amount); function calculateTokenAmount(uint256 _weiAmount, address beneficiary) view returns (uint256 amount); function getToken() view returns(ERC20); } /** * @title FixedPoolWithBonusTokenDistributionStrategy * @dev Strategy that distributes a fixed number of tokens among the contributors, * with a percentage depending in when the contribution is made, defined by periods. * It's done in two steps. First, it registers all of the contributions while the sale is active. * After the crowdsale has ended the contract compensate buyers proportionally to their contributions. * This class is abstract, the intervals have to be defined by subclassing */ contract FixedPoolWithBonusTokenDistributionStrategy is TokenDistributionStrategy { using SafeMath for uint256; uint256 constant MAX_DISCOUNT = 100; // Definition of the interval when the bonus is applicable struct BonusInterval { //end timestamp uint256 endPeriod; // percentage uint256 bonus; } BonusInterval[] bonusIntervals; bool intervalsConfigured = false; // The token being sold ERC20 token; mapping(address => uint256) contributions; uint256 totalContributed; //mapping(uint256 => BonusInterval) bonusIntervals; function FixedPoolWithBonusTokenDistributionStrategy(ERC20 _token, uint256 _rate) TokenDistributionStrategy(_rate) public { token = _token; } // First period will go from crowdsale.start_date to bonusIntervals[0].end // Next intervals have to end after the previous ones // Last interval must end when the crowdsale ends // All intervals must have a positive bonus (penalizations are not contemplated) modifier validateIntervals { _; require(intervalsConfigured == false); intervalsConfigured = true; require(bonusIntervals.length > 0); for(uint i = 0; i < bonusIntervals.length; ++i) { require(bonusIntervals[i].bonus <= MAX_DISCOUNT); require(bonusIntervals[i].bonus >= 0); require(crowdsale.startTime() < bonusIntervals[i].endPeriod); require(bonusIntervals[i].endPeriod <= crowdsale.endTime()); if (i != 0) { require(bonusIntervals[i-1].endPeriod < bonusIntervals[i].endPeriod); } } } // Init intervals function initIntervals() validateIntervals { } function calculateTokenAmount(uint256 _weiAmount, address beneficiary) view returns (uint256 tokens) { // calculate bonus in function of the time for (uint i = 0; i < bonusIntervals.length; i++) { if (now <= bonusIntervals[i].endPeriod) { // calculate token amount to be created tokens = _weiAmount.mul(rate); // OP : tokens + ((tokens * bonusIntervals[i].bonus) / 100) // BE CAREFULLY with decimals return tokens.add(tokens.mul(bonusIntervals[i].bonus).div(100)); } } return _weiAmount.mul(rate); } function distributeTokens(address _beneficiary, uint256 _tokenAmount) onlyCrowdsale { contributions[_beneficiary] = contributions[_beneficiary].add(_tokenAmount); totalContributed = totalContributed.add(_tokenAmount); require(totalContributed <= token.balanceOf(this)); } function compensate(address _beneficiary) { require(crowdsale.hasEnded()); if (token.transfer(_beneficiary, contributions[_beneficiary])) { contributions[_beneficiary] = 0; } } function getTokenContribution(address _beneficiary) view returns(uint256){ return contributions[_beneficiary]; } function getToken() view returns(ERC20) { return token; } function getIntervals() view returns (uint256[] _endPeriods, uint256[] _bonuss) { uint256[] memory endPeriods = new uint256[](bonusIntervals.length); uint256[] memory bonuss = new uint256[](bonusIntervals.length); for (uint256 i=0; i<bonusIntervals.length; i++) { endPeriods[i] = bonusIntervals[i].endPeriod; bonuss[i] = bonusIntervals[i].bonus; } return (endPeriods, bonuss); } } /** * @title VestedTokenDistributionStrategy * @dev Strategy that distributes a fixed number of tokens among the contributors. * It's done in two steps. First, it registers all of the contributions while the sale is active. * After the crowdsale has ended the contract compensate buyers proportionally to their contributions. */ contract VestedTokenDistributionStrategy is Ownable, FixedPoolWithBonusTokenDistributionStrategy { event Released(address indexed beneficiary, uint256 indexed amount); //Time after which is allowed to compensates uint256 public vestingStart; bool public vestingConfigured = false; uint256 public vestingDuration; mapping (address => uint256) public released; modifier vestingPeriodStarted { require(crowdsale.hasEnded()); require(vestingConfigured == true); require(now > vestingStart); _; } function VestedTokenDistributionStrategy(ERC20 _token, uint256 _rate) Ownable() FixedPoolWithBonusTokenDistributionStrategy(_token, _rate) { } /** * set the parameters for the compensation. Required to call before compensation * @dev WARNING, ONE TIME OPERATION * @param _vestingStart we start allowing the return of tokens after this * @param _vestingDuration percent each day (1 is 1% each day, 2 is % each 2 days, max 100) */ function configureVesting(uint256 _vestingStart, uint256 _vestingDuration) onlyOwner { require(vestingConfigured == false); require(_vestingStart > crowdsale.endTime()); require(_vestingDuration > 0); vestingStart = _vestingStart; vestingDuration = _vestingDuration; vestingConfigured = true; } /** * Will transfer the tokens vested until now to the beneficiary, if the vestingPeriodStarted * and there is an amount left to transfer * @param _beneficiary crowdsale contributor */ function compensate(address _beneficiary) public onlyOwner vestingPeriodStarted { uint256 unreleased = releasableAmount(_beneficiary); require(unreleased > 0); released[_beneficiary] = released[_beneficiary].add(unreleased); require(token.transfer(_beneficiary, unreleased)); Released(_beneficiary,unreleased); } /** * Calculates how many tokens the beneficiary should get taking in account already * released * @param _beneficiary the contributor * @return token number */ function releasableAmount(address _beneficiary) public view returns (uint256) { return vestedAmount(_beneficiary).sub(released[_beneficiary]); } /** * Calculates how many tokens the beneficiary have vested * vested = how many does she have according to the time * @param _beneficiary address of the contributor that needs the tokens * @return amount of tokens */ function vestedAmount(address _beneficiary) public view returns (uint256) { uint256 totalBalance = contributions[_beneficiary]; //Duration("after",vestingStart.add(vestingDuration)); if (now < vestingStart || vestingConfigured == false) { return 0; } else if (now >= vestingStart.add(vestingDuration)) { return totalBalance; } else { return totalBalance.mul(now.sub(vestingStart)).div(vestingDuration); } } function getReleased(address _beneficiary) public view returns (uint256) { return released[_beneficiary]; } } /** * @title WhitelistedDistributionStrategy * @dev This is an extension to add whitelist to a token distributionStrategy * */ contract WhitelistedDistributionStrategy is Ownable, VestedTokenDistributionStrategy { uint256 public constant maximumBidAllowed = 500 ether; uint256 rate_for_investor; mapping(address=>uint) public registeredAmount; event RegistrationStatusChanged(address target, bool isRegistered); function WhitelistedDistributionStrategy(ERC20 _token, uint256 _rate, uint256 _whitelisted_rate) VestedTokenDistributionStrategy(_token,_rate){ rate_for_investor = _whitelisted_rate; } /** * @dev Changes registration status of an address for participation. * @param target Address that will be registered/deregistered. * @param amount the amount of eht to invest for a investor bonus. */ function changeRegistrationStatus(address target, uint256 amount) public onlyOwner { require(amount <= maximumBidAllowed); registeredAmount[target] = amount; if (amount > 0){ RegistrationStatusChanged(target, true); }else{ RegistrationStatusChanged(target, false); } } /** * @dev Changes registration statuses of addresses for participation. * @param targets Addresses that will be registered/deregistered. * @param amounts the list of amounts of eth for every investor to invest for a investor bonus. */ function changeRegistrationStatuses(address[] targets, uint256[] amounts) public onlyOwner { require(targets.length == amounts.length); for (uint i = 0; i < targets.length; i++) { changeRegistrationStatus(targets[i], amounts[i]); } } /** * @dev overriding calculateTokenAmount for whilelist investors * @return bonus rate if it applies for the investor, * otherwise, return token amount according to super class */ function calculateTokenAmount(uint256 _weiAmount, address beneficiary) view returns (uint256 tokens) { if (_weiAmount >= registeredAmount[beneficiary] && registeredAmount[beneficiary] > 0 ){ tokens = _weiAmount.mul(rate_for_investor); } else{ tokens = super.calculateTokenAmount(_weiAmount, beneficiary); } } /** * @dev getRegisteredAmount for whilelist investors * @return registered amount if it applies for the investor, * otherwise, return 0 */ function whitelistRegisteredAmount(address beneficiary) view returns (uint256 amount) { amount = registeredAmount[beneficiary]; } } /** * @title EthicHubTokenDistributionStrategy * @dev Strategy that distributes a fixed number of tokens among the contributors, * with a percentage deppending in when the contribution is made, defined by periods. * It's done in two steps. First, it registers all of the contributions while the sale is active. * After the crowdsale has ended the contract compensate buyers proportionally to their contributions. * Contributors registered to the whitelist will have better rates */ contract EthicHubTokenDistributionStrategy is Ownable, WhitelistedDistributionStrategy { event UnsoldTokensReturned(address indexed destination, uint256 amount); function EthicHubTokenDistributionStrategy(EthixToken _token, uint256 _rate, uint256 _rateForWhitelisted) WhitelistedDistributionStrategy(_token, _rate, _rateForWhitelisted) public { } // Init intervals function initIntervals() onlyOwner validateIntervals { //For extra security, we check the owner of the crowdsale is the same of the owner of the distribution require(owner == crowdsale.owner()); bonusIntervals.push(BonusInterval(crowdsale.startTime() + 1 days,10)); bonusIntervals.push(BonusInterval(crowdsale.startTime() + 2 days,10)); bonusIntervals.push(BonusInterval(crowdsale.startTime() + 3 days,8)); bonusIntervals.push(BonusInterval(crowdsale.startTime() + 4 days,6)); bonusIntervals.push(BonusInterval(crowdsale.startTime() + 5 days,4)); bonusIntervals.push(BonusInterval(crowdsale.startTime() + 6 days,2)); } function returnUnsoldTokens(address _wallet) onlyCrowdsale { //require(crowdsale.endTime() <= now); //this made no sense if (token.balanceOf(this) == 0) { UnsoldTokensReturned(_wallet,0); return; } uint256 balance = token.balanceOf(this).sub(totalContributed); require(balance > 0); if(token.transfer(_wallet, balance)) { UnsoldTokensReturned(_wallet, balance); } } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title CompositeCrowdsale * @dev CompositeCrowdsale is a base contract for managing a token crowdsale. * Contrary to a classic crowdsale, it favours composition over inheritance. * * Crowdsale behaviour can be modified by specifying TokenDistributionStrategy * which is a dedicated smart contract that delegates all of the logic managing * token distribution. * */ contract CompositeCrowdsale is Ownable { using SafeMath for uint256; // The token being sold TokenDistributionStrategy public tokenDistribution; // start and end timestamps where investments are allowed (both inclusive) uint256 public startTime; uint256 public endTime; // address where funds are collected address public wallet; // amount of raised money in wei uint256 public weiRaised; /** * event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); function CompositeCrowdsale(uint256 _startTime, uint256 _endTime, address _wallet, TokenDistributionStrategy _tokenDistribution) public { require(_startTime >= now); require(_endTime >= _startTime); require(_wallet != 0x0); require(address(_tokenDistribution) != address(0)); startTime = _startTime; endTime = _endTime; tokenDistribution = _tokenDistribution; tokenDistribution.initializeDistribution(this); wallet = _wallet; } // fallback function can be used to buy tokens function () payable { buyTokens(msg.sender); } // low level token purchase function function buyTokens(address beneficiary) payable { require(beneficiary != 0x0); require(validPurchase()); uint256 weiAmount = msg.value; // calculate token amount to be created uint256 tokens = tokenDistribution.calculateTokenAmount(weiAmount, beneficiary); // update state weiRaised = weiRaised.add(weiAmount); tokenDistribution.distributeTokens(beneficiary, tokens); TokenPurchase(msg.sender, beneficiary, weiAmount, tokens); forwardFunds(); } // send ether to the fund collection wallet // override to create custom fund forwarding mechanisms function forwardFunds() internal { wallet.transfer(msg.value); } // @return true if the transaction can buy tokens function validPurchase() internal view returns (bool) { bool withinPeriod = now >= startTime && now <= endTime; bool nonZeroPurchase = msg.value != 0; return withinPeriod && nonZeroPurchase; } // @return true if crowdsale event has ended function hasEnded() public view returns (bool) { return now > endTime; } } /** * @title CappedCompositeCrowdsale * @dev Extension of CompositeCrowdsale with a max amount of funds raised */ contract CappedCompositeCrowdsale is CompositeCrowdsale { using SafeMath for uint256; uint256 public cap; function CappedCompositeCrowdsale(uint256 _cap) public { require(_cap > 0); cap = _cap; } // overriding Crowdsale#validPurchase to add extra cap logic // @return true if investors can buy at the moment function validPurchase() internal view returns (bool) { bool withinCap = weiRaised.add(msg.value) <= cap; return withinCap && super.validPurchase(); } // overriding Crowdsale#hasEnded to add cap logic // @return true if crowdsale event has ended function hasEnded() public view returns (bool) { bool capReached = weiRaised >= cap; return super.hasEnded() || capReached; } } /** * @title FinalizableCompositeCrowdsale * @dev Extension of CompositeCrowdsale where an owner can do extra work * after finishing. */ contract FinalizableCompositeCrowdsale is CompositeCrowdsale { using SafeMath for uint256; bool public isFinalized = false; event Finalized(); /** * @dev Must be called after crowdsale ends, to do some extra finalization * work. Calls the contract's finalization function. */ function finalize() onlyOwner public { require(!isFinalized); require(hasEnded()); finalization(); Finalized(); isFinalized = true; } /** * @dev Can be overridden to add finalization logic. The overriding function * should call super.finalization() to ensure the chain of finalization is * executed entirely. */ function finalization() internal { } } /** * @title RefundVault * @dev This contract is used for storing funds while a crowdsale * is in progress. Supports refunding the money if crowdsale fails, * and forwarding it if crowdsale is successful. */ contract RefundVault is Ownable { using SafeMath for uint256; enum State { Active, Refunding, Closed } mapping (address => uint256) public deposited; address public wallet; State public state; event Closed(); event RefundsEnabled(); event Refunded(address indexed beneficiary, uint256 weiAmount); function RefundVault(address _wallet) public { require(_wallet != address(0)); wallet = _wallet; state = State.Active; } function deposit(address investor) onlyOwner public payable { require(state == State.Active); deposited[investor] = deposited[investor].add(msg.value); } function close() onlyOwner public { require(state == State.Active); state = State.Closed; Closed(); wallet.transfer(this.balance); } function enableRefunds() onlyOwner public { require(state == State.Active); state = State.Refunding; RefundsEnabled(); } function refund(address investor) public { require(state == State.Refunding); uint256 depositedValue = deposited[investor]; deposited[investor] = 0; investor.transfer(depositedValue); Refunded(investor, depositedValue); } } /** * @title RefundableCompositeCrowdsale * @dev Extension of CompositeCrowdsale contract that adds a funding goal, and * the possibility of users getting a refund if goal is not met. * Uses a RefundVault as the crowdsale's vault. */ contract RefundableCompositeCrowdsale is FinalizableCompositeCrowdsale { using SafeMath for uint256; // minimum amount of funds to be raised in weis uint256 public goal; // refund vault used to hold funds while crowdsale is running RefundVault public vault; function RefundableCompositeCrowdsale(uint256 _goal) { require(_goal > 0); vault = new RefundVault(wallet); goal = _goal; } // We're overriding the fund forwarding from Crowdsale. // In addition to sending the funds, we want to call // the RefundVault deposit function function forwardFunds() internal { vault.deposit.value(msg.value)(msg.sender); } // if crowdsale is unsuccessful, investors can claim refunds here function claimRefund() public { require(isFinalized); require(!goalReached()); vault.refund(msg.sender); } // vault finalization task, called when owner calls finalize() function finalization() internal { if (goalReached()) { vault.close(); } else { vault.enableRefunds(); } super.finalization(); } function goalReached() public view returns (bool) { return weiRaised >= goal; } } contract EthicHubPresale is Ownable, Pausable, CappedCompositeCrowdsale, RefundableCompositeCrowdsale { uint256 public constant minimumBidAllowed = 0.1 ether; uint256 public constant maximumBidAllowed = 100 ether; uint256 public constant WHITELISTED_PREMIUM_TIME = 1 days; mapping(address=>uint) public participated; /** * @dev since our wei/token conversion rate is different, we implement it separatedly * from Crowdsale * [EthicHubPresale description] * @param _startTime start time in unix timestamp format * @param _endTime time in unix timestamp format * @param _goal minimum wei amount to consider the project funded. * @param _cap maximum amount the crowdsale will accept. * @param _wallet where funds are collected. * @param _tokenDistribution Strategy to distributed tokens. */ function EthicHubPresale(uint256 _startTime, uint256 _endTime, uint256 _goal, uint256 _cap, address _wallet, EthicHubTokenDistributionStrategy _tokenDistribution) CompositeCrowdsale(_startTime, _endTime, _wallet, _tokenDistribution) CappedCompositeCrowdsale(_cap) RefundableCompositeCrowdsale(_goal) { //As goal needs to be met for a successful crowdsale //the value needs to less or equal than a cap which is limit for accepted funds require(_goal <= _cap); } function claimRefund() public { super.claimRefund(); } /** * We enforce a minimum purchase price and a maximum investemnt per wallet * @return valid */ function buyTokens(address beneficiary) whenNotPaused payable { require(msg.value >= minimumBidAllowed); require(participated[msg.sender].add(msg.value) <= maximumBidAllowed); participated[msg.sender] = participated[msg.sender].add(msg.value); super.buyTokens(beneficiary); } /** * Get user invested amount by his address, used to calculate user referral contribution * @return total invested amount */ function getInvestedAmount(address investor) view public returns(uint investedAmount){ investedAmount = participated[investor]; } // overriding Crowdsale#validPurchase to add extra cap logic // whitelisted user can purchase tokens one day before the ico stated // @return true if investors can buy at the moment function validPurchase() internal view returns (bool) { // whitelist exclusive purchasing time if ((now >= startTime.sub(WHITELISTED_PREMIUM_TIME)) && (now <= startTime)){ uint256 registeredAmount = tokenDistribution.whitelistRegisteredAmount(msg.sender); bool isWhitelisted = registeredAmount > 0; bool withinCap = weiRaised.add(msg.value) <= cap; bool nonZeroPurchase = msg.value != 0; return isWhitelisted && withinCap && nonZeroPurchase; } else { return super.validPurchase(); } } /** * When the crowdsale is finished, we send the remaining tokens back to the wallet */ function finalization() internal { super.finalization(); tokenDistribution.returnUnsoldTokens(wallet); } }
* @title FinalizableCompositeCrowdsale @dev Extension of CompositeCrowdsale where an owner can do extra work after finishing./
contract FinalizableCompositeCrowdsale is CompositeCrowdsale { using SafeMath for uint256; bool public isFinalized = false; event Finalized(); function finalize() onlyOwner public { require(!isFinalized); require(hasEnded()); finalization(); Finalized(); isFinalized = true; } function finalization() internal { } }
6,403,716
[ 1, 7951, 6934, 9400, 39, 492, 2377, 5349, 225, 10021, 434, 14728, 39, 492, 2377, 5349, 1625, 392, 3410, 848, 741, 2870, 1440, 1839, 4076, 310, 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, 16269, 6934, 9400, 39, 492, 2377, 5349, 353, 14728, 39, 492, 2377, 5349, 288, 203, 225, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 203, 225, 1426, 1071, 29200, 1235, 273, 629, 31, 203, 203, 225, 871, 16269, 1235, 5621, 203, 203, 225, 445, 12409, 1435, 1338, 5541, 1071, 288, 203, 565, 2583, 12, 5, 291, 7951, 1235, 1769, 203, 565, 2583, 12, 5332, 28362, 10663, 203, 203, 565, 727, 1588, 5621, 203, 565, 16269, 1235, 5621, 203, 203, 565, 29200, 1235, 273, 638, 31, 203, 225, 289, 203, 203, 225, 445, 727, 1588, 1435, 2713, 288, 203, 225, 289, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.5.9; // optimization enabled, runs: 10000, evm: constantinople /** * @title HomeWork Interface (version 1) - EIP165 ID 0xe5399799 * @author 0age * @notice Homework is a utility to find, share, and reuse "home" addresses for * contracts. Anyone can work to find a new home address by searching for keys, * a 32-byte value with the first 20 bytes equal to the finder's calling address * (or derived by hashing an arbitrary 32-byte salt and the caller's address), * and can then deploy any contract they like (even one with a constructor) to * the address, or mint an ERC721 token that the owner can redeem that will then * allow them to do the same. Also, if the contract is `SELFDESTRUCT`ed, a new * contract can be redeployed by the current controller to the same address! * @dev This contract allows contract addresses to be located ahead of time, and * for arbitrary bytecode to be deployed (and redeployed if so desired, i.e. * metamorphic contracts) to the located address by a designated controller. To * enable this, the contract first deploys an "initialization-code-in-runtime" * contract, with the creation code of the contract you want to deploy stored in * RUNTIME code. Then, to deploy the actual contract, it retrieves the address * of the storage contract and `DELEGATECALL`s into it to execute the init code * and, if successful, retrieves and returns the contract runtime code. Rather * than using a located address directly, you can also lock it in the contract * and mint and ERC721 token for it, which can then be redeemed in order to gain * control over deployment to the address (note that tokens may not be minted if * the contract they control currently has a deployed contract at that address). * Once a contract undergoes metamorphosis, all existing storage will be deleted * and any existing contract code will be replaced with the deployed contract * code of the new implementation contract. The mechanisms behind this contract * are highly experimental - proceed with caution and please share any exploits * or optimizations you discover. */ interface IHomeWork { // Fires when a contract is deployed or redeployed to a given home address. event NewResident( address indexed homeAddress, bytes32 key, bytes32 runtimeCodeHash ); // Fires when a new runtime storage contract is deployed. event NewRuntimeStorageContract( address runtimeStorageContract, bytes32 runtimeCodeHash ); // Fires when a controller is changed from the default controller. event NewController(bytes32 indexed key, address newController); // Fires when a new high score is submitted. event NewHighScore(bytes32 key, address submitter, uint256 score); // Track total contract deploys and current controller for each home address. struct HomeAddress { bool exists; address controller; uint88 deploys; } // Track derivation of key for a given home address based on salt & submitter. struct KeyInformation { bytes32 key; bytes32 salt; address submitter; } /** * @notice Deploy a new contract with the desired initialization code to the * home address corresponding to a given key. Two conditions must be met: the * submitter must be designated as the controller of the home address (with * the initial controller set to the address corresponding to the first twenty * bytes of the key), and there must not be a contract currently deployed at * the home address. These conditions can be checked by calling * `getHomeAddressInformation` and `isDeployable` with the same key. * @param key bytes32 The unique value used to derive the home address. * @param initializationCode bytes The contract creation code that will be * used to deploy the contract to the home address. * @return The home address of the deployed contract. * @dev In order to deploy the contract to the home address, a new contract * will be deployed with runtime code set to the initialization code of the * contract that will be deployed to the home address. Then, metamorphic * initialization code will retrieve that initialization code and use it to * set up and deploy the desired contract to the home address. Bear in mind * that the deployed contract will interpret msg.sender as the address of THIS * contract, and not the address of the submitter - if the constructor of the * deployed contract uses msg.sender to set up ownership or other variables, * you must modify it to accept a constructor argument with the appropriate * address, or alternately to hard-code the intended address. Also, if your * contract DOES have constructor arguments, remember to include them as * ABI-encoded arguments at the end of the initialization code, just as you * would when performing a standard deploy. You may also want to provide the * key to `setReverseLookup` in order to find it again using only the home * address to prevent accidentally losing the key. */ function deploy(bytes32 key, bytes calldata initializationCode) external payable returns (address homeAddress, bytes32 runtimeCodeHash); /** * @notice Mint an ERC721 token to the supplied owner that can be redeemed in * order to gain control of a home address corresponding to a given key. Two * conditions must be met: the submitter must be designated as the controller * of the home address (with the initial controller set to the address * corresponding to the first 20 bytes of the key), and there must not be a * contract currently deployed at the home address. These conditions can be * checked by calling `getHomeAddressInformation` and `isDeployable` with the * same key. * @param key bytes32 The unique value used to derive the home address. * @param owner address The account that will be granted ownership of the * ERC721 token. * @dev In order to mint an ERC721 token, the assocated home address cannot be * in use, or else the token will not be able to deploy to the home address. * The controller is set to this contract until the token is redeemed, at * which point the redeemer designates a new controller for the home address. * The key of the home address and the tokenID of the ERC721 token are the * same value, but different types (bytes32 vs. uint256). */ function lock(bytes32 key, address owner) external; /** * @notice Burn an ERC721 token to allow the supplied controller to gain the * ability to deploy to the home address corresponding to the key matching the * burned token. The submitter must be designated as either the owner of the * token or as an approved spender. * @param tokenId uint256 The ID of the ERC721 token to redeem. * @param controller address The account that will be granted control of the * home address corresponding to the given token. * @dev The controller cannot be designated as the address of this contract, * the null address, or the home address (the restriction on setting the home * address as the controller is due to the fact that the home address will not * be able to deploy to itself, as it needs to be empty before a contract can * be deployed to it). */ function redeem(uint256 tokenId, address controller) external; /** * @notice Transfer control over deployment to the home address corresponding * to a given key. The caller must be designated as the current controller of * the home address (with the initial controller set to the address * corresponding to the first 20 bytes of the key) - This condition can be * checked by calling `getHomeAddressInformation` with the same key. * @param key bytes32 The unique value used to derive the home address. * @param controller address The account that will be granted control of the * home address corresponding to the given key. * @dev The controller cannot be designated as the address of this contract, * the null address, or the home address (the restriction on setting the home * address as the controller is due to the fact that the home address will not * be able to deploy to itself, as it needs to be empty before a contract can * be deployed to it). */ function assignController(bytes32 key, address controller) external; /** * @notice Transfer control over deployment to the home address corresponding * to a given key to the null address, which will prevent it from being * deployed to again in the future. The caller must be designated as the * current controller of the corresponding home address (with the initial * controller set to the address corresponding to the first 20 bytes of the * key) - This condition can be checked by calling `getHomeAddressInformation` * with the same key. * @param key bytes32 The unique value used to derive the home address. */ function relinquishControl(bytes32 key) external; /** * @notice Burn an ERC721 token, set a supplied controller, and deploy a new * contract with the supplied initialization code to the corresponding home * address for the given token. The submitter must be designated as either the * owner of the token or as an approved spender. * @param tokenId uint256 The ID of the ERC721 token to redeem. * @param controller address The account that will be granted control of the * home address corresponding to the given token. * @param initializationCode bytes The contract creation code that will be * used to deploy the contract to the home address. * @return The home address and runtime code hash of the deployed contract. * @dev In order to deploy the contract to the home address, a new contract * will be deployed with runtime code set to the initialization code of the * contract that will be deployed to the home address. Then, metamorphic * initialization code will retrieve that initialization code and use it to * set up and deploy the desired contract to the home address. Bear in mind * that the deployed contract will interpret msg.sender as the address of THIS * contract, and not the address of the submitter - if the constructor of the * deployed contract uses msg.sender to set up ownership or other variables, * you must modify it to accept a constructor argument with the appropriate * address, or alternately to hard-code the intended address. Also, if your * contract DOES have constructor arguments, remember to include them as * ABI-encoded arguments at the end of the initialization code, just as you * would when performing a standard deploy. You may also want to provide the * key to `setReverseLookup` in order to find it again using only the home * address to prevent accidentally losing the key. The controller cannot be * designated as the address of this contract, the null address, or the home * address (the restriction on setting the home address as the controller is * due to the fact that the home address will not be able to deploy to itself, * as it needs to be empty before a contract can be deployed to it). Also, * checks on the contract at the home address being empty or not having the * correct controller are unnecessary, as they are performed when minting the * token and cannot be altered until the token is redeemed. */ function redeemAndDeploy( uint256 tokenId, address controller, bytes calldata initializationCode ) external payable returns (address homeAddress, bytes32 runtimeCodeHash); /** * @notice Derive a new key by concatenating an arbitrary 32-byte salt value * and the address of the caller and performing a keccak256 hash. This allows * for the creation of keys with additional entropy where desired while also * preventing collisions with standard keys. The caller will be set as the * controller of the derived key. * @param salt bytes32 The desired salt value to use (along with the address * of the caller) when deriving the resultant key and corresponding home * address. * @return The derived key. * @dev Home addresses from derived keys will take longer to "mine" or locate, * as an additional hash must be performed when computing the corresponding * home address for each given salt input. Each caller will derive a different * key even if they are supplying the same salt value. */ function deriveKey(bytes32 salt) external returns (bytes32 key); /** * @notice Mint an ERC721 token to the supplied owner that can be redeemed in * order to gain control of a home address corresponding to a given derived * key. Two conditions must be met: the submitter must be designated as the * current controller of the home address, and there must not be a contract * currently deployed at the home address. These conditions can be checked by * calling `getHomeAddressInformation` and `isDeployable` with the key * determined by calling `getDerivedKey`. * @param salt bytes32 The salt value that is used to derive the key. * @param owner address The account that will be granted ownership of the * ERC721 token. * @return The derived key. * @dev In order to mint an ERC721 token, the assocated home address cannot be * in use, or else the token will not be able to deploy to the home address. * The controller is set to this contract until the token is redeemed, at * which point the redeemer designates a new controller for the home address. * The key of the home address and the tokenID of the ERC721 token are the * same value, but different types (bytes32 vs. uint256). */ function deriveKeyAndLock(bytes32 salt, address owner) external returns (bytes32 key); /** * @notice Transfer control over deployment to the home address corresponding * to a given derived key. The caller must be designated as the current * controller of the home address - This condition can be checked by calling * `getHomeAddressInformation` with the key obtained via `getDerivedKey`. * @param salt bytes32 The salt value that is used to derive the key. * @param controller address The account that will be granted control of the * home address corresponding to the given derived key. * @return The derived key. * @dev The controller cannot be designated as the address of this contract, * the null address, or the home address (the restriction on setting the home * address as the controller is due to the fact that the home address will not * be able to deploy to itself, as it needs to be empty before a contract can * be deployed to it). */ function deriveKeyAndAssignController(bytes32 salt, address controller) external returns (bytes32 key); /** * @notice Transfer control over deployment to the home address corresponding * to a given derived key to the null address, which will prevent it from * being deployed to again in the future. The caller must be designated as the * current controller of the home address - This condition can be checked by * calling `getHomeAddressInformation` with the key determined by calling * `getDerivedKey`. * @param salt bytes32 The salt value that is used to derive the key. * @return The derived key. */ function deriveKeyAndRelinquishControl(bytes32 salt) external returns (bytes32 key); /** * @notice Record a key that corresponds to a given home address by supplying * said key and using it to derive the address. This enables reverse lookup * of a key using only the home address in question. This method may be called * by anyone - control of the key is not required. * @param key bytes32 The unique value used to derive the home address. * @dev This does not set the salt or submitter fields, as those apply only to * derived keys (although a derived key may also be set with this method, just * without the derived fields). */ function setReverseLookup(bytes32 key) external; /** * @notice Record the derived key that corresponds to a given home address by * supplying the salt and submitter that were used to derive the key. This * facititates reverse lookup of the derivation method of a key using only the * home address in question. This method may be called by anyone - control of * the derived key is not required. * @param salt bytes32 The salt value that is used to derive the key. * @param submitter address The account that submits the salt that is used to * derive the key. */ function setDerivedReverseLookup(bytes32 salt, address submitter) external; /** * @notice Deploy a new storage contract with the supplied code as runtime * code without deploying a contract to a home address. This can be used to * store the contract creation code for use in future deployments of contracts * to home addresses. * @param codePayload bytes The code to set as the runtime code of the * deployed contract. * @return The address of the deployed storage contract. * @dev Consider placing adequate protections on the storage contract to * prevent unwanted callers from modifying or destroying it. Also, if you are * placing contract contract creation code into the runtime storage contract, * remember to include any constructor parameters as ABI-encoded arguments at * the end of the contract creation code, similar to how you would perform a * standard deployment. */ function deployRuntimeStorageContract(bytes calldata codePayload) external returns (address runtimeStorageContract); /** * @notice Deploy a new contract with the initialization code stored in the * runtime code at the specified initialization runtime storage contract to * the home address corresponding to a given key. Two conditions must be met: * the submitter must be designated as the controller of the home address * (with the initial controller set to the address corresponding to the first * 20 bytes of the key), and there must not be a contract currently deployed * at the home address. These conditions can be checked by calling * `getHomeAddressInformation` and `isDeployable` with the same key. * @param key bytes32 The unique value used to derive the home address. * @param initializationRuntimeStorageContract address The storage contract * with runtime code equal to the contract creation code that will be used to * deploy the contract to the home address. * @return The home address and runtime code hash of the deployed contract. * @dev When deploying a contract to a home address via this method, the * metamorphic initialization code will retrieve whatever initialization code * currently resides at the specified address and use it to set up and deploy * the desired contract to the home address. Bear in mind that the deployed * contract will interpret msg.sender as the address of THIS contract, and not * the address of the submitter - if the constructor of the deployed contract * uses msg.sender to set up ownership or other variables, you must modify it * to accept a constructor argument with the appropriate address, or * alternately to hard-code the intended address. Also, if your contract DOES * have constructor arguments, remember to include them as ABI-encoded * arguments at the end of the initialization code, just as you would when * performing a standard deploy. You may also want to provide the key to * `setReverseLookup` in order to find it again using only the home address to * prevent accidentally losing the key. */ function deployViaExistingRuntimeStorageContract( bytes32 key, address initializationRuntimeStorageContract ) external payable returns (address homeAddress, bytes32 runtimeCodeHash); /** * @notice Burn an ERC721 token, set a supplied controller, and deploy a new * contract with the initialization code stored in the runtime code at the * specified initialization runtime storage contract to the home address * corresponding to a given key. The submitter must be designated as either * the owner of the token or as an approved spender. * @param tokenId uint256 The ID of the ERC721 token to redeem. * @param controller address The account that will be granted control of the * home address corresponding to the given token. * @param initializationRuntimeStorageContract address The storage contract * with runtime code equal to the contract creation code that will be used to * deploy the contract to the home address. * @return The home address and runtime code hash of the deployed contract. * @dev When deploying a contract to a home address via this method, the * metamorphic initialization code will retrieve whatever initialization code * currently resides at the specified address and use it to set up and deploy * the desired contract to the home address. Bear in mind that the deployed * contract will interpret msg.sender as the address of THIS contract, and not * the address of the submitter - if the constructor of the deployed contract * uses msg.sender to set up ownership or other variables, you must modify it * to accept a constructor argument with the appropriate address, or * alternately to hard-code the intended address. Also, if your contract DOES * have constructor arguments, remember to include them as ABI-encoded * arguments at the end of the initialization code, just as you would when * performing a standard deploy. You may also want to provide the key to * `setReverseLookup` in order to find it again using only the home address to * prevent accidentally losing the key. The controller cannot be designated as * the address of this contract, the null address, or the home address (the * restriction on setting the home address as the controller is due to the * fact that the home address will not be able to deploy to itself, as it * needs to be empty before a contract can be deployed to it). Also, checks on * the contract at the home address being empty or not having the correct * controller are unnecessary, as they are performed when minting the token * and cannot be altered until the token is redeemed. */ function redeemAndDeployViaExistingRuntimeStorageContract( uint256 tokenId, address controller, address initializationRuntimeStorageContract ) external payable returns (address homeAddress, bytes32 runtimeCodeHash); /** * @notice Deploy a new contract with the desired initialization code to the * home address corresponding to a given derived key. Two conditions must be * met: the submitter must be designated as the controller of the home * address, and there must not be a contract currently deployed at the home * address. These conditions can be checked by calling * `getHomeAddressInformation` and `isDeployable` with the key obtained by * calling `getDerivedKey`. * @param salt bytes32 The salt value that is used to derive the key. * @param initializationCode bytes The contract creation code that will be * used to deploy the contract to the home address. * @return The home address, derived key, and runtime code hash of the * deployed contract. * @dev In order to deploy the contract to the home address, a new contract * will be deployed with runtime code set to the initialization code of the * contract that will be deployed to the home address. Then, metamorphic * initialization code will retrieve that initialization code and use it to * set up and deploy the desired contract to the home address. Bear in mind * that the deployed contract will interpret msg.sender as the address of THIS * contract, and not the address of the submitter - if the constructor of the * deployed contract uses msg.sender to set up ownership or other variables, * you must modify it to accept a constructor argument with the appropriate * address, or alternately to hard-code the intended address. Also, if your * contract DOES have constructor arguments, remember to include them as * ABI-encoded arguments at the end of the initialization code, just as you * would when performing a standard deploy. You may want to provide the salt * and submitter to `setDerivedReverseLookup` in order to find the salt, * submitter, and derived key using only the home address to prevent * accidentally losing them. */ function deriveKeyAndDeploy(bytes32 salt, bytes calldata initializationCode) external payable returns (address homeAddress, bytes32 key, bytes32 runtimeCodeHash); /** * @notice Deploy a new contract with the initialization code stored in the * runtime code at the specified initialization runtime storage contract to * the home address corresponding to a given derived key. Two conditions must * be met: the submitter must be designated as the controller of the home * address, and there must not be a contract currently deployed at the home * address. These conditions can be checked by calling * `getHomeAddressInformation` and `isDeployable` with the key obtained by * calling `getDerivedKey`. * @param salt bytes32 The salt value that is used to derive the key. * @param initializationRuntimeStorageContract address The storage contract * with runtime code equal to the contract creation code that will be used to * deploy the contract to the home address. * @return The home address, derived key, and runtime code hash of the * deployed contract. * @dev When deploying a contract to a home address via this method, the * metamorphic initialization code will retrieve whatever initialization code * currently resides at the specified address and use it to set up and deploy * the desired contract to the home address. Bear in mind that the deployed * contract will interpret msg.sender as the address of THIS contract, and not * the address of the submitter - if the constructor of the deployed contract * uses msg.sender to set up ownership or other variables, you must modify it * to accept a constructor argument with the appropriate address, or * alternately to hard-code the intended address. Also, if your contract DOES * have constructor arguments, remember to include them as ABI-encoded * arguments at the end of the initialization code, just as you would when * performing a standard deploy. You may want to provide the salt and * submitter to `setDerivedReverseLookup` in order to find the salt, * submitter, and derived key using only the home address to prevent * accidentally losing them. */ function deriveKeyAndDeployViaExistingRuntimeStorageContract( bytes32 salt, address initializationRuntimeStorageContract ) external payable returns (address homeAddress, bytes32 key, bytes32 runtimeCodeHash); /** * @notice Mint multiple ERC721 tokens, designated by their keys, to the * specified owner. Keys that aren't controlled, or that point to home * addresses that are currently deployed, will be skipped. * @param owner address The account that will be granted ownership of the * ERC721 tokens. * @param keys bytes32[] An array of values used to derive each home address. * @dev If you plan to use this method regularly or want to keep gas costs to * an absolute minimum, and are willing to go without standard ABI encoding, * see `batchLock_63efZf` for a more efficient (and unforgiving) * implementation. For batch token minting with *derived* keys, see * `deriveKeysAndBatchLock`. */ function batchLock(address owner, bytes32[] calldata keys) external; /** * @notice Mint multiple ERC721 tokens, designated by salts that are hashed * with the caller's address to derive each key, to the specified owner. * Derived keys that aren't controlled, or that point to home addresses that * are currently deployed, will be skipped. * @param owner address The account that will be granted ownership of the * ERC721 tokens. * @param salts bytes32[] An array of values used to derive each key and * corresponding home address. * @dev See `batchLock` for batch token minting with standard, non-derived * keys. */ function deriveKeysAndBatchLock(address owner, bytes32[] calldata salts) external; /** * @notice Efficient version of `batchLock` that uses less gas. The first 20 * bytes of each key are automatically populated using msg.sender, and the * remaining key segments are passed in as a packed byte array, using twelve * bytes per segment, with a function selector of 0x00000000 followed by a * twenty-byte segment for the desired owner of the minted ERC721 tokens. Note * that an attempt to lock a key that is not controlled or with its contract * already deployed will cause the entire batch to revert. Checks on whether * the owner is a valid ERC721 receiver are also skipped, similar to using * `transferFrom` instead of `safeTransferFrom`. */ function batchLock_63efZf(/* packed owner and key segments */) external; /** * @notice Submit a key to claim the "high score" - the lower the uint160 * value of the key's home address, the higher the score. The high score * holder has the exclusive right to recover lost ether and tokens on this * contract. * @param key bytes32 The unique value used to derive the home address that * will determine the resultant score. * @dev The high score must be claimed by a direct key (one that is submitted * by setting the first 20 bytes of the key to the address of the submitter) * and not by a derived key, and is non-transferrable. If you want to help * people recover their lost tokens, you might consider deploying a contract * to the high score address (probably a metamorphic one so that you can use * the home address later) with your contact information. */ function claimHighScore(bytes32 key) external; /** * @notice Transfer any ether or ERC20 tokens that have somehow ended up at * this contract by specifying a token address (set to the null address for * ether) as well as a recipient address. Only the high score holder can * recover lost ether and tokens on this contract. * @param token address The contract address of the ERC20 token to recover, or * the null address for recovering Ether. * @param recipient address payable The account where recovered funds should * be transferred. * @dev If you are trying to recover funds that were accidentally sent into * this contract, see if you can contact the holder of the current high score, * found by calling `getHighScore`. Better yet, try to find a new high score * yourself! */ function recover(IERC20 token, address payable recipient) external; /** * @notice "View" function to determine if a contract can currently be * deployed to a home address given the corresponding key. A contract is only * deployable if no account currently exists at the address - any existing * contract must be destroyed via `SELFDESTRUCT` before a new contract can be * deployed to a home address. This method does not modify state but is * inaccessible via staticcall. * @param key bytes32 The unique value used to derive the home address. * @return A boolean signifying if a contract can be deployed to the home * address that corresponds to the provided key. * @dev This will not detect if a contract is not deployable due control * having been relinquished on the key. */ function isDeployable(bytes32 key) external /* view */ returns (bool deployable); /** * @notice View function to get the current "high score", or the lowest * uint160 value of a home address of all keys submitted. The high score * holder has the exclusive right to recover lost ether and tokens on this * contract. * @return The current high score holder, their score, and the submitted key. */ function getHighScore() external view returns (address holder, uint256 score, bytes32 key); /** * @notice View function to get information on a home address given the * corresponding key. * @param key bytes32 The unique value used to derive the home address. * @return The home address, the current controller of the address, the number * of times the home address has been deployed to, and the code hash of the * runtime currently found at the home address, if any. * @dev There is also an `isDeployable` method for determining if a contract * can be deployed to the address, but in extreme cases it must actually * perform a dry-run to determine if the contract is deployable, which means * that it does not support staticcalls. There is also a convenience method, * `hasNeverBeenDeployed`, but the information it conveys can be determined * from this method alone as well. */ function getHomeAddressInformation(bytes32 key) external view returns ( address homeAddress, address controller, uint256 deploys, bytes32 currentRuntimeCodeHash ); /** * @notice View function to determine if no contract has ever been deployed to * a home address given the corresponding key. This can be used to ensure that * a given key or corresponding token is "new" or not. * @param key bytes32 The unique value used to derive the home address. * @return A boolean signifying if a contract has never been deployed using * the supplied key before. */ function hasNeverBeenDeployed(bytes32 key) external view returns (bool neverBeenDeployed); /** * @notice View function to search for a known key, salt, and/or submitter * given a supplied home address. Keys can be controlled directly by an * address that matches the first 20 bytes of the key, or they can be derived * from a salt and a submitter - if the key is not a derived key, the salt and * submitter fields will both have a value of zero. * @param homeAddress address The home address to check for key information. * @return The key, salt, and/or submitter used to deploy to the home address, * assuming they have been submitted to the reverse lookup. * @dev To populate these values, call `setReverseLookup` for cases where keys * are used directly or are the only value known, or `setDerivedReverseLookup` * for cases where keys are derived from a known salt and submitter. */ function reverseLookup(address homeAddress) external view returns (bytes32 key, bytes32 salt, address submitter); /** * @notice Pure function to determine the key that is derived from a given * salt and submitting address. * @param salt bytes32 The salt value that is used to derive the key. * @param submitter address The submitter of the salt value used to derive the * key. * @return The derived key. */ function getDerivedKey(bytes32 salt, address submitter) external pure returns (bytes32 key); /** * @notice Pure function to determine the home address that corresponds to * a given key. * @param key bytes32 The unique value used to derive the home address. * @return The home address. */ function getHomeAddress(bytes32 key) external pure returns (address homeAddress); /** * @notice Pure function for retrieving the metamorphic initialization code * used to deploy arbitrary contracts to home addresses. Provided for easy * verification and for use in other applications. * @return The 32-byte metamorphic initialization code. * @dev This metamorphic init code works via the "metamorphic delegator" * mechanism, which is explained in greater detail at `_deployToHomeAddress`. */ function getMetamorphicDelegatorInitializationCode() external pure returns (bytes32 metamorphicDelegatorInitializationCode); /** * @notice Pure function for retrieving the keccak256 of the metamorphic * initialization code used to deploy arbitrary contracts to home addresses. * This is the value that you should use, along with this contract's address * and a caller address that you control, to mine for an partucular type of * home address (such as one at a compact or gas-efficient address). * @return The keccak256 hash of the metamorphic initialization code. */ function getMetamorphicDelegatorInitializationCodeHash() external pure returns (bytes32 metamorphicDelegatorInitializationCodeHash); /** * @notice Pure function for retrieving the prelude that will be inserted * ahead of the code payload in order to deploy a runtime storage contract. * @return The 11-byte "arbitrary runtime" prelude. */ function getArbitraryRuntimeCodePrelude() external pure returns (bytes11 prelude); } /** * @title ERC721 Non-Fungible Token Standard basic interface * @dev see https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721 { 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); function balanceOf(address owner) external view returns (uint256 balance); function ownerOf(uint256 tokenId) external view returns (address owner); 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 transferFrom(address from, address to, uint256 tokenId) external; function safeTransferFrom(address from, address to, uint256 tokenId) external; function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable { function totalSupply() external view returns (uint256); function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); function tokenByIndex(uint256 index) external view returns (uint256); } /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata { function name() external pure returns (string memory); function symbol() external pure returns (string memory); function tokenURI(uint256 tokenId) external view returns (string memory); } /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @notice Handle the receipt of an NFT * @dev The ERC721 smart contract calls this function on the recipient * after a `safeTransfer`. 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 calldata data) external returns (bytes4); } /** * @title ERC1412 Batch Transfers For Non-Fungible Tokens * @dev the ERC-165 identifier for this interface is 0x2b89bcaa */ interface IERC1412 { /// @notice Transfers the ownership of multiple NFTs from one address to another address /// @param _from The current owner of the NFT /// @param _to The new owner /// @param _tokenIds The NFTs to transfer /// @param _data Additional data with no specified format, sent in call to `_to` function safeBatchTransferFrom(address _from, address _to, uint256[] calldata _tokenIds, bytes calldata _data) external; /// @notice Transfers the ownership of multiple NFTs from one address to another address /// @param _from The current owner of the NFT /// @param _to The new owner /// @param _tokenIds The NFTs to transfer function safeBatchTransferFrom(address _from, address _to, uint256[] calldata _tokenIds) external; } /** * @title IERC165 * @dev https://eips.ethereum.org/EIPS/eip-165 */ interface IERC165 { /** * @notice Query if a contract implements an interface * @param interfaceId The interface identifier, as specified in ERC-165 * @dev Interface identification is specified in ERC-165. This function * uses less than 30,000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } /** * @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); } /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, "SafeMath: division by zero"); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, "SafeMath: modulo by zero"); return a % b; } } /** * Utility library of inline functions on addresses */ library Address { /** * Returns whether the target address is a contract * @dev This function will return false if invoked during the constructor of a contract, * as the code is not actually created until after the constructor finishes. * @param account address of the account to check * @return whether the target address is a contract */ function isContract(address account) internal view returns (bool) { uint256 size; // XXX Currently there is no better way to check if there is a contract in an address // than to check the size of the code at that address. // See https://ethereum.stackexchange.com/a/14016/36603 // for more details about how this works. // TODO Check this again before the Serenity release, because all addresses will be // contracts then. // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } } /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids * * Include with `using Counters for Counters.Counter;` * 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); } } /** * @dev Implementation of the `IERC165` interface. * * Contracts may inherit from this and call `_registerInterface` to declare * their support of an interface. */ contract ERC165 is IERC165 { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; constructor () internal { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev See `IERC165.supportsInterface`. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) public view returns (bool) { //inject PUBLIC FUNC TO EXTERNAL 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; } } /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721 is 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 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; /* * 0x80ac58cd === * bytes4(keccak256('balanceOf(address)')) ^ * bytes4(keccak256('ownerOf(uint256)')) ^ * bytes4(keccak256('approve(address,uint256)')) ^ * bytes4(keccak256('getApproved(uint256)')) ^ * bytes4(keccak256('setApprovalForAll(address,bool)')) ^ * bytes4(keccak256('isApprovedForAll(address,address)')) ^ * bytes4(keccak256('transferFrom(address,address,uint256)')) ^ * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) ^ * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) */ 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)); 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)); 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); require(msg.sender == owner || isApprovedForAll(owner, msg.sender)); _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)); 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 != msg.sender); _operatorApprovals[msg.sender][to] = approved; emit ApprovalForAll(msg.sender, to, approved); } /** * @dev Tells whether an operator is approved by a given owner * @param owner owner address which you want to query the approval of * @param operator operator address which you want to query the approval of * @return bool whether the given operator is approved by the given owner */ function isApprovedForAll(address owner, address operator) public view returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev Transfers the ownership of a given token ID to another address * 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 { require(_isApprovedOrOwner(msg.sender, tokenId)); _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 `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 `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) public { transferFrom(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data)); } /** * @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) { address owner = ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @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)); require(!_exists(tokenId)); _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(uint256) 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); _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); require(to != address(0)); _clearApproval(tokenId); _ownedTokensCount[from].decrement(); _ownedTokensCount[to].increment(); _tokenOwner[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Internal function to invoke `onERC721Received` on a target address * The call is not executed if the target address is not a contract * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) internal returns (bool) { if (!to.isContract()) { return true; } bytes4 retval = IERC721Receiver(to).onERC721Received(msg.sender, 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 (_tokenApprovals[tokenId] != address(0)) { _tokenApprovals[tokenId] = address(0); } } } /** * @title ERC-721 Non-Fungible Token with optional enumeration extension logic * @dev See https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721Enumerable is 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 _burn(uint256) 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 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 (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 _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; } } /** * @title HomeWork (version 1) * @author 0age * @notice Homework is a utility to find, share, and reuse "home" addresses for * contracts. Anyone can work to find a new home address by searching for keys, * a 32-byte value with the first 20 bytes equal to the finder's calling address * (or derived by hashing an arbitrary 32-byte salt and the caller's address), * and can then deploy any contract they like (even one with a constructor) to * the address, or mint an ERC721 token that the owner can redeem that will then * allow them to do the same. Also, if the contract is `SELFDESTRUCT`ed, a new * contract can be redeployed by the current controller to the same address! * @dev This contract allows contract addresses to be located ahead of time, and * for arbitrary bytecode to be deployed (and redeployed if so desired, i.e. * metamorphic contracts) to the located address by a designated controller. To * enable this, the contract first deploys an "initialization-code-in-runtime" * contract, with the creation code of the contract you want to deploy stored in * RUNTIME code. Then, to deploy the actual contract, it retrieves the address * of the storage contract and `DELEGATECALL`s into it to execute the init code * and, if successful, retrieves and returns the contract runtime code. Rather * than using a located address directly, you can also lock it in the contract * and mint and ERC721 token for it, which can then be redeemed in order to gain * control over deployment to the address (note that tokens may not be minted if * the contract they control currently has a deployed contract at that address). * Once a contract undergoes metamorphosis, all existing storage will be deleted * and any existing contract code will be replaced with the deployed contract * code of the new implementation contract. The mechanisms behind this contract * are highly experimental - proceed with caution and please share any exploits * or optimizations you discover. */ contract HomeWork is IHomeWork, ERC721Enumerable, IERC721Metadata, IERC1412 { // Allocate storage to track the current initialization-in-runtime contract. address private _initializationRuntimeStorageContract; // Finder of home address with lowest uint256 value can recover lost funds. bytes32 private _highScoreKey; // Track information on the Home address corresponding to each key. mapping (bytes32 => HomeAddress) private _home; // Provide optional reverse-lookup for key derivation of a given home address. mapping (address => KeyInformation) private _key; // Set 0xff + address(this) as a constant to use when deriving home addresses. bytes21 private constant _FF_AND_THIS_CONTRACT = bytes21( 0xff0000000000001b84b1cb32787B0D64758d019317 ); // Set the address of the tokenURI runtime storage contract as a constant. address private constant _URI_END_SEGMENT_STORAGE = address( 0x000000000071C1c84915c17BF21728BfE4Dac3f3 ); // Deploy arbitrary contracts to home addresses using metamorphic init code. bytes32 private constant _HOME_INIT_CODE = bytes32( 0x5859385958601c335a585952fa1582838382515af43d3d93833e601e57fd5bf3 ); // Compute hash of above metamorphic init code in order to compute addresses. bytes32 private constant _HOME_INIT_CODE_HASH = bytes32( 0x7816562e7f85866cae07183593075f3b5ec32aeff914a0693e20aaf39672babc ); // Write arbitrary code to a contract's runtime using the following prelude. bytes11 private constant _ARBITRARY_RUNTIME_PRELUDE = bytes11( 0x600b5981380380925939f3 ); // Set EIP165 interface IDs as constants (already set 165 and 721+enumerable). bytes4 private constant _INTERFACE_ID_HOMEWORK = 0xe5399799; /* this.deploy.selector ^ this.lock.selector ^ this.redeem.selector ^ this.assignController.selector ^ this.relinquishControl.selector ^ this.redeemAndDeploy.selector ^ this.deriveKey.selector ^ this.deriveKeyAndLock.selector ^ this.deriveKeyAndAssignController.selector ^ this.deriveKeyAndRelinquishControl.selector ^ this.setReverseLookup.selector ^ this.setDerivedReverseLookup.selector ^ this.deployRuntimeStorageContract.selector ^ this.deployViaExistingRuntimeStorageContract.selector ^ this.redeemAndDeployViaExistingRuntimeStorageContract.selector ^ this.deriveKeyAndDeploy.selector ^ this.deriveKeyAndDeployViaExistingRuntimeStorageContract.selector ^ this.batchLock.selector ^ this.deriveKeysAndBatchLock.selector ^ this.batchLock_63efZf.selector ^ this.claimHighScore.selector ^ this.recover.selector ^ this.isDeployable.selector ^ this.getHighScore.selector ^ this.getHomeAddressInformation.selector ^ this.hasNeverBeenDeployed.selector ^ this.reverseLookup.selector ^ this.getDerivedKey.selector ^ this.getHomeAddress.selector ^ this.getMetamorphicDelegatorInitializationCode.selector ^ this.getMetamorphicDelegatorInitializationCodeHash.selector ^ this.getArbitraryRuntimeCodePrelude.selector == 0xe5399799 */ bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; bytes4 private constant _INTERFACE_ID_ERC1412_BATCH_TRANSFERS = 0x2b89bcaa; // Set name of this contract as a constant (hex encoding is to support emoji). string private constant _NAME = ( hex"486f6d65576f726b20f09f8fa0f09f9ba0efb88f" ); // Set symbol of this contract as a constant. string private constant _SYMBOL = "HWK"; // Set the start of each token URI for issued ERC721 tokens as a constant. bytes private constant _URI_START_SEGMENT = abi.encodePacked( hex"646174613a6170706c69636174696f6e2f6a736f6e2c7b226e616d65223a22486f6d65", hex"253230416464726573732532302d2532303078" ); /* data:application/json,{"name":"Home%20Address%20-%200x */ // Store reused revert messages as constants. string private constant _ACCOUNT_EXISTS = string( "Only non-existent accounts can be deployed or used to mint tokens." ); string private constant _ONLY_CONTROLLER = string( "Only the designated controller can call this function." ); string private constant _NO_INIT_CODE_SUPPLIED = string( "Cannot deploy a contract with no initialization code supplied." ); /** * @notice In the constructor, verify that deployment addresses are correct * and that supplied constant hash value of the contract creation code used to * deploy arbitrary contracts to home addresses is valid, and set an initial * high score key with the null address as the high score "holder". ERC165 * supported interfaces are all registered during initizialization as well. */ constructor() public { // Verify that the deployment address is set correctly as a constant. assert(address(this) == address(uint160(uint168(_FF_AND_THIS_CONTRACT)))); // Verify the derivation of the deployment address. bytes32 initialDeployKey = bytes32( 0x486f6d65576f726b20f09f8fa0f09f9ba0efb88faa3c548a76f9bd3c000c0000 ); assert(address(this) == address( uint160( // Downcast to match the address type. uint256( // Convert to uint to truncate upper digits. keccak256( // Compute the CREATE2 hash using 4 inputs. abi.encodePacked( // Pack all inputs to the hash together. bytes1(0xff), // Start with 0xff to distinguish from RLP. msg.sender, // The deployer will be the caller. initialDeployKey, // Pass in the supplied key as the salt. _HOME_INIT_CODE_HASH // The metamorphic initialization code hash. ) ) ) ) )); // Verify the derivation of the tokenURI runtime storage address. bytes32 uriDeployKey = bytes32( 0x486f6d65576f726b202d20746f6b656e55524920c21352fee5a62228db000000 ); bytes32 uriInitCodeHash = bytes32( 0xdea98294867e3fdc48eb5975ecc53a79e2e1ea6e7e794137a9c34c4dd1565ba2 ); assert(_URI_END_SEGMENT_STORAGE == address( uint160( // Downcast to match the address type. uint256( // Convert to uint to truncate upper digits. keccak256( // Compute the CREATE2 hash using 4 inputs. abi.encodePacked( // Pack all inputs to the hash together. bytes1(0xff), // Start with 0xff to distinguish from RLP. msg.sender, // The deployer will be the caller. uriDeployKey, // Pass in the supplied key as the salt. uriInitCodeHash // The storage contract init code hash. ) ) ) ) )); // Verify that the correct runtime code is at the tokenURI storage contract. bytes32 expectedRuntimeStorageHash = bytes32( 0x8834602968080bb1df9c44c9834c0a93533b72bbfa3865ee2c5be6a0c4125fc3 ); address runtimeStorage = _URI_END_SEGMENT_STORAGE; bytes32 runtimeStorageHash; assembly { runtimeStorageHash := extcodehash(runtimeStorage) } assert(runtimeStorageHash == expectedRuntimeStorageHash); // Verify that the supplied hash for the metamorphic init code is valid. assert(keccak256(abi.encode(_HOME_INIT_CODE)) == _HOME_INIT_CODE_HASH); // Set an initial high score key with the null address as the submitter. _highScoreKey = bytes32( 0x0000000000000000000000000000000000000000ffffffffffffffffffffffff ); // Register EIP165 interface for HomeWork. _registerInterface(_INTERFACE_ID_HOMEWORK); // Register EIP165 interface for ERC721 metadata. _registerInterface(_INTERFACE_ID_ERC721_METADATA); // Register EIP165 interface for ERC1412 (batch transfers). _registerInterface(_INTERFACE_ID_ERC1412_BATCH_TRANSFERS); } /** * @notice Deploy a new contract with the desired initialization code to the * home address corresponding to a given key. Two conditions must be met: the * submitter must be designated as the controller of the home address (with * the initial controller set to the address corresponding to the first twenty * bytes of the key), and there must not be a contract currently deployed at * the home address. These conditions can be checked by calling * `getHomeAddressInformation` and `isDeployable` with the same key. * @param key bytes32 The unique value used to derive the home address. * @param initializationCode bytes The contract creation code that will be * used to deploy the contract to the home address. * @return The home address of the deployed contract. * @dev In order to deploy the contract to the home address, a new contract * will be deployed with runtime code set to the initialization code of the * contract that will be deployed to the home address. Then, metamorphic * initialization code will retrieve that initialization code and use it to * set up and deploy the desired contract to the home address. Bear in mind * that the deployed contract will interpret msg.sender as the address of THIS * contract, and not the address of the submitter - if the constructor of the * deployed contract uses msg.sender to set up ownership or other variables, * you must modify it to accept a constructor argument with the appropriate * address, or alternately to hard-code the intended address. Also, if your * contract DOES have constructor arguments, remember to include them as * ABI-encoded arguments at the end of the initialization code, just as you * would when performing a standard deploy. You may also want to provide the * key to `setReverseLookup` in order to find it again using only the home * address to prevent accidentally losing the key. */ function deploy(bytes32 key, bytes calldata initializationCode) external payable onlyEmpty(key) onlyControllerDeployer(key) returns (address homeAddress, bytes32 runtimeCodeHash) { // Ensure that initialization code was supplied. require(initializationCode.length > 0, _NO_INIT_CODE_SUPPLIED); // Deploy the initialization storage contract and set address in storage. _initializationRuntimeStorageContract = _deployRuntimeStorageContract( initializationCode ); // Use metamorphic initialization code to deploy contract to home address. (homeAddress, runtimeCodeHash) = _deployToHomeAddress(key); } /** * @notice Mint an ERC721 token to the supplied owner that can be redeemed in * order to gain control of a home address corresponding to a given key. Two * conditions must be met: the submitter must be designated as the controller * of the home address (with the initial controller set to the address * corresponding to the first 20 bytes of the key), and there must not be a * contract currently deployed at the home address. These conditions can be * checked by calling `getHomeAddressInformation` and `isDeployable` with the * same key. * @param key bytes32 The unique value used to derive the home address. * @param owner address The account that will be granted ownership of the * ERC721 token. * @dev In order to mint an ERC721 token, the assocated home address cannot be * in use, or else the token will not be able to deploy to the home address. * The controller is set to this contract until the token is redeemed, at * which point the redeemer designates a new controller for the home address. * The key of the home address and the tokenID of the ERC721 token are the * same value, but different types (bytes32 vs. uint256). */ function lock(bytes32 key, address owner) public //inject PUBLIC FUNC TO EXTERNAL onlyEmpty(key) onlyController(key) { // Ensure that the specified owner is a valid ERC721 receiver. _validateOwner(owner, key); // Get the HomeAddress storage struct from the mapping using supplied key. HomeAddress storage home = _home[key]; // Set the exists flag to true and the controller to this contract. home.exists = true; home.controller = address(this); // Emit an event signifying that this contract is now the controller. emit NewController(key, address(this)); // Mint the ERC721 token to the designated owner. _mint(owner, uint256(key)); } /** * @notice Burn an ERC721 token to allow the supplied controller to gain the * ability to deploy to the home address corresponding to the key matching the * burned token. The submitter must be designated as either the owner of the * token or as an approved spender. * @param tokenId uint256 The ID of the ERC721 token to redeem. * @param controller address The account that will be granted control of the * home address corresponding to the given token. * @dev The controller cannot be designated as the address of this contract, * the null address, or the home address (the restriction on setting the home * address as the controller is due to the fact that the home address will not * be able to deploy to itself, as it needs to be empty before a contract can * be deployed to it). */ function redeem(uint256 tokenId, address controller) public //inject PUBLIC FUNC TO EXTERNAL onlyTokenOwnerOrApprovedSpender(tokenId) { // Convert the token ID to a bytes32 key. bytes32 key = bytes32(tokenId); // Prevent the controller from being set to prohibited account values. _validateController(controller, key); // Burn the ERC721 token in question. _burn(tokenId); // Assign the new controller to the corresponding home address. _home[key].controller = controller; // Emit an event with the new controller. emit NewController(key, controller); } /** * @notice Transfer control over deployment to the home address corresponding * to a given key. The caller must be designated as the current controller of * the home address (with the initial controller set to the address * corresponding to the first 20 bytes of the key) - This condition can be * checked by calling `getHomeAddressInformation` with the same key. * @param key bytes32 The unique value used to derive the home address. * @param controller address The account that will be granted control of the * home address corresponding to the given key. * @dev The controller cannot be designated as the address of this contract, * the null address, or the home address (the restriction on setting the home * address as the controller is due to the fact that the home address will not * be able to deploy to itself, as it needs to be empty before a contract can * be deployed to it). */ function assignController(bytes32 key, address controller) public //inject PUBLIC FUNC TO EXTERNAL onlyController(key) { // Prevent the controller from being set to prohibited account values. _validateController(controller, key); // Assign the new controller to the corresponding home address. HomeAddress storage home = _home[key]; home.exists = true; home.controller = controller; // Emit an event with the new controller. emit NewController(key, controller); } /** * @notice Transfer control over deployment to the home address corresponding * to a given key to the null address, which will prevent it from being * deployed to again in the future. The caller must be designated as the * current controller of the corresponding home address (with the initial * controller set to the address corresponding to the first 20 bytes of the * key) - This condition can be checked by calling `getHomeAddressInformation` * with the same key. * @param key bytes32 The unique value used to derive the home address. */ function relinquishControl(bytes32 key) public //inject PUBLIC FUNC TO EXTERNAL onlyController(key) { // Assign the null address as the controller of the given key. HomeAddress storage home = _home[key]; home.exists = true; home.controller = address(0); // Emit an event with the null address as the controller. emit NewController(key, address(0)); } /** * @notice Burn an ERC721 token, set a supplied controller, and deploy a new * contract with the supplied initialization code to the corresponding home * address for the given token. The submitter must be designated as either the * owner of the token or as an approved spender. * @param tokenId uint256 The ID of the ERC721 token to redeem. * @param controller address The account that will be granted control of the * home address corresponding to the given token. * @param initializationCode bytes The contract creation code that will be * used to deploy the contract to the home address. * @return The home address and runtime code hash of the deployed contract. * @dev In order to deploy the contract to the home address, a new contract * will be deployed with runtime code set to the initialization code of the * contract that will be deployed to the home address. Then, metamorphic * initialization code will retrieve that initialization code and use it to * set up and deploy the desired contract to the home address. Bear in mind * that the deployed contract will interpret msg.sender as the address of THIS * contract, and not the address of the submitter - if the constructor of the * deployed contract uses msg.sender to set up ownership or other variables, * you must modify it to accept a constructor argument with the appropriate * address, or alternately to hard-code the intended address. Also, if your * contract DOES have constructor arguments, remember to include them as * ABI-encoded arguments at the end of the initialization code, just as you * would when performing a standard deploy. You may also want to provide the * key to `setReverseLookup` in order to find it again using only the home * address to prevent accidentally losing the key. The controller cannot be * designated as the address of this contract, the null address, or the home * address (the restriction on setting the home address as the controller is * due to the fact that the home address will not be able to deploy to itself, * as it needs to be empty before a contract can be deployed to it). Also, * checks on the contract at the home address being empty or not having the * correct controller are unnecessary, as they are performed when minting the * token and cannot be altered until the token is redeemed. */ function redeemAndDeploy( uint256 tokenId, address controller, bytes calldata initializationCode ) external payable onlyTokenOwnerOrApprovedSpender(tokenId) returns (address homeAddress, bytes32 runtimeCodeHash) { // Ensure that initialization code was supplied. require(initializationCode.length > 0, _NO_INIT_CODE_SUPPLIED); // Convert the token ID to a bytes32 key. bytes32 key = bytes32(tokenId); // Prevent the controller from being set to prohibited account values. _validateController(controller, key); // Burn the ERC721 token in question. _burn(tokenId); // Deploy the initialization storage contract and set address in storage. _initializationRuntimeStorageContract = _deployRuntimeStorageContract( initializationCode ); // Set provided controller and increment contract deploy count at once. HomeAddress storage home = _home[key]; home.exists = true; home.controller = controller; home.deploys += 1; // Emit an event with the new controller. emit NewController(key, controller); // Use metamorphic initialization code to deploy contract to home address. (homeAddress, runtimeCodeHash) = _deployToHomeAddress(key); } /** * @notice Derive a new key by concatenating an arbitrary 32-byte salt value * and the address of the caller and performing a keccak256 hash. This allows * for the creation of keys with additional entropy where desired while also * preventing collisions with standard keys. The caller will be set as the * controller of the derived key. * @param salt bytes32 The desired salt value to use (along with the address * of the caller) when deriving the resultant key and corresponding home * address. * @return The derived key. * @dev Home addresses from derived keys will take longer to "mine" or locate, * as an additional hash must be performed when computing the corresponding * home address for each given salt input. Each caller will derive a different * key even if they are supplying the same salt value. */ function deriveKey(bytes32 salt) public returns (bytes32 key) { //inject PUBLIC FUNC TO EXTERNAL // Derive the key using the supplied salt and the calling address. key = _deriveKey(salt, msg.sender); // Register key and set caller as controller if it is not yet registered. HomeAddress storage home = _home[key]; if (!home.exists) { home.exists = true; home.controller = msg.sender; // Emit an event with the sender as the new controller. emit NewController(key, msg.sender); } } /** * @notice Mint an ERC721 token to the supplied owner that can be redeemed in * order to gain control of a home address corresponding to a given derived * key. Two conditions must be met: the submitter must be designated as the * current controller of the home address, and there must not be a contract * currently deployed at the home address. These conditions can be checked by * calling `getHomeAddressInformation` and `isDeployable` with the key * determined by calling `getDerivedKey`. * @param salt bytes32 The salt value that is used to derive the key. * @param owner address The account that will be granted ownership of the * ERC721 token. * @return The derived key. * @dev In order to mint an ERC721 token, the assocated home address cannot be * in use, or else the token will not be able to deploy to the home address. * The controller is set to this contract until the token is redeemed, at * which point the redeemer designates a new controller for the home address. * The key of the home address and the tokenID of the ERC721 token are the * same value, but different types (bytes32 vs. uint256). */ function deriveKeyAndLock(bytes32 salt, address owner) public //inject PUBLIC FUNC TO EXTERNAL returns (bytes32 key) { // Derive the key using the supplied salt and the calling address. key = _deriveKey(salt, msg.sender); // Ensure that the specified owner is a valid ERC721 receiver. _validateOwner(owner, key); // Ensure that a contract is not currently deployed to the home address. require(_isNotDeployed(key), _ACCOUNT_EXISTS); // Ensure that the caller is the controller of the derived key. HomeAddress storage home = _home[key]; if (home.exists) { require(home.controller == msg.sender, _ONLY_CONTROLLER); } // Set the exists flag to true and the controller to this contract. home.exists = true; home.controller = address(this); // Mint the ERC721 token to the designated owner. _mint(owner, uint256(key)); // Emit an event signifying that this contract is now the controller. emit NewController(key, address(this)); } /** * @notice Transfer control over deployment to the home address corresponding * to a given derived key. The caller must be designated as the current * controller of the home address - This condition can be checked by calling * `getHomeAddressInformation` with the key obtained via `getDerivedKey`. * @param salt bytes32 The salt value that is used to derive the key. * @param controller address The account that will be granted control of the * home address corresponding to the given derived key. * @return The derived key. * @dev The controller cannot be designated as the address of this contract, * the null address, or the home address (the restriction on setting the home * address as the controller is due to the fact that the home address will not * be able to deploy to itself, as it needs to be empty before a contract can * be deployed to it). */ function deriveKeyAndAssignController(bytes32 salt, address controller) public //inject PUBLIC FUNC TO EXTERNAL returns (bytes32 key) { // Derive the key using the supplied salt and the calling address. key = _deriveKey(salt, msg.sender); // Prevent the controller from being set to prohibited account values. _validateController(controller, key); // Ensure that the caller is the controller of the derived key. HomeAddress storage home = _home[key]; if (home.exists) { require(home.controller == msg.sender, _ONLY_CONTROLLER); } // Assign the new controller to the corresponding home address. home.exists = true; home.controller = controller; // Emit an event with the new controller. emit NewController(key, controller); } /** * @notice Transfer control over deployment to the home address corresponding * to a given derived key to the null address, which will prevent it from * being deployed to again in the future. The caller must be designated as the * current controller of the home address - This condition can be checked by * calling `getHomeAddressInformation` with the key determined by calling * `getDerivedKey`. * @param salt bytes32 The salt value that is used to derive the key. * @return The derived key. */ function deriveKeyAndRelinquishControl(bytes32 salt) public //inject PUBLIC FUNC TO EXTERNAL returns (bytes32 key) { // Derive the key using the supplied salt and the calling address. key = _deriveKey(salt, msg.sender); // Ensure that the caller is the controller of the derived key. HomeAddress storage home = _home[key]; if (home.exists) { require(home.controller == msg.sender, _ONLY_CONTROLLER); } // Assign the null address as the controller of the given derived key. home.exists = true; home.controller = address(0); // Emit an event with the null address as the controller. emit NewController(key, address(0)); } /** * @notice Record a key that corresponds to a given home address by supplying * said key and using it to derive the address. This enables reverse lookup * of a key using only the home address in question. This method may be called * by anyone - control of the key is not required. * @param key bytes32 The unique value used to derive the home address. * @dev This does not set the salt or submitter fields, as those apply only to * derived keys (although a derived key may also be set with this method, just * without the derived fields). */ function setReverseLookup(bytes32 key) public { //inject PUBLIC FUNC TO EXTERNAL // Derive home address of given key and set home address and key in mapping. _key[_getHomeAddress(key)].key = key; } /** * @notice Record the derived key that corresponds to a given home address by * supplying the salt and submitter that were used to derive the key. This * facititates reverse lookup of the derivation method of a key using only the * home address in question. This method may be called by anyone - control of * the derived key is not required. * @param salt bytes32 The salt value that is used to derive the key. * @param submitter address The account that submits the salt that is used to * derive the key. */ function setDerivedReverseLookup(bytes32 salt, address submitter) public { //inject PUBLIC FUNC TO EXTERNAL // Derive the key using the supplied salt and submitter. bytes32 key = _deriveKey(salt, submitter); // Derive home address and set it along with all other relevant information. _key[_getHomeAddress(key)] = KeyInformation({ key: key, salt: salt, submitter: submitter }); } /** * @notice Deploy a new storage contract with the supplied code as runtime * code without deploying a contract to a home address. This can be used to * store the contract creation code for use in future deployments of contracts * to home addresses. * @param codePayload bytes The code to set as the runtime code of the * deployed contract. * @return The address of the deployed storage contract. * @dev Consider placing adequate protections on the storage contract to * prevent unwanted callers from modifying or destroying it. Also, if you are * placing contract contract creation code into the runtime storage contract, * remember to include any constructor parameters as ABI-encoded arguments at * the end of the contract creation code, similar to how you would perform a * standard deployment. */ function deployRuntimeStorageContract(bytes calldata codePayload) external returns (address runtimeStorageContract) { // Ensure that a code payload was supplied. require(codePayload.length > 0, "No runtime code payload supplied."); // Deploy payload to the runtime storage contract and return the address. runtimeStorageContract = _deployRuntimeStorageContract(codePayload); } /** * @notice Deploy a new contract with the initialization code stored in the * runtime code at the specified initialization runtime storage contract to * the home address corresponding to a given key. Two conditions must be met: * the submitter must be designated as the controller of the home address * (with the initial controller set to the address corresponding to the first * 20 bytes of the key), and there must not be a contract currently deployed * at the home address. These conditions can be checked by calling * `getHomeAddressInformation` and `isDeployable` with the same key. * @param key bytes32 The unique value used to derive the home address. * @param initializationRuntimeStorageContract address The storage contract * with runtime code equal to the contract creation code that will be used to * deploy the contract to the home address. * @return The home address and runtime code hash of the deployed contract. * @dev When deploying a contract to a home address via this method, the * metamorphic initialization code will retrieve whatever initialization code * currently resides at the specified address and use it to set up and deploy * the desired contract to the home address. Bear in mind that the deployed * contract will interpret msg.sender as the address of THIS contract, and not * the address of the submitter - if the constructor of the deployed contract * uses msg.sender to set up ownership or other variables, you must modify it * to accept a constructor argument with the appropriate address, or * alternately to hard-code the intended address. Also, if your contract DOES * have constructor arguments, remember to include them as ABI-encoded * arguments at the end of the initialization code, just as you would when * performing a standard deploy. You may also want to provide the key to * `setReverseLookup` in order to find it again using only the home address to * prevent accidentally losing the key. */ function deployViaExistingRuntimeStorageContract( bytes32 key, address initializationRuntimeStorageContract ) public //inject PUBLIC FUNC TO EXTERNAL payable onlyEmpty(key) onlyControllerDeployer(key) returns (address homeAddress, bytes32 runtimeCodeHash) { // Ensure that the supplied runtime storage contract is not empty. _validateRuntimeStorageIsNotEmpty(initializationRuntimeStorageContract); // Set initialization runtime storage contract address in contract storage. _initializationRuntimeStorageContract = initializationRuntimeStorageContract; // Use metamorphic initialization code to deploy contract to home address. (homeAddress, runtimeCodeHash) = _deployToHomeAddress(key); } /** * @notice Burn an ERC721 token, set a supplied controller, and deploy a new * contract with the initialization code stored in the runtime code at the * specified initialization runtime storage contract to the home address * corresponding to a given key. The submitter must be designated as either * the owner of the token or as an approved spender. * @param tokenId uint256 The ID of the ERC721 token to redeem. * @param controller address The account that will be granted control of the * home address corresponding to the given token. * @param initializationRuntimeStorageContract address The storage contract * with runtime code equal to the contract creation code that will be used to * deploy the contract to the home address. * @return The home address and runtime code hash of the deployed contract. * @dev When deploying a contract to a home address via this method, the * metamorphic initialization code will retrieve whatever initialization code * currently resides at the specified address and use it to set up and deploy * the desired contract to the home address. Bear in mind that the deployed * contract will interpret msg.sender as the address of THIS contract, and not * the address of the submitter - if the constructor of the deployed contract * uses msg.sender to set up ownership or other variables, you must modify it * to accept a constructor argument with the appropriate address, or * alternately to hard-code the intended address. Also, if your contract DOES * have constructor arguments, remember to include them as ABI-encoded * arguments at the end of the initialization code, just as you would when * performing a standard deploy. You may also want to provide the key to * `setReverseLookup` in order to find it again using only the home address to * prevent accidentally losing the key. The controller cannot be designated as * the address of this contract, the null address, or the home address (the * restriction on setting the home address as the controller is due to the * fact that the home address will not be able to deploy to itself, as it * needs to be empty before a contract can be deployed to it). Also, checks on * the contract at the home address being empty or not having the correct * controller are unnecessary, as they are performed when minting the token * and cannot be altered until the token is redeemed. */ function redeemAndDeployViaExistingRuntimeStorageContract( uint256 tokenId, address controller, address initializationRuntimeStorageContract ) public //inject PUBLIC FUNC TO EXTERNAL payable onlyTokenOwnerOrApprovedSpender(tokenId) returns (address homeAddress, bytes32 runtimeCodeHash) { // Ensure that the supplied runtime storage contract is not empty. _validateRuntimeStorageIsNotEmpty(initializationRuntimeStorageContract); // Convert the token ID to a bytes32 key. bytes32 key = bytes32(tokenId); // Prevent the controller from being set to prohibited account values. _validateController(controller, key); // Burn the ERC721 token in question. _burn(tokenId); // Set initialization runtime storage contract address in contract storage. _initializationRuntimeStorageContract = initializationRuntimeStorageContract; // Set provided controller and increment contract deploy count at once. HomeAddress storage home = _home[key]; home.exists = true; home.controller = controller; home.deploys += 1; // Emit an event with the new controller. emit NewController(key, controller); // Use metamorphic initialization code to deploy contract to home address. (homeAddress, runtimeCodeHash) = _deployToHomeAddress(key); } /** * @notice Deploy a new contract with the desired initialization code to the * home address corresponding to a given derived key. Two conditions must be * met: the submitter must be designated as the controller of the home * address, and there must not be a contract currently deployed at the home * address. These conditions can be checked by calling * `getHomeAddressInformation` and `isDeployable` with the key obtained by * calling `getDerivedKey`. * @param salt bytes32 The salt value that is used to derive the key. * @param initializationCode bytes The contract creation code that will be * used to deploy the contract to the home address. * @return The home address, derived key, and runtime code hash of the * deployed contract. * @dev In order to deploy the contract to the home address, a new contract * will be deployed with runtime code set to the initialization code of the * contract that will be deployed to the home address. Then, metamorphic * initialization code will retrieve that initialization code and use it to * set up and deploy the desired contract to the home address. Bear in mind * that the deployed contract will interpret msg.sender as the address of THIS * contract, and not the address of the submitter - if the constructor of the * deployed contract uses msg.sender to set up ownership or other variables, * you must modify it to accept a constructor argument with the appropriate * address, or alternately to hard-code the intended address. Also, if your * contract DOES have constructor arguments, remember to include them as * ABI-encoded arguments at the end of the initialization code, just as you * would when performing a standard deploy. You may want to provide the salt * and submitter to `setDerivedReverseLookup` in order to find the salt, * submitter, and derived key using only the home address to prevent * accidentally losing them. */ function deriveKeyAndDeploy(bytes32 salt, bytes calldata initializationCode) external payable returns (address homeAddress, bytes32 key, bytes32 runtimeCodeHash) { // Ensure that initialization code was supplied. require(initializationCode.length > 0, _NO_INIT_CODE_SUPPLIED); // Derive key and prepare to deploy using supplied salt and calling address. key = _deriveKeyAndPrepareToDeploy(salt); // Deploy the initialization storage contract and set address in storage. _initializationRuntimeStorageContract = _deployRuntimeStorageContract( initializationCode ); // Use metamorphic initialization code to deploy contract to home address. (homeAddress, runtimeCodeHash) = _deployToHomeAddress(key); } /** * @notice Deploy a new contract with the initialization code stored in the * runtime code at the specified initialization runtime storage contract to * the home address corresponding to a given derived key. Two conditions must * be met: the submitter must be designated as the controller of the home * address, and there must not be a contract currently deployed at the home * address. These conditions can be checked by calling * `getHomeAddressInformation` and `isDeployable` with the key obtained by * calling `getDerivedKey`. * @param salt bytes32 The salt value that is used to derive the key. * @param initializationRuntimeStorageContract address The storage contract * with runtime code equal to the contract creation code that will be used to * deploy the contract to the home address. * @return The home address, derived key, and runtime code hash of the * deployed contract. * @dev When deploying a contract to a home address via this method, the * metamorphic initialization code will retrieve whatever initialization code * currently resides at the specified address and use it to set up and deploy * the desired contract to the home address. Bear in mind that the deployed * contract will interpret msg.sender as the address of THIS contract, and not * the address of the submitter - if the constructor of the deployed contract * uses msg.sender to set up ownership or other variables, you must modify it * to accept a constructor argument with the appropriate address, or * alternately to hard-code the intended address. Also, if your contract DOES * have constructor arguments, remember to include them as ABI-encoded * arguments at the end of the initialization code, just as you would when * performing a standard deploy. You may want to provide the salt and * submitter to `setDerivedReverseLookup` in order to find the salt, * submitter, and derived key using only the home address to prevent * accidentally losing them. */ function deriveKeyAndDeployViaExistingRuntimeStorageContract( bytes32 salt, address initializationRuntimeStorageContract ) public //inject PUBLIC FUNC TO EXTERNAL payable returns (address homeAddress, bytes32 key, bytes32 runtimeCodeHash) { // Ensure that the supplied runtime storage contract is not empty. _validateRuntimeStorageIsNotEmpty(initializationRuntimeStorageContract); // Derive key and prepare to deploy using supplied salt and calling address. key = _deriveKeyAndPrepareToDeploy(salt); // Set the initialization runtime storage contract in contract storage. _initializationRuntimeStorageContract = initializationRuntimeStorageContract; // Use metamorphic initialization code to deploy contract to home address. (homeAddress, runtimeCodeHash) = _deployToHomeAddress(key); } /** * @notice Mint multiple ERC721 tokens, designated by their keys, to the * specified owner. Keys that aren't controlled, or that point to home * addresses that are currently deployed, will be skipped. * @param owner address The account that will be granted ownership of the * ERC721 tokens. * @param keys bytes32[] An array of values used to derive each home address. * @dev If you plan to use this method regularly or want to keep gas costs to * an absolute minimum, and are willing to go without standard ABI encoding, * see `batchLock_63efZf` for a more efficient (and unforgiving) * implementation. For batch token minting with *derived* keys, see * `deriveKeysAndBatchLock`. */ function batchLock(address owner, bytes32[] calldata keys) external { // Track each key in the array of keys. bytes32 key; // Ensure that the specified owner is a valid ERC721 receiver. if (keys.length > 0) { _validateOwner(owner, keys[0]); } // Iterate through each provided key argument. for (uint256 i; i < keys.length; i++) { key = keys[i]; // Skip if the key currently has a contract deployed to its home address. if (!_isNotDeployed(key)) { continue; } // Skip if the caller is not the controller. if (_getController(key) != msg.sender) { continue; } // Set the exists flag to true and the controller to this contract. HomeAddress storage home = _home[key]; home.exists = true; home.controller = address(this); // Emit an event signifying that this contract is now the controller. emit NewController(key, address(this)); // Mint the ERC721 token to the designated owner. _mint(owner, uint256(key)); } } /** * @notice Mint multiple ERC721 tokens, designated by salts that are hashed * with the caller's address to derive each key, to the specified owner. * Derived keys that aren't controlled, or that point to home addresses that * are currently deployed, will be skipped. * @param owner address The account that will be granted ownership of the * ERC721 tokens. * @param salts bytes32[] An array of values used to derive each key and * corresponding home address. * @dev See `batchLock` for batch token minting with standard, non-derived * keys. */ function deriveKeysAndBatchLock(address owner, bytes32[] calldata salts) external { // Track each key derived from the array of salts. bytes32 key; // Ensure that the specified owner is a valid ERC721 receiver. if (salts.length > 0) { _validateOwner(owner, _deriveKey(salts[0], msg.sender)); } // Iterate through each provided salt argument. for (uint256 i; i < salts.length; i++) { // Derive the key using the supplied salt and the calling address. key = _deriveKey(salts[i], msg.sender); // Skip if the key currently has a contract deployed to its home address. if (!_isNotDeployed(key)) { continue; } // Skip if the caller is not the controller. HomeAddress storage home = _home[key]; if (home.exists && home.controller != msg.sender) { continue; } // Set the exists flag to true and the controller to this contract. home.exists = true; home.controller = address(this); // Emit an event signifying that this contract is now the controller. emit NewController(key, address(this)); // Mint the ERC721 token to the designated owner. _mint(owner, uint256(key)); } } /** * @notice Safely transfers the ownership of a group of token IDs to another * address in a batch. If the target address is a contract, it must implement * `onERC721Received`, called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; * otherwise, or if another error occurs, the entire batch is reverted. * Requires msg.sender to be the owner, approved, or operator of the tokens. * @param from address The current owner of the tokens. * @param to address The account to receive ownership of the given tokens. * @param tokenIds uint256[] ID of the tokens to be transferred. */ function safeBatchTransferFrom( address from, address to, uint256[] calldata tokenIds ) external { // Track each token ID in the batch. uint256 tokenId; // Iterate over each supplied token ID. for (uint256 i = 0; i < tokenIds.length; i++) { // Set the current token ID. tokenId = tokenIds[i]; // Perform the token transfer. safeTransferFrom(from, to, tokenId); } } /** * @notice Safely transfers the ownership of a group of token IDs to another * address in a batch. If the target address is a contract, it must implement * `onERC721Received`, called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; * otherwise, or if another error occurs, the entire batch is reverted. * Requires msg.sender to be the owner, approved, or operator of the tokens. * @param from address The current owner of the tokens. * @param to address The account to receive ownership of the given tokens. * @param tokenIds uint256[] ID of the tokens to be transferred. * @param data bytes A data payload to include with each transfer. */ function safeBatchTransferFrom( address from, address to, uint256[] calldata tokenIds, bytes calldata data ) external { // Track each token ID in the batch. uint256 tokenId; // Iterate over each supplied token ID. for (uint256 i = 0; i < tokenIds.length; i++) { // Set the current token ID. tokenId = tokenIds[i]; // Perform the token transfer. safeTransferFrom(from, to, tokenId, data); } } /** * @notice Efficient version of `batchLock` that uses less gas. The first 20 * bytes of each key are automatically populated using msg.sender, and the * remaining key segments are passed in as a packed byte array, using twelve * bytes per segment, with a function selector of 0x00000000 followed by a * twenty-byte segment for the desired owner of the minted ERC721 tokens. Note * that an attempt to lock a key that is not controlled or with its contract * already deployed will cause the entire batch to revert. Checks on whether * the owner is a valid ERC721 receiver are also skipped, similar to using * `transferFrom` instead of `safeTransferFrom`. */ function batchLock_63efZf(/* packed owner and key segments */) public { //inject PUBLIC FUNC TO EXTERNAL // Get the owner from calldata, located at bytes 4-23 (sig is bytes 0-3). address owner; // Determine number of 12-byte key segments in calldata from byte 24 on. uint256 passedSaltSegments; // Get the owner and calculate the total number of key segments. assembly { owner := shr(0x60, calldataload(4)) // comes after sig passedSaltSegments := div(sub(calldatasize, 24), 12) // after sig & owner } // Track each key, located at each 12-byte segment from byte 24 on. bytes32 key; // Iterate through each provided key segment argument. for (uint256 i; i < passedSaltSegments; i++) { // Construct keys by concatenating msg.sender with each key segment. assembly { key := add( // Combine msg.sender & provided key. shl(0x60, caller), // Place msg.sender at start of word. shr(0xa0, calldataload(add(24, mul(i, 12)))) // Segment at end. ) } // Ensure that the key does not currently have a deployed contract. require(_isNotDeployed(key), _ACCOUNT_EXISTS); // Ensure that the caller is the controller of the key. HomeAddress storage home = _home[key]; if (home.exists) { require(home.controller == msg.sender, _ONLY_CONTROLLER); } // Set the exists flag to true and the controller to this contract. home.exists = true; home.controller = address(this); // Emit an event signifying that this contract is now the controller. emit NewController(key, address(this)); // Mint the ERC721 token to the designated owner. _mint(owner, uint256(key)); } } /** * @notice Perform a dry-run of the deployment of a contract using a given key * and revert on successful deployment. It cannot be called from outside the * contract (even though it is marked as external). * @param key bytes32 The unique value used to derive the home address. * @dev This contract is called by `_isNotDeployable` in extreme cases where * the deployability of the contract cannot be determined conclusively. */ function staticCreate2Check(bytes32 key) public { //inject PUBLIC FUNC TO EXTERNAL require( msg.sender == address(this), "This function can only be called by this contract." ); assembly { // Write the 32-byte metamorphic initialization code to scratch space. mstore( 0, 0x5859385958601c335a585952fa1582838382515af43d3d93833e601e57fd5bf3 ) // Call `CREATE2` using metamorphic init code with supplied key as salt. let deploymentAddress := create2(0, 0, 32, key) // Revert and return the metamorphic init code on successful deployment. if deploymentAddress { revert(0, 32) } } } /** * @notice Submit a key to claim the "high score" - the lower the uint160 * value of the key's home address, the higher the score. The high score * holder has the exclusive right to recover lost ether and tokens on this * contract. * @param key bytes32 The unique value used to derive the home address that * will determine the resultant score. * @dev The high score must be claimed by a direct key (one that is submitted * by setting the first 20 bytes of the key to the address of the submitter) * and not by a derived key, and is non-transferrable. If you want to help * people recover their lost tokens, you might consider deploying a contract * to the high score address (probably a metamorphic one so that you can use * the home address later) with your contact information. */ function claimHighScore(bytes32 key) public { //inject PUBLIC FUNC TO EXTERNAL require( msg.sender == address(bytes20(key)), "Only submitters directly encoded in a given key may claim a high score." ); // Derive the "home address" of the current high score key. address currentHighScore = _getHomeAddress(_highScoreKey); // Derive the "home address" of the new high score key. address newHighScore = _getHomeAddress(key); // Use addresses to ensure that supplied key is in fact a new high score. require( uint160(newHighScore) < uint160(currentHighScore), "Submitted high score is not better than the current high score." ); // Set the new high score to the supplied key. _highScoreKey = key; // The score is equal to (2^160 - 1) - ("home address" of high score key). uint256 score = uint256(uint160(-1) - uint160(newHighScore)); // Emit an event to signify that a new high score has been reached. emit NewHighScore(key, msg.sender, score); } /** * @notice Transfer any ether or ERC20 tokens that have somehow ended up at * this contract by specifying a token address (set to the null address for * ether) as well as a recipient address. Only the high score holder can * recover lost ether and tokens on this contract. * @param token address The contract address of the ERC20 token to recover, or * the null address for recovering Ether. * @param recipient address payable The account where recovered funds should * be transferred. * @dev If you are trying to recover funds that were accidentally sent into * this contract, see if you can contact the holder of the current high score, * found by calling `getHighScore`. Better yet, try to find a new high score * yourself! */ function recover(IERC20 token, address payable recipient) public { //inject PUBLIC FUNC TO EXTERNAL require( msg.sender == address(bytes20(_highScoreKey)), "Only the current high score holder may recover tokens." ); if (address(token) == address(0)) { // Recover ETH if the token's contract address is set to the null address. recipient.transfer(address(this).balance); } else { // Determine the given ERC20 token balance and transfer to the recipient. uint256 balance = token.balanceOf(address(this)); token.transfer(recipient, balance); } } /** * @notice "View" function to determine if a contract can currently be * deployed to a home address given the corresponding key. A contract is only * deployable if no account currently exists at the address - any existing * contract must be destroyed via `SELFDESTRUCT` before a new contract can be * deployed to a home address. This method does not modify state but is * inaccessible via staticcall. * @param key bytes32 The unique value used to derive the home address. * @return A boolean signifying if a contract can be deployed to the home * address that corresponds to the provided key. * @dev This will not detect if a contract is not deployable due control * having been relinquished on the key. */ function isDeployable(bytes32 key) public //inject PUBLIC FUNC TO EXTERNAL /* view */ returns (bool deployable) { deployable = _isNotDeployed(key); } /** * @notice View function to get the current "high score", or the lowest * uint160 value of a home address of all keys submitted. The high score * holder has the exclusive right to recover lost ether and tokens on this * contract. * @return The current high score holder, their score, and the submitted key. */ function getHighScore() public //inject PUBLIC FUNC TO EXTERNAL view returns (address holder, uint256 score, bytes32 key) { // Get the key and subbmitter holding the current high score. key = _highScoreKey; holder = address(bytes20(key)); // The score is equal to (2^160 - 1) - ("home address" of high score key). score = uint256(uint160(-1) - uint160(_getHomeAddress(key))); } /** * @notice View function to get information on a home address given the * corresponding key. * @param key bytes32 The unique value used to derive the home address. * @return The home address, the current controller of the address, the number * of times the home address has been deployed to, and the code hash of the * runtime currently found at the home address, if any. * @dev There is also an `isDeployable` method for determining if a contract * can be deployed to the address, but in extreme cases it must actually * perform a dry-run to determine if the contract is deployable, which means * that it does not support staticcalls. There is also a convenience method, * `hasNeverBeenDeployed`, but the information it conveys can be determined * from this method alone as well. */ function getHomeAddressInformation(bytes32 key) public //inject PUBLIC FUNC TO EXTERNAL view returns ( address homeAddress, address controller, uint256 deploys, bytes32 currentRuntimeCodeHash ) { // Derive home address and retrieve other information using supplied key. homeAddress = _getHomeAddress(key); HomeAddress memory home = _home[key]; // If the home address has not been seen before, use the default controller. if (!home.exists) { controller = address(bytes20(key)); } else { controller = home.controller; } // Retrieve the count of total deploys to the home address. deploys = home.deploys; // Retrieve keccak256 hash of runtime code currently at the home address. assembly { currentRuntimeCodeHash := extcodehash(homeAddress) } } /** * @notice View function to determine if no contract has ever been deployed to * a home address given the corresponding key. This can be used to ensure that * a given key or corresponding token is "new" or not. * @param key bytes32 The unique value used to derive the home address. * @return A boolean signifying if a contract has never been deployed using * the supplied key before. */ function hasNeverBeenDeployed(bytes32 key) public //inject PUBLIC FUNC TO EXTERNAL view returns (bool neverBeenDeployed) { neverBeenDeployed = (_home[key].deploys == 0); } /** * @notice View function to search for a known key, salt, and/or submitter * given a supplied home address. Keys can be controlled directly by an * address that matches the first 20 bytes of the key, or they can be derived * from a salt and a submitter - if the key is not a derived key, the salt and * submitter fields will both have a value of zero. * @param homeAddress address The home address to check for key information. * @return The key, salt, and/or submitter used to deploy to the home address, * assuming they have been submitted to the reverse lookup. * @dev To populate these values, call `setReverseLookup` for cases where keys * are used directly or are the only value known, or `setDerivedReverseLookup` * for cases where keys are derived from a known salt and submitter. */ function reverseLookup(address homeAddress) public //inject PUBLIC FUNC TO EXTERNAL view returns (bytes32 key, bytes32 salt, address submitter) { KeyInformation memory keyInformation = _key[homeAddress]; key = keyInformation.key; salt = keyInformation.salt; submitter = keyInformation.submitter; } /** * @notice View function used by the metamorphic initialization code when * deploying a contract to a home address. It returns the address of the * runtime storage contract that holds the contract creation code, which the * metamorphic creation code then `DELEGATECALL`s into in order to set up the * contract and deploy the target runtime code. * @return The current runtime storage contract that contains the target * contract creation code. * @dev This method is not meant to be part of the user-facing contract API, * but is rather a mechanism for enabling the deployment of arbitrary code via * fixed initialization code. The odd naming is chosen so that function * selector will be 0x00000009 - that way, the metamorphic contract can simply * use the `PC` opcode in order to push the selector to the stack. */ function getInitializationCodeFromContractRuntime_6CLUNS() public //inject PUBLIC FUNC TO EXTERNAL view returns (address initializationRuntimeStorageContract) { // Return address of contract with initialization code set as runtime code. initializationRuntimeStorageContract = _initializationRuntimeStorageContract; } /** * @notice View function to return an URI for a given token ID. Throws if the * token ID does not exist. * @param tokenId uint256 ID of the token to query. * @return String representing the URI data encoding of JSON metadata. * @dev The URI returned by this method takes the following form (with all * returns and initial whitespace removed - it's just here for clarity): * * data:application/json,{ * "name":"Home%20Address%20-%200x********************", * "description":"< ... HomeWork NFT desription ... >", * "image":"data:image/svg+xml;charset=utf-8;base64,< ... Image ... >"} * * where ******************** represents the checksummed home address that the * token confers control over. */ function tokenURI(uint256 tokenId) public //inject PUBLIC FUNC TO EXTERNAL view returns (string memory) { // Only return a URI for tokens that exist. require(_exists(tokenId), "A token with the given ID does not exist."); // Get the home address that the given tokenId corresponds to. address homeAddress = _getHomeAddress(bytes32(tokenId)); // Get the checksummed, ascii-encoded representation of the home address. string memory asciiHomeAddress = _toChecksummedAsciiString(homeAddress); bytes memory uriEndSegment = _getTokenURIStorageRuntime(); // Insert checksummed address into URI in name and image fields and return. return string( abi.encodePacked( // Concatenate all the string segments together. _URI_START_SEGMENT, // Data URI ID and initial formatting is constant. asciiHomeAddress, // Checksummed home address is in the name field. uriEndSegment // Description, image, and formatting is constant. ) ); } /** * @notice Pure function to get the token name. * @return String representing the token name. */ function name() public pure returns (string memory) { //inject PUBLIC FUNC TO EXTERNAL return _NAME; } /** * @notice Pure function to get the token symbol. * @return String representing the token symbol. */ function symbol() public pure returns (string memory) { //inject PUBLIC FUNC TO EXTERNAL return _SYMBOL; } /** * @notice Pure function to determine the key that is derived from a given * salt and submitting address. * @param salt bytes32 The salt value that is used to derive the key. * @param submitter address The submitter of the salt value used to derive the * key. * @return The derived key. */ function getDerivedKey(bytes32 salt, address submitter) public //inject PUBLIC FUNC TO EXTERNAL pure returns (bytes32 key) { // Derive the key using the supplied salt and submitter. key = _deriveKey(salt, submitter); } /** * @notice Pure function to determine the home address that corresponds to * a given key. * @param key bytes32 The unique value used to derive the home address. * @return The home address. */ function getHomeAddress(bytes32 key) public //inject PUBLIC FUNC TO EXTERNAL pure returns (address homeAddress) { // Derive the home address using the supplied key. homeAddress = _getHomeAddress(key); } /** * @notice Pure function for retrieving the metamorphic initialization code * used to deploy arbitrary contracts to home addresses. Provided for easy * verification and for use in other applications. * @return The 32-byte metamorphic initialization code. * @dev This metamorphic init code works via the "metamorphic delegator" * mechanism, which is explained in greater detail at `_deployToHomeAddress`. */ function getMetamorphicDelegatorInitializationCode() public //inject PUBLIC FUNC TO EXTERNAL pure returns (bytes32 metamorphicDelegatorInitializationCode) { metamorphicDelegatorInitializationCode = _HOME_INIT_CODE; } /** * @notice Pure function for retrieving the keccak256 of the metamorphic * initialization code used to deploy arbitrary contracts to home addresses. * This is the value that you should use, along with this contract's address * and a caller address that you control, to mine for an partucular type of * home address (such as one at a compact or gas-efficient address). * @return The keccak256 hash of the metamorphic initialization code. */ function getMetamorphicDelegatorInitializationCodeHash() public //inject PUBLIC FUNC TO EXTERNAL pure returns (bytes32 metamorphicDelegatorInitializationCodeHash) { metamorphicDelegatorInitializationCodeHash = _HOME_INIT_CODE_HASH; } /** * @notice Pure function for retrieving the prelude that will be inserted * ahead of the code payload in order to deploy a runtime storage contract. * @return The 11-byte "arbitrary runtime" prelude. */ function getArbitraryRuntimeCodePrelude() public //inject PUBLIC FUNC TO EXTERNAL pure returns (bytes11 prelude) { prelude = _ARBITRARY_RUNTIME_PRELUDE; } /** * @notice Internal function for deploying a runtime storage contract given a * particular payload. * @return The address of the runtime storage contract. * @dev To take the provided code payload and deploy a contract with that * payload as its runtime code, use the following prelude: * * 0x600b5981380380925939f3... * * 00 60 push1 0b [11 -> offset] * 02 59 msize [offset, 0] * 03 81 dup2 [offset, 0, offset] * 04 38 codesize [offset, 0, offset, codesize] * 05 03 sub [offset, 0, codesize - offset] * 06 80 dup1 [offset, 0, codesize - offset, codesize - offset] * 07 92 swap3 [codesize - offset, 0, codesize - offset, offset] * 08 59 msize [codesize - offset, 0, codesize - offset, offset, 0] * 09 39 codecopy [codesize - offset, 0] <init_code_in_runtime> * 10 f3 return [] *init_code_in_runtime* * ... init_code */ function _deployRuntimeStorageContract(bytes memory payload) internal returns (address runtimeStorageContract) { // Construct the contract creation code using the prelude and the payload. bytes memory runtimeStorageContractCreationCode = abi.encodePacked( _ARBITRARY_RUNTIME_PRELUDE, payload ); assembly { // Get the location and length of the newly-constructed creation code. let encoded_data := add(0x20, runtimeStorageContractCreationCode) let encoded_size := mload(runtimeStorageContractCreationCode) // Deploy the runtime storage contract via standard `CREATE`. runtimeStorageContract := create(0, encoded_data, encoded_size) // Pass along revert message if the contract did not deploy successfully. if iszero(runtimeStorageContract) { returndatacopy(0, 0, returndatasize) revert(0, returndatasize) } } // Emit an event with address of newly-deployed runtime storage contract. emit NewRuntimeStorageContract(runtimeStorageContract, keccak256(payload)); } /** * @notice Internal function for deploying arbitrary contract code to the home * address corresponding to a suppied key via metamorphic initialization code. * @return The home address and the hash of the deployed runtime code. * @dev This deployment method uses the "metamorphic delegator" pattern, where * it will retrieve the address of the contract that contains the target * initialization code, then delegatecall into it, which executes the * initialization code stored there and returns the runtime code (or reverts). * Then, the runtime code returned by the delegatecall is returned, and since * we are still in the initialization context, it will be set as the runtime * code of the metamorphic contract. The 32-byte metamorphic initialization * code is as follows: * * 0x5859385958601c335a585952fa1582838382515af43d3d93833e601e57fd5bf3 * * 00 58 PC [0] * 01 59 MSIZE [0, 0] * 02 38 CODESIZE [0, 0, codesize -> 32] * returndatac03 59 MSIZE [0, 0, 32, 0] * 04 58 PC [0, 0, 32, 0, 4] * 05 60 PUSH1 0x1c [0, 0, 32, 0, 4, 28] * 07 33 CALLER [0, 0, 32, 0, 4, 28, caller] * 08 5a GAS [0, 0, 32, 0, 4, 28, caller, gas] * 09 58 PC [0, 0, 32, 0, 4, 28, caller, gas, 9 -> selector] * 10 59 MSIZE [0, 0, 32, 0, 4, 28, caller, gas, selector, 0] * 11 52 MSTORE [0, 0, 32, 0, 4, 28, caller, gas] <selector> * 12 fa STATICCALL [0, 0, 1 => success] <init_in_runtime_address> * 13 15 ISZERO [0, 0, 0] * 14 82 DUP3 [0, 0, 0, 0] * 15 83 DUP4 [0, 0, 0, 0, 0] * 16 83 DUP4 [0, 0, 0, 0, 0, 0] * 17 82 DUP3 [0, 0, 0, 0, 0, 0, 0] * 18 51 MLOAD [0, 0, 0, 0, 0, 0, init_in_runtime_address] * 19 5a GAS [0, 0, 0, 0, 0, 0, init_in_runtime_address, gas] * 20 f4 DELEGATECALL [0, 0, 1 => success] {runtime_code} * 21 3d RETURNDATASIZE [0, 0, 1 => success, size] * 22 3d RETURNDATASIZE [0, 0, 1 => success, size, size] * 23 93 SWAP4 [size, 0, 1 => success, size, 0] * 24 83 DUP4 [size, 0, 1 => success, size, 0, 0] * 25 3e RETURNDATACOPY [size, 0, 1 => success] <runtime_code> * 26 60 PUSH1 0x1e [size, 0, 1 => success, 30] * 28 57 JUMPI [size, 0] * 29 fd REVERT [] *runtime_code* * 30 5b JUMPDEST [size, 0] * 31 f3 RETURN [] */ function _deployToHomeAddress(bytes32 key) internal returns (address homeAddress, bytes32 runtimeCodeHash) { assembly { // Write the 32-byte metamorphic initialization code to scratch space. mstore( 0, 0x5859385958601c335a585952fa1582838382515af43d3d93833e601e57fd5bf3 ) // Call `CREATE2` using above init code with the supplied key as the salt. homeAddress := create2(callvalue, 0, 32, key) // Pass along revert message if the contract did not deploy successfully. if iszero(homeAddress) { returndatacopy(0, 0, returndatasize) revert(0, returndatasize) } // Get the runtime hash of the deployed contract. runtimeCodeHash := extcodehash(homeAddress) } // Clear the address of the runtime storage contract from storage. delete _initializationRuntimeStorageContract; // Emit an event with home address, key, and runtime hash of new contract. emit NewResident(homeAddress, key, runtimeCodeHash); } /** * @notice Internal function for deriving a key given a particular salt and * caller and for performing verifications of, and modifications to, the * information set on that key. * @param salt bytes32 The value used to derive the key. * @return The derived key. */ function _deriveKeyAndPrepareToDeploy(bytes32 salt) internal returns (bytes32 key) { // Derive the key using the supplied salt and the calling address. key = _deriveKey(salt, msg.sender); // Ensure that a contract is not currently deployed to the home address. require(_isNotDeployed(key), _ACCOUNT_EXISTS); // Set appropriate controller and increment contract deploy count at once. HomeAddress storage home = _home[key]; if (!home.exists) { home.exists = true; home.controller = msg.sender; home.deploys += 1; // Emit an event signifying that this contract is now the controller. emit NewController(key, msg.sender); } else { home.deploys += 1; } // Ensure that the caller is the designated controller before proceeding. require(home.controller == msg.sender, _ONLY_CONTROLLER); } /** * @notice Internal function for verifying that an owner that cannot accept * ERC721 tokens has not been supplied. * @param owner address The specified owner. * @param key bytes32 The unique value used to derive the home address. */ function _validateOwner(address owner, bytes32 key) internal { // Ensure that the specified owner is a valid ERC721 receiver. require( _checkOnERC721Received(address(0), owner, uint256(key), bytes("")), "Owner must be an EOA or a contract that implements `onERC721Received`." ); } /** * @notice Internal "view" function for determining if a contract currently * exists at a given home address corresponding to a particular key. * @param key bytes32 The unique value used to derive the home address. * @return A boolean signifying whether the home address has a contract * deployed or not. */ function _isNotDeployed(bytes32 key) internal /* view */ returns (bool notDeployed) { // Derive the home address using the supplied key. address homeAddress = _getHomeAddress(key); // Check whether account at home address is non-existent using EXTCODEHASH. bytes32 hash; assembly { hash := extcodehash(homeAddress) } // Account does not exist, and contract is not deployed, if hash equals 0. if (hash == bytes32(0)) { return true; } // Contract is deployed (notDeployed = false) if codesize is greater than 0. uint256 size; assembly { size := extcodesize(homeAddress) } if (size > 0) { return false; } // Declare variable to move current runtime storage from storage to memory. address currentStorage; // Set runtime storage contract to null address temporarily if necessary. if (_initializationRuntimeStorageContract != address(0)) { // Place the current runtime storage contract address in memory. currentStorage = _initializationRuntimeStorageContract; // Remove the existing runtime storage contract address from storage. delete _initializationRuntimeStorageContract; } // Set gas to use when performing dry-run deployment (future-proof a bit). uint256 checkGas = 27000 + (block.gaslimit / 1000); // As a last resort, deploy a contract to the address and revert on success. (bool contractExists, bytes memory code) = address(this).call.gas(checkGas)( abi.encodeWithSelector(this.staticCreate2Check.selector, key) ); // Place runtime storage contract back in storage if necessary. if (currentStorage != address(0)) { _initializationRuntimeStorageContract = currentStorage; } // Check revert string to ensure failure is due to successful deployment. bytes32 revertMessage; assembly { revertMessage := mload(add(code, 32)) } // Contract is not deployed if `staticCreate2Check` reverted with message. notDeployed = !contractExists && revertMessage == _HOME_INIT_CODE; } /** * @notice Internal view function for verifying that a restricted controller * has not been supplied. * @param controller address The specified controller. * @param key bytes32 The unique value used to derive the home address. */ function _validateController(address controller, bytes32 key) internal view { // Prevent the controller from being set to prohibited account values. require( controller != address(0), "The null address may not be set as the controller using this function." ); require( controller != address(this), "This contract may not be set as the controller using this function." ); require( controller != _getHomeAddress(key), "Home addresses cannot be set as the controller of themselves." ); } /** * @notice Internal view function for verifying that a supplied runtime * storage contract is not empty. * @param target address The runtime storage contract. */ function _validateRuntimeStorageIsNotEmpty(address target) internal view { // Ensure that the runtime storage contract is not empty. require( target.isContract(), "No runtime code found at the supplied runtime storage address." ); } /** * @notice Internal view function for retrieving the controller of a home * address corresponding to a particular key. * @param key bytes32 The unique value used to derive the home address. * @return The controller of the home address corresponding to the supplied * key. */ function _getController(bytes32 key) internal view returns (address controller) { // Get controller from mapping, defaulting to first 20 bytes of the key. HomeAddress memory home = _home[key]; if (!home.exists) { controller = address(bytes20(key)); } else { controller = home.controller; } } /** * @notice Internal view function for getting the runtime code at the tokenURI * data storage address. * @return The runtime code at the tokenURI storage address. */ function _getTokenURIStorageRuntime() internal view returns (bytes memory runtime) { // Bring the tokenURI storage address into memory for use in assembly block. address target = _URI_END_SEGMENT_STORAGE; assembly { // Retrieve the size of the external code. let size := extcodesize(target) // Allocate output byte array. runtime := mload(0x40) // Set new "memory end" including padding. mstore(0x40, add(runtime, and(add(size, 0x3f), not(0x1f)))) // Store length in memory. mstore(runtime, size) // Get the code using extcodecopy. extcodecopy(target, add(runtime, 0x20), 0, size) } } /** * @notice Internal pure function for calculating a home address given a * particular key. * @param key bytes32 The unique value used to derive the home address. * @return The home address corresponding to the supplied key. */ function _getHomeAddress(bytes32 key) internal pure returns (address homeAddress) { // Determine the home address by replicating CREATE2 logic. homeAddress = address( uint160( // Downcast to match the address type. uint256( // Cast to uint to truncate upper digits. keccak256( // Compute CREATE2 hash using 4 inputs. abi.encodePacked( // Pack all inputs to the hash together. _FF_AND_THIS_CONTRACT, // This contract will be the caller. key, // Pass in the supplied key as the salt. _HOME_INIT_CODE_HASH // The metamorphic init code hash. ) ) ) ) ); } /** * @notice Internal pure function for deriving a key given a particular salt * and caller. * @param salt bytes32 The value used to derive the key. * @param submitter address The submitter of the salt used to derive the key. * @return The derived key. */ function _deriveKey(bytes32 salt, address submitter) internal pure returns (bytes32 key) { // Set the key as the keccak256 hash of the salt and submitter. key = keccak256(abi.encodePacked(salt, submitter)); } /** * @notice Internal pure function for converting the bytes representation of * an address to an ASCII string. This function is derived from the function * at https://ethereum.stackexchange.com/a/56499/48410 * @param data bytes20 The account address to be converted. * @return The account string in ASCII format. Note that leading "0x" is not * included. */ function _toAsciiString(bytes20 data) internal pure returns (string memory asciiString) { // Create an in-memory fixed-size bytes array. bytes memory asciiBytes = new bytes(40); // Declare variable types. uint8 oneByte; uint8 leftNibble; uint8 rightNibble; // Iterate over bytes, processing left and right nibble in each iteration. for (uint256 i = 0; i < data.length; i++) { // locate the byte and extract each nibble. oneByte = uint8(uint160(data) / (2 ** (8 * (19 - i)))); leftNibble = oneByte / 16; rightNibble = oneByte - 16 * leftNibble; // To convert to ascii characters, add 48 to 0-9 and 87 to a-f. asciiBytes[2 * i] = byte(leftNibble + (leftNibble < 10 ? 48 : 87)); asciiBytes[2 * i + 1] = byte(rightNibble + (rightNibble < 10 ? 48 : 87)); } asciiString = string(asciiBytes); } /** * @notice Internal pure function for getting a fixed-size array of whether or * not each character in an account will be capitalized in the checksum. * @param account address The account to get the checksum capitalization * information for. * @return A fixed-size array of booleans that signify if each character or * "nibble" of the hex encoding of the address will be capitalized by the * checksum. */ function _getChecksumCapitalizedCharacters(address account) internal pure returns (bool[40] memory characterIsCapitalized) { // Convert the address to bytes. bytes20 addressBytes = bytes20(account); // Hash the address (used to calculate checksum). bytes32 hash = keccak256(abi.encodePacked(_toAsciiString(addressBytes))); // Declare variable types. uint8 leftNibbleAddress; uint8 rightNibbleAddress; uint8 leftNibbleHash; uint8 rightNibbleHash; // Iterate over bytes, processing left and right nibble in each iteration. for (uint256 i; i < addressBytes.length; i++) { // locate the byte and extract each nibble for the address and the hash. rightNibbleAddress = uint8(addressBytes[i]) % 16; leftNibbleAddress = (uint8(addressBytes[i]) - rightNibbleAddress) / 16; rightNibbleHash = uint8(hash[i]) % 16; leftNibbleHash = (uint8(hash[i]) - rightNibbleHash) / 16; // Set the capitalization flags based on the characters and the checksums. characterIsCapitalized[2 * i] = ( leftNibbleAddress > 9 && leftNibbleHash > 7 ); characterIsCapitalized[2 * i + 1] = ( rightNibbleAddress > 9 && rightNibbleHash > 7 ); } } /** * @notice Internal pure function for converting the bytes representation of * an address to a checksummed ASCII string. * @param account address The account address to be converted. * @return The checksummed account string in ASCII format. Note that leading * "0x" is not included. */ function _toChecksummedAsciiString(address account) internal pure returns (string memory checksummedAsciiString) { // Get capitalized characters in the checksum. bool[40] memory caps = _getChecksumCapitalizedCharacters(account); // Create an in-memory fixed-size bytes array. bytes memory asciiBytes = new bytes(40); // Declare variable types. uint8 oneByte; uint8 leftNibble; uint8 rightNibble; uint8 leftNibbleOffset; uint8 rightNibbleOffset; // Convert account to bytes20. bytes20 data = bytes20(account); // Iterate over bytes, processing left and right nibble in each iteration. for (uint256 i = 0; i < data.length; i++) { // locate the byte and extract each nibble. oneByte = uint8(uint160(data) / (2 ** (8 * (19 - i)))); leftNibble = oneByte / 16; rightNibble = oneByte - 16 * leftNibble; // To convert to ascii characters, add 48 to 0-9, 55 to A-F, & 87 to a-f. if (leftNibble < 10) { leftNibbleOffset = 48; } else if (caps[i * 2]) { leftNibbleOffset = 55; } else { leftNibbleOffset = 87; } if (rightNibble < 10) { rightNibbleOffset = 48; } else { rightNibbleOffset = caps[(i * 2) + 1] ? 55 : 87; // instrumentation fix } asciiBytes[2 * i] = byte(leftNibble + leftNibbleOffset); asciiBytes[2 * i + 1] = byte(rightNibble + rightNibbleOffset); } checksummedAsciiString = string(asciiBytes); } /** * @notice Modifier to ensure that a contract is not currently deployed to the * home address corresponding to a given key on the decorated function. * @param key bytes32 The unique value used to derive the home address. */ modifier onlyEmpty(bytes32 key) { require(_isNotDeployed(key), _ACCOUNT_EXISTS); _; } /** * @notice Modifier to ensure that the caller of the decorated function is the * controller of the home address corresponding to a given key. * @param key bytes32 The unique value used to derive the home address. */ modifier onlyController(bytes32 key) { require(_getController(key) == msg.sender, _ONLY_CONTROLLER); _; } /** * @notice Modifier to track initial controllers and to count deploys, and to * validate that only the designated controller has access to the decorated * function. * @param key bytes32 The unique value used to derive the home address. */ modifier onlyControllerDeployer(bytes32 key) { HomeAddress storage home = _home[key]; // Set appropriate controller and increment contract deploy count at once. if (!home.exists) { home.exists = true; home.controller = address(bytes20(key)); home.deploys += 1; } else { home.deploys += 1; } require(home.controller == msg.sender, _ONLY_CONTROLLER); _; } /** * @notice Modifier to ensure that only the owner of the supplied ERC721 * token, or an approved spender, can access the decorated function. * @param tokenId uint256 The ID of the ERC721 token. */ modifier onlyTokenOwnerOrApprovedSpender(uint256 tokenId) { require( _isApprovedOrOwner(msg.sender, tokenId), "Only the token owner or an approved spender may call this function." ); _; } } /** * @title HomeWork Deployer (alpha version) * @author 0age * @notice This contract is a stripped-down version of HomeWork that is used to * deploy HomeWork itself. * HomeWork Deploy code at runtime: 0x7Cf7708ab4A064B14B02F34aecBd2511f3605395 * HomeWork Runtime code at: 0x0000000000001b84b1cb32787b0d64758d019317 */ contract HomeWorkDeployer { // Fires when HomeWork has been deployed. event HomeWorkDeployment(address homeAddress, bytes32 key); // Fires HomeWork's initialization-in-runtime storage contract is deployed. event StorageContractDeployment(address runtimeStorageContract); // Allocate storage to track the current initialization-in-runtime contract. address private _initializationRuntimeStorageContract; // Once HomeWork has been deployed, disable this contract. bool private _disabled; // Write arbitrary code to a contract's runtime using the following prelude. bytes11 private constant _ARBITRARY_RUNTIME_PRELUDE = bytes11( 0x600b5981380380925939f3 ); /** * @notice Perform phase one of the deployment. * @param code bytes The contract creation code for HomeWork. */ function phaseOne(bytes calldata code) external onlyUntilDisabled { // Deploy payload to the runtime storage contract and set the address. _initializationRuntimeStorageContract = _deployRuntimeStorageContract( bytes32(0), code ); } /** * @notice Perform phase two of the deployment (tokenURI data). * @param key bytes32 The salt to provide to create2. */ function phaseTwo(bytes32 key) public onlyUntilDisabled { //inject PUBLIC FUNC TO EXTERNAL // Deploy runtime storage contract with the string used to construct end of // token URI for issued ERC721s (data URI with a base64-encoded jpeg image). bytes memory code = abi.encodePacked( hex"222c226465736372697074696f6e223a22546869732532304e465425323063616e25", hex"3230626525323072656465656d65642532306f6e253230486f6d65576f726b253230", hex"746f2532306772616e7425323061253230636f6e74726f6c6c657225323074686525", hex"32306578636c75736976652532307269676874253230746f2532306465706c6f7925", hex"3230636f6e7472616374732532307769746825323061726269747261727925323062", hex"797465636f6465253230746f25323074686525323064657369676e61746564253230", hex"686f6d65253230616464726573732e222c22696d616765223a22646174613a696d61", hex"67652f7376672b786d6c3b636861727365743d7574662d383b6261736536342c5048", hex"4e325a79423462577875637a30696148523063446f764c336433647935334d793576", hex"636d63764d6a41774d43397a646d636949485a705a58644362336739496a41674d43", hex"41784e4451674e7a4969506a787a64486c735a543438495674445245465551567375", hex"516e747a64484a766132557462476c755a57707661573436636d3931626d52394c6b", hex"4e37633352796232746c4c5731706447567962476c74615851364d5442394c6b5237", hex"633352796232746c4c5864705a48526f4f6a4a394c6b56375a6d6c7362446f6a4f57", hex"4935596a6c686653354765334e30636d39725a5331736157356c593246774f6e4a76", hex"6457356b66563164506a7776633352356247552b5047636764484a68626e4e6d6233", hex"4a7450534a74595852796158676f4d5334774d694177494441674d5334774d694134", hex"4c6a45674d436b69506a78775958526f49475a706247773949694e6d5a6d59694947", hex"5139496b30784f53417a4d6d677a4e4859794e4567784f586f694c7a34385a79427a", hex"64484a766132553949694d774d44416949474e7359584e7a50534a4349454d675243", hex"492b50484268644767675a6d6c7362443069493245314e7a6b7a4f5349675a443069", hex"545449314944517761446c324d545a6f4c546c364969382b50484268644767675a6d", hex"6c7362443069497a6b795a444e6d4e5349675a443069545451774944517761446832", hex"4e3267744f486f694c7a3438634746306143426d615778735053496a5a5745315954", hex"51334969426b50534a4e4e544d674d7a4a494d546c324c5446734d5459744d545967", hex"4d5467674d545a364969382b50484268644767675a6d6c7362443069626d39755a53", hex"49675a4430695454453549444d7961444d30646a49305344453565694976506a7877", hex"5958526f49475a706247773949694e6c595456684e44636949475139496b30794f53", hex"41794d5777744e53413164693035614456364969382b5043396e506a77765a7a3438", hex"5a794230636d467563325a76636d3039496d316864484a70654367754f4451674d43", hex"4177494334344e4341324e5341314b53492b50484268644767675a44306954546b75", hex"4e5341794d693435624451754f4341324c6a52684d7934784d69417a4c6a45794944", hex"41674d4341784c544d674d693479624330304c6a67744e6934305979347a4c544575", hex"4e4341784c6a59744d69343049444d744d693479656949675a6d6c73624430694932", hex"517759325a6a5a534976506a78775958526f49475a706247773949694d774d544178", hex"4d44456949475139496b30304d53343349444d344c6a56734e5334784c5459754e53", hex"4976506a78775958526f49475139496b30304d693435494449334c6a684d4d546775", hex"4e4341314f4334784944493049445979624449784c6a67744d6a63754d7941794c6a", hex"4d744d693434656949675932786863334d39496b55694c7a3438634746306143426d", hex"615778735053496a4d4445774d5441784969426b50534a4e4e444d754e4341794f53", hex"347a624330304c6a63674e5334344969382b50484268644767675a44306954545132", hex"4c6a67674d7a4a6a4d793479494449754e6941344c6a63674d533479494445794c6a", hex"45744d793479637a4d754e6930354c6a6b754d7930784d693431624330314c6a4567", hex"4e6934314c5449754f4330754d5330754e7930794c6a63674e5334784c5459754e57", hex"4d744d7934794c5449754e6930344c6a63744d5334794c5445794c6a45674d793479", hex"6379307a4c6a59674f5334354c53347a494445794c6a556949474e7359584e7a5053", hex"4a464969382b50484268644767675a6d6c7362443069493245314e7a6b7a4f534967", hex"5a443069545449334c6a4d674d6a5a734d5445754f4341784e53343349444d754e43", hex"41794c6a51674f533478494445304c6a51744d793479494449754d79307849433433", hex"4c5445774c6a49744d544d754e6930784c6a4d744d7934354c5445784c6a67744d54", hex"55754e336f694c7a3438634746306143426b50534a4e4d5449674d546b754f577731", hex"4c6a6b674e793435494445774c6a49744e7934324c544d754e4330304c6a567a4e69", hex"34344c5455754d5341784d4334334c5451754e574d77494441744e6934324c544d74", hex"4d544d754d7941784c6a46544d5449674d546b754f5341784d6941784f5334356569", hex"49675932786863334d39496b55694c7a34385a79426d6157787350534a756232356c", hex"4969427a64484a766132553949694d774d44416949474e7359584e7a50534a434945", hex"4d675243492b50484268644767675a44306954545579494455344c6a6c4d4e444175", hex"4f5341304d7934796243307a4c6a45744d69347a4c5445774c6a59744d5451754e79", hex"30794c6a6b674d693479494445774c6a59674d5451754e7941784c6a45674d793432", hex"494445784c6a55674d5455754e58704e4d5449754e5341784f533434624455754f43", hex"4134494445774c6a4d744e7934304c544d754d7930304c6a5a7a4e6934354c545567", hex"4d5441754f4330304c6a4e6a4d4341774c5459754e69307a4c6a45744d544d754d79", hex"3435637930784d43347a494463754e4330784d43347a494463754e4870744c544975", hex"4e6941794c6a6c734e433433494459754e574d744c6a55674d53347a4c5445754e79", hex"41794c6a45744d7941794c6a4a734c5451754e7930324c6a566a4c6a4d744d533430", hex"494445754e6930794c6a51674d7930794c6a4a364969382b50484268644767675a44", hex"3069545451784c6a4d674d7a67754e5777314c6a45744e6934316253307a4c6a5574", hex"4d693433624330304c6a59674e533434625467754d53307a4c6a466a4d7934794944", hex"49754e6941344c6a63674d533479494445794c6a45744d793479637a4d754e693035", hex"4c6a6b754d7930784d693431624330314c6a45674e6934314c5449754f4330754d53", hex"30754f4330794c6a63674e5334784c5459754e574d744d7934794c5449754e693034", hex"4c6a63744d5334794c5445794c6a45674d7934794c544d754e4341304c6a4d744d79", hex"343249446b754f5330754d7941784d6934314969426a6247467a637a306952694976", hex"506a78775958526f49475139496b307a4d433434494451304c6a524d4d546b674e54", hex"67754f57773049444d674d5441744d5449754e7949675932786863334d39496b5969", hex"4c7a34384c32632b5043396e506a777663335a6e50673d3d227d" ); /* ","description":"This%20NFT%20can%20be%20redeemed%20on%20HomeWork%20 to%20grant%20a%20controller%20the%20exclusive%20right%20to%20deploy%20 contracts%20with%20arbitrary%20bytecode%20to%20the%20designated%20home %20address.","image":"data:image/svg+xml;charset=utf-8;base64,..."} */ // Deploy payload to the runtime storage contract. _deployRuntimeStorageContract(key, code); } /** * @notice Perform phase three of the deployment and disable this contract. * @param key bytes32 The salt to provide to create2. */ function phaseThree(bytes32 key) public onlyUntilDisabled { //inject PUBLIC FUNC TO EXTERNAL // Use metamorphic initialization code to deploy contract to home address. _deployToHomeAddress(key); // Disable this contract from here on out - use HomeWork itself instead. _disabled = true; } /** * @notice View function used by the metamorphic initialization code when * deploying a contract to a home address. It returns the address of the * runtime storage contract that holds the contract creation code, which the * metamorphic creation code then `DELEGATECALL`s into in order to set up the * contract and deploy the target runtime code. * @return The current runtime storage contract that contains the target * contract creation code. * @dev This method is not meant to be part of the user-facing contract API, * but is rather a mechanism for enabling the deployment of arbitrary code via * fixed initialization code. The odd naming is chosen so that function * selector will be 0x00000009 - that way, the metamorphic contract can simply * use the `PC` opcode in order to push the selector to the stack. */ function getInitializationCodeFromContractRuntime_6CLUNS() public //inject PUBLIC FUNC TO EXTERNAL view returns (address initializationRuntimeStorageContract) { // Return address of contract with initialization code set as runtime code. initializationRuntimeStorageContract = _initializationRuntimeStorageContract; } /** * @notice Internal function for deploying a runtime storage contract given a * particular payload. * @dev To take the provided code payload and deploy a contract with that * payload as its runtime code, use the following prelude: * * 0x600b5981380380925939f3... * * 00 60 push1 0b [11 -> offset] * 02 59 msize [offset, 0] * 03 81 dup2 [offset, 0, offset] * 04 38 codesize [offset, 0, offset, codesize] * 05 03 sub [offset, 0, codesize - offset] * 06 80 dup1 [offset, 0, codesize - offset, codesize - offset] * 07 92 swap3 [codesize - offset, 0, codesize - offset, offset] * 08 59 msize [codesize - offset, 0, codesize - offset, offset, 0] * 09 39 codecopy [codesize - offset, 0] <init_code_in_runtime> * 10 f3 return [] *init_code_in_runtime* * ... init_code */ function _deployRuntimeStorageContract(bytes32 key, bytes memory payload) internal returns (address runtimeStorageContract) { // Construct the contract creation code using the prelude and the payload. bytes memory runtimeStorageContractCreationCode = abi.encodePacked( _ARBITRARY_RUNTIME_PRELUDE, payload ); assembly { // Get the location and length of the newly-constructed creation code. let encoded_data := add(0x20, runtimeStorageContractCreationCode) let encoded_size := mload(runtimeStorageContractCreationCode) // Deploy the runtime storage contract via `CREATE2`. runtimeStorageContract := create2(0, encoded_data, encoded_size, key) // Pass along revert message if the contract did not deploy successfully. if iszero(runtimeStorageContract) { returndatacopy(0, 0, returndatasize) revert(0, returndatasize) } } // Emit an event with address of newly-deployed runtime storage contract. emit StorageContractDeployment(runtimeStorageContract); } /** * @notice Internal function for deploying arbitrary contract code to the home * address corresponding to a suppied key via metamorphic initialization code. * @dev This deployment method uses the "metamorphic delegator" pattern, where * it will retrieve the address of the contract that contains the target * initialization code, then delegatecall into it, which executes the * initialization code stored there and returns the runtime code (or reverts). * Then, the runtime code returned by the delegatecall is returned, and since * we are still in the initialization context, it will be set as the runtime * code of the metamorphic contract. The 32-byte metamorphic initialization * code is as follows: * * 0x5859385958601c335a585952fa1582838382515af43d3d93833e601e57fd5bf3 * * 00 58 PC [0] * 01 59 MSIZE [0, 0] * 02 38 CODESIZE [0, 0, codesize -> 32] * returndatac03 59 MSIZE [0, 0, 32, 0] * 04 58 PC [0, 0, 32, 0, 4] * 05 60 PUSH1 0x1c [0, 0, 32, 0, 4, 28] * 07 33 CALLER [0, 0, 32, 0, 4, 28, caller] * 08 5a GAS [0, 0, 32, 0, 4, 28, caller, gas] * 09 58 PC [0, 0, 32, 0, 4, 28, caller, gas, 9 -> selector] * 10 59 MSIZE [0, 0, 32, 0, 4, 28, caller, gas, selector, 0] * 11 52 MSTORE [0, 0, 32, 0, 4, 28, caller, gas] <selector> * 12 fa STATICCALL [0, 0, 1 => success] <init_in_runtime_address> * 13 15 ISZERO [0, 0, 0] * 14 82 DUP3 [0, 0, 0, 0] * 15 83 DUP4 [0, 0, 0, 0, 0] * 16 83 DUP4 [0, 0, 0, 0, 0, 0] * 17 82 DUP3 [0, 0, 0, 0, 0, 0, 0] * 18 51 MLOAD [0, 0, 0, 0, 0, 0, init_in_runtime_address] * 19 5a GAS [0, 0, 0, 0, 0, 0, init_in_runtime_address, gas] * 20 f4 DELEGATECALL [0, 0, 1 => success] {runtime_code} * 21 3d RETURNDATASIZE [0, 0, 1 => success, size] * 22 3d RETURNDATASIZE [0, 0, 1 => success, size, size] * 23 93 SWAP4 [size, 0, 1 => success, size, 0] * 24 83 DUP4 [size, 0, 1 => success, size, 0, 0] * 25 3e RETURNDATACOPY [size, 0, 1 => success] <runtime_code> * 26 60 PUSH1 0x1e [size, 0, 1 => success, 30] * 28 57 JUMPI [size, 0] * 29 fd REVERT [] *runtime_code* * 30 5b JUMPDEST [size, 0] * 31 f3 RETURN [] */ function _deployToHomeAddress(bytes32 key) internal { // Declare a variable for the home address. address homeAddress; assembly { // Write the 32-byte metamorphic initialization code to scratch space. mstore( 0, 0x5859385958601c335a585952fa1582838382515af43d3d93833e601e57fd5bf3 ) // Call `CREATE2` using above init code with the supplied key as the salt. homeAddress := create2(callvalue, 0, 32, key) // Pass along revert message if the contract did not deploy successfully. if iszero(homeAddress) { returndatacopy(0, 0, returndatasize) revert(0, returndatasize) } } // Clear the address of the runtime storage contract from storage. delete _initializationRuntimeStorageContract; // Emit an event with home address and key for the newly-deployed contract. emit HomeWorkDeployment(homeAddress, key); } /** * @notice Modifier to disable the contract once deployment is complete. */ modifier onlyUntilDisabled() { require(!_disabled, "Contract is disabled."); _; } }
Get the location and length of the newly-constructed creation code. Deploy the runtime storage contract via `CREATE2`. Pass along revert message if the contract did not deploy successfully.
function getInitializationCodeFromContractRuntime_6CLUNS() view returns (address initializationRuntimeStorageContract) } function _deployRuntimeStorageContract(bytes32 key, bytes memory payload) internal returns (address runtimeStorageContract) assembly { let encoded_data := add(0x20, runtimeStorageContractCreationCode) let encoded_size := mload(runtimeStorageContractCreationCode) runtimeStorageContract := create2(0, encoded_data, encoded_size, key) if iszero(runtimeStorageContract) { returndatacopy(0, 0, returndatasize) revert(0, returndatasize) } }
15,818,011
[ 1, 967, 326, 2117, 471, 769, 434, 326, 10894, 17, 10062, 329, 6710, 981, 18, 7406, 326, 3099, 2502, 6835, 3970, 1375, 9344, 22, 8338, 10311, 7563, 15226, 883, 309, 326, 6835, 5061, 486, 7286, 4985, 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, 225, 445, 336, 17701, 1085, 1265, 8924, 5576, 67, 26, 5017, 2124, 55, 1435, 203, 565, 1476, 203, 565, 1135, 261, 2867, 10313, 5576, 3245, 8924, 13, 203, 225, 289, 203, 203, 225, 445, 389, 12411, 5576, 3245, 8924, 12, 3890, 1578, 498, 16, 1731, 3778, 2385, 13, 203, 565, 2713, 203, 565, 1135, 261, 2867, 3099, 3245, 8924, 13, 203, 565, 19931, 288, 203, 1377, 2231, 3749, 67, 892, 519, 527, 12, 20, 92, 3462, 16, 3099, 3245, 8924, 9906, 1085, 13, 203, 1377, 2231, 3749, 67, 1467, 519, 312, 945, 12, 9448, 3245, 8924, 9906, 1085, 13, 203, 203, 1377, 3099, 3245, 8924, 519, 752, 22, 12, 20, 16, 3749, 67, 892, 16, 3749, 67, 1467, 16, 498, 13, 203, 203, 1377, 309, 353, 7124, 12, 9448, 3245, 8924, 13, 288, 203, 3639, 327, 892, 3530, 12, 20, 16, 374, 16, 327, 13178, 554, 13, 203, 3639, 15226, 12, 20, 16, 327, 13178, 554, 13, 203, 1377, 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 ]
//Address: 0x7268f9c2bc9c9e65b4a16888cb5672531ce8e945 //Contract name: DayToken //Balance: 0 Ether //Verification Date: 9/15/2017 //Transacion Count: 4246 // CODE STARTS HERE pragma solidity ^0.4.13; ////////////////// >>>>> Wallet Contract <<<<< /////////////////// /// @title Multisignature wallet - Allows multiple parties to agree on transactions before execution. /// @author Stefan George - <[email protected]> contract MultiSigWallet { uint constant public MAX_OWNER_COUNT = 50; event Confirmation(address indexed sender, uint indexed transactionId); event Revocation(address indexed sender, uint indexed transactionId); event Submission(uint indexed transactionId); event Execution(uint indexed transactionId); event ExecutionFailure(uint indexed transactionId); event Deposit(address indexed sender, uint value); event OwnerAddition(address indexed owner); event OwnerRemoval(address indexed owner); event RequirementChange(uint required); mapping (uint => Transaction) public transactions; mapping (uint => mapping (address => bool)) public confirmations; mapping (address => bool) public isOwner; address[] public owners; uint public required; uint public transactionCount; struct Transaction { address destination; uint value; bytes data; bool executed; } modifier onlyWallet() { if (msg.sender != address(this)) throw; _; } modifier ownerDoesNotExist(address owner) { if (isOwner[owner]) throw; _; } modifier ownerExists(address owner) { if (!isOwner[owner]) throw; _; } modifier transactionExists(uint transactionId) { if (transactions[transactionId].destination == 0) throw; _; } modifier confirmed(uint transactionId, address owner) { if (!confirmations[transactionId][owner]) throw; _; } modifier notConfirmed(uint transactionId, address owner) { if (confirmations[transactionId][owner]) throw; _; } modifier notExecuted(uint transactionId) { if (transactions[transactionId].executed) throw; _; } modifier notNull(address _address) { if (_address == 0) throw; _; } modifier validRequirement(uint ownerCount, uint _required) { if ( ownerCount > MAX_OWNER_COUNT || _required > ownerCount || _required == 0 || ownerCount == 0) throw; _; } /// @dev Fallback function allows to deposit ether. function() payable { if (msg.value > 0) Deposit(msg.sender, msg.value); } /* * Public functions */ /// @dev Contract constructor sets initial owners and required number of confirmations. /// @param _owners List of initial owners. /// @param _required Number of required confirmations. function MultiSigWallet(address[] _owners, uint _required) public validRequirement(_owners.length, _required) { for (uint i=0; i<_owners.length; i++) { if (isOwner[_owners[i]] || _owners[i] == 0) throw; isOwner[_owners[i]] = true; } owners = _owners; required = _required; } /// @dev Allows to add a new owner. Transaction has to be sent by wallet. /// @param owner Address of new owner. function addOwner(address owner) public onlyWallet ownerDoesNotExist(owner) notNull(owner) validRequirement(owners.length + 1, required) { isOwner[owner] = true; owners.push(owner); OwnerAddition(owner); } /// @dev Allows to remove an owner. Transaction has to be sent by wallet. /// @param owner Address of owner. function removeOwner(address owner) public onlyWallet ownerExists(owner) { isOwner[owner] = false; for (uint i=0; i<owners.length - 1; i++) if (owners[i] == owner) { owners[i] = owners[owners.length - 1]; break; } owners.length -= 1; if (required > owners.length) changeRequirement(owners.length); OwnerRemoval(owner); } /// @dev Allows to replace an owner with a new owner. Transaction has to be sent by wallet. /// @param owner Address of owner to be replaced. /// @param owner Address of new owner. function replaceOwner(address owner, address newOwner) public onlyWallet ownerExists(owner) ownerDoesNotExist(newOwner) { for (uint i=0; i<owners.length; i++) if (owners[i] == owner) { owners[i] = newOwner; break; } isOwner[owner] = false; isOwner[newOwner] = true; OwnerRemoval(owner); OwnerAddition(newOwner); } /// @dev Allows to change the number of required confirmations. Transaction has to be sent by wallet. /// @param _required Number of required confirmations. function changeRequirement(uint _required) public onlyWallet validRequirement(owners.length, _required) { required = _required; RequirementChange(_required); } /// @dev Allows an owner to submit and confirm a transaction. /// @param destination Transaction target address. /// @param value Transaction ether value. /// @param data Transaction data payload. /// @return Returns transaction ID. function submitTransaction(address destination, uint value, bytes data) public returns (uint transactionId) { transactionId = addTransaction(destination, value, data); confirmTransaction(transactionId); } /// @dev Allows an owner to confirm a transaction. /// @param transactionId Transaction ID. function confirmTransaction(uint transactionId) public ownerExists(msg.sender) transactionExists(transactionId) notConfirmed(transactionId, msg.sender) { confirmations[transactionId][msg.sender] = true; Confirmation(msg.sender, transactionId); executeTransaction(transactionId); } /// @dev Allows an owner to revoke a confirmation for a transaction. /// @param transactionId Transaction ID. function revokeConfirmation(uint transactionId) public ownerExists(msg.sender) confirmed(transactionId, msg.sender) notExecuted(transactionId) { confirmations[transactionId][msg.sender] = false; Revocation(msg.sender, transactionId); } /// @dev Allows anyone to execute a confirmed transaction. /// @param transactionId Transaction ID. function executeTransaction(uint transactionId) public notExecuted(transactionId) { if (isConfirmed(transactionId)) { Transaction tx = transactions[transactionId]; tx.executed = true; if (tx.destination.call.value(tx.value)(tx.data)) Execution(transactionId); else { ExecutionFailure(transactionId); tx.executed = false; } } } /// @dev Returns the confirmation status of a transaction. /// @param transactionId Transaction ID. /// @return Confirmation status. function isConfirmed(uint transactionId) public constant returns (bool) { uint count = 0; for (uint i=0; i<owners.length; i++) { if (confirmations[transactionId][owners[i]]) count += 1; if (count == required) return true; } } /* * Internal functions */ /// @dev Adds a new transaction to the transaction mapping, if transaction does not exist yet. /// @param destination Transaction target address. /// @param value Transaction ether value. /// @param data Transaction data payload. /// @return Returns transaction ID. function addTransaction(address destination, uint value, bytes data) internal notNull(destination) returns (uint transactionId) { transactionId = transactionCount; transactions[transactionId] = Transaction({ destination: destination, value: value, data: data, executed: false }); transactionCount += 1; Submission(transactionId); } /* * Web3 call functions */ /// @dev Returns number of confirmations of a transaction. /// @param transactionId Transaction ID. /// @return Number of confirmations. function getConfirmationCount(uint transactionId) public constant returns (uint count) { for (uint i=0; i<owners.length; i++) if (confirmations[transactionId][owners[i]]) count += 1; } /// @dev Returns total number of transactions after filers are applied. /// @param pending Include pending transactions. /// @param executed Include executed transactions. /// @return Total number of transactions after filters are applied. function getTransactionCount(bool pending, bool executed) public constant returns (uint count) { for (uint i=0; i<transactionCount; i++) if ( pending && !transactions[i].executed || executed && transactions[i].executed) count += 1; } /// @dev Returns list of owners. /// @return List of owner addresses. function getOwners() public constant returns (address[]) { return owners; } /// @dev Returns array with owner addresses, which confirmed transaction. /// @param transactionId Transaction ID. /// @return Returns array of owner addresses. function getConfirmations(uint transactionId) public constant returns (address[] _confirmations) { address[] memory confirmationsTemp = new address[](owners.length); uint count = 0; uint i; for (i=0; i<owners.length; i++) if (confirmations[transactionId][owners[i]]) { confirmationsTemp[count] = owners[i]; count += 1; } _confirmations = new address[](count); for (i=0; i<count; i++) _confirmations[i] = confirmationsTemp[i]; } /// @dev Returns list of transaction IDs in defined range. /// @param from Index start position of transaction array. /// @param to Index end position of transaction array. /// @param pending Include pending transactions. /// @param executed Include executed transactions. /// @return Returns array of transaction IDs. function getTransactionIds(uint from, uint to, bool pending, bool executed) public constant returns (uint[] _transactionIds) { uint[] memory transactionIdsTemp = new uint[](transactionCount); uint count = 0; uint i; for (i=0; i<transactionCount; i++) if ( pending && !transactions[i].executed || executed && transactions[i].executed) { transactionIdsTemp[count] = i; count += 1; } _transactionIds = new uint[](to - from); for (i=from; i<to; i++) _transactionIds[i - from] = transactionIdsTemp[i]; } } ////////////////// >>>>> Library Contracts <<<<< /////////////////// contract SafeMathLib { function safeMul(uint a, uint b) constant returns (uint) { uint c = a * b; assert(a == 0 || c / a == b); return c; } function safeSub(uint a, uint b) constant returns (uint) { assert(b <= a); return a - b; } function safeAdd(uint a, uint b) constant returns (uint) { uint c = a + b; assert(c>=a); return c; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; address public newOwner; event OwnershipTransferred(address indexed _from, address indexed _to); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) onlyOwner { newOwner = _newOwner; } function acceptOwnership() { require(msg.sender == newOwner); OwnershipTransferred(owner, newOwner); owner = newOwner; } } ////////////////// >>>>> Token Contracts <<<<< /////////////////// /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20Basic { uint public totalSupply; function balanceOf(address _owner) constant returns (uint balance); function transfer(address _to, uint _value) returns (bool success); event Transfer(address indexed _from, address indexed _to, uint _value); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address _owner, address _spender) constant returns (uint remaining); function transferFrom(address _from, address _to, uint _value) returns (bool success); function approve(address _spender, uint _value) returns (bool success); event Approval(address indexed _owner, address indexed _spender, uint _value); } /** * Standard ERC20 token with Short Hand Attack and approve() race condition mitigation. * * Based on code by FirstBlood: * https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, SafeMathLib { /* Token supply got increased and a new owner received these tokens */ event Minted(address receiver, uint amount); /* Actual balances of token holders */ mapping(address => uint) balances; /* approve() allowances */ mapping (address => mapping (address => uint)) allowed; function transfer(address _to, uint _value) returns (bool success) { if (balances[msg.sender] >= _value && _value > 0 && balances[_to] + _value > balances[_to] ) { balances[msg.sender] = safeSub(balances[msg.sender],_value); balances[_to] = safeAdd(balances[_to],_value); Transfer(msg.sender, _to, _value); return true; } else{ return false; } } function transferFrom(address _from, address _to, uint _value) returns (bool success) { uint _allowance = allowed[_from][msg.sender]; if (balances[_from] >= _value // From a/c has balance && _allowance >= _value // Transfer approved && _value > 0 // Non-zero transfer && balances[_to] + _value > balances[_to] // Overflow check ){ balances[_to] = safeAdd(balances[_to],_value); balances[_from] = safeSub(balances[_from],_value); allowed[_from][msg.sender] = safeSub(_allowance,_value); Transfer(_from, _to, _value); return true; } else { return false; } } function balanceOf(address _owner) constant returns (uint balance) { return balances[_owner]; } function approve(address _spender, uint _value) returns (bool success) { // 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; } function allowance(address _owner, address _spender) constant returns (uint remaining) { return allowed[_owner][_spender]; } } /** * A token that can increase its supply by another contract. * * This allows uncapped crowdsale by dynamically increasing the supply when money pours in. * Only mint agents, contracts whitelisted by owner, can mint new tokens. * */ contract MintableToken is StandardToken, Ownable { bool public mintingFinished = false; /** List of agents that are allowed to create new tokens */ mapping (address => bool) public mintAgents; event MintingAgentChanged(address addr, bool state ); /** * Create new tokens and allocate them to an address.. * * Only callably by a crowdsale contract (mint agent). */ function mint(address receiver, uint amount) onlyMintAgent canMint public { totalSupply = safeAdd(totalSupply, amount); balances[receiver] = safeAdd(balances[receiver], amount); // This will make the mint transaction apper in EtherScan.io // We can remove this after there is a standardized minting event Transfer(0, receiver, amount); } /** * Owner can allow a crowdsale contract to mint new tokens. */ function setMintAgent(address addr, bool state) onlyOwner canMint public { mintAgents[addr] = state; MintingAgentChanged(addr, state); } modifier onlyMintAgent() { // Only crowdsale contracts are allowed to mint new tokens require(mintAgents[msg.sender]); _; } /** Make sure we are not done yet. */ modifier canMint() { require(!mintingFinished); _; } } /** * Define interface for releasing the token transfer after a successful crowdsale. */ contract ReleasableToken is ERC20, Ownable { /* The finalizer contract that allows unlift the transfer limits on this token */ address public releaseAgent; /** A crowdsale contract can release us to the wild if ICO success. * If false we are are in transfer lock up period. */ bool public released = false; /** Map of agents that are allowed to transfer tokens regardless of the lock down period. * These are crowdsale contracts and possible the team multisig itself. */ mapping (address => bool) public transferAgents; /** * Limit token transfer until the crowdsale is over. */ modifier canTransfer(address _sender) { if (!released) { require(transferAgents[_sender]); } _; } /** * Set the contract that can call release and make the token transferable. * * Design choice. Allow reset the release agent to fix fat finger mistakes. */ function setReleaseAgent(address addr) onlyOwner inReleaseState(false) public { // We don't do interface check here as we might want to a normal wallet address to act as a release agent releaseAgent = addr; } /** * Owner can allow a particular address (a crowdsale contract) to transfer tokens despite the lock up period. */ function setTransferAgent(address addr, bool state) onlyOwner inReleaseState(false) public { transferAgents[addr] = state; } /** * One way function to release the tokens to the wild. * * Can be called only from the release agent that is the final ICO contract. * It is only called if the crowdsale has been success (first milestone reached). */ function releaseTokenTransfer() public onlyReleaseAgent { released = true; } /** The function can be called only before or after the tokens have been releasesd */ modifier inReleaseState(bool releaseState) { require(releaseState == released); _; } /** The function can be called only by a whitelisted release agent. */ modifier onlyReleaseAgent() { require(msg.sender == releaseAgent); _; } function transfer(address _to, uint _value) canTransfer(msg.sender) returns (bool success) { // Call StandardToken.transfer() return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint _value) canTransfer(_from) returns (bool success) { // Call StandardToken.transferForm() return super.transferFrom(_from, _to, _value); } } /** * Upgrade agent interface inspired by Lunyr. * * Upgrade agent transfers tokens to a new contract. * Upgrade agent itself can be the token contract, or just a middle man contract doing the heavy lifting. */ contract UpgradeAgent { uint public originalSupply; /** Interface marker */ function isUpgradeAgent() public constant returns (bool) { return true; } function upgradeFrom(address _from, uint256 _value) public; } /** * A token upgrade mechanism where users can opt-in amount of tokens to the next smart contract revision. * * First envisioned by Golem and Lunyr projects. */ contract UpgradeableToken is StandardToken { /** Contract / person who can set the upgrade path. * This can be the same as team multisig wallet, as what it is with its default value. */ address public upgradeMaster; /** The next contract where the tokens will be migrated. */ UpgradeAgent public upgradeAgent; /** How many tokens we have upgraded by now. */ uint256 public totalUpgraded; /** * Upgrade states. * * - NotAllowed: The child contract has not reached a condition where the upgrade can bgun * - WaitingForAgent: Token allows upgrade, but we don't have a new agent yet * - ReadyToUpgrade: The agent is set, but not a single token has been upgraded yet * - Upgrading: Upgrade agent is set and the balance holders can upgrade their tokens * */ enum UpgradeState {Unknown, NotAllowed, WaitingForAgent, ReadyToUpgrade, Upgrading} /** * Somebody has upgraded some of their tokens. */ event Upgrade(address indexed _from, address indexed _to, uint256 _value); /** * New upgrade agent available. */ event UpgradeAgentSet(address agent); /** * Do not allow construction without upgrade master set. */ function UpgradeableToken(address _upgradeMaster) { upgradeMaster = _upgradeMaster; } /** * Allow the token holder to upgrade some of their tokens to a new contract. */ function upgrade(uint256 value) public { UpgradeState state = getUpgradeState(); require((state == UpgradeState.ReadyToUpgrade || state == UpgradeState.Upgrading)); // Validate input value. require(value!=0); balances[msg.sender] = safeSub(balances[msg.sender],value); // Take tokens out from circulation totalSupply = safeSub(totalSupply,value); totalUpgraded = safeAdd(totalUpgraded,value); // Upgrade agent reissues the tokens upgradeAgent.upgradeFrom(msg.sender, value); Upgrade(msg.sender, upgradeAgent, value); } /** * Set an upgrade agent that handles */ function setUpgradeAgent(address agent) external { require(canUpgrade()); require(agent != 0x0); // Only a master can designate the next agent require(msg.sender == upgradeMaster); // Upgrade has already begun for an agent require(getUpgradeState() != UpgradeState.Upgrading); upgradeAgent = UpgradeAgent(agent); // Bad interface require(upgradeAgent.isUpgradeAgent()); // Make sure that token supplies match in source and target require(upgradeAgent.originalSupply() == totalSupply); UpgradeAgentSet(upgradeAgent); } /** * Get the state of the token upgrade. */ function getUpgradeState() public constant returns(UpgradeState) { if (!canUpgrade()) return UpgradeState.NotAllowed; else if(address(upgradeAgent) == 0x00) return UpgradeState.WaitingForAgent; else if(totalUpgraded == 0) return UpgradeState.ReadyToUpgrade; else return UpgradeState.Upgrading; } /** * Change the upgrade master. * * This allows us to set a new owner for the upgrade mechanism. */ function setUpgradeMaster(address master) public { require(master != 0x0); require(msg.sender == upgradeMaster); upgradeMaster = master; } /** * Child contract can enable to provide the condition when the upgrade can begun. */ function canUpgrade() public constant returns(bool) { return true; } } /** * A crowdsale token. * * An ERC-20 token designed specifically for crowdsales with investor protection and * further development path. * * - The token transfer() is disabled until the crowdsale is over * - The token contract gives an opt-in upgrade path to a new contract * - The same token can be part of several crowdsales through approve() mechanism * - The token can be capped (supply set in the constructor) * or uncapped (crowdsale contract can mint new tokens) */ contract DayToken is ReleasableToken, MintableToken, UpgradeableToken { enum sellingStatus {NOTONSALE, EXPIRED, ONSALE} /** Basic structure for a contributor with a minting Address * adr address of the contributor * initialContributionDay initial contribution of the contributor in wei * lastUpdatedOn day count from Minting Epoch when the account balance was last updated * mintingPower Initial Minting power of the address * expiryBlockNumber Variable to mark end of Minting address sale. Set by user * minPriceInDay minimum price of Minting address in Day tokens. Set by user * status Selling status Variable for transfer Minting address. * sellingPriceInDay Variable for transfer Minting address. Price at which the address is actually sold */ struct Contributor { address adr; uint256 initialContributionDay; uint256 lastUpdatedOn; //Day from Minting Epoch uint256 mintingPower; uint expiryBlockNumber; uint256 minPriceInDay; sellingStatus status; } /* Stores maximum days for which minting will happen since minting epoch */ uint256 public maxMintingDays = 1095; /* Mapping to store id of each minting address */ mapping (address => uint) public idOf; /* Mapping from id of each minting address to their respective structures */ mapping (uint256 => Contributor) public contributors; /* mapping to store unix timestamp of when the minting address is issued to each team member */ mapping (address => uint256) public teamIssuedTimestamp; mapping (address => bool) public soldAddresses; mapping (address => uint256) public sellingPriceInDayOf; /* Stores the id of the first contributor */ uint256 public firstContributorId; /* Stores total Pre + Post ICO TimeMints */ uint256 public totalNormalContributorIds; /* Stores total Normal TimeMints allocated */ uint256 public totalNormalContributorIdsAllocated = 0; /* Stores the id of the first team TimeMint */ uint256 public firstTeamContributorId; /* Stores the total team TimeMints */ uint256 public totalTeamContributorIds; /* Stores total team TimeMints allocated */ uint256 public totalTeamContributorIdsAllocated = 0; /* Stores the id of the first Post ICO contributor (for auctionable TimeMints) */ uint256 public firstPostIcoContributorId; /* Stores total Post ICO TimeMints (for auction) */ uint256 public totalPostIcoContributorIds; /* Stores total Auction TimeMints allocated */ uint256 public totalPostIcoContributorIdsAllocated = 0; /* Maximum number of address */ uint256 public maxAddresses; /* Min Minting power with 19 decimals: 0.5% : 5000000000000000000 */ uint256 public minMintingPower; /* Max Minting power with 19 decimals: 1% : 10000000000000000000 */ uint256 public maxMintingPower; /* Halving cycle in days (88) */ uint256 public halvingCycle; /* Unix timestamp when minting is to be started */ uint256 public initialBlockTimestamp; /* Flag to prevent setting initialBlockTimestamp more than once */ bool public isInitialBlockTimestampSet; /* number of decimals in minting power */ uint256 public mintingDec; /* Minimum Balance in Day tokens required to sell a minting address */ uint256 public minBalanceToSell; /* Team address lock down period from issued time, in seconds */ uint256 public teamLockPeriodInSec; //Initialize and set function /* Duration in secs that we consider as a day. (For test deployment purposes, if we want to decrease length of a day. default: 84600)*/ uint256 public DayInSecs; event UpdatedTokenInformation(string newName, string newSymbol); event MintingAdrTransferred(uint id, address from, address to); event ContributorAdded(address adr, uint id); event TimeMintOnSale(uint id, address seller, uint minPriceInDay, uint expiryBlockNumber); event TimeMintSold(uint id, address buyer, uint offerInDay); event PostInvested(address investor, uint weiAmount, uint tokenAmount, uint customerId, uint contributorId); event TeamAddressAdded(address teamAddress, uint id); // Tell us invest was success event Invested(address receiver, uint weiAmount, uint tokenAmount, uint customerId, uint contributorId); modifier onlyContributor(uint id){ require(isValidContributorId(id)); _; } string public name; string public symbol; uint8 public decimals; /** * Construct the token. * * This token must be created through a team multisig wallet, so that it is owned by that wallet. * * @param _name Token name * @param _symbol Token symbol - should be all caps * @param _initialSupply How many tokens we start with * @param _decimals Number of decimal places * _mintable Are new tokens created over the crowdsale or do we distribute only the initial supply? */ function DayToken(string _name, string _symbol, uint _initialSupply, uint8 _decimals, bool _mintable, uint _maxAddresses, uint _firstTeamContributorId, uint _totalTeamContributorIds, uint _totalPostIcoContributorIds, uint256 _minMintingPower, uint256 _maxMintingPower, uint _halvingCycle, uint256 _minBalanceToSell, uint256 _dayInSecs, uint256 _teamLockPeriodInSec) UpgradeableToken(msg.sender) { // Create any address, can be transferred // to team multisig via changeOwner(), // also remember to call setUpgradeMaster() owner = msg.sender; name = _name; symbol = _symbol; totalSupply = _initialSupply; decimals = _decimals; // Create initially all balance on the team multisig balances[owner] = totalSupply; maxAddresses = _maxAddresses; require(maxAddresses > 1); // else division by zero will occur in setInitialMintingPowerOf firstContributorId = 1; totalNormalContributorIds = maxAddresses - _totalTeamContributorIds - _totalPostIcoContributorIds; // check timeMint total is sane require(totalNormalContributorIds >= 1); firstTeamContributorId = _firstTeamContributorId; totalTeamContributorIds = _totalTeamContributorIds; totalPostIcoContributorIds = _totalPostIcoContributorIds; // calculate first contributor id to be auctioned post ICO firstPostIcoContributorId = maxAddresses - totalPostIcoContributorIds + 1; minMintingPower = _minMintingPower; maxMintingPower = _maxMintingPower; halvingCycle = _halvingCycle; // setting future date far far away, year 2020, // call setInitialBlockTimestamp to set proper timestamp initialBlockTimestamp = 1577836800; isInitialBlockTimestampSet = false; // use setMintingDec to change this mintingDec = 19; minBalanceToSell = _minBalanceToSell; DayInSecs = _dayInSecs; teamLockPeriodInSec = _teamLockPeriodInSec; if (totalSupply > 0) { Minted(owner, totalSupply); } if (!_mintable) { mintingFinished = true; require(totalSupply != 0); } } /** * Used to set timestamp at which minting power of TimeMints is activated * Can be called only by owner * @param _initialBlockTimestamp timestamp to be set. */ function setInitialBlockTimestamp(uint _initialBlockTimestamp) internal onlyOwner { require(!isInitialBlockTimestampSet); isInitialBlockTimestampSet = true; initialBlockTimestamp = _initialBlockTimestamp; } /** * check if mintining power is activated and Day token and Timemint transfer is enabled */ function isDayTokenActivated() constant returns (bool isActivated) { return (block.timestamp >= initialBlockTimestamp); } /** * to check if an id is a valid contributor * @param _id contributor id to check. */ function isValidContributorId(uint _id) constant returns (bool isValidContributor) { return (_id > 0 && _id <= maxAddresses && contributors[_id].adr != 0 && idOf[contributors[_id].adr] == _id); // cross checking } /** * to check if an address is a valid contributor * @param _address contributor address to check. */ function isValidContributorAddress(address _address) constant returns (bool isValidContributor) { return isValidContributorId(idOf[_address]); } /** * In case of Team address check if lock-in period is over (returns true for all non team addresses) * @param _address team address to check lock in period for. */ function isTeamLockInPeriodOverIfTeamAddress(address _address) constant returns (bool isLockInPeriodOver) { isLockInPeriodOver = true; if (teamIssuedTimestamp[_address] != 0) { if (block.timestamp - teamIssuedTimestamp[_address] < teamLockPeriodInSec) isLockInPeriodOver = false; } return isLockInPeriodOver; } /** * Used to set mintingDec * Can be called only by owner * @param _mintingDec bounty to be set. */ function setMintingDec(uint256 _mintingDec) onlyOwner { require(!isInitialBlockTimestampSet); mintingDec = _mintingDec; } /** * When token is released to be transferable, enforce no new tokens can be created. */ function releaseTokenTransfer() public onlyOwner { require(isInitialBlockTimestampSet); mintingFinished = true; super.releaseTokenTransfer(); } /** * Allow upgrade agent functionality kick in only if the crowdsale was success. */ function canUpgrade() public constant returns(bool) { return released && super.canUpgrade(); } /** * Owner can update token information here */ function setTokenInformation(string _name, string _symbol) onlyOwner { name = _name; symbol = _symbol; UpdatedTokenInformation(name, symbol); } /** * Returns the current phase. * Note: Phase starts with 1 * @param _day Number of days since Minting Epoch */ function getPhaseCount(uint _day) public constant returns (uint phase) { phase = (_day/halvingCycle) + 1; return (phase); } /** * Returns current day number since minting epoch * or zero if initialBlockTimestamp is in future or its DayZero. */ function getDayCount() public constant returns (uint daySinceMintingEpoch) { daySinceMintingEpoch = 0; if (isDayTokenActivated()) daySinceMintingEpoch = (block.timestamp - initialBlockTimestamp)/DayInSecs; return daySinceMintingEpoch; } /** * Calculates and Sets the minting power of a particular id. * Called before Minting Epoch by constructor * @param _id id of the address whose minting power is to be set. */ function setInitialMintingPowerOf(uint256 _id) internal onlyContributor(_id) { contributors[_id].mintingPower = (maxMintingPower - ((_id-1) * (maxMintingPower - minMintingPower)/(maxAddresses-1))); } /** * Returns minting power of a particular id. * @param _id Contribution id whose minting power is to be returned */ function getMintingPowerById(uint _id) public constant returns (uint256 mintingPower) { return contributors[_id].mintingPower/(2**(getPhaseCount(getDayCount())-1)); } /** * Returns minting power of a particular address. * @param _adr Address whose minting power is to be returned */ function getMintingPowerByAddress(address _adr) public constant returns (uint256 mintingPower) { return getMintingPowerById(idOf[_adr]); } /** * Calculates and returns the balance based on the minting power, day and phase. * Can only be called internally * Can calculate balance based on last updated. * @param _id id whose balnce is to be calculated * @param _dayCount day count upto which balance is to be updated */ function availableBalanceOf(uint256 _id, uint _dayCount) internal returns (uint256) { uint256 balance = balances[contributors[_id].adr]; uint maxUpdateDays = _dayCount < maxMintingDays ? _dayCount : maxMintingDays; uint i = contributors[_id].lastUpdatedOn + 1; while(i <= maxUpdateDays) { uint phase = getPhaseCount(i); uint phaseEndDay = phase * halvingCycle - 1; // as first day is 0 uint constantFactor = contributors[_id].mintingPower / 2**(phase-1); for (uint j = i; j <= phaseEndDay && j <= maxUpdateDays; j++) { balance = safeAdd( balance, constantFactor * balance / 10**(mintingDec + 2) ); } i = j; } return balance; } /** * Updates the balance of the specified id in its structure and also in the balances[] mapping. * returns true if successful. * Only for internal calls. Not public. * @param _id id whose balance is to be updated. */ function updateBalanceOf(uint256 _id) internal returns (bool success) { // check if its contributor if (isValidContributorId(_id)) { uint dayCount = getDayCount(); // proceed only if not already updated today if (contributors[_id].lastUpdatedOn != dayCount && contributors[_id].lastUpdatedOn < maxMintingDays) { address adr = contributors[_id].adr; uint oldBalance = balances[adr]; totalSupply = safeSub(totalSupply, oldBalance); uint newBalance = availableBalanceOf(_id, dayCount); balances[adr] = newBalance; totalSupply = safeAdd(totalSupply, newBalance); contributors[_id].lastUpdatedOn = dayCount; Transfer(0, adr, newBalance - oldBalance); return true; } } return false; } /** * Standard ERC20 function overridden. * Returns the balance of the specified address. * Calculates the balance on fly only if it is a minting address else * simply returns balance from balances[] mapping. * For public calls. * @param _adr address whose balance is to be returned. */ function balanceOf(address _adr) constant returns (uint balance) { uint id = idOf[_adr]; if (id != 0) return balanceById(id); else return balances[_adr]; } /** * Standard ERC20 function overridden. * Returns the balance of the specified id. * Calculates the balance on fly only if it is a minting address else * simply returns balance from balances[] mapping. * For public calls. * @param _id address whose balance is to be returned. */ function balanceById(uint _id) public constant returns (uint256 balance) { address adr = contributors[_id].adr; if (isDayTokenActivated()) { if (isValidContributorId(_id)) { return ( availableBalanceOf(_id, getDayCount()) ); } } return balances[adr]; } /** * Returns totalSupply of DAY tokens. */ function getTotalSupply() public constant returns (uint) { return totalSupply; } /** Function to update balance of a Timemint * returns true if balance updated, false otherwise * @param _id TimeMint to update */ function updateTimeMintBalance(uint _id) public returns (bool) { require(isDayTokenActivated()); return updateBalanceOf(_id); } /** Function to update balance of sender's Timemint * returns true if balance updated, false otherwise */ function updateMyTimeMintBalance() public returns (bool) { require(isDayTokenActivated()); return updateBalanceOf(idOf[msg.sender]); } /** * Standard ERC20 function overidden. * Used to transfer day tokens from caller's address to another * @param _to address to which Day tokens are to be transferred * @param _value Number of Day tokens to be transferred */ function transfer(address _to, uint _value) public returns (bool success) { require(isDayTokenActivated()); // if Team address, check if lock-in period is over require(isTeamLockInPeriodOverIfTeamAddress(msg.sender)); updateBalanceOf(idOf[msg.sender]); // Check sender account has enough balance and transfer amount is non zero require ( balanceOf(msg.sender) >= _value && _value != 0 ); updateBalanceOf(idOf[_to]); balances[msg.sender] = safeSub(balances[msg.sender], _value); balances[_to] = safeAdd(balances[_to], _value); Transfer(msg.sender, _to, _value); return true; } /** * Standard ERC20 Standard Token function overridden. Added Team address vesting period lock. */ function transferFrom(address _from, address _to, uint _value) public returns (bool success) { require(isDayTokenActivated()); // if Team address, check if lock-in period is over require(isTeamLockInPeriodOverIfTeamAddress(_from)); uint _allowance = allowed[_from][msg.sender]; updateBalanceOf(idOf[_from]); // Check from account has enough balance, transfer amount is non zero // and _value is allowed to be transferred require ( balanceOf(_from) >= _value && _value != 0 && _value <= _allowance); updateBalanceOf(idOf[_to]); allowed[_from][msg.sender] = safeSub(_allowance, _value); balances[_from] = safeSub(balances[_from], _value); balances[_to] = safeAdd(balances[_to], _value); Transfer(_from, _to, _value); return true; } /** * Add any contributor structure (For every kind of contributors: Team/Pre-ICO/ICO/Test) * @param _adr Address of the contributor to be added * @param _initialContributionDay Initial Contribution of the contributor to be added */ function addContributor(uint contributorId, address _adr, uint _initialContributionDay) internal onlyOwner { require(contributorId <= maxAddresses); //address should not be an existing contributor require(!isValidContributorAddress(_adr)); //TimeMint should not be already allocated require(!isValidContributorId(contributorId)); contributors[contributorId].adr = _adr; idOf[_adr] = contributorId; setInitialMintingPowerOf(contributorId); contributors[contributorId].initialContributionDay = _initialContributionDay; contributors[contributorId].lastUpdatedOn = getDayCount(); ContributorAdded(_adr, contributorId); contributors[contributorId].status = sellingStatus.NOTONSALE; } /** Function to be called by minting addresses in order to sell their address * @param _minPriceInDay Minimum price in DAY tokens set by the seller * @param _expiryBlockNumber Expiry Block Number set by the seller */ function sellMintingAddress(uint256 _minPriceInDay, uint _expiryBlockNumber) public returns (bool) { require(isDayTokenActivated()); require(_expiryBlockNumber > block.number); // if Team address, check if lock-in period is over require(isTeamLockInPeriodOverIfTeamAddress(msg.sender)); uint id = idOf[msg.sender]; require(contributors[id].status == sellingStatus.NOTONSALE); // update balance of sender address before checking for minimum required balance updateBalanceOf(id); require(balances[msg.sender] >= minBalanceToSell); contributors[id].minPriceInDay = _minPriceInDay; contributors[id].expiryBlockNumber = _expiryBlockNumber; contributors[id].status = sellingStatus.ONSALE; balances[msg.sender] = safeSub(balances[msg.sender], minBalanceToSell); balances[this] = safeAdd(balances[this], minBalanceToSell); Transfer(msg.sender, this, minBalanceToSell); TimeMintOnSale(id, msg.sender, contributors[id].minPriceInDay, contributors[id].expiryBlockNumber); return true; } /** Function to be called by minting address in order to cancel the sale of their TimeMint */ function cancelSaleOfMintingAddress() onlyContributor(idOf[msg.sender]) public { uint id = idOf[msg.sender]; // TimeMint should be on sale require(contributors[id].status == sellingStatus.ONSALE); contributors[id].status = sellingStatus.EXPIRED; } /** Function to be called by any user to get a list of all On Sale TimeMints */ function getOnSaleIds() constant public returns(uint[]) { uint[] memory idsOnSale = new uint[](maxAddresses); uint j = 0; for(uint i=1; i <= maxAddresses; i++) { if ( isValidContributorId(i) && block.number <= contributors[i].expiryBlockNumber && contributors[i].status == sellingStatus.ONSALE ) { idsOnSale[j] = i; j++; } } return idsOnSale; } /** Function to be called by any user to get status of a Time Mint. * returns status 0 - Not on sale, 1 - Expired, 2 - On sale, * @param _id ID number of the Time Mint */ function getSellingStatus(uint _id) constant public returns(sellingStatus status) { require(isValidContributorId(_id)); status = contributors[_id].status; if ( block.number > contributors[_id].expiryBlockNumber && status == sellingStatus.ONSALE ) status = sellingStatus.EXPIRED; return status; } /** Function to be called by any user to buy a onsale address by offering an amount * @param _offerId ID number of the address to be bought by the buyer * @param _offerInDay Offer given by the buyer in number of DAY tokens */ function buyMintingAddress(uint _offerId, uint256 _offerInDay) public returns(bool) { if (contributors[_offerId].status == sellingStatus.ONSALE && block.number > contributors[_offerId].expiryBlockNumber) { contributors[_offerId].status = sellingStatus.EXPIRED; } address soldAddress = contributors[_offerId].adr; require(contributors[_offerId].status == sellingStatus.ONSALE); require(_offerInDay >= contributors[_offerId].minPriceInDay); // prevent seller from cancelling sale in between contributors[_offerId].status = sellingStatus.NOTONSALE; // first get the offered DayToken in the token contract & // then transfer the total sum (minBalanceToSend+_offerInDay) to the seller balances[msg.sender] = safeSub(balances[msg.sender], _offerInDay); balances[this] = safeAdd(balances[this], _offerInDay); Transfer(msg.sender, this, _offerInDay); if(transferMintingAddress(contributors[_offerId].adr, msg.sender)) { //mark the offer as sold & let seller pull the proceed to their own account. sellingPriceInDayOf[soldAddress] = _offerInDay; soldAddresses[soldAddress] = true; TimeMintSold(_offerId, msg.sender, _offerInDay); } return true; } /** * Transfer minting address from one user to another * Gives the transfer-to address, the id of the original address * returns true if successful and false if not. * @param _to address of the user to which minting address is to be tranferred */ function transferMintingAddress(address _from, address _to) internal onlyContributor(idOf[_from]) returns (bool) { require(isDayTokenActivated()); // _to should be non minting address require(!isValidContributorAddress(_to)); uint id = idOf[_from]; // update balance of from address before transferring minting power updateBalanceOf(id); contributors[id].adr = _to; idOf[_to] = id; idOf[_from] = 0; contributors[id].initialContributionDay = 0; // needed as id is assigned to new address contributors[id].lastUpdatedOn = getDayCount(); contributors[id].expiryBlockNumber = 0; contributors[id].minPriceInDay = 0; MintingAdrTransferred(id, _from, _to); return true; } /** Function to allow seller to get back their deposited amount of day tokens(minBalanceToSell) and * offer made by buyer after successful sale. * Throws if sale is not successful */ function fetchSuccessfulSaleProceed() public returns(bool) { require(soldAddresses[msg.sender] == true); // to prevent re-entrancy attack soldAddresses[msg.sender] = false; uint saleProceed = safeAdd(minBalanceToSell, sellingPriceInDayOf[msg.sender]); balances[this] = safeSub(balances[this], saleProceed); balances[msg.sender] = safeAdd(balances[msg.sender], saleProceed); Transfer(this, msg.sender, saleProceed); return true; } /** Function that lets a seller get their deposited day tokens (minBalanceToSell) back, if no buyer turns up. * Allowed only after expiryBlockNumber * Throws if any other state other than EXPIRED */ function refundFailedAuctionAmount() onlyContributor(idOf[msg.sender]) public returns(bool){ uint id = idOf[msg.sender]; if(block.number > contributors[id].expiryBlockNumber && contributors[id].status == sellingStatus.ONSALE) { contributors[id].status = sellingStatus.EXPIRED; } require(contributors[id].status == sellingStatus.EXPIRED); // reset selling status contributors[id].status = sellingStatus.NOTONSALE; balances[this] = safeSub(balances[this], minBalanceToSell); // update balance of seller address before refunding updateBalanceOf(id); balances[msg.sender] = safeAdd(balances[msg.sender], minBalanceToSell); contributors[id].minPriceInDay = 0; contributors[id].expiryBlockNumber = 0; Transfer(this, msg.sender, minBalanceToSell); return true; } /** Function to add a team address as a contributor and store it's time issued to calculate vesting period * Called by owner */ function addTeamTimeMints(address _adr, uint _id, uint _tokens, bool _isTest) public onlyOwner { //check if Id is in range of team Ids require(_id >= firstTeamContributorId && _id < firstTeamContributorId + totalTeamContributorIds); require(totalTeamContributorIdsAllocated < totalTeamContributorIds); addContributor(_id, _adr, 0); totalTeamContributorIdsAllocated++; // enforce lockin period if not test address if(!_isTest) teamIssuedTimestamp[_adr] = block.timestamp; mint(_adr, _tokens); TeamAddressAdded(_adr, _id); } /** Function to add reserved aution TimeMints post-ICO. Only by owner * @param _receiver Address of the minting to be added * @param _customerId Server side id of the customer * @param _id contributorId */ function postAllocateAuctionTimeMints(address _receiver, uint _customerId, uint _id) public onlyOwner { //check if Id is in range of Auction Ids require(_id >= firstPostIcoContributorId && _id < firstPostIcoContributorId + totalPostIcoContributorIds); require(totalPostIcoContributorIdsAllocated < totalPostIcoContributorIds); require(released == true); addContributor(_id, _receiver, 0); totalPostIcoContributorIdsAllocated++; PostInvested(_receiver, 0, 0, _customerId, _id); } /** Function to add all contributors except team, test and Auctions TimeMints. Only by owner * @param _receiver Address of the minting to be added * @param _customerId Server side id of the customer * @param _id contributor id * @param _tokens day tokens to allocate * @param _weiAmount ether invested in wei */ function allocateNormalTimeMints(address _receiver, uint _customerId, uint _id, uint _tokens, uint _weiAmount) public onlyOwner { // check if Id is in range of Normal Ids require(_id >= firstContributorId && _id <= totalNormalContributorIds); require(totalNormalContributorIdsAllocated < totalNormalContributorIds); addContributor(_id, _receiver, _tokens); totalNormalContributorIdsAllocated++; mint(_receiver, _tokens); Invested(_receiver, _weiAmount, _tokens, _customerId, _id); } /** Function to release token * Called by owner */ function releaseToken(uint _initialBlockTimestamp) public onlyOwner { require(!released); // check not already released setInitialBlockTimestamp(_initialBlockTimestamp); // Make token transferable releaseTokenTransfer(); } }
Stores total Post ICO TimeMints (for auction) */
uint256 public totalPostIcoContributorIds;
1,800,510
[ 1, 13125, 2078, 5616, 467, 3865, 2647, 49, 28142, 261, 1884, 279, 4062, 13, 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 ]
[ 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, 2254, 5034, 1071, 2078, 3349, 45, 2894, 442, 19293, 2673, 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 ]
./full_match/3/0xc85c82020e83F3A45E8Ae0AfFE502A5437d32895/sources/tt.sol
Return remainder if exist
function universalTransferFromSenderToThis(IERC20 token, uint256 amount) internal { if (amount == 0) { return; } if (isBCH(token)) { if (msg.value > amount) { msg.sender.transfer(msg.value.sub(amount)); } token.safeTransferFrom(msg.sender, address(this), amount); } }
8,248,820
[ 1, 990, 10022, 309, 1005, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 26182, 5912, 1265, 12021, 774, 2503, 12, 45, 654, 39, 3462, 1147, 16, 2254, 5034, 3844, 13, 2713, 288, 203, 3639, 309, 261, 8949, 422, 374, 13, 288, 203, 5411, 327, 31, 203, 3639, 289, 203, 203, 3639, 309, 261, 291, 38, 1792, 12, 2316, 3719, 288, 203, 5411, 309, 261, 3576, 18, 1132, 405, 3844, 13, 288, 203, 7734, 1234, 18, 15330, 18, 13866, 12, 3576, 18, 1132, 18, 1717, 12, 8949, 10019, 203, 5411, 289, 203, 5411, 1147, 18, 4626, 5912, 1265, 12, 3576, 18, 15330, 16, 1758, 12, 2211, 3631, 3844, 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 ]
/** *Submitted for verification at Etherscan.io on 2021-06-03 */ // SPDX-License-Identifier: MIT // Sources flattened with hardhat v2.0.5 https://hardhat.org // File @openzeppelin/contracts-upgradeable/token/ERC20/[email protected] pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval( address indexed owner, address indexed spender, uint256 value ); } // File @openzeppelin/contracts-upgradeable/math/[email protected] pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMathUpgradeable { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File @openzeppelin/contracts-upgradeable/utils/[email protected] pragma solidity >=0.6.2 <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; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require( address(this).balance >= amount, "Address: insufficient balance" ); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require( success, "Address: unable to send value, recipient may have reverted" ); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue( target, data, value, "Address: low-level call with value failed" ); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require( address(this).balance >= value, "Address: insufficient balance for call" ); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall( target, data, "Address: low-level static call failed" ); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) private pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File @openzeppelin/contracts-upgradeable/token/ERC20/[email protected] pragma solidity >=0.6.0 <0.8.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20Upgradeable { using SafeMathUpgradeable for uint256; using AddressUpgradeable for address; function safeTransfer( IERC20Upgradeable token, address to, uint256 value ) internal { _callOptionalReturn( token, abi.encodeWithSelector(token.transfer.selector, to, value) ); } function safeTransferFrom( IERC20Upgradeable 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( IERC20Upgradeable 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( IERC20Upgradeable 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( IERC20Upgradeable 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(IERC20Upgradeable token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall( data, "SafeERC20: low-level call failed" ); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require( abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed" ); } } } // File contracts/interface/IInterestRateModelInterface.sol pragma solidity 0.6.12; /** * @title dForce Lending Protocol's InterestRateModel Interface. * @author dForce Team. */ interface IInterestRateModelInterface { function isInterestRateModel() external view returns (bool); /** * @dev Calculates the current borrow interest rate per block. * @param cash The total amount of cash the market has. * @param borrows The total amount of borrows the market has. * @param reserves The total amnount of reserves the market has. * @return The borrow rate per block (as a percentage, and scaled by 1e18). */ function getBorrowRate( uint256 cash, uint256 borrows, uint256 reserves ) external view returns (uint256); /** * @dev Calculates the current supply interest rate per block. * @param cash The total amount of cash the market has. * @param borrows The total amount of borrows the market has. * @param reserves The total amnount of reserves the market has. * @param reserveRatio The current reserve factor the market has. * @return The supply rate per block (as a percentage, and scaled by 1e18). */ function getSupplyRate( uint256 cash, uint256 borrows, uint256 reserves, uint256 reserveRatio ) external view returns (uint256); } // File contracts/interface/IControllerInterface.sol pragma solidity 0.6.12; interface IControllerAdminInterface { /// @notice Emitted when an admin supports a market event MarketAdded( address iToken, uint256 collateralFactor, uint256 borrowFactor, uint256 supplyCapacity, uint256 borrowCapacity, uint256 distributionFactor ); function _addMarket( address _iToken, uint256 _collateralFactor, uint256 _borrowFactor, uint256 _supplyCapacity, uint256 _borrowCapacity, uint256 _distributionFactor ) external; /// @notice Emitted when new price oracle is set event NewPriceOracle(address oldPriceOracle, address newPriceOracle); function _setPriceOracle(address newOracle) external; /// @notice Emitted when close factor is changed by admin event NewCloseFactor( uint256 oldCloseFactorMantissa, uint256 newCloseFactorMantissa ); function _setCloseFactor(uint256 newCloseFactorMantissa) external; /// @notice Emitted when liquidation incentive is changed by admin event NewLiquidationIncentive( uint256 oldLiquidationIncentiveMantissa, uint256 newLiquidationIncentiveMantissa ); function _setLiquidationIncentive(uint256 newLiquidationIncentiveMantissa) external; /// @notice Emitted when iToken's collateral factor is changed by admin event NewCollateralFactor( address iToken, uint256 oldCollateralFactorMantissa, uint256 newCollateralFactorMantissa ); function _setCollateralFactor( address iToken, uint256 newCollateralFactorMantissa ) external; /// @notice Emitted when iToken's borrow factor is changed by admin event NewBorrowFactor( address iToken, uint256 oldBorrowFactorMantissa, uint256 newBorrowFactorMantissa ); function _setBorrowFactor(address iToken, uint256 newBorrowFactorMantissa) external; /// @notice Emitted when iToken's borrow capacity is changed by admin event NewBorrowCapacity( address iToken, uint256 oldBorrowCapacity, uint256 newBorrowCapacity ); function _setBorrowCapacity(address iToken, uint256 newBorrowCapacity) external; /// @notice Emitted when iToken's supply capacity is changed by admin event NewSupplyCapacity( address iToken, uint256 oldSupplyCapacity, uint256 newSupplyCapacity ); function _setSupplyCapacity(address iToken, uint256 newSupplyCapacity) external; /// @notice Emitted when pause guardian is changed by admin event NewPauseGuardian(address oldPauseGuardian, address newPauseGuardian); function _setPauseGuardian(address newPauseGuardian) external; /// @notice Emitted when mint is paused/unpaused by admin or pause guardian event MintPaused(address iToken, bool paused); function _setMintPaused(address iToken, bool paused) external; function _setAllMintPaused(bool paused) external; /// @notice Emitted when redeem is paused/unpaused by admin or pause guardian event RedeemPaused(address iToken, bool paused); function _setRedeemPaused(address iToken, bool paused) external; function _setAllRedeemPaused(bool paused) external; /// @notice Emitted when borrow is paused/unpaused by admin or pause guardian event BorrowPaused(address iToken, bool paused); function _setBorrowPaused(address iToken, bool paused) external; function _setAllBorrowPaused(bool paused) external; /// @notice Emitted when transfer is paused/unpaused by admin or pause guardian event TransferPaused(bool paused); function _setTransferPaused(bool paused) external; /// @notice Emitted when seize is paused/unpaused by admin or pause guardian event SeizePaused(bool paused); function _setSeizePaused(bool paused) external; function _setiTokenPaused(address iToken, bool paused) external; function _setProtocolPaused(bool paused) external; event NewRewardDistributor( address oldRewardDistributor, address _newRewardDistributor ); function _setRewardDistributor(address _newRewardDistributor) external; } interface IControllerPolicyInterface { function beforeMint( address iToken, address account, uint256 mintAmount ) external; function afterMint( address iToken, address minter, uint256 mintAmount, uint256 mintedAmount ) external; function beforeRedeem( address iToken, address redeemer, uint256 redeemAmount ) external; function afterRedeem( address iToken, address redeemer, uint256 redeemAmount, uint256 redeemedAmount ) external; function beforeBorrow( address iToken, address borrower, uint256 borrowAmount ) external; function afterBorrow( address iToken, address borrower, uint256 borrowedAmount ) external; function beforeRepayBorrow( address iToken, address payer, address borrower, uint256 repayAmount ) external; function afterRepayBorrow( address iToken, address payer, address borrower, uint256 repayAmount ) external; function beforeLiquidateBorrow( address iTokenBorrowed, address iTokenCollateral, address liquidator, address borrower, uint256 repayAmount ) external; function afterLiquidateBorrow( address iTokenBorrowed, address iTokenCollateral, address liquidator, address borrower, uint256 repaidAmount, uint256 seizedAmount ) external; function beforeSeize( address iTokenBorrowed, address iTokenCollateral, address liquidator, address borrower, uint256 seizeAmount ) external; function afterSeize( address iTokenBorrowed, address iTokenCollateral, address liquidator, address borrower, uint256 seizedAmount ) external; function beforeTransfer( address iToken, address from, address to, uint256 amount ) external; function afterTransfer( address iToken, address from, address to, uint256 amount ) external; function beforeFlashloan( address iToken, address to, uint256 amount ) external; function afterFlashloan( address iToken, address to, uint256 amount ) external; } interface IControllerAccountEquityInterface { function calcAccountEquity(address account) external view returns ( uint256, uint256, uint256, uint256 ); function liquidateCalculateSeizeTokens( address iTokenBorrowed, address iTokenCollateral, uint256 actualRepayAmount ) external view returns (uint256); } interface IControllerAccountInterface { function hasEnteredMarket(address account, address iToken) external view returns (bool); function getEnteredMarkets(address account) external view returns (address[] memory); /// @notice Emitted when an account enters a market event MarketEntered(address iToken, address account); function enterMarkets(address[] calldata iTokens) external returns (bool[] memory); /// @notice Emitted when an account exits a market event MarketExited(address iToken, address account); function exitMarkets(address[] calldata iTokens) external returns (bool[] memory); /// @notice Emitted when an account add a borrow asset event BorrowedAdded(address iToken, address account); /// @notice Emitted when an account remove a borrow asset event BorrowedRemoved(address iToken, address account); function hasBorrowed(address account, address iToken) external view returns (bool); function getBorrowedAssets(address account) external view returns (address[] memory); } interface IControllerInterface is IControllerAdminInterface, IControllerPolicyInterface, IControllerAccountEquityInterface, IControllerAccountInterface { /** * @notice Security checks when updating the comptroller of a market, always expect to return true. */ function isController() external view returns (bool); /** * @notice Return all of the iTokens * @return The list of iToken addresses */ function getAlliTokens() external view returns (address[] memory); /** * @notice Check whether a iToken is listed in controller * @param _iToken The iToken to check for * @return true if the iToken is listed otherwise false */ function hasiToken(address _iToken) external view returns (bool); } // File contracts/interface/IiToken.sol pragma solidity 0.6.12; interface IiToken { function isSupported() external returns (bool); function isiToken() external returns (bool); //---------------------------------- //********* User Interface ********* //---------------------------------- function mint(address recipient, uint256 mintAmount) external; function redeem(address from, uint256 redeemTokens) external; function redeemUnderlying(address from, uint256 redeemAmount) external; function borrow(uint256 borrowAmount) external; function repayBorrow(uint256 repayAmount) external; function repayBorrowBehalf(address borrower, uint256 repayAmount) external; function liquidateBorrow( address borrower, uint256 repayAmount, address iTokenCollateral ) external; function flashloan( address recipient, uint256 loanAmount, bytes memory data ) external; function seize( address _liquidator, address _borrower, uint256 _seizeTokens ) external; function updateInterest() external returns (bool); function controller() external view returns (address); function exchangeRateCurrent() external returns (uint256); function exchangeRateStored() external view returns (uint256); function totalBorrowsCurrent() external returns (uint256); function totalBorrows() external view returns (uint256); function borrowBalanceCurrent(address _user) external returns (uint256); function borrowBalanceStored(address _user) external view returns (uint256); function borrowIndex() external view returns (uint256); function getAccountSnapshot(address _account) external view returns ( uint256, uint256, uint256 ); function borrowRatePerBlock() external view returns (uint256); function supplyRatePerBlock() external view returns (uint256); function getCash() external view returns (uint256); //---------------------------------- //********* Owner Actions ********** //---------------------------------- function _setNewReserveRatio(uint256 _newReserveRatio) external; function _setNewFlashloanFeeRatio(uint256 _newFlashloanFeeRatio) external; function _setNewProtocolFeeRatio(uint256 _newProtocolFeeRatio) external; function _setController(IControllerInterface _newController) external; function _setInterestRateModel( IInterestRateModelInterface _newInterestRateModel ) external; function _withdrawReserves(uint256 _withdrawAmount) external; } // File contracts/interface/IRewardDistributorV3.sol pragma solidity 0.6.12; interface IRewardDistributorV3 { function _setRewardToken(address newRewardToken) external; /// @notice Emitted reward token address is changed by admin event NewRewardToken(address oldRewardToken, address newRewardToken); function _addRecipient(address _iToken, uint256 _distributionFactor) external; event NewRecipient(address iToken, uint256 distributionFactor); /// @notice Emitted when mint is paused/unpaused by admin event Paused(bool paused); function _pause() external; function _unpause( address[] calldata _borrowiTokens, uint256[] calldata _borrowSpeeds, address[] calldata _supplyiTokens, uint256[] calldata _supplySpeeds ) external; /// @notice Emitted when Global Distribution speed for both supply and borrow are updated event GlobalDistributionSpeedsUpdated( uint256 borrowSpeed, uint256 supplySpeed ); /// @notice Emitted when iToken's Distribution borrow speed is updated event DistributionBorrowSpeedUpdated(address iToken, uint256 borrowSpeed); /// @notice Emitted when iToken's Distribution supply speed is updated event DistributionSupplySpeedUpdated(address iToken, uint256 supplySpeed); /// @notice Emitted when iToken's Distribution factor is changed by admin event NewDistributionFactor( address iToken, uint256 oldDistributionFactorMantissa, uint256 newDistributionFactorMantissa ); function updateDistributionState(address _iToken, bool _isBorrow) external; function updateReward( address _iToken, address _account, bool _isBorrow ) external; function updateRewardBatch( address[] memory _holders, address[] memory _iTokens ) external; function claimReward(address[] memory _holders, address[] memory _iTokens) external; function claimAllReward(address[] memory _holders) external; /// @notice Emitted when reward of amount is distributed into account event RewardDistributed( address iToken, address account, uint256 amount, uint256 accountIndex ); } // File contracts/interface/IPriceOracle.sol pragma solidity 0.6.12; interface IPriceOracle { /** * @notice Get the underlying price of a iToken asset * @param _iToken The iToken to get the underlying price of * @return The underlying asset price mantissa (scaled by 1e18). * Zero means the price is unavailable. */ function getUnderlyingPrice(address _iToken) external view returns (uint256); /** * @notice Get the price of a underlying asset * @param _iToken The iToken to get the underlying price of * @return The underlying asset price mantissa (scaled by 1e18). * Zero means the price is unavailable and whether the price is valid. */ function getUnderlyingPriceAndStatus(address _iToken) external view returns (uint256, bool); } // File contracts/library/Initializable.sol pragma solidity 0.6.12; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require( !_initialized, "Initializable: contract is already initialized" ); _; _initialized = true; } } // File contracts/library/Ownable.sol pragma solidity 0.6.12; /** * @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 {_setPendingOwner} and {_acceptOwner}. */ contract Ownable { /** * @dev Returns the address of the current owner. */ address payable public owner; /** * @dev Returns the address of the current pending owner. */ address payable public pendingOwner; event NewOwner(address indexed previousOwner, address indexed newOwner); event NewPendingOwner( address indexed oldPendingOwner, address indexed newPendingOwner ); /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner == msg.sender, "onlyOwner: caller is not the owner"); _; } /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal { owner = msg.sender; emit NewOwner(address(0), msg.sender); } /** * @notice Base on the inputing parameter `newPendingOwner` to check the exact error reason. * @dev Transfer contract control to a new owner. The newPendingOwner must call `_acceptOwner` to finish the transfer. * @param newPendingOwner New pending owner. */ function _setPendingOwner(address payable newPendingOwner) external onlyOwner { require( newPendingOwner != address(0) && newPendingOwner != pendingOwner, "_setPendingOwner: New owenr can not be zero address and owner has been set!" ); // Gets current owner. address oldPendingOwner = pendingOwner; // Sets new pending owner. pendingOwner = newPendingOwner; emit NewPendingOwner(oldPendingOwner, newPendingOwner); } /** * @dev Accepts the admin rights, but only for pendingOwenr. */ function _acceptOwner() external { require( msg.sender == pendingOwner, "_acceptOwner: Only for pending owner!" ); // Gets current values for events. address oldOwner = owner; address oldPendingOwner = pendingOwner; // Set the new contract owner. owner = pendingOwner; // Clear the pendingOwner. pendingOwner = address(0); emit NewOwner(oldOwner, owner); emit NewPendingOwner(oldPendingOwner, pendingOwner); } uint256[50] private __gap; } // File contracts/library/SafeRatioMath.sol pragma solidity 0.6.12; library SafeRatioMath { using SafeMathUpgradeable for uint256; uint256 private constant BASE = 10**18; uint256 private constant DOUBLE = 10**36; function divup(uint256 x, uint256 y) internal pure returns (uint256 z) { z = x.add(y.sub(1)).div(y); } function rmul(uint256 x, uint256 y) internal pure returns (uint256 z) { z = x.mul(y).div(BASE); } function rdiv(uint256 x, uint256 y) internal pure returns (uint256 z) { z = x.mul(BASE).div(y); } function rdivup(uint256 x, uint256 y) internal pure returns (uint256 z) { z = x.mul(BASE).add(y.sub(1)).div(y); } function tmul( uint256 x, uint256 y, uint256 z ) internal pure returns (uint256 result) { result = x.mul(y).mul(z).div(DOUBLE); } function rpow( uint256 x, uint256 n, uint256 base ) internal pure returns (uint256 z) { assembly { switch x case 0 { switch n case 0 { z := base } default { z := 0 } } default { switch mod(n, 2) case 0 { z := base } default { z := x } let half := div(base, 2) // for rounding. for { n := div(n, 2) } n { n := div(n, 2) } { let xx := mul(x, x) if iszero(eq(div(xx, x), x)) { revert(0, 0) } let xxRound := add(xx, half) if lt(xxRound, xx) { revert(0, 0) } x := div(xxRound, base) if mod(n, 2) { let zx := mul(z, x) if and( iszero(iszero(x)), iszero(eq(div(zx, x), z)) ) { revert(0, 0) } let zxRound := add(zx, half) if lt(zxRound, zx) { revert(0, 0) } z := div(zxRound, base) } } } } } } // File @openzeppelin/contracts-upgradeable/utils/[email protected] pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSetUpgradeable { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping(bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require( set._values.length > index, "EnumerableSet: index out of bounds" ); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // File contracts/interface/IRewardDistributor.sol pragma solidity 0.6.12; interface IRewardDistributor { function _setRewardToken(address newRewardToken) external; /// @notice Emitted reward token address is changed by admin event NewRewardToken(address oldRewardToken, address newRewardToken); function _addRecipient(address _iToken, uint256 _distributionFactor) external; event NewRecipient(address iToken, uint256 distributionFactor); /// @notice Emitted when mint is paused/unpaused by admin event Paused(bool paused); function _pause() external; function _unpause(uint256 _borrowSpeed, uint256 _supplySpeed) external; /// @notice Emitted when Global Distribution speed for both supply and borrow are updated event GlobalDistributionSpeedsUpdated( uint256 borrowSpeed, uint256 supplySpeed ); function _setGlobalDistributionSpeeds( uint256 borrowSpeed, uint256 supplySpeed ) external; /// @notice Emitted when iToken's Distribution speed is updated event DistributionSpeedsUpdated( address iToken, uint256 borrowSpeed, uint256 supplySpeed ); function updateDistributionSpeed() external; /// @notice Emitted when iToken's Distribution factor is changed by admin event NewDistributionFactor( address iToken, uint256 oldDistributionFactorMantissa, uint256 newDistributionFactorMantissa ); function _setDistributionFactors( address[] calldata iToken, uint256[] calldata distributionFactors ) external; function updateDistributionState(address _iToken, bool _isBorrow) external; function updateReward( address _iToken, address _account, bool _isBorrow ) external; function updateRewardBatch( address[] memory _holders, address[] memory _iTokens ) external; function claimReward(address[] memory _holders, address[] memory _iTokens) external; function claimAllReward(address[] memory _holders) external; /// @notice Emitted when reward of amount is distributed into account event RewardDistributed( address iToken, address account, uint256 amount, uint256 accountIndex ); } // File contracts/Controller.sol pragma solidity 0.6.12; /** * @title dForce's lending controller Contract * @author dForce */ contract Controller is Initializable, Ownable, IControllerInterface { using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet; using SafeRatioMath for uint256; using SafeMathUpgradeable for uint256; using SafeERC20Upgradeable for IERC20Upgradeable; /// @dev EnumerableSet of all iTokens EnumerableSetUpgradeable.AddressSet internal iTokens; struct Market { /* * Multiplier representing the most one can borrow against their collateral in this market. * For instance, 0.9 to allow borrowing 90% of collateral value. * Must be in [0, 0.9], and stored as a mantissa. */ uint256 collateralFactorMantissa; /* * Multiplier representing the most one can borrow the asset. * For instance, 0.5 to allow borrowing this asset 50% * collateral value * collateralFactor. * When calculating equity, 0.5 with 100 borrow balance will produce 200 borrow value * Must be between (0, 1], and stored as a mantissa. */ uint256 borrowFactorMantissa; /* * The borrow capacity of the asset, will be checked in beforeBorrow() * -1 means there is no limit on the capacity * 0 means the asset can not be borrowed any more */ uint256 borrowCapacity; /* * The supply capacity of the asset, will be checked in beforeMint() * -1 means there is no limit on the capacity * 0 means the asset can not be supplied any more */ uint256 supplyCapacity; // Whether market's mint is paused bool mintPaused; // Whether market's redeem is paused bool redeemPaused; // Whether market's borrow is paused bool borrowPaused; } /// @notice Mapping of iTokens to corresponding markets mapping(address => Market) public markets; struct AccountData { // Account's collateral assets EnumerableSetUpgradeable.AddressSet collaterals; // Account's borrowed assets EnumerableSetUpgradeable.AddressSet borrowed; } /// @dev Mapping of accounts' data, including collateral and borrowed assets mapping(address => AccountData) internal accountsData; /** * @notice Oracle to query the price of a given asset */ address public priceOracle; /** * @notice Multiplier used to calculate the maximum repayAmount when liquidating a borrow */ uint256 public closeFactorMantissa; // closeFactorMantissa must be strictly greater than this value uint256 internal constant closeFactorMinMantissa = 0.05e18; // 0.05 // closeFactorMantissa must not exceed this value uint256 internal constant closeFactorMaxMantissa = 0.9e18; // 0.9 /** * @notice Multiplier representing the discount on collateral that a liquidator receives */ uint256 public liquidationIncentiveMantissa; // liquidationIncentiveMantissa must be no less than this value uint256 internal constant liquidationIncentiveMinMantissa = 1.0e18; // 1.0 // liquidationIncentiveMantissa must be no greater than this value uint256 internal constant liquidationIncentiveMaxMantissa = 1.5e18; // 1.5 // collateralFactorMantissa must not exceed this value uint256 internal constant collateralFactorMaxMantissa = 1e18; // 1.0 // borrowFactorMantissa must not exceed this value uint256 internal constant borrowFactorMaxMantissa = 1e18; // 1.0 /** * @notice Guardian who can pause mint/borrow/liquidate/transfer in case of emergency */ address public pauseGuardian; /// @notice whether global transfer is paused bool public transferPaused; /// @notice whether global seize is paused bool public seizePaused; /** * @notice the address of reward distributor */ address public rewardDistributor; /** * @dev Check if called by owner or pauseGuardian, and only owner can unpause */ modifier checkPauser(bool _paused) { require( msg.sender == owner || (msg.sender == pauseGuardian && _paused), "Only owner and guardian can pause and only owner can unpause" ); _; } /** * @notice Initializes the contract. */ function initialize() external initializer { __Ownable_init(); } /*********************************/ /******** Security Check *********/ /*********************************/ /** * @notice Ensure this is a Controller contract. */ function isController() external view override returns (bool) { return true; } /*********************************/ /******** Admin Operations *******/ /*********************************/ /** * @notice Admin function to add iToken into supported markets * Checks if the iToken already exsits * Will `revert()` if any check fails * @param _iToken The _iToken to add * @param _collateralFactor The _collateralFactor of _iToken * @param _borrowFactor The _borrowFactor of _iToken * @param _supplyCapacity The _supplyCapacity of _iToken * @param _distributionFactor The _distributionFactor of _iToken */ function _addMarket( address _iToken, uint256 _collateralFactor, uint256 _borrowFactor, uint256 _supplyCapacity, uint256 _borrowCapacity, uint256 _distributionFactor ) external override onlyOwner { require(IiToken(_iToken).isSupported(), "Token is not supported"); // Market must not have been listed, EnumerableSet.add() will return false if it exsits require(iTokens.add(_iToken), "Token has already been listed"); require( _collateralFactor <= collateralFactorMaxMantissa, "Collateral factor invalid" ); require( _borrowFactor > 0 && _borrowFactor <= borrowFactorMaxMantissa, "Borrow factor invalid" ); // Its value will be taken into account when calculate account equity // Check if the price is available for the calculation require( IPriceOracle(priceOracle).getUnderlyingPrice(_iToken) != 0, "Underlying price is unavailable" ); markets[_iToken] = Market({ collateralFactorMantissa: _collateralFactor, borrowFactorMantissa: _borrowFactor, borrowCapacity: _borrowCapacity, supplyCapacity: _supplyCapacity, mintPaused: false, redeemPaused: false, borrowPaused: false }); IRewardDistributor(rewardDistributor)._addRecipient( _iToken, _distributionFactor ); emit MarketAdded( _iToken, _collateralFactor, _borrowFactor, _supplyCapacity, _borrowCapacity, _distributionFactor ); } /** * @notice Sets price oracle * @dev Admin function to set price oracle * @param _newOracle New oracle contract */ function _setPriceOracle(address _newOracle) external override onlyOwner { address _oldOracle = priceOracle; require( _newOracle != address(0) && _newOracle != _oldOracle, "Oracle address invalid" ); priceOracle = _newOracle; emit NewPriceOracle(_oldOracle, _newOracle); } /** * @notice Sets the closeFactor used when liquidating borrows * @dev Admin function to set closeFactor * @param _newCloseFactorMantissa New close factor, scaled by 1e18 */ function _setCloseFactor(uint256 _newCloseFactorMantissa) external override onlyOwner { require( _newCloseFactorMantissa >= closeFactorMinMantissa && _newCloseFactorMantissa <= closeFactorMaxMantissa, "Close factor invalid" ); uint256 _oldCloseFactorMantissa = closeFactorMantissa; closeFactorMantissa = _newCloseFactorMantissa; emit NewCloseFactor(_oldCloseFactorMantissa, _newCloseFactorMantissa); } /** * @notice Sets liquidationIncentive * @dev Admin function to set liquidationIncentive * @param _newLiquidationIncentiveMantissa New liquidationIncentive scaled by 1e18 */ function _setLiquidationIncentive(uint256 _newLiquidationIncentiveMantissa) external override onlyOwner { require( _newLiquidationIncentiveMantissa >= liquidationIncentiveMinMantissa && _newLiquidationIncentiveMantissa <= liquidationIncentiveMaxMantissa, "Liquidation incentive invalid" ); uint256 _oldLiquidationIncentiveMantissa = liquidationIncentiveMantissa; liquidationIncentiveMantissa = _newLiquidationIncentiveMantissa; emit NewLiquidationIncentive( _oldLiquidationIncentiveMantissa, _newLiquidationIncentiveMantissa ); } /** * @notice Sets the collateralFactor for a iToken * @dev Admin function to set collateralFactor for a iToken * @param _iToken The token to set the factor on * @param _newCollateralFactorMantissa The new collateral factor, scaled by 1e18 */ function _setCollateralFactor( address _iToken, uint256 _newCollateralFactorMantissa ) external override onlyOwner { _checkiTokenListed(_iToken); require( _newCollateralFactorMantissa <= collateralFactorMaxMantissa, "Collateral factor invalid" ); // Its value will be taken into account when calculate account equity // Check if the price is available for the calculation require( IPriceOracle(priceOracle).getUnderlyingPrice(_iToken) != 0, "Failed to set collateral factor, underlying price is unavailable" ); Market storage _market = markets[_iToken]; uint256 _oldCollateralFactorMantissa = _market.collateralFactorMantissa; _market.collateralFactorMantissa = _newCollateralFactorMantissa; emit NewCollateralFactor( _iToken, _oldCollateralFactorMantissa, _newCollateralFactorMantissa ); } /** * @notice Sets the borrowFactor for a iToken * @dev Admin function to set borrowFactor for a iToken * @param _iToken The token to set the factor on * @param _newBorrowFactorMantissa The new borrow factor, scaled by 1e18 */ function _setBorrowFactor(address _iToken, uint256 _newBorrowFactorMantissa) external override onlyOwner { _checkiTokenListed(_iToken); require( _newBorrowFactorMantissa > 0 && _newBorrowFactorMantissa <= borrowFactorMaxMantissa, "Borrow factor invalid" ); // Its value will be taken into account when calculate account equity // Check if the price is available for the calculation require( IPriceOracle(priceOracle).getUnderlyingPrice(_iToken) != 0, "Failed to set borrow factor, underlying price is unavailable" ); Market storage _market = markets[_iToken]; uint256 _oldBorrowFactorMantissa = _market.borrowFactorMantissa; _market.borrowFactorMantissa = _newBorrowFactorMantissa; emit NewBorrowFactor( _iToken, _oldBorrowFactorMantissa, _newBorrowFactorMantissa ); } /** * @notice Sets the borrowCapacity for a iToken * @dev Admin function to set borrowCapacity for a iToken * @param _iToken The token to set the capacity on * @param _newBorrowCapacity The new borrow capacity */ function _setBorrowCapacity(address _iToken, uint256 _newBorrowCapacity) external override onlyOwner { _checkiTokenListed(_iToken); Market storage _market = markets[_iToken]; uint256 oldBorrowCapacity = _market.borrowCapacity; _market.borrowCapacity = _newBorrowCapacity; emit NewBorrowCapacity(_iToken, oldBorrowCapacity, _newBorrowCapacity); } /** * @notice Sets the supplyCapacity for a iToken * @dev Admin function to set supplyCapacity for a iToken * @param _iToken The token to set the capacity on * @param _newSupplyCapacity The new supply capacity */ function _setSupplyCapacity(address _iToken, uint256 _newSupplyCapacity) external override onlyOwner { _checkiTokenListed(_iToken); Market storage _market = markets[_iToken]; uint256 oldSupplyCapacity = _market.supplyCapacity; _market.supplyCapacity = _newSupplyCapacity; emit NewSupplyCapacity(_iToken, oldSupplyCapacity, _newSupplyCapacity); } /** * @notice Sets the pauseGuardian * @dev Admin function to set pauseGuardian * @param _newPauseGuardian The new pause guardian */ function _setPauseGuardian(address _newPauseGuardian) external override onlyOwner { address _oldPauseGuardian = pauseGuardian; require( _newPauseGuardian != address(0) && _newPauseGuardian != _oldPauseGuardian, "Pause guardian address invalid" ); pauseGuardian = _newPauseGuardian; emit NewPauseGuardian(_oldPauseGuardian, _newPauseGuardian); } /** * @notice pause/unpause mint() for all iTokens * @dev Admin function, only owner and pauseGuardian can call this * @param _paused whether to pause or unpause */ function _setAllMintPaused(bool _paused) external override checkPauser(_paused) { EnumerableSetUpgradeable.AddressSet storage _iTokens = iTokens; uint256 _len = _iTokens.length(); for (uint256 i = 0; i < _len; i++) { _setMintPausedInternal(_iTokens.at(i), _paused); } } /** * @notice pause/unpause mint() for the iToken * @dev Admin function, only owner and pauseGuardian can call this * @param _iToken The iToken to pause/unpause * @param _paused whether to pause or unpause */ function _setMintPaused(address _iToken, bool _paused) external override checkPauser(_paused) { _checkiTokenListed(_iToken); _setMintPausedInternal(_iToken, _paused); } function _setMintPausedInternal(address _iToken, bool _paused) internal { markets[_iToken].mintPaused = _paused; emit MintPaused(_iToken, _paused); } /** * @notice pause/unpause redeem() for all iTokens * @dev Admin function, only owner and pauseGuardian can call this * @param _paused whether to pause or unpause */ function _setAllRedeemPaused(bool _paused) external override checkPauser(_paused) { EnumerableSetUpgradeable.AddressSet storage _iTokens = iTokens; uint256 _len = _iTokens.length(); for (uint256 i = 0; i < _len; i++) { _setRedeemPausedInternal(_iTokens.at(i), _paused); } } /** * @notice pause/unpause redeem() for the iToken * @dev Admin function, only owner and pauseGuardian can call this * @param _iToken The iToken to pause/unpause * @param _paused whether to pause or unpause */ function _setRedeemPaused(address _iToken, bool _paused) external override checkPauser(_paused) { _checkiTokenListed(_iToken); _setRedeemPausedInternal(_iToken, _paused); } function _setRedeemPausedInternal(address _iToken, bool _paused) internal { markets[_iToken].redeemPaused = _paused; emit RedeemPaused(_iToken, _paused); } /** * @notice pause/unpause borrow() for all iTokens * @dev Admin function, only owner and pauseGuardian can call this * @param _paused whether to pause or unpause */ function _setAllBorrowPaused(bool _paused) external override checkPauser(_paused) { EnumerableSetUpgradeable.AddressSet storage _iTokens = iTokens; uint256 _len = _iTokens.length(); for (uint256 i = 0; i < _len; i++) { _setBorrowPausedInternal(_iTokens.at(i), _paused); } } /** * @notice pause/unpause borrow() for the iToken * @dev Admin function, only owner and pauseGuardian can call this * @param _iToken The iToken to pause/unpause * @param _paused whether to pause or unpause */ function _setBorrowPaused(address _iToken, bool _paused) external override checkPauser(_paused) { _checkiTokenListed(_iToken); _setBorrowPausedInternal(_iToken, _paused); } function _setBorrowPausedInternal(address _iToken, bool _paused) internal { markets[_iToken].borrowPaused = _paused; emit BorrowPaused(_iToken, _paused); } /** * @notice pause/unpause global transfer() * @dev Admin function, only owner and pauseGuardian can call this * @param _paused whether to pause or unpause */ function _setTransferPaused(bool _paused) external override checkPauser(_paused) { _setTransferPausedInternal(_paused); } function _setTransferPausedInternal(bool _paused) internal { transferPaused = _paused; emit TransferPaused(_paused); } /** * @notice pause/unpause global seize() * @dev Admin function, only owner and pauseGuardian can call this * @param _paused whether to pause or unpause */ function _setSeizePaused(bool _paused) external override checkPauser(_paused) { _setSeizePausedInternal(_paused); } function _setSeizePausedInternal(bool _paused) internal { seizePaused = _paused; emit SeizePaused(_paused); } /** * @notice pause/unpause all actions iToken, including mint/redeem/borrow * @dev Admin function, only owner and pauseGuardian can call this * @param _paused whether to pause or unpause */ function _setiTokenPaused(address _iToken, bool _paused) external override checkPauser(_paused) { _checkiTokenListed(_iToken); _setiTokenPausedInternal(_iToken, _paused); } function _setiTokenPausedInternal(address _iToken, bool _paused) internal { Market storage _market = markets[_iToken]; _market.mintPaused = _paused; emit MintPaused(_iToken, _paused); _market.redeemPaused = _paused; emit RedeemPaused(_iToken, _paused); _market.borrowPaused = _paused; emit BorrowPaused(_iToken, _paused); } /** * @notice pause/unpause entire protocol, including mint/redeem/borrow/seize/transfer * @dev Admin function, only owner and pauseGuardian can call this * @param _paused whether to pause or unpause */ function _setProtocolPaused(bool _paused) external override checkPauser(_paused) { EnumerableSetUpgradeable.AddressSet storage _iTokens = iTokens; uint256 _len = _iTokens.length(); for (uint256 i = 0; i < _len; i++) { address _iToken = _iTokens.at(i); _setiTokenPausedInternal(_iToken, _paused); } _setTransferPausedInternal(_paused); _setSeizePausedInternal(_paused); } /** * @notice Sets Reward Distributor * @dev Admin function to set reward distributor * @param _newRewardDistributor new reward distributor */ function _setRewardDistributor(address _newRewardDistributor) external override onlyOwner { address _oldRewardDistributor = rewardDistributor; require( _newRewardDistributor != address(0) && _newRewardDistributor != _oldRewardDistributor, "Reward Distributor address invalid" ); rewardDistributor = _newRewardDistributor; emit NewRewardDistributor(_oldRewardDistributor, _newRewardDistributor); } /*********************************/ /******** Poclicy Hooks **********/ /*********************************/ /** * @notice Hook function before iToken `mint()` * Checks if the account should be allowed to mint the given iToken * Will `revert()` if any check fails * @param _iToken The iToken to check the mint against * @param _minter The account which would get the minted tokens * @param _mintAmount The amount of underlying being minted to iToken */ function beforeMint( address _iToken, address _minter, uint256 _mintAmount ) external override { _checkiTokenListed(_iToken); Market storage _market = markets[_iToken]; require(!_market.mintPaused, "Token mint has been paused"); // Check the iToken's supply capacity, -1 means no limit uint256 _totalSupplyUnderlying = IERC20Upgradeable(_iToken).totalSupply().rmul( IiToken(_iToken).exchangeRateStored() ); require( _totalSupplyUnderlying.add(_mintAmount) <= _market.supplyCapacity, "Token supply capacity reached" ); // Update the Reward Distribution Supply state and distribute reward to suppplier IRewardDistributor(rewardDistributor).updateDistributionState( _iToken, false ); IRewardDistributor(rewardDistributor).updateReward( _iToken, _minter, false ); } /** * @notice Hook function after iToken `mint()` * Will `revert()` if any operation fails * @param _iToken The iToken being minted * @param _minter The account which would get the minted tokens * @param _mintAmount The amount of underlying being minted to iToken * @param _mintedAmount The amount of iToken being minted */ function afterMint( address _iToken, address _minter, uint256 _mintAmount, uint256 _mintedAmount ) external override { _iToken; _minter; _mintAmount; _mintedAmount; } /** * @notice Hook function before iToken `redeem()` * Checks if the account should be allowed to redeem the given iToken * Will `revert()` if any check fails * @param _iToken The iToken to check the redeem against * @param _redeemer The account which would redeem iToken * @param _redeemAmount The amount of iToken to redeem */ function beforeRedeem( address _iToken, address _redeemer, uint256 _redeemAmount ) external override { // _redeemAllowed below will check whether _iToken is listed require(!markets[_iToken].redeemPaused, "Token redeem has been paused"); _redeemAllowed(_iToken, _redeemer, _redeemAmount); // Update the Reward Distribution Supply state and distribute reward to suppplier IRewardDistributor(rewardDistributor).updateDistributionState( _iToken, false ); IRewardDistributor(rewardDistributor).updateReward( _iToken, _redeemer, false ); } /** * @notice Hook function after iToken `redeem()` * Will `revert()` if any operation fails * @param _iToken The iToken being redeemed * @param _redeemer The account which redeemed iToken * @param _redeemAmount The amount of iToken being redeemed * @param _redeemedUnderlying The amount of underlying being redeemed */ function afterRedeem( address _iToken, address _redeemer, uint256 _redeemAmount, uint256 _redeemedUnderlying ) external override { _iToken; _redeemer; _redeemAmount; _redeemedUnderlying; } /** * @notice Hook function before iToken `borrow()` * Checks if the account should be allowed to borrow the given iToken * Will `revert()` if any check fails * @param _iToken The iToken to check the borrow against * @param _borrower The account which would borrow iToken * @param _borrowAmount The amount of underlying to borrow */ function beforeBorrow( address _iToken, address _borrower, uint256 _borrowAmount ) external override { _checkiTokenListed(_iToken); Market storage _market = markets[_iToken]; require(!_market.borrowPaused, "Token borrow has been paused"); if (!hasBorrowed(_borrower, _iToken)) { // Unlike collaterals, borrowed asset can only be added by iToken, // rather than enabled by user directly. require(msg.sender == _iToken, "sender must be iToken"); // Have checked _iToken is listed, just add it _addToBorrowed(_borrower, _iToken); } // Check borrower's equity (, uint256 _shortfall, , ) = calcAccountEquityWithEffect(_borrower, _iToken, 0, _borrowAmount); require(_shortfall == 0, "Account has some shortfall"); // Check the iToken's borrow capacity, -1 means no limit uint256 _totalBorrows = IiToken(_iToken).totalBorrows(); require( _totalBorrows.add(_borrowAmount) <= _market.borrowCapacity, "Token borrow capacity reached" ); // Update the Reward Distribution Borrow state and distribute reward to borrower IRewardDistributor(rewardDistributor).updateDistributionState( _iToken, true ); IRewardDistributor(rewardDistributor).updateReward( _iToken, _borrower, true ); } /** * @notice Hook function after iToken `borrow()` * Will `revert()` if any operation fails * @param _iToken The iToken being borrewd * @param _borrower The account which borrowed iToken * @param _borrowedAmount The amount of underlying being borrowed */ function afterBorrow( address _iToken, address _borrower, uint256 _borrowedAmount ) external override { _iToken; _borrower; _borrowedAmount; } /** * @notice Hook function before iToken `repayBorrow()` * Checks if the account should be allowed to repay the given iToken * for the borrower. Will `revert()` if any check fails * @param _iToken The iToken to verify the repay against * @param _payer The account which would repay iToken * @param _borrower The account which has borrowed * @param _repayAmount The amount of underlying to repay */ function beforeRepayBorrow( address _iToken, address _payer, address _borrower, uint256 _repayAmount ) external override { _checkiTokenListed(_iToken); // Update the Reward Distribution Borrow state and distribute reward to borrower IRewardDistributor(rewardDistributor).updateDistributionState( _iToken, true ); IRewardDistributor(rewardDistributor).updateReward( _iToken, _borrower, true ); _payer; _repayAmount; } /** * @notice Hook function after iToken `repayBorrow()` * Will `revert()` if any operation fails * @param _iToken The iToken being repaid * @param _payer The account which would repay * @param _borrower The account which has borrowed * @param _repayAmount The amount of underlying being repaied */ function afterRepayBorrow( address _iToken, address _payer, address _borrower, uint256 _repayAmount ) external override { _checkiTokenListed(_iToken); // Remove _iToken from borrowed list if new borrow balance is 0 if (IiToken(_iToken).borrowBalanceStored(_borrower) == 0) { // Only allow called by iToken as we are going to remove this token from borrower's borrowed list require(msg.sender == _iToken, "sender must be iToken"); // Have checked _iToken is listed, just remove it _removeFromBorrowed(_borrower, _iToken); } _payer; _repayAmount; } /** * @notice Hook function before iToken `liquidateBorrow()` * Checks if the account should be allowed to liquidate the given iToken * for the borrower. Will `revert()` if any check fails * @param _iTokenBorrowed The iToken was borrowed * @param _iTokenCollateral The collateral iToken to be liqudate with * @param _liquidator The account which would repay the borrowed iToken * @param _borrower The account which has borrowed * @param _repayAmount The amount of underlying to repay */ function beforeLiquidateBorrow( address _iTokenBorrowed, address _iTokenCollateral, address _liquidator, address _borrower, uint256 _repayAmount ) external override { // Tokens must have been listed require( iTokens.contains(_iTokenBorrowed) && iTokens.contains(_iTokenCollateral), "Tokens have not been listed" ); (, uint256 _shortfall, , ) = calcAccountEquity(_borrower); require(_shortfall > 0, "Account does not have shortfall"); // Only allowed to repay the borrow balance's close factor uint256 _borrowBalance = IiToken(_iTokenBorrowed).borrowBalanceStored(_borrower); uint256 _maxRepay = _borrowBalance.rmul(closeFactorMantissa); require(_repayAmount <= _maxRepay, "Repay exceeds max repay allowed"); _liquidator; } /** * @notice Hook function after iToken `liquidateBorrow()` * Will `revert()` if any operation fails * @param _iTokenBorrowed The iToken was borrowed * @param _iTokenCollateral The collateral iToken to be seized * @param _liquidator The account which would repay and seize * @param _borrower The account which has borrowed * @param _repaidAmount The amount of underlying being repaied * @param _seizedAmount The amount of collateral being seized */ function afterLiquidateBorrow( address _iTokenBorrowed, address _iTokenCollateral, address _liquidator, address _borrower, uint256 _repaidAmount, uint256 _seizedAmount ) external override { _iTokenBorrowed; _iTokenCollateral; _liquidator; _borrower; _repaidAmount; _seizedAmount; // Unlike repayBorrow, liquidateBorrow does not allow to repay all borrow balance // No need to check whether should remove from borrowed asset list } /** * @notice Hook function before iToken `seize()` * Checks if the liquidator should be allowed to seize the collateral iToken * Will `revert()` if any check fails * @param _iTokenCollateral The collateral iToken to be seize * @param _iTokenBorrowed The iToken was borrowed * @param _liquidator The account which has repaid the borrowed iToken * @param _borrower The account which has borrowed * @param _seizeAmount The amount of collateral iToken to seize */ function beforeSeize( address _iTokenCollateral, address _iTokenBorrowed, address _liquidator, address _borrower, uint256 _seizeAmount ) external override { require(!seizePaused, "Seize has been paused"); // Markets must have been listed require( iTokens.contains(_iTokenBorrowed) && iTokens.contains(_iTokenCollateral), "Tokens have not been listed" ); // Sanity Check the controllers require( IiToken(_iTokenBorrowed).controller() == IiToken(_iTokenCollateral).controller(), "Controller mismatch between Borrowed and Collateral" ); // Update the Reward Distribution Supply state on collateral IRewardDistributor(rewardDistributor).updateDistributionState( _iTokenCollateral, false ); // Update reward of liquidator and borrower on collateral IRewardDistributor(rewardDistributor).updateReward( _iTokenCollateral, _liquidator, false ); IRewardDistributor(rewardDistributor).updateReward( _iTokenCollateral, _borrower, false ); _seizeAmount; } /** * @notice Hook function after iToken `seize()` * Will `revert()` if any operation fails * @param _iTokenCollateral The collateral iToken to be seized * @param _iTokenBorrowed The iToken was borrowed * @param _liquidator The account which has repaid and seized * @param _borrower The account which has borrowed * @param _seizedAmount The amount of collateral being seized */ function afterSeize( address _iTokenCollateral, address _iTokenBorrowed, address _liquidator, address _borrower, uint256 _seizedAmount ) external override { _iTokenBorrowed; _iTokenCollateral; _liquidator; _borrower; _seizedAmount; } /** * @notice Hook function before iToken `transfer()` * Checks if the transfer should be allowed * Will `revert()` if any check fails * @param _iToken The iToken to be transfered * @param _from The account to be transfered from * @param _to The account to be transfered to * @param _amount The amount to be transfered */ function beforeTransfer( address _iToken, address _from, address _to, uint256 _amount ) external override { // _redeemAllowed below will check whether _iToken is listed require(!transferPaused, "Transfer has been paused"); // Check account equity with this amount to decide whether the transfer is allowed _redeemAllowed(_iToken, _from, _amount); // Update the Reward Distribution supply state IRewardDistributor(rewardDistributor).updateDistributionState( _iToken, false ); // Update reward of from and to IRewardDistributor(rewardDistributor).updateReward( _iToken, _from, false ); IRewardDistributor(rewardDistributor).updateReward(_iToken, _to, false); } /** * @notice Hook function after iToken `transfer()` * Will `revert()` if any operation fails * @param _iToken The iToken was transfered * @param _from The account was transfer from * @param _to The account was transfer to * @param _amount The amount was transfered */ function afterTransfer( address _iToken, address _from, address _to, uint256 _amount ) external override { _iToken; _from; _to; _amount; } /** * @notice Hook function before iToken `flashloan()` * Checks if the flashloan should be allowed * Will `revert()` if any check fails * @param _iToken The iToken to be flashloaned * @param _to The account flashloaned transfer to * @param _amount The amount to be flashloaned */ function beforeFlashloan( address _iToken, address _to, uint256 _amount ) external override { // Flashloan share the same pause state with borrow require(!markets[_iToken].borrowPaused, "Token borrow has been paused"); _checkiTokenListed(_iToken); _to; _amount; // Update the Reward Distribution Borrow state IRewardDistributor(rewardDistributor).updateDistributionState( _iToken, true ); } /** * @notice Hook function after iToken `flashloan()` * Will `revert()` if any operation fails * @param _iToken The iToken was flashloaned * @param _to The account flashloan transfer to * @param _amount The amount was flashloaned */ function afterFlashloan( address _iToken, address _to, uint256 _amount ) external override { _iToken; _to; _amount; } /*********************************/ /***** Internal Functions *******/ /*********************************/ function _redeemAllowed( address _iToken, address _redeemer, uint256 _amount ) private view { _checkiTokenListed(_iToken); // No need to check liquidity if _redeemer has not used _iToken as collateral if (!accountsData[_redeemer].collaterals.contains(_iToken)) { return; } (, uint256 _shortfall, , ) = calcAccountEquityWithEffect(_redeemer, _iToken, _amount, 0); require(_shortfall == 0, "Account has some shortfall"); } /** * @dev Check if _iToken is listed */ function _checkiTokenListed(address _iToken) private view { require(iTokens.contains(_iToken), "Token has not been listed"); } /*********************************/ /** Account equity calculation ***/ /*********************************/ /** * @notice Calculates current account equity * @param _account The account to query equity of * @return account equity, shortfall, collateral value, borrowed value. */ function calcAccountEquity(address _account) public view override returns ( uint256, uint256, uint256, uint256 ) { return calcAccountEquityWithEffect(_account, address(0), 0, 0); } /** * @dev Local vars for avoiding stack-depth limits in calculating account liquidity. * Note that `iTokenBalance` is the number of iTokens the account owns in the collateral, * whereas `borrowBalance` is the amount of underlying that the account has borrowed. */ struct AccountEquityLocalVars { uint256 sumCollateral; uint256 sumBorrowed; uint256 iTokenBalance; uint256 borrowBalance; uint256 exchangeRateMantissa; uint256 underlyingPrice; uint256 collateralValue; uint256 borrowValue; } /** * @notice Calculates current account equity plus some token and amount to effect * @param _account The account to query equity of * @param _tokenToEffect The token address to add some additional redeeem/borrow * @param _redeemAmount The additional amount to redeem * @param _borrowAmount The additional amount to borrow * @return account euqity, shortfall, collateral value, borrowed value plus the effect. */ function calcAccountEquityWithEffect( address _account, address _tokenToEffect, uint256 _redeemAmount, uint256 _borrowAmount ) internal view virtual returns ( uint256, uint256, uint256, uint256 ) { AccountEquityLocalVars memory _local; AccountData storage _accountData = accountsData[_account]; // Calculate value of all collaterals // collateralValuePerToken = underlyingPrice * exchangeRate * collateralFactor // collateralValue = balance * collateralValuePerToken // sumCollateral += collateralValue uint256 _len = _accountData.collaterals.length(); for (uint256 i = 0; i < _len; i++) { IiToken _token = IiToken(_accountData.collaterals.at(i)); _local.iTokenBalance = IERC20Upgradeable(address(_token)).balanceOf( _account ); _local.exchangeRateMantissa = _token.exchangeRateStored(); if (_tokenToEffect == address(_token) && _redeemAmount > 0) { _local.iTokenBalance = _local.iTokenBalance.sub(_redeemAmount); } _local.underlyingPrice = IPriceOracle(priceOracle) .getUnderlyingPrice(address(_token)); require( _local.underlyingPrice != 0, "Invalid price to calculate account equity" ); _local.collateralValue = _local .iTokenBalance .mul(_local.underlyingPrice) .rmul(_local.exchangeRateMantissa) .rmul(markets[address(_token)].collateralFactorMantissa); _local.sumCollateral = _local.sumCollateral.add( _local.collateralValue ); } // Calculate all borrowed value // borrowValue = underlyingPrice * underlyingBorrowed / borrowFactor // sumBorrowed += borrowValue _len = _accountData.borrowed.length(); for (uint256 i = 0; i < _len; i++) { IiToken _token = IiToken(_accountData.borrowed.at(i)); _local.borrowBalance = _token.borrowBalanceStored(_account); if (_tokenToEffect == address(_token) && _borrowAmount > 0) { _local.borrowBalance = _local.borrowBalance.add(_borrowAmount); } _local.underlyingPrice = IPriceOracle(priceOracle) .getUnderlyingPrice(address(_token)); require( _local.underlyingPrice != 0, "Invalid price to calculate account equity" ); // borrowFactorMantissa can not be set to 0 _local.borrowValue = _local .borrowBalance .mul(_local.underlyingPrice) .rdiv(markets[address(_token)].borrowFactorMantissa); _local.sumBorrowed = _local.sumBorrowed.add(_local.borrowValue); } // Should never underflow return _local.sumCollateral > _local.sumBorrowed ? ( _local.sumCollateral - _local.sumBorrowed, uint256(0), _local.sumCollateral, _local.sumBorrowed ) : ( uint256(0), _local.sumBorrowed - _local.sumCollateral, _local.sumCollateral, _local.sumBorrowed ); } /** * @notice Calculate amount of collateral iToken to seize after repaying an underlying amount * @dev Used in liquidation * @param _iTokenBorrowed The iToken was borrowed * @param _iTokenCollateral The collateral iToken to be seized * @param _actualRepayAmount The amount of underlying token liquidator has repaied * @return _seizedTokenCollateral amount of iTokenCollateral tokens to be seized */ function liquidateCalculateSeizeTokens( address _iTokenBorrowed, address _iTokenCollateral, uint256 _actualRepayAmount ) external view virtual override returns (uint256 _seizedTokenCollateral) { /* Read oracle prices for borrowed and collateral assets */ uint256 _priceBorrowed = IPriceOracle(priceOracle).getUnderlyingPrice(_iTokenBorrowed); uint256 _priceCollateral = IPriceOracle(priceOracle).getUnderlyingPrice(_iTokenCollateral); require( _priceBorrowed != 0 && _priceCollateral != 0, "Borrowed or Collateral asset price is invalid" ); uint256 _valueRepayPlusIncentive = _actualRepayAmount.mul(_priceBorrowed).rmul( liquidationIncentiveMantissa ); // Use stored value here as it is view function uint256 _exchangeRateMantissa = IiToken(_iTokenCollateral).exchangeRateStored(); // seizedTokenCollateral = valueRepayPlusIncentive / valuePerTokenCollateral // valuePerTokenCollateral = exchangeRateMantissa * priceCollateral _seizedTokenCollateral = _valueRepayPlusIncentive .rdiv(_exchangeRateMantissa) .div(_priceCollateral); } /*********************************/ /*** Account Markets Operation ***/ /*********************************/ /** * @notice Returns the markets list the account has entered * @param _account The address of the account to query * @return _accountCollaterals The markets list the account has entered */ function getEnteredMarkets(address _account) external view override returns (address[] memory _accountCollaterals) { AccountData storage _accountData = accountsData[_account]; uint256 _len = _accountData.collaterals.length(); _accountCollaterals = new address[](_len); for (uint256 i = 0; i < _len; i++) { _accountCollaterals[i] = _accountData.collaterals.at(i); } } /** * @notice Add markets to `msg.sender`'s markets list for liquidity calculations * @param _iTokens The list of addresses of the iToken markets to be entered * @return _results Success indicator for whether each corresponding market was entered */ function enterMarkets(address[] calldata _iTokens) external override returns (bool[] memory _results) { uint256 _len = _iTokens.length; _results = new bool[](_len); for (uint256 i = 0; i < _len; i++) { _results[i] = _enterMarket(_iTokens[i], msg.sender); } } /** * @notice Add the market to the account's markets list for liquidity calculations * @param _iToken The market to enter * @param _account The address of the account to modify * @return True if entered successfully, false for non-listed market or other errors */ function _enterMarket(address _iToken, address _account) internal returns (bool) { // Market not listed, skip it if (!iTokens.contains(_iToken)) { return false; } // add() will return false if iToken is in account's market list if (accountsData[_account].collaterals.add(_iToken)) { emit MarketEntered(_iToken, _account); } return true; } /** * @notice Returns whether the given account has entered the market * @param _account The address of the account to check * @param _iToken The iToken to check against * @return True if the account has entered the market, otherwise false. */ function hasEnteredMarket(address _account, address _iToken) external view override returns (bool) { return accountsData[_account].collaterals.contains(_iToken); } /** * @notice Remove markets from `msg.sender`'s collaterals for liquidity calculations * @param _iTokens The list of addresses of the iToken to exit * @return _results Success indicators for whether each corresponding market was exited */ function exitMarkets(address[] calldata _iTokens) external override returns (bool[] memory _results) { uint256 _len = _iTokens.length; _results = new bool[](_len); for (uint256 i = 0; i < _len; i++) { _results[i] = _exitMarket(_iTokens[i], msg.sender); } } /** * @notice Remove the market to the account's markets list for liquidity calculations * @param _iToken The market to exit * @param _account The address of the account to modify * @return True if exit successfully, false for non-listed market or other errors */ function _exitMarket(address _iToken, address _account) internal returns (bool) { // Market not listed, skip it if (!iTokens.contains(_iToken)) { return true; } // Account has not entered this market, skip it if (!accountsData[_account].collaterals.contains(_iToken)) { return true; } // Get the iToken balance uint256 _balance = IERC20Upgradeable(_iToken).balanceOf(_account); // Check account's equity if all balance are redeemed // which means iToken can be removed from collaterals _redeemAllowed(_iToken, _account, _balance); // Have checked account has entered market before accountsData[_account].collaterals.remove(_iToken); emit MarketExited(_iToken, _account); return true; } /** * @notice Returns the asset list the account has borrowed * @param _account The address of the account to query * @return _borrowedAssets The asset list the account has borrowed */ function getBorrowedAssets(address _account) external view override returns (address[] memory _borrowedAssets) { AccountData storage _accountData = accountsData[_account]; uint256 _len = _accountData.borrowed.length(); _borrowedAssets = new address[](_len); for (uint256 i = 0; i < _len; i++) { _borrowedAssets[i] = _accountData.borrowed.at(i); } } /** * @notice Add the market to the account's borrowed list for equity calculations * @param _iToken The iToken of underlying to borrow * @param _account The address of the account to modify */ function _addToBorrowed(address _account, address _iToken) internal { // add() will return false if iToken is in account's market list if (accountsData[_account].borrowed.add(_iToken)) { emit BorrowedAdded(_iToken, _account); } } /** * @notice Returns whether the given account has borrowed the given iToken * @param _account The address of the account to check * @param _iToken The iToken to check against * @return True if the account has borrowed the iToken, otherwise false. */ function hasBorrowed(address _account, address _iToken) public view override returns (bool) { return accountsData[_account].borrowed.contains(_iToken); } /** * @notice Remove the iToken from the account's borrowed list * @param _iToken The iToken to remove * @param _account The address of the account to modify */ function _removeFromBorrowed(address _account, address _iToken) internal { // remove() will return false if iToken does not exist in account's borrowed list if (accountsData[_account].borrowed.remove(_iToken)) { emit BorrowedRemoved(_iToken, _account); } } /*********************************/ /****** General Information ******/ /*********************************/ /** * @notice Return all of the iTokens * @return _alliTokens The list of iToken addresses */ function getAlliTokens() public view override returns (address[] memory _alliTokens) { EnumerableSetUpgradeable.AddressSet storage _iTokens = iTokens; uint256 _len = _iTokens.length(); _alliTokens = new address[](_len); for (uint256 i = 0; i < _len; i++) { _alliTokens[i] = _iTokens.at(i); } } /** * @notice Check whether a iToken is listed in controller * @param _iToken The iToken to check for * @return true if the iToken is listed otherwise false */ function hasiToken(address _iToken) public view override returns (bool) { return iTokens.contains(_iToken); } } // File contracts/RewardDistributorV3.sol pragma solidity 0.6.12; /** * @title dForce's lending reward distributor Contract * @author dForce */ contract RewardDistributorV3 is Initializable, Ownable, IRewardDistributorV3 { using SafeRatioMath for uint256; using SafeMathUpgradeable for uint256; using SafeERC20Upgradeable for IERC20Upgradeable; /// @notice the controller Controller public controller; /// @notice the global Reward distribution speed uint256 public globalDistributionSpeed; /// @notice the Reward distribution speed of each iToken mapping(address => uint256) public distributionSpeed; /// @notice the Reward distribution factor of each iToken, 1.0 by default. stored as a mantissa mapping(address => uint256) public distributionFactorMantissa; struct DistributionState { // Token's last updated index, stored as a mantissa uint256 index; // The block number the index was last updated at uint256 block; } /// @notice the Reward distribution supply state of each iToken mapping(address => DistributionState) public distributionSupplyState; /// @notice the Reward distribution borrow state of each iToken mapping(address => DistributionState) public distributionBorrowState; /// @notice the Reward distribution state of each account of each iToken mapping(address => mapping(address => uint256)) public distributionSupplierIndex; /// @notice the Reward distribution state of each account of each iToken mapping(address => mapping(address => uint256)) public distributionBorrowerIndex; /// @notice the Reward distributed into each account mapping(address => uint256) public reward; /// @notice the Reward token address address public rewardToken; /// @notice whether the reward distribution is paused bool public paused; /// @notice the Reward distribution speed supply side of each iToken mapping(address => uint256) public distributionSupplySpeed; /// @notice the global Reward distribution speed for supply uint256 public globalDistributionSupplySpeed; /** * @dev Throws if called by any account other than the controller. */ modifier onlyController() { require( address(controller) == msg.sender, "onlyController: caller is not the controller" ); _; } /** * @notice Initializes the contract. */ function initialize(Controller _controller) external initializer { require( address(_controller) != address(0), "initialize: controller address should not be zero address!" ); __Ownable_init(); controller = _controller; paused = true; } /** * @notice set reward token address * @dev Admin function, only owner can call this * @param _newRewardToken the address of reward token */ function _setRewardToken(address _newRewardToken) external override onlyOwner { address _oldRewardToken = rewardToken; require( _newRewardToken != address(0) && _newRewardToken != _oldRewardToken, "Reward token address invalid" ); rewardToken = _newRewardToken; emit NewRewardToken(_oldRewardToken, _newRewardToken); } /** * @notice Add the iToken as receipient * @dev Admin function, only controller can call this * @param _iToken the iToken to add as recipient * @param _distributionFactor the distribution factor of the recipient */ function _addRecipient(address _iToken, uint256 _distributionFactor) external override onlyController { distributionFactorMantissa[_iToken] = _distributionFactor; distributionSupplyState[_iToken] = DistributionState({ index: 0, block: block.number }); distributionBorrowState[_iToken] = DistributionState({ index: 0, block: block.number }); emit NewRecipient(_iToken, _distributionFactor); } /** * @notice Pause the reward distribution * @dev Admin function, pause will set global speed to 0 to stop the accumulation */ function _pause() external override onlyOwner { // Set the global distribution speed to 0 to stop accumulation address[] memory _iTokens = controller.getAlliTokens(); uint256 _len = _iTokens.length; for (uint256 i = 0; i < _len; i++) { _setDistributionBorrowSpeed(_iTokens[i], 0); _setDistributionSupplySpeed(_iTokens[i], 0); } _refreshGlobalDistributionSpeeds(); _setPaused(true); } /** * @notice Unpause and set distribution speeds * @dev Admin function * @param _borrowiTokens The borrow asset array * @param _borrowSpeeds The borrow speed array * @param _supplyiTokens The supply asset array * @param _supplySpeeds The supply speed array */ function _unpause( address[] calldata _borrowiTokens, uint256[] calldata _borrowSpeeds, address[] calldata _supplyiTokens, uint256[] calldata _supplySpeeds ) external override onlyOwner { _setPaused(false); _setDistributionSpeedsInternal( _borrowiTokens, _borrowSpeeds, _supplyiTokens, _supplySpeeds ); _refreshGlobalDistributionSpeeds(); } /** * @notice Pause/Unpause the reward distribution * @dev Admin function * @param _paused whether to pause/unpause the distribution */ function _setPaused(bool _paused) internal { paused = _paused; emit Paused(_paused); } /** * @notice Set distribution speeds * @dev Admin function, will fail when paused * @param _borrowiTokens The borrow asset array * @param _borrowSpeeds The borrow speed array * @param _supplyiTokens The supply asset array * @param _supplySpeeds The supply speed array */ function _setDistributionSpeeds( address[] calldata _borrowiTokens, uint256[] calldata _borrowSpeeds, address[] calldata _supplyiTokens, uint256[] calldata _supplySpeeds ) external onlyOwner { require(!paused, "Can not change speeds when paused"); _setDistributionSpeedsInternal( _borrowiTokens, _borrowSpeeds, _supplyiTokens, _supplySpeeds ); _refreshGlobalDistributionSpeeds(); } function _setDistributionSpeedsInternal( address[] memory _borrowiTokens, uint256[] memory _borrowSpeeds, address[] memory _supplyiTokens, uint256[] memory _supplySpeeds ) internal { _setDistributionBorrowSpeedsInternal(_borrowiTokens, _borrowSpeeds); _setDistributionSupplySpeedsInternal(_supplyiTokens, _supplySpeeds); } /** * @notice Set borrow distribution speeds * @dev Admin function, will fail when paused * @param _iTokens The borrow asset array * @param _borrowSpeeds The borrow speed array */ function _setDistributionBorrowSpeeds( address[] calldata _iTokens, uint256[] calldata _borrowSpeeds ) external onlyOwner { require(!paused, "Can not change borrow speeds when paused"); _setDistributionBorrowSpeedsInternal(_iTokens, _borrowSpeeds); _refreshGlobalDistributionSpeeds(); } /** * @notice Set supply distribution speeds * @dev Admin function, will fail when paused * @param _iTokens The supply asset array * @param _supplySpeeds The supply speed array */ function _setDistributionSupplySpeeds( address[] calldata _iTokens, uint256[] calldata _supplySpeeds ) external onlyOwner { require(!paused, "Can not change supply speeds when paused"); _setDistributionSupplySpeedsInternal(_iTokens, _supplySpeeds); _refreshGlobalDistributionSpeeds(); } function _refreshGlobalDistributionSpeeds() internal { address[] memory _iTokens = controller.getAlliTokens(); uint256 _len = _iTokens.length; uint256 _borrowSpeed; uint256 _supplySpeed; for (uint256 i = 0; i < _len; i++) { _borrowSpeed = _borrowSpeed.add(distributionSpeed[_iTokens[i]]); _supplySpeed = _supplySpeed.add( distributionSupplySpeed[_iTokens[i]] ); } globalDistributionSpeed = _borrowSpeed; globalDistributionSupplySpeed = _supplySpeed; emit GlobalDistributionSpeedsUpdated(_borrowSpeed, _supplySpeed); } function _setDistributionBorrowSpeedsInternal( address[] memory _iTokens, uint256[] memory _borrowSpeeds ) internal { require( _iTokens.length == _borrowSpeeds.length, "Length of _iTokens and _borrowSpeeds mismatch" ); uint256 _len = _iTokens.length; for (uint256 i = 0; i < _len; i++) { _setDistributionBorrowSpeed(_iTokens[i], _borrowSpeeds[i]); } } function _setDistributionSupplySpeedsInternal( address[] memory _iTokens, uint256[] memory _supplySpeeds ) internal { require( _iTokens.length == _supplySpeeds.length, "Length of _iTokens and _supplySpeeds mismatch" ); uint256 _len = _iTokens.length; for (uint256 i = 0; i < _len; i++) { _setDistributionSupplySpeed(_iTokens[i], _supplySpeeds[i]); } } function _setDistributionBorrowSpeed(address _iToken, uint256 _borrowSpeed) internal { // iToken must have been listed require(controller.hasiToken(_iToken), "Token has not been listed"); // Update borrow state before updating new speed _updateDistributionState(_iToken, true); distributionSpeed[_iToken] = _borrowSpeed; emit DistributionBorrowSpeedUpdated(_iToken, _borrowSpeed); } function _setDistributionSupplySpeed(address _iToken, uint256 _supplySpeed) internal { // iToken must have been listed require(controller.hasiToken(_iToken), "Token has not been listed"); // Update supply state before updating new speed _updateDistributionState(_iToken, false); distributionSupplySpeed[_iToken] = _supplySpeed; emit DistributionSupplySpeedUpdated(_iToken, _supplySpeed); } /** * @notice Update the iToken's Reward distribution state * @dev Will be called every time when the iToken's supply/borrow changes * @param _iToken The iToken to be updated * @param _isBorrow whether to update the borrow state */ function updateDistributionState(address _iToken, bool _isBorrow) external override { // Skip all updates if it is paused if (paused) { return; } _updateDistributionState(_iToken, _isBorrow); } function _updateDistributionState(address _iToken, bool _isBorrow) internal { require(controller.hasiToken(_iToken), "Token has not been listed"); DistributionState storage state = _isBorrow ? distributionBorrowState[_iToken] : distributionSupplyState[_iToken]; uint256 _speed = _isBorrow ? distributionSpeed[_iToken] : distributionSupplySpeed[_iToken]; uint256 _blockNumber = block.number; uint256 _deltaBlocks = _blockNumber.sub(state.block); if (_deltaBlocks > 0 && _speed > 0) { uint256 _totalToken = _isBorrow ? IiToken(_iToken).totalBorrows() : IERC20Upgradeable(_iToken).totalSupply(); uint256 _totalDistributed = _speed.mul(_deltaBlocks); // Reward distributed per token since last time uint256 _distributedPerToken = _totalToken > 0 ? _totalDistributed.rdiv(_totalToken) : 0; state.index = state.index.add(_distributedPerToken); } state.block = _blockNumber; } /** * @notice Update the account's Reward distribution state * @dev Will be called every time when the account's supply/borrow changes * @param _iToken The iToken to be updated * @param _account The account to be updated * @param _isBorrow whether to update the borrow state */ function updateReward( address _iToken, address _account, bool _isBorrow ) external override { // Skip all updates if it is paused if (paused) { return; } _updateReward(_iToken, _account, _isBorrow); } function _updateReward( address _iToken, address _account, bool _isBorrow ) internal { require(_account != address(0), "Invalid account address!"); require(controller.hasiToken(_iToken), "Token has not been listed"); uint256 _iTokenIndex; uint256 _accountIndex; uint256 _accountBalance; if (_isBorrow) { _iTokenIndex = distributionBorrowState[_iToken].index; _accountIndex = distributionBorrowerIndex[_iToken][_account]; _accountBalance = IiToken(_iToken).borrowBalanceStored(_account); // Update the account state to date distributionBorrowerIndex[_iToken][_account] = _iTokenIndex; } else { _iTokenIndex = distributionSupplyState[_iToken].index; _accountIndex = distributionSupplierIndex[_iToken][_account]; _accountBalance = IERC20Upgradeable(_iToken).balanceOf(_account); // Update the account state to date distributionSupplierIndex[_iToken][_account] = _iTokenIndex; } uint256 _deltaIndex = _iTokenIndex.sub(_accountIndex); uint256 _amount = _accountBalance.rmul(_deltaIndex); if (_amount > 0) { reward[_account] = reward[_account].add(_amount); emit RewardDistributed(_iToken, _account, _amount, _accountIndex); } } /** * @notice Update reward accrued in iTokens by the holders regardless of paused or not * @param _holders The account to update * @param _iTokens The _iTokens to update */ function updateRewardBatch( address[] memory _holders, address[] memory _iTokens ) public override { // Update rewards for all _iTokens for holders for (uint256 i = 0; i < _iTokens.length; i++) { address _iToken = _iTokens[i]; _updateDistributionState(_iToken, false); _updateDistributionState(_iToken, true); for (uint256 j = 0; j < _holders.length; j++) { _updateReward(_iToken, _holders[j], false); _updateReward(_iToken, _holders[j], true); } } } /** * @notice Claim reward accrued in iTokens by the holders * @param _holders The account to claim for * @param _iTokens The _iTokens to claim from */ function claimReward(address[] memory _holders, address[] memory _iTokens) public override { updateRewardBatch(_holders, _iTokens); // Withdraw all reward for all holders for (uint256 j = 0; j < _holders.length; j++) { address _account = _holders[j]; uint256 _reward = reward[_account]; if (_reward > 0) { reward[_account] = 0; IERC20Upgradeable(rewardToken).safeTransfer(_account, _reward); } } } /** * @notice Claim reward accrued in all iTokens by the holders * @param _holders The account to claim for */ function claimAllReward(address[] memory _holders) external override { claimReward(_holders, controller.getAlliTokens()); } }
* @notice Update the account's Reward distribution state @dev Will be called every time when the account's supply/borrow changes @param _iToken The iToken to be updated @param _account The account to be updated @param _isBorrow whether to update the borrow state/ Skip all updates if it is paused
function updateReward( address _iToken, address _account, bool _isBorrow ) external override { if (paused) { return; } _updateReward(_iToken, _account, _isBorrow); }
2,030,357
[ 1, 1891, 326, 2236, 1807, 534, 359, 1060, 7006, 919, 225, 9980, 506, 2566, 3614, 813, 1347, 326, 2236, 1807, 14467, 19, 70, 15318, 3478, 225, 389, 77, 1345, 1021, 277, 1345, 358, 506, 3526, 225, 389, 4631, 1021, 2236, 358, 506, 3526, 225, 389, 291, 38, 15318, 2856, 358, 1089, 326, 29759, 919, 19, 6611, 777, 4533, 309, 518, 353, 17781, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 565, 445, 1089, 17631, 1060, 12, 203, 3639, 1758, 389, 77, 1345, 16, 203, 3639, 1758, 389, 4631, 16, 203, 3639, 1426, 389, 291, 38, 15318, 203, 565, 262, 3903, 3849, 288, 203, 3639, 309, 261, 8774, 3668, 13, 288, 203, 5411, 327, 31, 203, 3639, 289, 203, 203, 3639, 389, 2725, 17631, 1060, 24899, 77, 1345, 16, 389, 4631, 16, 389, 291, 38, 15318, 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 ]
// SPDX-License-Identifier: BlueOak-1.0.0 pragma solidity 0.8.9; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "contracts/interfaces/IAsset.sol"; import "contracts/interfaces/IAssetRegistry.sol"; import "contracts/interfaces/IMain.sol"; import "contracts/interfaces/ITrading.sol"; import "contracts/libraries/Fixed.sol"; // Gnosis: uint96 ~= 7e28 uint256 constant GNOSIS_MAX_TOKENS = 7e28; /** * @title TradingLibP0 * @notice An informal extension of the Trading mixin that provides trade preparation views * @dev The caller must implement the ITrading interface! */ library TradingLibP0 { using FixLib for uint192; /// Prepare an trade to sell `sellAmount` that guarantees a reasonable closing price, /// without explicitly aiming at a particular quantity to purchase. /// @param sellAmount {sellTok} /// @return notDust True when the trade is larger than the dust amount /// @return trade The prepared trade function prepareTradeSell( IAsset sell, IAsset buy, uint192 sellAmount ) public view returns (bool notDust, TradeRequest memory trade) { assert(sell.price().neq(FIX_ZERO) && buy.price().neq(FIX_ZERO)); trade.sell = sell; trade.buy = buy; // Don't sell dust. if (sellAmount.lt(dustThreshold(sell))) return (false, trade); // {sellTok} uint192 s = fixMin(sellAmount, sell.maxTradeVolume().div(sell.price(), FLOOR)); trade.sellAmount = s.shiftl_toUint(int8(sell.erc20().decimals()), FLOOR); // Do not consider 1 qTok a viable sell amount if (trade.sellAmount <= 1) return (false, trade); // Do not overflow auction mechanism - sell side if (trade.sellAmount > GNOSIS_MAX_TOKENS) { trade.sellAmount = GNOSIS_MAX_TOKENS; s = shiftl_toFix(trade.sellAmount, -int8(sell.erc20().decimals())); } // {buyTok} = {sellTok} * {UoA/sellTok} / {UoA/buyTok} uint192 b = s.mul(FIX_ONE.minus(maxTradeSlippage())).mulDiv( sell.price(), buy.price(), CEIL ); trade.minBuyAmount = b.shiftl_toUint(int8(buy.erc20().decimals()), CEIL); // Do not overflow auction mechanism - buy side if (trade.minBuyAmount > GNOSIS_MAX_TOKENS) { uint192 over = FIX_ONE.muluDivu(trade.minBuyAmount, GNOSIS_MAX_TOKENS); trade.sellAmount = divFix(trade.sellAmount, over).toUint(FLOOR); trade.minBuyAmount = divFix(trade.minBuyAmount, over).toUint(CEIL); } return (true, trade); } /// Assuming we have `maxSellAmount` sell tokens avaialable, prepare an trade to /// cover as much of our deficit as possible, given expected trade slippage. /// @param maxSellAmount {sellTok} /// @param deficitAmount {buyTok} /// @return notDust Whether the prepared trade is large enough to be worth trading /// @return trade The prepared trade function prepareTradeToCoverDeficit( IAsset sell, IAsset buy, uint192 maxSellAmount, uint192 deficitAmount ) public view returns (bool notDust, TradeRequest memory trade) { // Don't sell dust. if (maxSellAmount.lt(dustThreshold(sell))) return (false, trade); // Don't buy dust. deficitAmount = fixMax(deficitAmount, dustThreshold(buy)); // {sellTok} = {buyTok} * {UoA/buyTok} / {UoA/sellTok} uint192 exactSellAmount = deficitAmount.mulDiv(buy.price(), sell.price(), CEIL); // exactSellAmount: Amount to sell to buy `deficitAmount` if there's no slippage // slippedSellAmount: Amount needed to sell to buy `deficitAmount`, counting slippage uint192 slippedSellAmount = exactSellAmount.div(FIX_ONE.minus(maxTradeSlippage()), CEIL); uint192 sellAmount = fixMin(slippedSellAmount, maxSellAmount); return prepareTradeSell(sell, buy, sellAmount); } // Compute max surpluse relative to basketTop and max deficit relative to basketBottom /// @param useFallenTarget If true, trade towards a reduced BU target /// @return surplus Surplus asset OR address(0) /// @return deficit Deficit collateral OR address(0) /// @return sellAmount {sellTok} Surplus amount (whole tokens) /// @return buyAmount {buyTok} Deficit amount (whole tokens) function largestSurplusAndDeficit(bool useFallenTarget) external view returns ( IAsset surplus, ICollateral deficit, uint192 sellAmount, uint192 buyAmount ) { IERC20[] memory erc20s = assetRegistry().erc20s(); // Compute basketTop and basketBottom // basketTop is the lowest number of BUs to which we'll try to sell surplus assets // basketBottom is the greatest number of BUs to which we'll try to buy deficit assets uint192 basketTop = rToken().basketsNeeded(); // {BU} uint192 basketBottom = basketTop; // {BU} if (useFallenTarget) { uint192 tradeVolume; // {UoA} uint192 totalValue; // {UoA} for (uint256 i = 0; i < erc20s.length; i++) { IAsset asset = assetRegistry().toAsset(erc20s[i]); // Ignore dust amounts for assets not in the basket uint192 bal = asset.bal(address(this)); // {tok} if (basket().quantity(erc20s[i]).gt(FIX_ZERO) || bal.gt(dustThreshold(asset))) { // {UoA} = {UoA} + {UoA/tok} * {tok} totalValue = totalValue.plus(asset.price().mul(bal, FLOOR)); } } basketTop = totalValue.div(basket().price(), CEIL); for (uint256 i = 0; i < erc20s.length; i++) { IAsset asset = assetRegistry().toAsset(erc20s[i]); if (!asset.isCollateral()) continue; uint192 needed = basketTop.mul(basket().quantity(erc20s[i]), CEIL); // {tok} uint192 held = asset.bal(address(this)); // {tok} if (held.lt(needed)) { // {UoA} = {UoA} + ({tok} - {tok}) * {UoA/tok} tradeVolume = tradeVolume.plus(needed.minus(held).mul(asset.price(), FLOOR)); } } // bBot {BU} = (totalValue - mTS * tradeVolume) / basket.price basketBottom = totalValue.minus(maxTradeSlippage().mul(tradeVolume)).div( basket().price(), CEIL ); } return surplusDeficitHelper(erc20s, basketTop, basketBottom); } /// @param basketTop {BU} The lowest number of BUs at which we would be willing to sell /// @param basketBottom {BU} The greatest number of BUs at which we would be willing to buy function surplusDeficitHelper( IERC20[] memory erc20s, uint192 basketTop, uint192 basketBottom ) private view returns ( IAsset surplus, ICollateral deficit, uint192 sellAmount, uint192 buyAmount ) { uint192 maxSurplus; uint192 maxDeficit; for (uint256 i = 0; i < erc20s.length; i++) { if (erc20s[i] == rsr()) continue; // do not consider RSR IAsset asset = assetRegistry().toAsset(erc20s[i]); uint192 bal = asset.bal(address(this)); // Token Threshold - top uint192 tokenThreshold = basketTop.mul(basket().quantity(erc20s[i]), CEIL); // {tok}; if (bal.gt(tokenThreshold)) { // {UoA} = ({tok} - {tok}) * {UoA/tok} uint192 deltaTop = bal.minus(tokenThreshold).mul(asset.price(), FLOOR); if (deltaTop.gt(maxSurplus)) { surplus = asset; maxSurplus = deltaTop; // {tok} = {UoA} / {UoA/tok} sellAmount = fixMin(bal, maxSurplus.div(surplus.price())); } } else { // Token Threshold - bottom tokenThreshold = basketBottom.mul(basket().quantity(erc20s[i]), CEIL); // {tok} if (bal.lt(tokenThreshold)) { // {UoA} = ({tok} - {tok}) * {UoA/tok} uint192 deltaBottom = tokenThreshold.minus(bal).mul(asset.price(), CEIL); if (deltaBottom.gt(maxDeficit)) { deficit = ICollateral(address(asset)); maxDeficit = deltaBottom; // {tok} = {UoA} / {UoA/tok} buyAmount = maxDeficit.div(deficit.price(), CEIL); } } } } } // === Getters === /// @return {%} function maxTradeSlippage() private view returns (uint192) { return ITrading(address(this)).maxTradeSlippage(); } /// @return {tok} The least amount of whole tokens ever worth trying to sell function dustThreshold(IAsset asset) private view returns (uint192) { // {tok} = {UoA} / {UoA/tok} return ITrading(address(this)).dustAmount().div(asset.price()); } /// @return The AssetRegistry function assetRegistry() private view returns (IAssetRegistry) { return ITrading(address(this)).main().assetRegistry(); } /// @return The BasketHandler function basket() private view returns (IBasketHandler) { return ITrading(address(this)).main().basketHandler(); } /// @return The RToken function rToken() private view returns (IRToken) { return ITrading(address(this)).main().rToken(); } /// @return The RSR associated with this RToken function rsr() private view returns (IERC20) { return ITrading(address(this)).main().rsr(); } }
@return The AssetRegistry
function assetRegistry() private view returns (IAssetRegistry) { return ITrading(address(this)).main().assetRegistry(); }
6,433,972
[ 1, 2463, 1021, 10494, 4243, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 3310, 4243, 1435, 3238, 1476, 1135, 261, 45, 6672, 4243, 13, 288, 203, 3639, 327, 467, 1609, 7459, 12, 2867, 12, 2211, 13, 2934, 5254, 7675, 9406, 4243, 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 ]
// File: @openzeppelin/contracts-ethereum-package/contracts/Initializable.sol 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; } // File: @openzeppelin/contracts-ethereum-package/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) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts-ethereum-package/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)); } } // File: @openzeppelin/contracts-ethereum-package/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) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } } // File: @openzeppelin/contracts-ethereum-package/contracts/GSN/Context.sol pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ 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; } // File: @openzeppelin/contracts-ethereum-package/contracts/access/AccessControl.sol pragma solidity ^0.6.0; /** * @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; } // File: @openzeppelin/contracts-ethereum-package/contracts/token/ERC20/IERC20.sol pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: contracts/EnhancedERC20.sol pragma solidity 0.6.2; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20MinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract EnhancedERC20 is Initializable, ContextUpgradeSafe, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ function __ERC20_init(string memory name, string memory symbol) internal initializer { __Context_init_unchained(); __ERC20_init_unchained(name, symbol); } function __ERC20_init_unchained(string memory name, string memory symbol) internal initializer { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /* Above this line is original Openzeppelin code from ERC20UpgradeSafe. Below are changes required necessary to expose private variables or hooks to make the contract more flexible or gas-efficient. */ /** * @dev Hook that is called before minting of tokens. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeMint(address from, address to, uint256 amount) internal virtual { } /** * @dev Hook that is called before a transfering tokens out of an account to one or more token holders * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransferBatch() internal virtual { } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeMint(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransferBatch(); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** * @dev Send multiple transfers as a batch within a single transaction * This is much more efficient than sending independent transactions. * This method should between 28% of gas (2 transfers) * and 50%-60% of gas (10+ transfers) * * Calling conditions: * * Emits an {Transfer} event for each individual successful transfer. * * Requirements: * * - `recipients[]` length must equal `amounts[]` length. * - The amount to send `recipients[i]` must be at `amounts[i]` * - `recipient` cannot be the zero address. * - `balance` of the calling account must be >= the sum of values in `amounts` going to other accounts */ function transferBatch(address[] calldata recipients, uint256[] calldata amounts) external virtual returns (bool) { require(recipients.length == amounts.length); _beforeTokenTransferBatch(); address sender = _msgSender(); uint256 senderBalance = _balances[sender]; for (uint i = 0; i < amounts.length; i++) { uint amount = amounts[i]; address recipient = recipients[i]; require(senderBalance >= amount, "ERC20: Insufficient balance for batch transfer"); require(recipient != address(0), "ERC20: transfer to the zero address"); if(sender != recipient){ senderBalance = senderBalance - amount; _balances[recipient] += amount; } emit Transfer(sender, recipient, amount); } _balances[sender] = senderBalance; return true; } uint256[44] private __gap; } // File: @openzeppelin/contracts-ethereum-package/contracts/utils/Pausable.sol pragma solidity ^0.6.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. */ 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; } // File: contracts/ManagedEnhancedERC20.sol pragma solidity 0.6.2; /** * @dev ERC20 token with pausable token transfers. * * Useful as an emergency switch for freezing all token transfers in the * event of a large bug or major project-impacting event. */ abstract contract ManagedEnhancedERC20 is Initializable, ContextUpgradeSafe, AccessControlUpgradeSafe, EnhancedERC20, PausableUpgradeSafe { bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); function __ManagedEnhancedERC20_init(string memory name, string memory symbol) internal initializer { __Context_init_unchained(); __AccessControl_init_unchained(); __ERC20_init_unchained(name, symbol); __Pausable_init_unchained(); __ManagedEnhancedERC20_init_unchained(); } function __ManagedEnhancedERC20_init_unchained() internal initializer { _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); _setupRole(PAUSER_ROLE, _msgSender()); } /** * @dev Pauses all token transfers. * * See {ERC20Pausable} and {Pausable-_pause}. * * Requirements: * * - the caller must have the `PAUSER_ROLE`. */ function pause() public { require(hasRole(PAUSER_ROLE, _msgSender()), "PauseableEnhancedERC20: 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 { require(hasRole(PAUSER_ROLE, _msgSender()), "PauseableEnhancedERC20: must have pauser role to unpause"); _unpause(); } /** * @dev See {EnhancedERC20-_beforeTokenTransferBatch}. * * Requirements: * * - the contract must not be paused. */ function _beforeTokenTransferBatch() internal virtual override { super._beforeTokenTransferBatch(); require(!paused(), "ManagedEnhancedERC20: token transfer while paused"); } uint256[50] private __gap; } // File: contracts/SHOPToken.sol pragma solidity 0.6.2; /** * @dev ShopCity.com ERC20 Token * * Supply capped at 1 billion. */ contract SHOPToken is Initializable, ManagedEnhancedERC20 { using SafeMath for uint256; uint256 private _maxSupply; function initialize(string memory name, string memory symbol) public initializer { __Context_init_unchained(); __AccessControl_init_unchained(); __ERC20_init_unchained(name, symbol); __Pausable_init_unchained(); __ManagedEnhancedERC20_init_unchained(); __SHOPToken_init_unchained(); } function __SHOPToken_init_unchained() internal initializer { _maxSupply = 1000000000e18; _mint(_msgSender(), _maxSupply); } function _beforeMint(address from, address to, uint256 amount) internal virtual override { require(totalSupply().add(amount) <= _maxSupply); super._beforeMint(from, to, amount); } }
* @dev Send multiple transfers as a batch within a single transaction This is much more efficient than sending independent transactions. This method should between 28% of gas (2 transfers) and 50%-60% of gas (10+ transfers) Calling conditions: Emits an {Transfer} event for each individual successful transfer. Requirements: - `recipients[]` length must equal `amounts[]` length. - The amount to send `recipients[i]` must be at `amounts[i]` - `recipient` cannot be the zero address. - `balance` of the calling account must be >= the sum of values in `amounts` going to other accounts/
function transferBatch(address[] calldata recipients, uint256[] calldata amounts) external virtual returns (bool) { require(recipients.length == amounts.length); _beforeTokenTransferBatch(); address sender = _msgSender(); uint256 senderBalance = _balances[sender]; for (uint i = 0; i < amounts.length; i++) { uint amount = amounts[i]; address recipient = recipients[i]; require(senderBalance >= amount, "ERC20: Insufficient balance for batch transfer"); require(recipient != address(0), "ERC20: transfer to the zero address"); if(sender != recipient){ senderBalance = senderBalance - amount; _balances[recipient] += amount; } emit Transfer(sender, recipient, amount); } _balances[sender] = senderBalance; return true; } uint256[44] private __gap;
13,763,103
[ 1, 3826, 3229, 29375, 487, 279, 2581, 3470, 279, 2202, 2492, 1220, 353, 9816, 1898, 14382, 2353, 5431, 14807, 8938, 18, 1220, 707, 1410, 3086, 9131, 9, 434, 16189, 261, 22, 29375, 13, 471, 6437, 9, 17, 4848, 9, 434, 16189, 261, 2163, 15, 29375, 13, 21020, 4636, 30, 7377, 1282, 392, 288, 5912, 97, 871, 364, 1517, 7327, 6873, 7412, 18, 29076, 30, 300, 1375, 27925, 8526, 68, 769, 1297, 3959, 225, 1375, 8949, 87, 8526, 68, 769, 18, 300, 225, 1021, 3844, 358, 1366, 1375, 27925, 63, 77, 65, 68, 1297, 506, 622, 1375, 8949, 87, 63, 77, 65, 68, 300, 1375, 20367, 68, 2780, 506, 326, 3634, 1758, 18, 300, 1375, 12296, 68, 434, 326, 4440, 2236, 1297, 506, 1545, 326, 2142, 434, 924, 316, 1375, 8949, 87, 68, 8554, 358, 1308, 9484, 19, 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, 7412, 4497, 12, 2867, 8526, 745, 892, 12045, 16, 2254, 5034, 8526, 745, 892, 30980, 13, 3903, 5024, 1135, 261, 6430, 13, 288, 203, 3639, 2583, 12, 27925, 18, 2469, 422, 30980, 18, 2469, 1769, 203, 3639, 389, 5771, 1345, 5912, 4497, 5621, 203, 203, 3639, 1758, 5793, 273, 389, 3576, 12021, 5621, 203, 3639, 2254, 5034, 5793, 13937, 273, 389, 70, 26488, 63, 15330, 15533, 203, 3639, 364, 261, 11890, 277, 273, 374, 31, 277, 411, 30980, 18, 2469, 31, 277, 27245, 288, 203, 5411, 2254, 3844, 273, 30980, 63, 77, 15533, 203, 5411, 1758, 8027, 273, 12045, 63, 77, 15533, 203, 5411, 2583, 12, 15330, 13937, 1545, 3844, 16, 315, 654, 39, 3462, 30, 22085, 11339, 11013, 364, 2581, 7412, 8863, 203, 5411, 2583, 12, 20367, 480, 1758, 12, 20, 3631, 315, 654, 39, 3462, 30, 7412, 358, 326, 3634, 1758, 8863, 203, 5411, 309, 12, 15330, 480, 8027, 15329, 203, 7734, 5793, 13937, 273, 5793, 13937, 300, 3844, 31, 203, 7734, 389, 70, 26488, 63, 20367, 65, 1011, 3844, 31, 203, 5411, 289, 203, 1082, 202, 18356, 12279, 12, 15330, 16, 8027, 16, 3844, 1769, 203, 3639, 289, 203, 3639, 389, 70, 26488, 63, 15330, 65, 273, 5793, 13937, 31, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 203, 565, 2254, 5034, 63, 6334, 65, 3238, 1001, 14048, 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 ]
// SPDX-License-Identifier: GPL-3.0 /** * @title Complete the Punks: Project * @dev Per-project contract for managing Bodies + Legs * @author earlybail.eth | Cranky Brain Labs * @notice #GetBodied #LegsFuknGooo */ /* ;╟██▓▒ :╟██▓▒ ,φ▒╣╬╬╩╩Γ ╙╩╬╬╬▓▒░ ,╓φ╣▓█╬Γ ╚╣█▓╬▒╓, ,,╓╓╓╓, φ╣▓▓╬╩"" ""╚╣▓▓▒░ ]╟▓████▓▒ φφ╬╬╬╬╩╙ '╚╩╬╬╬▒▒░ φ╫███▓╬╬╬▓▒░ ]╟▓█▓▒ :╟▓█▓▒ φ╫██╬▒ ╚╣█▓╬φ,, :╟██▓▒ :╟██▓▒ φ╫██▓▒ "╙╠╣▓▓▒░ :╟██▓▒ :╟██▓▒ φφ▒▒▒▒╬╬╬╩╩' φ╫██▓▒ :╟██▓▒ ,,, :╟██▓▒ ]╟▓████▓╬⌐ φ╫██▓▒ :╟██▓▒ .╠╣▓▓▒ :╟██▓▒ :╟███╬╩"' φ╫██▓▒ :╟██▓▒ :╟██▓▒ φφ▒φ░ ,φ▒▒░ :╟██▓▒ :╟██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒ '╠▓█▓▒ ╚╣█▓╬⌐:╟███▒≥, '╠▓█▓╬≥, ,,φ╣██╬░ :╟██▓▒ :╟██▓▒ ^"╙"' "╙╙" :╟█████▓▒~ ^"╙╠╣▓▓▒~ φ╣▓▓╬╩╙" :╟██▓▒ :╟██▓▒ :╟████▓╬╬▒▒φ ╠▓██╬[ ╠▓██╬[ :╟██▓▒ :╟██▓▒ :╟███▒ ╚╟▓█╬▒╓╠▓██╬[ ╠▓██╬[ :╟██▓▒ :╟██▓▒ :╟██▓▒ "╙╚╣▓▓████╬[ ╠▓██╬[ :╟██▓▒ :╟██▓▒ :╟██▓▒ ╚╬╬████╬[ ╠▓██╬[ :╟██▓▒ :╟██▓▒ :╟███▒╓, ╚╣██╬⌐ ╠▓██╬[ :╟██▓▒ :╟██▓▒ :╟█████▓▒~ '"╙╙" ╠▓██╬[ :╟██▓▒ :╟██▓▒ :╟████▓╬╬▒▒φ ≤φ▒╬╬╬╬╚ :╟██▓▒ :╟██▓▒ :╟███▒ ╚╣██╬▒,,,,,,,φ╟▓█▓╩ :╟██▓▒ :╟██▓▒ :╟██▓▒ "╙╩╬╣▓▓▓▓▓▓▓▓╬╬╚╙' :╟██▓▒ :╟██▓▒ :╟██▓▒ ╚╬▓▓▓▓▓▓▓╬╩░ :╟██▓▒ :╟██▓▒ :╟██▓▒ :╟██▓▒ :╟██▓▒ :╟██▓▒ :╟██▓▒ :╟██▓▒ :╟██▓▒ :╟██▓▒ :╟██▓▒ :╟██▓▒ :╟██▓▒ :╟██▓▒ :╟██▓▒ :╟██▓▒ :╟██▓▒ :╟██▓▒ :╟██▓▒ :╟██▓▒ :╟██▓▒ :╟██▓▒ :╟██▓▒ ]φ╣▓▒░ :╟██▓▒ :╟██▓▒ :╟██▓▒ "╠╬▓╩░ :╟██▓▒ :╟███▒, :╟██▓▒ :╟██▓▒ :╟████▓▒▒ :╟██▓▒ :╟██▓▒ ╚╬█████▓▒▒╣██▓▒ :╟██▓▒ "╠▓████████▓▒ :╟██▓▒ */ /* φ╫██▓▒ :╟██▓▒ φ╫██▓▒ ,φ▒▓▓▓▓▓▓▓▓▓▓▓▓▓▒▒░ :╟██▓▒ φ╫██▓▒ φ╣███████████████▓▒ :╟██▓▒ φ╫██▓▒ φ╫██▓╩╙╙╙╙╙╙╙╚╣██▓▒ :╟██▓▒ φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒ φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒ φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒ φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒ φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒ φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒ φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒ φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒ φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒ φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒ φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒ φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒ φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒ φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒ φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒ φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒ φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒ φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒ φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒ φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒ φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒ φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒ φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒ φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒ φ╫██▓▒ "╩╬▓╬▒φφ, :╟██▓▒ ╚╬▓╬╬▒φε φ╫██▓▒ 7╟▓█▓▒, ;╟██▓▒ `╠╣█▓╬░ φ╫██▓▒ "╙╩╬╣▓▓▓▓▓███▓▒ ^╙╩╬╣▓▓▓▓▓▒░ φ╫██▓▒ ╚╠╣███████▓▒ "╠╬████╬╬▒φε φ╫██▓▒ ```╠╠███▒, ```░╠╣██╬[ φ╫████▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓█████▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓████╬[ "╠╬███████████████████████████████████████████████╬╩ `^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ */ // Directives. pragma solidity 0.8.9; // Third-party deps. import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/finance/PaymentSplitter.sol"; import "@openzeppelin/contracts/utils/Context.sol"; import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol"; // Local deps. import "./Bodies.sol"; import "./Legs.sol"; // Contract. contract Project is ReentrancyGuard, Ownable, PaymentSplitter { // Events. event StatusChange(Status _newStatus); // Mint statuses. enum Status { Paused, Whitelist, Mintpass, Public } // Current mint status, defaults to Status[0] (Paused). Status public status; // Bodies. Bodies public bodies; // Legs. Legs public legs; // Pricing. // @notice settable, use mintPrice() for latest. uint256 public whitelistPrice = 0.02 ether; uint256 public mintpassPrice = 0.04 ether; uint256 public publicPrice = 0.04 ether; // Mint limits. // @notice settable, use mintLimit() for latest. uint256 public whitelistMintLimit = 4; uint256 public mintpassMintLimit = 20; uint256 public publicMintLimit = 40; // Max tokens. uint256 public maxSupply = 10000; // Mintpassed contracts. address[] public mintpassedContracts; // Whitelist Merkle root. bytes32 public merkleRoot = 0x05ba199ba71527baf0f85acf24728a2e559447f3228c1ff56d0d90f8bb269f7d; // Constructor. constructor ( string memory _name, string memory _symbol, uint256 _tokenStartId, address[] memory _payees, uint256[] memory _shares ) PaymentSplitter(_payees, _shares) { // Deploy and set Bodies contract. bodies = new Bodies( string(abi.encodePacked(_name, ": Bodies")), // Extend name. string(abi.encodePacked(_symbol, "B")), // Extend symbol. _tokenStartId ); // Set this Project contract as parent project. bodies.setProjectAddress(address(this)); // Transfer bodies contract ownership to deployer. bodies.transferOwnership(_msgSender()); // Deploy and set Legs contract. legs = new Legs( string(abi.encodePacked(_name, ": Legs")), // Extend name. string(abi.encodePacked(_symbol, "L")), // Extend symbol. _tokenStartId ); // Set this Project contract as parent project. legs.setProjectAddress(address(this)); // Transfer legs contract ownership to deployer. legs.transferOwnership(_msgSender()); } // Mint check helper. modifier mintCheck (address _to, uint256 _numToMint) { // Early bail if paused. require(status != Status.Paused, "Minting is paused"); // Ensure sender. require(_to == _msgSender(), "Can only mint for self"); // Protect against contract minting. require(!Address.isContract(_msgSender()), "Cannot mint from contract"); // Ensure non-zero mint amount. require(_numToMint > 0, "Cannot mint zero tokens"); // Ensure available supply. require(totalSupply() + _numToMint <= maxSupply, "Max supply exceeded"); // Ensure mint limit not exceeded. require(_numToMint <= mintLimit(), "Cannot mint this many tokens"); // Ensure proper payment. require(msg.value == _numToMint * mintPrice(), "Incorrect payment amount sent"); _; } // Set mint price. function setPrice (Status _status, uint256 _newPrice) external onlyOwner { if (_status == Status.Whitelist) { whitelistPrice = _newPrice; } if (_status == Status.Mintpass) { mintpassPrice = _newPrice; } if (_status == Status.Public) { publicPrice = _newPrice; } } // Set mint limit. function setMintLimit (Status _status, uint256 _newLimit) external onlyOwner { if (_status == Status.Whitelist) { whitelistMintLimit = _newLimit; } if (_status == Status.Mintpass) { mintpassMintLimit = _newLimit; } if (_status == Status.Public) { publicMintLimit = _newLimit; } } // Set the bodies contract. function setBodies (address _newAddr) external onlyOwner { bodies = Bodies(_newAddr); } // Set the legs contract. function setLegs (address _newAddr) external onlyOwner { legs = Legs(_newAddr); } // (Re-)set the whitelist Merkle root. function setMerkleRoot (bytes32 _newRoot) external onlyOwner { merkleRoot = _newRoot; } // Set the mint status. function setStatus (Status _newStatus) external onlyOwner { // Update. status = _newStatus; // Broadcast. emit StatusChange(_newStatus); } // (Re-)set the list of Mintpassed Contracts. function setMintpassedContracts (address[] calldata _newAddrs) external onlyOwner { delete mintpassedContracts; mintpassedContracts = _newAddrs; } // Add a new Mintpassed Contract. function addMintpassedContract (address _addr) external onlyOwner { mintpassedContracts.push(_addr); } // Check if an address is whitelisted via Merkle proof validation. function isWhitelistedAddress (address _addr, bytes32[] calldata _merkleProof) public view returns (bool) { // Verify Merkle tree proof. bytes32 leaf = keccak256(abi.encodePacked(_addr)); return MerkleProof.verify(_merkleProof, merkleRoot, leaf); } // Check if an address is mintpassed (has a balance on a Mintpassed Contract). function isMintpassedAddress (address _addr) public view returns (bool) { // Cache array length to save gas. uint256 len = mintpassedContracts.length; // Loop through Mintpassed Contracts. for (uint256 i = 0; i < len; i++) { // Instantiate this Mintpassed Contract. MintpassedContract mintpassedContract = MintpassedContract(mintpassedContracts[i]); // Check if the address has a non-zero balance. if (mintpassedContract.balanceOf(_addr) > 0) { return true; } } // Not allowed. return false; } // Proxy supply to bodies. function totalSupply () public view returns (uint256) { return bodies.totalSupply(); } // Proxy balance to bodies. function balanceOf (address _owner) public view returns (uint256) { return bodies.balanceOf(_owner); } // Dynamic mint price. function mintPrice () public view returns (uint256) { // Paused. if (status == Status.Paused) { // Failsafe, but if you find a way go for it. return 1000000 ether; } // Whitelist. if (status == Status.Whitelist) { return whitelistPrice; } // Mintpass. if (status == Status.Mintpass) { return mintpassPrice; } // Public. return publicPrice; } // Dynamic mint limit. function mintLimit () public view returns (uint256) { // Paused. if (status == Status.Paused) { return 0; } // Whitelist. if (status == Status.Whitelist) { return whitelistMintLimit; } // Mintpass. if (status == Status.Mintpass) { return mintpassMintLimit; } // Public. return publicMintLimit; } // Mint. function mint (address _to, uint256 _numToMint) external payable nonReentrant mintCheck(_to, _numToMint) { // Not for whitelist mints. require(status != Status.Whitelist, "Whitelist mints must provide proof via mintWhitelist()"); // Mintpass. if (status == Status.Mintpass) { // Check eligibility. require(isMintpassedAddress(_to), "Address is not mintpassed"); } // Okay mint. _mint(_to, _numToMint); } // Mint whitelist. function mintWhitelist (address _to, uint256 _numToMint, bytes32[] calldata _merkleProof) external payable nonReentrant mintCheck(_to, _numToMint) { // Require whitelist status. require(status == Status.Whitelist, "Whitelist mints only"); // Check balance. require((balanceOf(_to) + _numToMint) <= mintLimit(), "Whitelist mint limit exceeded"); // Check whitelist eligibility. require(isWhitelistedAddress(_to, _merkleProof), "Address is not whitelisted"); // Okay mint. _mint(_to, _numToMint); } // Actually mint. function _mint (address _to, uint256 _numToMint) private { // Mint bodies & legs. bodies.mint(_to, _numToMint); legs.mint(_to, _numToMint); } } // Mintpassed Contract interface. interface MintpassedContract { function balanceOf(address _account) external view returns (uint256); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol) pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (finance/PaymentSplitter.sol) pragma solidity ^0.8.0; import "../token/ERC20/utils/SafeERC20.sol"; import "../utils/Address.sol"; import "../utils/Context.sol"; /** * @title PaymentSplitter * @dev This contract allows to split Ether payments among a group of accounts. The sender does not need to be aware * that the Ether will be split in this way, since it is handled transparently by the contract. * * The split can be in equal parts or in any other arbitrary proportion. The way this is specified is by assigning each * account to a number of shares. Of all the Ether that this contract receives, each account will then be able to claim * an amount proportional to the percentage of total shares they were assigned. * * `PaymentSplitter` follows a _pull payment_ model. This means that payments are not automatically forwarded to the * accounts but kept in this contract, and the actual transfer is triggered as a separate step by calling the {release} * function. * * NOTE: This contract assumes that ERC20 tokens will behave similarly to native tokens (Ether). Rebasing tokens, and * tokens that apply fees during transfers, are likely to not be supported as expected. If in doubt, we encourage you * to run tests before sending real value to this contract. */ contract PaymentSplitter is Context { event PayeeAdded(address account, uint256 shares); event PaymentReleased(address to, uint256 amount); event ERC20PaymentReleased(IERC20 indexed token, address to, uint256 amount); event PaymentReceived(address from, uint256 amount); uint256 private _totalShares; uint256 private _totalReleased; mapping(address => uint256) private _shares; mapping(address => uint256) private _released; address[] private _payees; mapping(IERC20 => uint256) private _erc20TotalReleased; mapping(IERC20 => mapping(address => uint256)) private _erc20Released; /** * @dev Creates an instance of `PaymentSplitter` where each account in `payees` is assigned the number of shares at * the matching position in the `shares` array. * * All addresses in `payees` must be non-zero. Both arrays must have the same non-zero length, and there must be no * duplicates in `payees`. */ constructor(address[] memory payees, uint256[] memory shares_) payable { require(payees.length == shares_.length, "PaymentSplitter: payees and shares length mismatch"); require(payees.length > 0, "PaymentSplitter: no payees"); for (uint256 i = 0; i < payees.length; i++) { _addPayee(payees[i], shares_[i]); } } /** * @dev The Ether received will be logged with {PaymentReceived} events. Note that these events are not fully * reliable: it's possible for a contract to receive Ether without triggering this function. This only affects the * reliability of the events, and not the actual splitting of Ether. * * To learn more about this see the Solidity documentation for * https://solidity.readthedocs.io/en/latest/contracts.html#fallback-function[fallback * functions]. */ receive() external payable virtual { emit PaymentReceived(_msgSender(), msg.value); } /** * @dev Getter for the total shares held by payees. */ function totalShares() public view returns (uint256) { return _totalShares; } /** * @dev Getter for the total amount of Ether already released. */ function totalReleased() public view returns (uint256) { return _totalReleased; } /** * @dev Getter for the total amount of `token` already released. `token` should be the address of an IERC20 * contract. */ function totalReleased(IERC20 token) public view returns (uint256) { return _erc20TotalReleased[token]; } /** * @dev Getter for the amount of shares held by an account. */ function shares(address account) public view returns (uint256) { return _shares[account]; } /** * @dev Getter for the amount of Ether already released to a payee. */ function released(address account) public view returns (uint256) { return _released[account]; } /** * @dev Getter for the amount of `token` tokens already released to a payee. `token` should be the address of an * IERC20 contract. */ function released(IERC20 token, address account) public view returns (uint256) { return _erc20Released[token][account]; } /** * @dev Getter for the address of the payee number `index`. */ function payee(uint256 index) public view returns (address) { return _payees[index]; } /** * @dev Triggers a transfer to `account` of the amount of Ether they are owed, according to their percentage of the * total shares and their previous withdrawals. */ function release(address payable account) public virtual { require(_shares[account] > 0, "PaymentSplitter: account has no shares"); uint256 totalReceived = address(this).balance + totalReleased(); uint256 payment = _pendingPayment(account, totalReceived, released(account)); require(payment != 0, "PaymentSplitter: account is not due payment"); _released[account] += payment; _totalReleased += payment; Address.sendValue(account, payment); emit PaymentReleased(account, payment); } /** * @dev Triggers a transfer to `account` of the amount of `token` tokens they are owed, according to their * percentage of the total shares and their previous withdrawals. `token` must be the address of an IERC20 * contract. */ function release(IERC20 token, address account) public virtual { require(_shares[account] > 0, "PaymentSplitter: account has no shares"); uint256 totalReceived = token.balanceOf(address(this)) + totalReleased(token); uint256 payment = _pendingPayment(account, totalReceived, released(token, account)); require(payment != 0, "PaymentSplitter: account is not due payment"); _erc20Released[token][account] += payment; _erc20TotalReleased[token] += payment; SafeERC20.safeTransfer(token, account, payment); emit ERC20PaymentReleased(token, account, payment); } /** * @dev internal logic for computing the pending payment of an `account` given the token historical balances and * already released amounts. */ function _pendingPayment( address account, uint256 totalReceived, uint256 alreadyReleased ) private view returns (uint256) { return (totalReceived * _shares[account]) / _totalShares - alreadyReleased; } /** * @dev Add a new payee to the contract. * @param account The address of the payee to add. * @param shares_ The number of shares owned by the payee. */ function _addPayee(address account, uint256 shares_) private { require(account != address(0), "PaymentSplitter: account is the zero address"); require(shares_ > 0, "PaymentSplitter: shares are 0"); require(_shares[account] == 0, "PaymentSplitter: account already has shares"); _payees.push(account); _shares[account] = shares_; _totalShares = _totalShares + shares_; emit PayeeAdded(account, shares_); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (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) } } } // SPDX-License-Identifier: MIT /** * @title Complete the Punks: Bodies * @dev Mints Body NFTs for a parent Punk project * @author earlybail.eth | Cranky Brain Labs * @notice #GetBodied */ /* ;╟██▓▒ :╟██▓▒ ,φ▒╣╬╬╩╩Γ ╙╩╬╬╬▓▒░ ,╓φ╣▓█╬Γ ╚╣█▓╬▒╓, ,,╓╓╓╓, φ╣▓▓╬╩"" ""╚╣▓▓▒░ ]╟▓████▓▒ φφ╬╬╬╬╩╙ '╚╩╬╬╬▒▒░ φ╫███▓╬╬╬▓▒░ ]╟▓█▓▒ :╟▓█▓▒ φ╫██╬▒ ╚╣█▓╬φ,, :╟██▓▒ :╟██▓▒ φ╫██▓▒ "╙╠╣▓▓▒░ :╟██▓▒ :╟██▓▒ φφ▒▒▒▒╬╬╬╩╩' φ╫██▓▒ :╟██▓▒ ,,, :╟██▓▒ ]╟▓████▓╬⌐ φ╫██▓▒ :╟██▓▒ .╠╣▓▓▒ :╟██▓▒ :╟███╬╩"' φ╫██▓▒ :╟██▓▒ :╟██▓▒ φφ▒φ░ ,φ▒▒░ :╟██▓▒ :╟██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒ '╠▓█▓▒ ╚╣█▓╬⌐:╟███▒≥, '╠▓█▓╬≥, ,,φ╣██╬░ :╟██▓▒ :╟██▓▒ ^"╙"' "╙╙" :╟█████▓▒~ ^"╙╠╣▓▓▒~ φ╣▓▓╬╩╙" :╟██▓▒ :╟██▓▒ :╟████▓╬╬▒▒φ ╠▓██╬[ ╠▓██╬[ :╟██▓▒ :╟██▓▒ :╟███▒ ╚╟▓█╬▒╓╠▓██╬[ ╠▓██╬[ :╟██▓▒ :╟██▓▒ :╟██▓▒ "╙╚╣▓▓████╬[ ╠▓██╬[ :╟██▓▒ :╟██▓▒ :╟██▓▒ ╚╬╬████╬[ ╠▓██╬[ :╟██▓▒ :╟██▓▒ :╟███▒╓, ╚╣██╬⌐ ╠▓██╬[ :╟██▓▒ :╟██▓▒ :╟█████▓▒~ '"╙╙" ╠▓██╬[ :╟██▓▒ :╟██▓▒ :╟████▓╬╬▒▒φ ≤φ▒╬╬╬╬╚ :╟██▓▒ :╟██▓▒ :╟███▒ ╚╣██╬▒,,,,,,,φ╟▓█▓╩ :╟██▓▒ :╟██▓▒ :╟██▓▒ "╙╩╬╣▓▓▓▓▓▓▓▓╬╬╚╙' :╟██▓▒ :╟██▓▒ :╟██▓▒ ╚╬▓▓▓▓▓▓▓╬╩░ :╟██▓▒ :╟██▓▒ :╟██▓▒ :╟██▓▒ :╟██▓▒ :╟██▓▒ :╟██▓▒ :╟██▓▒ :╟██▓▒ :╟██▓▒ :╟██▓▒ :╟██▓▒ :╟██▓▒ :╟██▓▒ :╟██▓▒ :╟██▓▒ :╟██▓▒ :╟██▓▒ :╟██▓▒ :╟██▓▒ :╟██▓▒ :╟██▓▒ :╟██▓▒ ]φ╣▓▒░ :╟██▓▒ :╟██▓▒ :╟██▓▒ "╠╬▓╩░ :╟██▓▒ :╟███▒, :╟██▓▒ :╟██▓▒ :╟████▓▒▒ :╟██▓▒ :╟██▓▒ ╚╬█████▓▒▒╣██▓▒ :╟██▓▒ "╠▓████████▓▒ :╟██▓▒ */ // Directives. pragma solidity 0.8.9; // Local deps. import "./Component.sol"; // Contract. contract Bodies is Component { // Constructor. constructor ( string memory _name, string memory _symbol, uint256 _tokenStartId ) Component(_name, _symbol, _tokenStartId) {} } // SPDX-License-Identifier: MIT /** * @title Complete the Punks: Legs * @dev Mints Leg NFTs for a parent Punk project * @author earlybail.eth | Cranky Brain Labs * @notice #LegsFuknGooo */ /* φ╫██▓▒ :╟██▓▒ φ╫██▓▒ ,φ▒▓▓▓▓▓▓▓▓▓▓▓▓▓▒▒░ :╟██▓▒ φ╫██▓▒ φ╣███████████████▓▒ :╟██▓▒ φ╫██▓▒ φ╫██▓╩╙╙╙╙╙╙╙╚╣██▓▒ :╟██▓▒ φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒ φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒ φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒ φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒ φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒ φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒ φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒ φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒ φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒ φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒ φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒ φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒ φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒ φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒ φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒ φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒ φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒ φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒ φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒ φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒ φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒ φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒ φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒ φ╫██▓▒ φ╫██▓▒ :╟██▓▒ :╟██▓▒ φ╫██▓▒ "╩╬▓╬▒φφ, :╟██▓▒ ╚╬▓╬╬▒φε φ╫██▓▒ 7╟▓█▓▒, ;╟██▓▒ `╠╣█▓╬░ φ╫██▓▒ "╙╩╬╣▓▓▓▓▓███▓▒ ^╙╩╬╣▓▓▓▓▓▒░ φ╫██▓▒ ╚╠╣███████▓▒ "╠╬████╬╬▒φε φ╫██▓▒ ```╠╠███▒, ```░╠╣██╬[ φ╫████▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓█████▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓████╬[ "╠╬███████████████████████████████████████████████╬╩ `^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ */ // Directives. pragma solidity 0.8.9; // Local deps. import "./Component.sol"; // Contract. contract Legs is Component { // Constructor. constructor ( string memory _name, string memory _symbol, uint256 _tokenStartId ) Component(_name, _symbol, _tokenStartId) {} } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol) pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `to`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `from` to `to` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT /** * @title Complete the Punks: Component * @dev Base component contract for Bodies + Legs * @author earlybail.eth | Cranky Brain Labs * @notice #GetBodied #LegsFuknGooo */ // Directives. pragma solidity 0.8.9; // Third-party deps. import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/Context.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; // Contract. contract Component is ERC721, ReentrancyGuard, Ownable { // Strings. using Strings for uint256; // Counters. using Counters for Counters.Counter; // Supply counter. Counters.Counter private _supply; // Parent Project contract address. address public projectAddress; // OpenSea Proxy contract address. address public openSeaProxyContractAddress = 0xa5409ec958C83C3f309868babACA7c86DCB077c1; // Base URI. string public baseURI; // Base extension. string public baseExtension = ""; // Provenance hash. string public provenanceHash; // Mint ID tracking. mapping(uint256 => uint256) private _tokenIdCache; uint256 public remainingTokenCount = 10000; // Token start ID. uint256 public tokenStartId = 0; // Constructor. constructor ( string memory _name, string memory _symbol, uint256 _tokenStartId ) ERC721(_name, _symbol) { // Set token start ID. tokenStartId = _tokenStartId; } // Only allow the project contract as caller. modifier onlyProject () { require(_msgSender() == projectAddress, "Only the parent Project contract can call this method"); _; } // Get base URI. function _baseURI () internal view virtual override returns (string memory) { return baseURI; } // Set project address. function setProjectAddress (address _newAddr) external onlyOwner { projectAddress = _newAddr; } // Set base URI. function setBaseURI (string memory _newBaseURI) external onlyOwner { baseURI = _newBaseURI; } // Set base extension. function setBaseExtension (string memory _newBaseExtension) external onlyOwner { baseExtension = _newBaseExtension; } // Set the token start ID. function setTokenStartId (uint256 _newId) external onlyOwner { tokenStartId = _newId; } // Set provenance hash. function setProvenanceHash (string memory _newHash) external onlyOwner { provenanceHash = _newHash; } // Set OpenSea proxy address. // Rinkeby: 0x1E525EEAF261cA41b809884CBDE9DD9E1619573A // Mainnet: 0xa5409ec958C83C3f309868babACA7c86DCB077c1 // Disable: 0x0000000000000000000000000000000000000000 function setOpenSeaProxyAddress (address _newAddress) external onlyOwner { openSeaProxyContractAddress = _newAddress; } // Token URI. function tokenURI (uint256 _tokenId) public view virtual override returns (string memory) { // Ensure existence. require(_exists(_tokenId), "Query for non-existent token"); // Cache. string memory currentBaseURI = _baseURI(); // Concatenate. return bytes(currentBaseURI).length > 0 ? string(abi.encodePacked(currentBaseURI, _tokenId.toString(), baseExtension)) : ""; } // Get the current total supply. function totalSupply () public view returns (uint256) { return _supply.current(); } // Mint. function mint (address _to, uint256 _numToMint) public nonReentrant onlyProject { _mintLoop(_to, _numToMint); } // Actually mint. function _mintLoop (address _to, uint256 _numToMint) private { for (uint256 i = 0; i < _numToMint; i++) { // Draw ID. uint256 tokenId = drawTokenId(); // Safe mint. _safeMint(_to, tokenId); // Increment supply counter. _supply.increment(); } } // Draw token ID. function drawTokenId () private returns (uint256) { // Generate an index. uint256 num = uint256( keccak256( abi.encode( _msgSender(), name(), symbol(), blockhash(block.number - 1), block.number, block.timestamp, block.difficulty, tx.gasprice, remainingTokenCount, projectAddress ) ) ); // Mod. uint256 index = num % remainingTokenCount; // If we haven't already drawn this index, use it directly as tokenId. // Otherwise, pull the tokenId we cached at this index last time. uint256 tokenId = _tokenIdCache[index] == 0 ? index : _tokenIdCache[index]; // Cache this index with the tail of remainingTokenCount. _tokenIdCache[index] = _tokenIdCache[remainingTokenCount - 1] == 0 ? remainingTokenCount - 1 : _tokenIdCache[remainingTokenCount - 1]; // Decrement remaining tokens. remainingTokenCount = remainingTokenCount - 1; // Return with optional start offset. return tokenId + tokenStartId; } // Public exists. function exists (uint256 _tokenId) public view returns (bool) { return _exists(_tokenId); } // Override operator approval. function isApprovedForAll (address _owner, address _operator) public override view returns (bool) { // Skip if disabled. if (openSeaProxyContractAddress != address(0)) { // Instantiate proxy registry. ProxyRegistry proxyRegistry = ProxyRegistry(openSeaProxyContractAddress); // Check proxy. if (address(proxyRegistry.proxies(_owner)) == _operator) { return true; } } // Defer. return super.isApprovedForAll(_owner, _operator); } } // Proxy. contract OwnableDelegateProxy {} // Proxy registry. contract ProxyRegistry { mapping(address => OwnableDelegateProxy) public proxies; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Counters.sol) pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library Counters { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/ERC721.sol) pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); _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 {} } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); }
Mint whitelist. Require whitelist status. Check balance. Check whitelist eligibility. Okay mint.
function mintWhitelist (address _to, uint256 _numToMint, bytes32[] calldata _merkleProof) external payable nonReentrant mintCheck(_to, _numToMint) { require(status == Status.Whitelist, "Whitelist mints only"); require((balanceOf(_to) + _numToMint) <= mintLimit(), "Whitelist mint limit exceeded"); require(isWhitelistedAddress(_to, _merkleProof), "Address is not whitelisted"); _mint(_to, _numToMint); }
13,613,448
[ 1, 49, 474, 10734, 18, 12981, 10734, 1267, 18, 2073, 11013, 18, 2073, 10734, 415, 360, 3628, 18, 16154, 528, 312, 474, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 312, 474, 18927, 261, 2867, 389, 869, 16, 2254, 5034, 389, 2107, 774, 49, 474, 16, 1731, 1578, 8526, 745, 892, 389, 6592, 15609, 20439, 13, 3903, 8843, 429, 1661, 426, 8230, 970, 312, 474, 1564, 24899, 869, 16, 389, 2107, 774, 49, 474, 13, 288, 203, 3639, 2583, 12, 2327, 422, 2685, 18, 18927, 16, 315, 18927, 312, 28142, 1338, 8863, 203, 203, 3639, 2583, 12443, 12296, 951, 24899, 869, 13, 397, 389, 2107, 774, 49, 474, 13, 1648, 312, 474, 3039, 9334, 315, 18927, 312, 474, 1800, 12428, 8863, 203, 203, 3639, 2583, 12, 291, 18927, 329, 1887, 24899, 869, 16, 389, 6592, 15609, 20439, 3631, 315, 1887, 353, 486, 26944, 8863, 203, 203, 3639, 389, 81, 474, 24899, 869, 16, 389, 2107, 774, 49, 474, 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 ]
./full_match/43114/0x9cdBd99D1392489d472BD672b2023739667e7215/sources/contracts/strategies/AaveStrategyV1.sol
* @title Aave strategy for ERC20/
contract AaveStrategyV1 is YakStrategyV2 { using SafeMath for uint256; IAaveIncentivesController private rewardController; ILendingPool private tokenDelegator; IPair private swapPairToken; IWAVAX private constant WAVAX = IWAVAX(0xB31f66AA3C1e785363F0875A1B74E27b85FD66c7); uint256 private leverageLevel; uint256 private safetyFactor; uint256 private leverageBips; uint256 private minMinting; address private avToken; address private avDebtToken; constructor( string memory _name, address _rewardController, address _tokenDelegator, address _depositToken, address _swapPairToken, address _avToken, address _avDebtToken, address _timelock, uint256 _leverageLevel, uint256 _safetyFactor, uint256 _leverageBips, uint256 _minMinting, uint256 _minTokensToReinvest, uint256 _adminFeeBips, uint256 _devFeeBips, uint256 _reinvestRewardBips pragma solidity ^0.7.0; ) { name = _name; rewardController = IAaveIncentivesController(_rewardController); tokenDelegator = ILendingPool(_tokenDelegator); rewardToken = IERC20(address(WAVAX)); _updateLeverage(_leverageLevel, _safetyFactor, _minMinting, _leverageBips); devAddr = msg.sender; depositToken = IERC20(_depositToken); avToken = _avToken; avDebtToken = _avDebtToken; assignSwapPairSafely(_swapPairToken); setAllowances(); updateMinTokensToReinvest(_minTokensToReinvest); updateAdminFee(_adminFeeBips); updateDevFee(_devFeeBips); updateReinvestReward(_reinvestRewardBips); updateDepositsEnabled(true); transferOwnership(_timelock); emit Reinvest(0, 0); } function assignSwapPairSafely(address _swapPairToken) private { require(_swapPairToken > address(0), "Swap pair is necessary but not supplied"); swapPairToken = IPair(_swapPairToken); require( isPairEquals(swapPairToken, depositToken, rewardToken) || isPairEquals(swapPairToken, rewardToken, depositToken), "Swap pair does not match depositToken and rewardToken." ); } function isPairEquals( IPair pair, IERC20 left, IERC20 right ) private returns (bool) { return pair.token0() == address(left) && pair.token1() == address(right); } function _getAccountData() internal view returns ( uint256 balance, uint256 borrowed, uint256 borrowable ) { balance = IERC20(avToken).balanceOf(address(this)); borrowed = IERC20(avDebtToken).balanceOf(address(this)); borrowable = 0; if (balance.mul(leverageLevel.sub(leverageBips)).div(leverageLevel) > borrowed) { borrowable = balance .mul(leverageLevel.sub(leverageBips)) .div(leverageLevel) .sub(borrowed); } } function _getAccountData() internal view returns ( uint256 balance, uint256 borrowed, uint256 borrowable ) { balance = IERC20(avToken).balanceOf(address(this)); borrowed = IERC20(avDebtToken).balanceOf(address(this)); borrowable = 0; if (balance.mul(leverageLevel.sub(leverageBips)).div(leverageLevel) > borrowed) { borrowable = balance .mul(leverageLevel.sub(leverageBips)) .div(leverageLevel) .sub(borrowed); } } function totalDeposits() public view override returns (uint256) { (uint256 balance, uint256 borrowed, ) = _getAccountData(); return balance.sub(borrowed); } function _updateLeverage( uint256 _leverageLevel, uint256 _safetyFactor, uint256 _minMinting, uint256 _leverageBips ) internal { leverageLevel = _leverageLevel; leverageBips = _leverageBips; safetyFactor = _safetyFactor; minMinting = _minMinting; } function updateLeverage( uint256 _leverageLevel, uint256 _safetyFactor, uint256 _minMinting, uint256 _leverageBips ) external onlyDev { _updateLeverage(_leverageLevel, _safetyFactor, _minMinting, _leverageBips); (uint256 balance, uint256 borrowed, ) = _getAccountData(); _unrollDebt(balance.sub(borrowed)); _rollupDebt(); } function setAllowances() public override onlyOwner { IERC20(depositToken).approve(address(tokenDelegator), type(uint256).max); IERC20(avToken).approve(address(tokenDelegator), type(uint256).max); } function deposit(uint256 amount) external override { _deposit(msg.sender, amount); } function depositFor(address account, uint256 amount) external override { _deposit(account, amount); } function depositWithPermit( uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external override { depositToken.permit(msg.sender, address(this), amount, deadline, v, r, s); _deposit(msg.sender, amount); } function _deposit(address account, uint256 amount) private onlyAllowedDeposits { require(DEPOSITS_ENABLED == true, "AaveStrategyV1::_deposit"); if (MAX_TOKENS_TO_DEPOSIT_WITHOUT_REINVEST > 0) { uint256 avaxRewards = _checkRewards(); if (avaxRewards > MAX_TOKENS_TO_DEPOSIT_WITHOUT_REINVEST) { _reinvest(avaxRewards); } } require( depositToken.transferFrom(account, address(this), amount), "AaveStrategyV1::transfer failed" ); _mint(account, getSharesForDepositTokens(amount)); _stakeDepositTokens(amount); emit Deposit(account, amount); } function _deposit(address account, uint256 amount) private onlyAllowedDeposits { require(DEPOSITS_ENABLED == true, "AaveStrategyV1::_deposit"); if (MAX_TOKENS_TO_DEPOSIT_WITHOUT_REINVEST > 0) { uint256 avaxRewards = _checkRewards(); if (avaxRewards > MAX_TOKENS_TO_DEPOSIT_WITHOUT_REINVEST) { _reinvest(avaxRewards); } } require( depositToken.transferFrom(account, address(this), amount), "AaveStrategyV1::transfer failed" ); _mint(account, getSharesForDepositTokens(amount)); _stakeDepositTokens(amount); emit Deposit(account, amount); } function _deposit(address account, uint256 amount) private onlyAllowedDeposits { require(DEPOSITS_ENABLED == true, "AaveStrategyV1::_deposit"); if (MAX_TOKENS_TO_DEPOSIT_WITHOUT_REINVEST > 0) { uint256 avaxRewards = _checkRewards(); if (avaxRewards > MAX_TOKENS_TO_DEPOSIT_WITHOUT_REINVEST) { _reinvest(avaxRewards); } } require( depositToken.transferFrom(account, address(this), amount), "AaveStrategyV1::transfer failed" ); _mint(account, getSharesForDepositTokens(amount)); _stakeDepositTokens(amount); emit Deposit(account, amount); } function withdraw(uint256 amount) external override { uint256 depositTokenAmount = getDepositTokensForShares(amount); require( depositTokenAmount > minMinting, "AaveStrategyV1::below minimum withdraw" ); if (depositTokenAmount > 0) { _burn(msg.sender, amount); uint256 withdrawnAmount = _withdrawDepositTokens(depositTokenAmount); _safeTransfer(address(depositToken), msg.sender, withdrawnAmount); emit Withdraw(msg.sender, withdrawnAmount); } } function withdraw(uint256 amount) external override { uint256 depositTokenAmount = getDepositTokensForShares(amount); require( depositTokenAmount > minMinting, "AaveStrategyV1::below minimum withdraw" ); if (depositTokenAmount > 0) { _burn(msg.sender, amount); uint256 withdrawnAmount = _withdrawDepositTokens(depositTokenAmount); _safeTransfer(address(depositToken), msg.sender, withdrawnAmount); emit Withdraw(msg.sender, withdrawnAmount); } } function _withdrawDepositTokens(uint256 amount) private returns (uint256) { _unrollDebt(amount); (uint256 balance, , ) = _getAccountData(); amount = amount > balance ? type(uint256).max : amount; uint256 withdrawn = tokenDelegator.withdraw( address(depositToken), amount, address(this) ); _rollupDebt(); return withdrawn; } function reinvest() external override onlyEOA { uint256 avaxRewards = _checkRewards(); require(avaxRewards >= MIN_TOKENS_TO_REINVEST, "AaveStrategyV1::reinvest"); _reinvest(avaxRewards); } function _reinvest(uint256 amount) private { address[] memory assets = new address[](2); assets[0] = avToken; assets[1] = avDebtToken; rewardController.claimRewards(assets, amount, address(this)); uint256 devFee = amount.mul(DEV_FEE_BIPS).div(BIPS_DIVISOR); if (devFee > 0) { _safeTransfer(address(rewardToken), devAddr, devFee); } uint256 adminFee = amount.mul(ADMIN_FEE_BIPS).div(BIPS_DIVISOR); if (adminFee > 0) { _safeTransfer(address(rewardToken), owner(), adminFee); } uint256 reinvestFee = amount.mul(REINVEST_REWARD_BIPS).div(BIPS_DIVISOR); if (reinvestFee > 0) { _safeTransfer(address(rewardToken), msg.sender, reinvestFee); } uint256 depositTokenAmount = DexLibrary.swap( amount.sub(devFee).sub(adminFee).sub(reinvestFee), address(rewardToken), address(depositToken), swapPairToken ); _stakeDepositTokens(depositTokenAmount); emit Reinvest(totalDeposits(), totalSupply); } function _reinvest(uint256 amount) private { address[] memory assets = new address[](2); assets[0] = avToken; assets[1] = avDebtToken; rewardController.claimRewards(assets, amount, address(this)); uint256 devFee = amount.mul(DEV_FEE_BIPS).div(BIPS_DIVISOR); if (devFee > 0) { _safeTransfer(address(rewardToken), devAddr, devFee); } uint256 adminFee = amount.mul(ADMIN_FEE_BIPS).div(BIPS_DIVISOR); if (adminFee > 0) { _safeTransfer(address(rewardToken), owner(), adminFee); } uint256 reinvestFee = amount.mul(REINVEST_REWARD_BIPS).div(BIPS_DIVISOR); if (reinvestFee > 0) { _safeTransfer(address(rewardToken), msg.sender, reinvestFee); } uint256 depositTokenAmount = DexLibrary.swap( amount.sub(devFee).sub(adminFee).sub(reinvestFee), address(rewardToken), address(depositToken), swapPairToken ); _stakeDepositTokens(depositTokenAmount); emit Reinvest(totalDeposits(), totalSupply); } function _reinvest(uint256 amount) private { address[] memory assets = new address[](2); assets[0] = avToken; assets[1] = avDebtToken; rewardController.claimRewards(assets, amount, address(this)); uint256 devFee = amount.mul(DEV_FEE_BIPS).div(BIPS_DIVISOR); if (devFee > 0) { _safeTransfer(address(rewardToken), devAddr, devFee); } uint256 adminFee = amount.mul(ADMIN_FEE_BIPS).div(BIPS_DIVISOR); if (adminFee > 0) { _safeTransfer(address(rewardToken), owner(), adminFee); } uint256 reinvestFee = amount.mul(REINVEST_REWARD_BIPS).div(BIPS_DIVISOR); if (reinvestFee > 0) { _safeTransfer(address(rewardToken), msg.sender, reinvestFee); } uint256 depositTokenAmount = DexLibrary.swap( amount.sub(devFee).sub(adminFee).sub(reinvestFee), address(rewardToken), address(depositToken), swapPairToken ); _stakeDepositTokens(depositTokenAmount); emit Reinvest(totalDeposits(), totalSupply); } function _reinvest(uint256 amount) private { address[] memory assets = new address[](2); assets[0] = avToken; assets[1] = avDebtToken; rewardController.claimRewards(assets, amount, address(this)); uint256 devFee = amount.mul(DEV_FEE_BIPS).div(BIPS_DIVISOR); if (devFee > 0) { _safeTransfer(address(rewardToken), devAddr, devFee); } uint256 adminFee = amount.mul(ADMIN_FEE_BIPS).div(BIPS_DIVISOR); if (adminFee > 0) { _safeTransfer(address(rewardToken), owner(), adminFee); } uint256 reinvestFee = amount.mul(REINVEST_REWARD_BIPS).div(BIPS_DIVISOR); if (reinvestFee > 0) { _safeTransfer(address(rewardToken), msg.sender, reinvestFee); } uint256 depositTokenAmount = DexLibrary.swap( amount.sub(devFee).sub(adminFee).sub(reinvestFee), address(rewardToken), address(depositToken), swapPairToken ); _stakeDepositTokens(depositTokenAmount); emit Reinvest(totalDeposits(), totalSupply); } function _rollupDebt() internal { (uint256 balance, uint256 borrowed, uint256 borrowable) = _getAccountData(); uint256 lendTarget = balance .sub(borrowed) .mul(leverageLevel.sub(safetyFactor)) .div(leverageBips); while (balance < lendTarget) { if (balance.add(borrowable) > lendTarget) { borrowable = lendTarget.sub(balance); } if (borrowable < minMinting) { break; } tokenDelegator.borrow( address(depositToken), borrowable, 0, address(this) ); tokenDelegator.deposit(address(depositToken), borrowable, address(this), 0); (balance, borrowed, borrowable) = _getAccountData(); } } function _rollupDebt() internal { (uint256 balance, uint256 borrowed, uint256 borrowable) = _getAccountData(); uint256 lendTarget = balance .sub(borrowed) .mul(leverageLevel.sub(safetyFactor)) .div(leverageBips); while (balance < lendTarget) { if (balance.add(borrowable) > lendTarget) { borrowable = lendTarget.sub(balance); } if (borrowable < minMinting) { break; } tokenDelegator.borrow( address(depositToken), borrowable, 0, address(this) ); tokenDelegator.deposit(address(depositToken), borrowable, address(this), 0); (balance, borrowed, borrowable) = _getAccountData(); } } function _rollupDebt() internal { (uint256 balance, uint256 borrowed, uint256 borrowable) = _getAccountData(); uint256 lendTarget = balance .sub(borrowed) .mul(leverageLevel.sub(safetyFactor)) .div(leverageBips); while (balance < lendTarget) { if (balance.add(borrowable) > lendTarget) { borrowable = lendTarget.sub(balance); } if (borrowable < minMinting) { break; } tokenDelegator.borrow( address(depositToken), borrowable, 0, address(this) ); tokenDelegator.deposit(address(depositToken), borrowable, address(this), 0); (balance, borrowed, borrowable) = _getAccountData(); } } function _rollupDebt() internal { (uint256 balance, uint256 borrowed, uint256 borrowable) = _getAccountData(); uint256 lendTarget = balance .sub(borrowed) .mul(leverageLevel.sub(safetyFactor)) .div(leverageBips); while (balance < lendTarget) { if (balance.add(borrowable) > lendTarget) { borrowable = lendTarget.sub(balance); } if (borrowable < minMinting) { break; } tokenDelegator.borrow( address(depositToken), borrowable, 0, address(this) ); tokenDelegator.deposit(address(depositToken), borrowable, address(this), 0); (balance, borrowed, borrowable) = _getAccountData(); } } function _getRedeemable( uint256 balance, uint256 borrowed, uint256 threshold ) internal pure returns (uint256) { return balance .sub(borrowed) .mul(1e18) .sub(borrowed.mul(13).div(10).mul(1e18).div(threshold).div(100000)) .div(1e18); } function _unrollDebt(uint256 amountToFreeUp) internal { (uint256 balance, uint256 borrowed, uint256 borrowable) = _getAccountData(); uint256 targetBorrow = balance .sub(borrowed) .sub(amountToFreeUp) .mul(leverageLevel.sub(safetyFactor)) .div(leverageBips) .sub(balance.sub(borrowed).sub(amountToFreeUp)); uint256 toRepay = borrowed.sub(targetBorrow); while (toRepay > 0) { uint256 unrollAmount = borrowable; if (unrollAmount > borrowed) { unrollAmount = borrowed; } tokenDelegator.withdraw(address(depositToken), unrollAmount, address(this)); tokenDelegator.repay(address(depositToken), unrollAmount, 2, address(this)); (balance, borrowed, borrowable) = _getAccountData(); if (targetBorrow >= borrowed) { break; } toRepay = borrowed.sub(targetBorrow); } } function _unrollDebt(uint256 amountToFreeUp) internal { (uint256 balance, uint256 borrowed, uint256 borrowable) = _getAccountData(); uint256 targetBorrow = balance .sub(borrowed) .sub(amountToFreeUp) .mul(leverageLevel.sub(safetyFactor)) .div(leverageBips) .sub(balance.sub(borrowed).sub(amountToFreeUp)); uint256 toRepay = borrowed.sub(targetBorrow); while (toRepay > 0) { uint256 unrollAmount = borrowable; if (unrollAmount > borrowed) { unrollAmount = borrowed; } tokenDelegator.withdraw(address(depositToken), unrollAmount, address(this)); tokenDelegator.repay(address(depositToken), unrollAmount, 2, address(this)); (balance, borrowed, borrowable) = _getAccountData(); if (targetBorrow >= borrowed) { break; } toRepay = borrowed.sub(targetBorrow); } } function _unrollDebt(uint256 amountToFreeUp) internal { (uint256 balance, uint256 borrowed, uint256 borrowable) = _getAccountData(); uint256 targetBorrow = balance .sub(borrowed) .sub(amountToFreeUp) .mul(leverageLevel.sub(safetyFactor)) .div(leverageBips) .sub(balance.sub(borrowed).sub(amountToFreeUp)); uint256 toRepay = borrowed.sub(targetBorrow); while (toRepay > 0) { uint256 unrollAmount = borrowable; if (unrollAmount > borrowed) { unrollAmount = borrowed; } tokenDelegator.withdraw(address(depositToken), unrollAmount, address(this)); tokenDelegator.repay(address(depositToken), unrollAmount, 2, address(this)); (balance, borrowed, borrowable) = _getAccountData(); if (targetBorrow >= borrowed) { break; } toRepay = borrowed.sub(targetBorrow); } } function _unrollDebt(uint256 amountToFreeUp) internal { (uint256 balance, uint256 borrowed, uint256 borrowable) = _getAccountData(); uint256 targetBorrow = balance .sub(borrowed) .sub(amountToFreeUp) .mul(leverageLevel.sub(safetyFactor)) .div(leverageBips) .sub(balance.sub(borrowed).sub(amountToFreeUp)); uint256 toRepay = borrowed.sub(targetBorrow); while (toRepay > 0) { uint256 unrollAmount = borrowable; if (unrollAmount > borrowed) { unrollAmount = borrowed; } tokenDelegator.withdraw(address(depositToken), unrollAmount, address(this)); tokenDelegator.repay(address(depositToken), unrollAmount, 2, address(this)); (balance, borrowed, borrowable) = _getAccountData(); if (targetBorrow >= borrowed) { break; } toRepay = borrowed.sub(targetBorrow); } } function _stakeDepositTokens(uint256 amount) private { require(amount > 0, "AaveStrategyV1::_stakeDepositTokens"); tokenDelegator.deposit(address(depositToken), amount, address(this), 0); _rollupDebt(); } function _safeTransfer( address token, address to, uint256 value ) private { require( IERC20(token).transfer(to, value), "AaveStrategyV1::TRANSFER_FROM_FAILED" ); } function _checkRewards() internal view returns (uint256 avaxAmount) { address[] memory assets = new address[](2); assets[0] = avToken; assets[1] = avDebtToken; return rewardController.getRewardsBalance(assets, address(this)); } function checkReward() public view override returns (uint256) { return _checkRewards(); } function getActualLeverage() public view returns (uint256) { (uint256 balance, uint256 borrowed, ) = _getAccountData(); return balance.mul(1e18).div(balance.sub(borrowed)); } function estimateDeployedBalance() external view override returns (uint256) { return totalDeposits(); } function rescueDeployedFunds(uint256 minReturnAmountAccepted, bool disableDeposits) external override onlyOwner { uint256 balanceBefore = depositToken.balanceOf(address(this)); (uint256 balance, uint256 borrowed, ) = _getAccountData(); _unrollDebt(balance.sub(borrowed)); tokenDelegator.withdraw(address(depositToken), type(uint256).max, address(this)); uint256 balanceAfter = depositToken.balanceOf(address(this)); require( balanceAfter.sub(balanceBefore) >= minReturnAmountAccepted, "AaveStrategyV1::rescueDeployedFunds" ); emit Reinvest(totalDeposits(), totalSupply); if (DEPOSITS_ENABLED == true && disableDeposits == true) { updateDepositsEnabled(false); } } function rescueDeployedFunds(uint256 minReturnAmountAccepted, bool disableDeposits) external override onlyOwner { uint256 balanceBefore = depositToken.balanceOf(address(this)); (uint256 balance, uint256 borrowed, ) = _getAccountData(); _unrollDebt(balance.sub(borrowed)); tokenDelegator.withdraw(address(depositToken), type(uint256).max, address(this)); uint256 balanceAfter = depositToken.balanceOf(address(this)); require( balanceAfter.sub(balanceBefore) >= minReturnAmountAccepted, "AaveStrategyV1::rescueDeployedFunds" ); emit Reinvest(totalDeposits(), totalSupply); if (DEPOSITS_ENABLED == true && disableDeposits == true) { updateDepositsEnabled(false); } } }
4,619,008
[ 1, 37, 836, 6252, 364, 4232, 39, 3462, 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, 16351, 432, 836, 4525, 58, 21, 353, 1624, 581, 4525, 58, 22, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 203, 565, 467, 37, 836, 382, 2998, 3606, 2933, 3238, 19890, 2933, 31, 203, 565, 467, 48, 2846, 2864, 3238, 1147, 15608, 639, 31, 203, 565, 2971, 1826, 3238, 7720, 4154, 1345, 31, 203, 565, 467, 59, 5856, 2501, 3238, 5381, 678, 5856, 2501, 273, 467, 59, 5856, 2501, 12, 20, 20029, 6938, 74, 6028, 5284, 23, 39, 21, 73, 27, 7140, 23, 4449, 42, 6840, 5877, 37, 21, 38, 5608, 41, 5324, 70, 7140, 16894, 6028, 71, 27, 1769, 203, 565, 2254, 5034, 3238, 884, 5682, 2355, 31, 203, 565, 2254, 5034, 3238, 24179, 6837, 31, 203, 565, 2254, 5034, 3238, 884, 5682, 38, 7146, 31, 203, 565, 2254, 5034, 3238, 1131, 49, 474, 310, 31, 203, 565, 1758, 3238, 1712, 1345, 31, 203, 565, 1758, 3238, 1712, 758, 23602, 1345, 31, 203, 203, 565, 3885, 12, 203, 3639, 533, 3778, 389, 529, 16, 203, 3639, 1758, 389, 266, 2913, 2933, 16, 203, 3639, 1758, 389, 2316, 15608, 639, 16, 203, 3639, 1758, 389, 323, 1724, 1345, 16, 203, 3639, 1758, 389, 22270, 4154, 1345, 16, 203, 3639, 1758, 389, 842, 1345, 16, 203, 3639, 1758, 389, 842, 758, 23602, 1345, 16, 203, 3639, 1758, 389, 8584, 292, 975, 16, 203, 3639, 2254, 5034, 389, 298, 5682, 2355, 16, 203, 3639, 2254, 5034, 389, 87, 1727, 14369, 6837, 16, 203, 3639, 2254, 5034, 389, 298, 5682, 38, 7146, 16, 203, 2 ]
// File: @aragon/os/contracts/acl/IACLOracle.sol /* * SPDX-License-Identifier: MIT */ pragma solidity ^0.4.24; interface IACLOracle { function canPerform(address who, address where, bytes32 what, uint256[] how) external view returns (bool); } // File: @aragon/os/contracts/acl/IACL.sol /* * SPDX-License-Identifier: MIT */ pragma solidity ^0.4.24; interface IACL { function initialize(address permissionsCreator) external; // TODO: this should be external // See https://github.com/ethereum/solidity/issues/4832 function hasPermission(address who, address where, bytes32 what, bytes how) public view returns (bool); } // File: @aragon/os/contracts/common/IVaultRecoverable.sol /* * SPDX-License-Identifier: MIT */ pragma solidity ^0.4.24; interface IVaultRecoverable { event RecoverToVault(address indexed vault, address indexed token, uint256 amount); function transferToVault(address token) external; function allowRecoverability(address token) external view returns (bool); function getRecoveryVault() external view returns (address); } // File: @aragon/os/contracts/kernel/IKernel.sol /* * SPDX-License-Identifier: MIT */ pragma solidity ^0.4.24; interface IKernelEvents { event SetApp(bytes32 indexed namespace, bytes32 indexed appId, address app); } // This should be an interface, but interfaces can't inherit yet :( contract IKernel is IKernelEvents, IVaultRecoverable { function acl() public view returns (IACL); function hasPermission(address who, address where, bytes32 what, bytes how) public view returns (bool); function setApp(bytes32 namespace, bytes32 appId, address app) public; function getApp(bytes32 namespace, bytes32 appId) public view returns (address); } // File: @aragon/os/contracts/apps/IAragonApp.sol /* * SPDX-License-Identifier: MIT */ pragma solidity ^0.4.24; contract IAragonApp { // Includes appId and kernel methods: bytes4 internal constant ARAGON_APP_INTERFACE_ID = bytes4(0x54053e6c); function kernel() public view returns (IKernel); function appId() public view returns (bytes32); } // File: @aragon/os/contracts/common/UnstructuredStorage.sol /* * SPDX-License-Identifier: MIT */ pragma solidity ^0.4.24; library UnstructuredStorage { function getStorageBool(bytes32 position) internal view returns (bool data) { assembly { data := sload(position) } } function getStorageAddress(bytes32 position) internal view returns (address data) { assembly { data := sload(position) } } function getStorageBytes32(bytes32 position) internal view returns (bytes32 data) { assembly { data := sload(position) } } function getStorageUint256(bytes32 position) internal view returns (uint256 data) { assembly { data := sload(position) } } function setStorageBool(bytes32 position, bool data) internal { assembly { sstore(position, data) } } function setStorageAddress(bytes32 position, address data) internal { assembly { sstore(position, data) } } function setStorageBytes32(bytes32 position, bytes32 data) internal { assembly { sstore(position, data) } } function setStorageUint256(bytes32 position, uint256 data) internal { assembly { sstore(position, data) } } } // File: @aragon/os/contracts/apps/AppStorage.sol /* * SPDX-License-Identifier: MIT */ pragma solidity ^0.4.24; contract AppStorage is IAragonApp { using UnstructuredStorage for bytes32; /* Hardcoded constants to save gas bytes32 internal constant KERNEL_POSITION = keccak256("aragonOS.appStorage.kernel"); bytes32 internal constant APP_ID_POSITION = keccak256("aragonOS.appStorage.appId"); */ bytes32 internal constant KERNEL_POSITION = 0x4172f0f7d2289153072b0a6ca36959e0cbe2efc3afe50fc81636caa96338137b; bytes32 internal constant APP_ID_POSITION = 0xd625496217aa6a3453eecb9c3489dc5a53e6c67b444329ea2b2cbc9ff547639b; function kernel() public view returns (IKernel) { return IKernel(KERNEL_POSITION.getStorageAddress()); } function appId() public view returns (bytes32) { return APP_ID_POSITION.getStorageBytes32(); } function setKernel(IKernel _kernel) internal { KERNEL_POSITION.setStorageAddress(address(_kernel)); } function setAppId(bytes32 _appId) internal { APP_ID_POSITION.setStorageBytes32(_appId); } } // File: @aragon/os/contracts/acl/ACLSyntaxSugar.sol /* * SPDX-License-Identifier: MIT */ pragma solidity ^0.4.24; contract ACLSyntaxSugar { function arr() internal pure returns (uint256[]) { return new uint256[](0); } function arr(bytes32 _a) internal pure returns (uint256[] r) { return arr(uint256(_a)); } function arr(bytes32 _a, bytes32 _b) internal pure returns (uint256[] r) { return arr(uint256(_a), uint256(_b)); } function arr(address _a) internal pure returns (uint256[] r) { return arr(uint256(_a)); } function arr(address _a, address _b) internal pure returns (uint256[] r) { return arr(uint256(_a), uint256(_b)); } function arr(address _a, uint256 _b, uint256 _c) internal pure returns (uint256[] r) { return arr(uint256(_a), _b, _c); } function arr(address _a, uint256 _b, uint256 _c, uint256 _d) internal pure returns (uint256[] r) { return arr(uint256(_a), _b, _c, _d); } function arr(address _a, uint256 _b) internal pure returns (uint256[] r) { return arr(uint256(_a), uint256(_b)); } function arr(address _a, address _b, uint256 _c, uint256 _d, uint256 _e) internal pure returns (uint256[] r) { return arr(uint256(_a), uint256(_b), _c, _d, _e); } function arr(address _a, address _b, address _c) internal pure returns (uint256[] r) { return arr(uint256(_a), uint256(_b), uint256(_c)); } function arr(address _a, address _b, uint256 _c) internal pure returns (uint256[] r) { return arr(uint256(_a), uint256(_b), uint256(_c)); } function arr(uint256 _a) internal pure returns (uint256[] r) { r = new uint256[](1); r[0] = _a; } function arr(uint256 _a, uint256 _b) internal pure returns (uint256[] r) { r = new uint256[](2); r[0] = _a; r[1] = _b; } function arr(uint256 _a, uint256 _b, uint256 _c) internal pure returns (uint256[] r) { r = new uint256[](3); r[0] = _a; r[1] = _b; r[2] = _c; } function arr(uint256 _a, uint256 _b, uint256 _c, uint256 _d) internal pure returns (uint256[] r) { r = new uint256[](4); r[0] = _a; r[1] = _b; r[2] = _c; r[3] = _d; } function arr(uint256 _a, uint256 _b, uint256 _c, uint256 _d, uint256 _e) internal pure returns (uint256[] r) { r = new uint256[](5); r[0] = _a; r[1] = _b; r[2] = _c; r[3] = _d; r[4] = _e; } } contract ACLHelpers { function decodeParamOp(uint256 _x) internal pure returns (uint8 b) { return uint8(_x >> (8 * 30)); } function decodeParamId(uint256 _x) internal pure returns (uint8 b) { return uint8(_x >> (8 * 31)); } function decodeParamsList(uint256 _x) internal pure returns (uint32 a, uint32 b, uint32 c) { a = uint32(_x); b = uint32(_x >> (8 * 4)); c = uint32(_x >> (8 * 8)); } } // File: @aragon/os/contracts/common/Uint256Helpers.sol pragma solidity ^0.4.24; library Uint256Helpers { uint256 private constant MAX_UINT64 = uint64(-1); string private constant ERROR_NUMBER_TOO_BIG = "UINT64_NUMBER_TOO_BIG"; function toUint64(uint256 a) internal pure returns (uint64) { require(a <= MAX_UINT64, ERROR_NUMBER_TOO_BIG); return uint64(a); } } // File: @aragon/os/contracts/common/TimeHelpers.sol /* * SPDX-License-Identifier: MIT */ pragma solidity ^0.4.24; contract TimeHelpers { using Uint256Helpers for uint256; /** * @dev Returns the current block number. * Using a function rather than `block.number` allows us to easily mock the block number in * tests. */ function getBlockNumber() internal view returns (uint256) { return block.number; } /** * @dev Returns the current block number, converted to uint64. * Using a function rather than `block.number` allows us to easily mock the block number in * tests. */ function getBlockNumber64() internal view returns (uint64) { return getBlockNumber().toUint64(); } /** * @dev Returns the current timestamp. * Using a function rather than `block.timestamp` allows us to easily mock it in * tests. */ function getTimestamp() internal view returns (uint256) { return block.timestamp; // solium-disable-line security/no-block-members } /** * @dev Returns the current timestamp, converted to uint64. * Using a function rather than `block.timestamp` allows us to easily mock it in * tests. */ function getTimestamp64() internal view returns (uint64) { return getTimestamp().toUint64(); } } // File: @aragon/os/contracts/common/Initializable.sol /* * SPDX-License-Identifier: MIT */ pragma solidity ^0.4.24; contract Initializable is TimeHelpers { using UnstructuredStorage for bytes32; // keccak256("aragonOS.initializable.initializationBlock") bytes32 internal constant INITIALIZATION_BLOCK_POSITION = 0xebb05b386a8d34882b8711d156f463690983dc47815980fb82aeeff1aa43579e; string private constant ERROR_ALREADY_INITIALIZED = "INIT_ALREADY_INITIALIZED"; string private constant ERROR_NOT_INITIALIZED = "INIT_NOT_INITIALIZED"; modifier onlyInit { require(getInitializationBlock() == 0, ERROR_ALREADY_INITIALIZED); _; } modifier isInitialized { require(hasInitialized(), ERROR_NOT_INITIALIZED); _; } /** * @return Block number in which the contract was initialized */ function getInitializationBlock() public view returns (uint256) { return INITIALIZATION_BLOCK_POSITION.getStorageUint256(); } /** * @return Whether the contract has been initialized by the time of the current block */ function hasInitialized() public view returns (bool) { uint256 initializationBlock = getInitializationBlock(); return initializationBlock != 0 && getBlockNumber() >= initializationBlock; } /** * @dev Function to be called by top level contract after initialization has finished. */ function initialized() internal onlyInit { INITIALIZATION_BLOCK_POSITION.setStorageUint256(getBlockNumber()); } /** * @dev Function to be called by top level contract after initialization to enable the contract * at a future block number rather than immediately. */ function initializedAt(uint256 _blockNumber) internal onlyInit { INITIALIZATION_BLOCK_POSITION.setStorageUint256(_blockNumber); } } // File: @aragon/os/contracts/common/Petrifiable.sol /* * SPDX-License-Identifier: MIT */ pragma solidity ^0.4.24; contract Petrifiable is Initializable { // Use block UINT256_MAX (which should be never) as the initializable date uint256 internal constant PETRIFIED_BLOCK = uint256(-1); function isPetrified() public view returns (bool) { return getInitializationBlock() == PETRIFIED_BLOCK; } /** * @dev Function to be called by top level contract to prevent being initialized. * Useful for freezing base contracts when they're used behind proxies. */ function petrify() internal onlyInit { initializedAt(PETRIFIED_BLOCK); } } // File: @aragon/os/contracts/common/Autopetrified.sol /* * SPDX-License-Identifier: MIT */ pragma solidity ^0.4.24; contract Autopetrified is Petrifiable { constructor() public { // Immediately petrify base (non-proxy) instances of inherited contracts on deploy. // This renders them uninitializable (and unusable without a proxy). petrify(); } } // File: @aragon/os/contracts/common/ConversionHelpers.sol pragma solidity ^0.4.24; library ConversionHelpers { string private constant ERROR_IMPROPER_LENGTH = "CONVERSION_IMPROPER_LENGTH"; function dangerouslyCastUintArrayToBytes(uint256[] memory _input) internal pure returns (bytes memory output) { // Force cast the uint256[] into a bytes array, by overwriting its length // Note that the bytes array doesn't need to be initialized as we immediately overwrite it // with the input and a new length. The input becomes invalid from this point forward. uint256 byteLength = _input.length * 32; assembly { output := _input mstore(output, byteLength) } } function dangerouslyCastBytesToUintArray(bytes memory _input) internal pure returns (uint256[] memory output) { // Force cast the bytes array into a uint256[], by overwriting its length // Note that the uint256[] doesn't need to be initialized as we immediately overwrite it // with the input and a new length. The input becomes invalid from this point forward. uint256 intsLength = _input.length / 32; require(_input.length == intsLength * 32, ERROR_IMPROPER_LENGTH); assembly { output := _input mstore(output, intsLength) } } } // File: @aragon/os/contracts/common/ReentrancyGuard.sol /* * SPDX-License-Identifier: MIT */ pragma solidity ^0.4.24; contract ReentrancyGuard { using UnstructuredStorage for bytes32; /* Hardcoded constants to save gas bytes32 internal constant REENTRANCY_MUTEX_POSITION = keccak256("aragonOS.reentrancyGuard.mutex"); */ bytes32 private constant REENTRANCY_MUTEX_POSITION = 0xe855346402235fdd185c890e68d2c4ecad599b88587635ee285bce2fda58dacb; string private constant ERROR_REENTRANT = "REENTRANCY_REENTRANT_CALL"; modifier nonReentrant() { // Ensure mutex is unlocked require(!REENTRANCY_MUTEX_POSITION.getStorageBool(), ERROR_REENTRANT); // Lock mutex before function call REENTRANCY_MUTEX_POSITION.setStorageBool(true); // Perform function call _; // Unlock mutex after function call REENTRANCY_MUTEX_POSITION.setStorageBool(false); } } // File: @aragon/os/contracts/lib/token/ERC20.sol // See https://github.com/OpenZeppelin/openzeppelin-solidity/blob/a9f910d34f0ab33a1ae5e714f69f9596a02b4d91/contracts/token/ERC20/ERC20.sol pragma solidity ^0.4.24; /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 { function totalSupply() public view returns (uint256); function balanceOf(address _who) public view returns (uint256); function allowance(address _owner, address _spender) public view returns (uint256); function transfer(address _to, uint256 _value) public returns (bool); function approve(address _spender, uint256 _value) public returns (bool); function transferFrom(address _from, address _to, uint256 _value) public returns (bool); event Transfer( address indexed from, address indexed to, uint256 value ); event Approval( address indexed owner, address indexed spender, uint256 value ); } // File: @aragon/os/contracts/common/EtherTokenConstant.sol /* * SPDX-License-Identifier: MIT */ pragma solidity ^0.4.24; // aragonOS and aragon-apps rely on address(0) to denote native ETH, in // contracts where both tokens and ETH are accepted contract EtherTokenConstant { address internal constant ETH = address(0); } // File: @aragon/os/contracts/common/IsContract.sol /* * SPDX-License-Identifier: MIT */ pragma solidity ^0.4.24; contract IsContract { /* * NOTE: this should NEVER be used for authentication * (see pitfalls: https://github.com/fergarrui/ethereum-security/tree/master/contracts/extcodesize). * * This is only intended to be used as a sanity check that an address is actually a contract, * RATHER THAN an address not being a contract. */ function isContract(address _target) internal view returns (bool) { if (_target == address(0)) { return false; } uint256 size; assembly { size := extcodesize(_target) } return size > 0; } } // File: @aragon/os/contracts/common/SafeERC20.sol // Inspired by AdEx (https://github.com/AdExNetwork/adex-protocol-eth/blob/b9df617829661a7518ee10f4cb6c4108659dd6d5/contracts/libs/SafeERC20.sol) // and 0x (https://github.com/0xProject/0x-monorepo/blob/737d1dc54d72872e24abce5a1dbe1b66d35fa21a/contracts/protocol/contracts/protocol/AssetProxy/ERC20Proxy.sol#L143) pragma solidity ^0.4.24; library SafeERC20 { // Before 0.5, solidity has a mismatch between `address.transfer()` and `token.transfer()`: // https://github.com/ethereum/solidity/issues/3544 bytes4 private constant TRANSFER_SELECTOR = 0xa9059cbb; string private constant ERROR_TOKEN_BALANCE_REVERTED = "SAFE_ERC_20_BALANCE_REVERTED"; string private constant ERROR_TOKEN_ALLOWANCE_REVERTED = "SAFE_ERC_20_ALLOWANCE_REVERTED"; function invokeAndCheckSuccess(address _addr, bytes memory _calldata) private returns (bool) { bool ret; assembly { let ptr := mload(0x40) // free memory pointer let success := call( gas, // forward all gas _addr, // address 0, // no value add(_calldata, 0x20), // calldata start mload(_calldata), // calldata length ptr, // write output over free memory 0x20 // uint256 return ) if gt(success, 0) { // Check number of bytes returned from last function call switch returndatasize // No bytes returned: assume success case 0 { ret := 1 } // 32 bytes returned: check if non-zero case 0x20 { // Only return success if returned data was true // Already have output in ptr ret := eq(mload(ptr), 1) } // Not sure what was returned: don't mark as success default { } } } return ret; } function staticInvoke(address _addr, bytes memory _calldata) private view returns (bool, uint256) { bool success; uint256 ret; assembly { let ptr := mload(0x40) // free memory pointer success := staticcall( gas, // forward all gas _addr, // address add(_calldata, 0x20), // calldata start mload(_calldata), // calldata length ptr, // write output over free memory 0x20 // uint256 return ) if gt(success, 0) { ret := mload(ptr) } } return (success, ret); } /** * @dev Same as a standards-compliant ERC20.transfer() that never reverts (returns false). * Note that this makes an external call to the token. */ function safeTransfer(ERC20 _token, address _to, uint256 _amount) internal returns (bool) { bytes memory transferCallData = abi.encodeWithSelector( TRANSFER_SELECTOR, _to, _amount ); return invokeAndCheckSuccess(_token, transferCallData); } /** * @dev Same as a standards-compliant ERC20.transferFrom() that never reverts (returns false). * Note that this makes an external call to the token. */ function safeTransferFrom(ERC20 _token, address _from, address _to, uint256 _amount) internal returns (bool) { bytes memory transferFromCallData = abi.encodeWithSelector( _token.transferFrom.selector, _from, _to, _amount ); return invokeAndCheckSuccess(_token, transferFromCallData); } /** * @dev Same as a standards-compliant ERC20.approve() that never reverts (returns false). * Note that this makes an external call to the token. */ function safeApprove(ERC20 _token, address _spender, uint256 _amount) internal returns (bool) { bytes memory approveCallData = abi.encodeWithSelector( _token.approve.selector, _spender, _amount ); return invokeAndCheckSuccess(_token, approveCallData); } /** * @dev Static call into ERC20.balanceOf(). * Reverts if the call fails for some reason (should never fail). */ function staticBalanceOf(ERC20 _token, address _owner) internal view returns (uint256) { bytes memory balanceOfCallData = abi.encodeWithSelector( _token.balanceOf.selector, _owner ); (bool success, uint256 tokenBalance) = staticInvoke(_token, balanceOfCallData); require(success, ERROR_TOKEN_BALANCE_REVERTED); return tokenBalance; } /** * @dev Static call into ERC20.allowance(). * Reverts if the call fails for some reason (should never fail). */ function staticAllowance(ERC20 _token, address _owner, address _spender) internal view returns (uint256) { bytes memory allowanceCallData = abi.encodeWithSelector( _token.allowance.selector, _owner, _spender ); (bool success, uint256 allowance) = staticInvoke(_token, allowanceCallData); require(success, ERROR_TOKEN_ALLOWANCE_REVERTED); return allowance; } /** * @dev Static call into ERC20.totalSupply(). * Reverts if the call fails for some reason (should never fail). */ function staticTotalSupply(ERC20 _token) internal view returns (uint256) { bytes memory totalSupplyCallData = abi.encodeWithSelector(_token.totalSupply.selector); (bool success, uint256 totalSupply) = staticInvoke(_token, totalSupplyCallData); require(success, ERROR_TOKEN_ALLOWANCE_REVERTED); return totalSupply; } } // File: @aragon/os/contracts/common/VaultRecoverable.sol /* * SPDX-License-Identifier: MIT */ pragma solidity ^0.4.24; contract VaultRecoverable is IVaultRecoverable, EtherTokenConstant, IsContract { using SafeERC20 for ERC20; string private constant ERROR_DISALLOWED = "RECOVER_DISALLOWED"; string private constant ERROR_VAULT_NOT_CONTRACT = "RECOVER_VAULT_NOT_CONTRACT"; string private constant ERROR_TOKEN_TRANSFER_FAILED = "RECOVER_TOKEN_TRANSFER_FAILED"; /** * @notice Send funds to recovery Vault. This contract should never receive funds, * but in case it does, this function allows one to recover them. * @param _token Token balance to be sent to recovery vault. */ function transferToVault(address _token) external { require(allowRecoverability(_token), ERROR_DISALLOWED); address vault = getRecoveryVault(); require(isContract(vault), ERROR_VAULT_NOT_CONTRACT); uint256 balance; if (_token == ETH) { balance = address(this).balance; vault.transfer(balance); } else { ERC20 token = ERC20(_token); balance = token.staticBalanceOf(this); require(token.safeTransfer(vault, balance), ERROR_TOKEN_TRANSFER_FAILED); } emit RecoverToVault(vault, _token, balance); } /** * @dev By default deriving from AragonApp makes it recoverable * @param token Token address that would be recovered * @return bool whether the app allows the recovery */ function allowRecoverability(address token) public view returns (bool) { return true; } // Cast non-implemented interface to be public so we can use it internally function getRecoveryVault() public view returns (address); } // File: @aragon/os/contracts/evmscript/IEVMScriptExecutor.sol /* * SPDX-License-Identifier: MIT */ pragma solidity ^0.4.24; interface IEVMScriptExecutor { function execScript(bytes script, bytes input, address[] blacklist) external returns (bytes); function executorType() external pure returns (bytes32); } // File: @aragon/os/contracts/evmscript/IEVMScriptRegistry.sol /* * SPDX-License-Identifier: MIT */ pragma solidity ^0.4.24; contract EVMScriptRegistryConstants { /* Hardcoded constants to save gas bytes32 internal constant EVMSCRIPT_REGISTRY_APP_ID = apmNamehash("evmreg"); */ bytes32 internal constant EVMSCRIPT_REGISTRY_APP_ID = 0xddbcfd564f642ab5627cf68b9b7d374fb4f8a36e941a75d89c87998cef03bd61; } interface IEVMScriptRegistry { function addScriptExecutor(IEVMScriptExecutor executor) external returns (uint id); function disableScriptExecutor(uint256 executorId) external; // TODO: this should be external // See https://github.com/ethereum/solidity/issues/4832 function getScriptExecutor(bytes script) public view returns (IEVMScriptExecutor); } // File: @aragon/os/contracts/kernel/KernelConstants.sol /* * SPDX-License-Identifier: MIT */ pragma solidity ^0.4.24; contract KernelAppIds { /* Hardcoded constants to save gas bytes32 internal constant KERNEL_CORE_APP_ID = apmNamehash("kernel"); bytes32 internal constant KERNEL_DEFAULT_ACL_APP_ID = apmNamehash("acl"); bytes32 internal constant KERNEL_DEFAULT_VAULT_APP_ID = apmNamehash("vault"); */ bytes32 internal constant KERNEL_CORE_APP_ID = 0x3b4bf6bf3ad5000ecf0f989d5befde585c6860fea3e574a4fab4c49d1c177d9c; bytes32 internal constant KERNEL_DEFAULT_ACL_APP_ID = 0xe3262375f45a6e2026b7e7b18c2b807434f2508fe1a2a3dfb493c7df8f4aad6a; bytes32 internal constant KERNEL_DEFAULT_VAULT_APP_ID = 0x7e852e0fcfce6551c13800f1e7476f982525c2b5277ba14b24339c68416336d1; } contract KernelNamespaceConstants { /* Hardcoded constants to save gas bytes32 internal constant KERNEL_CORE_NAMESPACE = keccak256("core"); bytes32 internal constant KERNEL_APP_BASES_NAMESPACE = keccak256("base"); bytes32 internal constant KERNEL_APP_ADDR_NAMESPACE = keccak256("app"); */ bytes32 internal constant KERNEL_CORE_NAMESPACE = 0xc681a85306374a5ab27f0bbc385296a54bcd314a1948b6cf61c4ea1bc44bb9f8; bytes32 internal constant KERNEL_APP_BASES_NAMESPACE = 0xf1f3eb40f5bc1ad1344716ced8b8a0431d840b5783aea1fd01786bc26f35ac0f; bytes32 internal constant KERNEL_APP_ADDR_NAMESPACE = 0xd6f028ca0e8edb4a8c9757ca4fdccab25fa1e0317da1188108f7d2dee14902fb; } // File: @aragon/os/contracts/evmscript/EVMScriptRunner.sol /* * SPDX-License-Identifier: MIT */ pragma solidity ^0.4.24; contract EVMScriptRunner is AppStorage, Initializable, EVMScriptRegistryConstants, KernelNamespaceConstants { string private constant ERROR_EXECUTOR_UNAVAILABLE = "EVMRUN_EXECUTOR_UNAVAILABLE"; string private constant ERROR_PROTECTED_STATE_MODIFIED = "EVMRUN_PROTECTED_STATE_MODIFIED"; /* This is manually crafted in assembly string private constant ERROR_EXECUTOR_INVALID_RETURN = "EVMRUN_EXECUTOR_INVALID_RETURN"; */ event ScriptResult(address indexed executor, bytes script, bytes input, bytes returnData); function getEVMScriptExecutor(bytes _script) public view returns (IEVMScriptExecutor) { return IEVMScriptExecutor(getEVMScriptRegistry().getScriptExecutor(_script)); } function getEVMScriptRegistry() public view returns (IEVMScriptRegistry) { address registryAddr = kernel().getApp(KERNEL_APP_ADDR_NAMESPACE, EVMSCRIPT_REGISTRY_APP_ID); return IEVMScriptRegistry(registryAddr); } function runScript(bytes _script, bytes _input, address[] _blacklist) internal isInitialized protectState returns (bytes) { IEVMScriptExecutor executor = getEVMScriptExecutor(_script); require(address(executor) != address(0), ERROR_EXECUTOR_UNAVAILABLE); bytes4 sig = executor.execScript.selector; bytes memory data = abi.encodeWithSelector(sig, _script, _input, _blacklist); bytes memory output; assembly { let success := delegatecall( gas, // forward all gas executor, // address add(data, 0x20), // calldata start mload(data), // calldata length 0, // don't write output (we'll handle this ourselves) 0 // don't write output ) output := mload(0x40) // free mem ptr get switch success case 0 { // If the call errored, forward its full error data returndatacopy(output, 0, returndatasize) revert(output, returndatasize) } default { switch gt(returndatasize, 0x3f) case 0 { // Need at least 0x40 bytes returned for properly ABI-encoded bytes values, // revert with "EVMRUN_EXECUTOR_INVALID_RETURN" // See remix: doing a `revert("EVMRUN_EXECUTOR_INVALID_RETURN")` always results in // this memory layout mstore(output, 0x08c379a000000000000000000000000000000000000000000000000000000000) // error identifier mstore(add(output, 0x04), 0x0000000000000000000000000000000000000000000000000000000000000020) // starting offset mstore(add(output, 0x24), 0x000000000000000000000000000000000000000000000000000000000000001e) // reason length mstore(add(output, 0x44), 0x45564d52554e5f4558454355544f525f494e56414c49445f52455455524e0000) // reason revert(output, 100) // 100 = 4 + 3 * 32 (error identifier + 3 words for the ABI encoded error) } default { // Copy result // // Needs to perform an ABI decode for the expected `bytes` return type of // `executor.execScript()` as solidity will automatically ABI encode the returned bytes as: // [ position of the first dynamic length return value = 0x20 (32 bytes) ] // [ output length (32 bytes) ] // [ output content (N bytes) ] // // Perform the ABI decode by ignoring the first 32 bytes of the return data let copysize := sub(returndatasize, 0x20) returndatacopy(output, 0x20, copysize) mstore(0x40, add(output, copysize)) // free mem ptr set } } } emit ScriptResult(address(executor), _script, _input, output); return output; } modifier protectState { address preKernel = address(kernel()); bytes32 preAppId = appId(); _; // exec require(address(kernel()) == preKernel, ERROR_PROTECTED_STATE_MODIFIED); require(appId() == preAppId, ERROR_PROTECTED_STATE_MODIFIED); } } // File: @aragon/os/contracts/lib/standards/ERC165.sol /* * SPDX-License-Identifier: MIT */ pragma solidity ^0.4.24; contract ERC165 { // Includes supportsInterface method: bytes4 internal constant ERC165_INTERFACE_ID = bytes4(0x01ffc9a7); /** * @dev Query if a contract implements a certain interface * @param _interfaceId The interface identifier being queried, as specified in ERC-165 * @return True if the contract implements the requested interface and if its not 0xffffffff, false otherwise */ function supportsInterface(bytes4 _interfaceId) public pure returns (bool) { return _interfaceId == ERC165_INTERFACE_ID; } } // File: @aragon/os/contracts/apps/AragonApp.sol /* * SPDX-License-Identifier: MIT */ pragma solidity ^0.4.24; // Contracts inheriting from AragonApp are, by default, immediately petrified upon deployment so // that they can never be initialized. // Unless overriden, this behaviour enforces those contracts to be usable only behind an AppProxy. // ReentrancyGuard, EVMScriptRunner, and ACLSyntaxSugar are not directly used by this contract, but // are included so that they are automatically usable by subclassing contracts contract AragonApp is ERC165, AppStorage, Autopetrified, VaultRecoverable, ReentrancyGuard, EVMScriptRunner, ACLSyntaxSugar { string private constant ERROR_AUTH_FAILED = "APP_AUTH_FAILED"; modifier auth(bytes32 _role) { require(canPerform(msg.sender, _role, new uint256[](0)), ERROR_AUTH_FAILED); _; } modifier authP(bytes32 _role, uint256[] _params) { require(canPerform(msg.sender, _role, _params), ERROR_AUTH_FAILED); _; } /** * @dev Check whether an action can be performed by a sender for a particular role on this app * @param _sender Sender of the call * @param _role Role on this app * @param _params Permission params for the role * @return Boolean indicating whether the sender has the permissions to perform the action. * Always returns false if the app hasn't been initialized yet. */ function canPerform(address _sender, bytes32 _role, uint256[] _params) public view returns (bool) { if (!hasInitialized()) { return false; } IKernel linkedKernel = kernel(); if (address(linkedKernel) == address(0)) { return false; } return linkedKernel.hasPermission( _sender, address(this), _role, ConversionHelpers.dangerouslyCastUintArrayToBytes(_params) ); } /** * @dev Get the recovery vault for the app * @return Recovery vault address for the app */ function getRecoveryVault() public view returns (address) { // Funds recovery via a vault is only available when used with a kernel return kernel().getRecoveryVault(); // if kernel is not set, it will revert } /** * @dev Query if a contract implements a certain interface * @param _interfaceId The interface identifier being queried, as specified in ERC-165 * @return True if the contract implements the requested interface and if its not 0xffffffff, false otherwise */ function supportsInterface(bytes4 _interfaceId) public pure returns (bool) { return super.supportsInterface(_interfaceId) || _interfaceId == ARAGON_APP_INTERFACE_ID; } } // File: @aragon/os/contracts/apps/disputable/IAgreement.sol /* * SPDX-License-Identifier: MIT */ pragma solidity ^0.4.24; contract IAgreement { event ActionSubmitted(uint256 indexed actionId, address indexed disputable); event ActionClosed(uint256 indexed actionId); event ActionChallenged(uint256 indexed actionId, uint256 indexed challengeId); event ActionSettled(uint256 indexed actionId, uint256 indexed challengeId); event ActionDisputed(uint256 indexed actionId, uint256 indexed challengeId); event ActionAccepted(uint256 indexed actionId, uint256 indexed challengeId); event ActionVoided(uint256 indexed actionId, uint256 indexed challengeId); event ActionRejected(uint256 indexed actionId, uint256 indexed challengeId); enum ChallengeState { Waiting, Settled, Disputed, Rejected, Accepted, Voided } function newAction(uint256 _disputableActionId, bytes _context, address _submitter) external returns (uint256); function closeAction(uint256 _actionId) external; function challengeAction(uint256 _actionId, uint256 _settlementOffer, bool _finishedSubmittingEvidence, bytes _context) external; function settleAction(uint256 _actionId) external; function disputeAction(uint256 _actionId, bool _finishedSubmittingEvidence) external; } // File: @aragon/os/contracts/apps/disputable/IDisputable.sol /* * SPDX-License-Identifier: MIT */ pragma solidity ^0.4.24; contract IDisputable is ERC165 { // Includes setAgreement, onDisputableActionChallenged, onDisputableActionAllowed, // onDisputableActionRejected, onDisputableActionVoided, getAgreement, canChallenge, and canClose methods: bytes4 internal constant DISPUTABLE_INTERFACE_ID = bytes4(0xf3d3bb51); event AgreementSet(IAgreement indexed agreement); function setAgreement(IAgreement _agreement) external; function onDisputableActionChallenged(uint256 _disputableActionId, uint256 _challengeId, address _challenger) external; function onDisputableActionAllowed(uint256 _disputableActionId) external; function onDisputableActionRejected(uint256 _disputableActionId) external; function onDisputableActionVoided(uint256 _disputableActionId) external; function getAgreement() external view returns (IAgreement); function canChallenge(uint256 _disputableActionId) external view returns (bool); function canClose(uint256 _disputableActionId) external view returns (bool); } // File: @aragon/os/contracts/lib/math/SafeMath64.sol // See https://github.com/OpenZeppelin/openzeppelin-solidity/blob/d51e38758e1d985661534534d5c61e27bece5042/contracts/math/SafeMath.sol // Adapted for uint64, pragma ^0.4.24, and satisfying our linter rules // Also optimized the mul() implementation, see https://github.com/aragon/aragonOS/pull/417 pragma solidity ^0.4.24; /** * @title SafeMath64 * @dev Math operations for uint64 with safety checks that revert on error */ library SafeMath64 { string private constant ERROR_ADD_OVERFLOW = "MATH64_ADD_OVERFLOW"; string private constant ERROR_SUB_UNDERFLOW = "MATH64_SUB_UNDERFLOW"; string private constant ERROR_MUL_OVERFLOW = "MATH64_MUL_OVERFLOW"; string private constant ERROR_DIV_ZERO = "MATH64_DIV_ZERO"; /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint64 _a, uint64 _b) internal pure returns (uint64) { uint256 c = uint256(_a) * uint256(_b); require(c < 0x010000000000000000, ERROR_MUL_OVERFLOW); // 2**64 (less gas this way) return uint64(c); } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint64 _a, uint64 _b) internal pure returns (uint64) { require(_b > 0, ERROR_DIV_ZERO); // Solidity only automatically asserts when dividing by 0 uint64 c = _a / _b; // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint64 _a, uint64 _b) internal pure returns (uint64) { require(_b <= _a, ERROR_SUB_UNDERFLOW); uint64 c = _a - _b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint64 _a, uint64 _b) internal pure returns (uint64) { uint64 c = _a + _b; require(c >= _a, ERROR_ADD_OVERFLOW); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint64 a, uint64 b) internal pure returns (uint64) { require(b != 0, ERROR_DIV_ZERO); return a % b; } } // File: @aragon/os/contracts/apps/disputable/DisputableAragonApp.sol /* * SPDX-License-Identifier: MIT */ pragma solidity ^0.4.24; contract DisputableAragonApp is IDisputable, AragonApp { /* Validation errors */ string internal constant ERROR_SENDER_NOT_AGREEMENT = "DISPUTABLE_SENDER_NOT_AGREEMENT"; string internal constant ERROR_AGREEMENT_STATE_INVALID = "DISPUTABLE_AGREEMENT_STATE_INVAL"; // This role is used to protect who can challenge actions in derived Disputable apps. However, it is not required // to be validated in the app itself as the connected Agreement is responsible for performing the check on a challenge. // bytes32 public constant CHALLENGE_ROLE = keccak256("CHALLENGE_ROLE"); bytes32 public constant CHALLENGE_ROLE = 0xef025787d7cd1a96d9014b8dc7b44899b8c1350859fb9e1e05f5a546dd65158d; // bytes32 public constant SET_AGREEMENT_ROLE = keccak256("SET_AGREEMENT_ROLE"); bytes32 public constant SET_AGREEMENT_ROLE = 0x8dad640ab1b088990c972676ada708447affc660890ec9fc9a5483241c49f036; // bytes32 internal constant AGREEMENT_POSITION = keccak256("aragonOS.appStorage.agreement"); bytes32 internal constant AGREEMENT_POSITION = 0x6dbe80ccdeafbf5f3fff5738b224414f85e9370da36f61bf21c65159df7409e9; modifier onlyAgreement() { require(address(_getAgreement()) == msg.sender, ERROR_SENDER_NOT_AGREEMENT); _; } /** * @notice Challenge disputable action #`_disputableActionId` * @dev This hook must be implemented by Disputable apps. We provide a base implementation to ensure that the `onlyAgreement` modifier * is included. Subclasses should implement the internal implementation of the hook. * @param _disputableActionId Identifier of the action to be challenged * @param _challengeId Identifier of the challenge in the context of the Agreement * @param _challenger Address that submitted the challenge */ function onDisputableActionChallenged(uint256 _disputableActionId, uint256 _challengeId, address _challenger) external onlyAgreement { _onDisputableActionChallenged(_disputableActionId, _challengeId, _challenger); } /** * @notice Allow disputable action #`_disputableActionId` * @dev This hook must be implemented by Disputable apps. We provide a base implementation to ensure that the `onlyAgreement` modifier * is included. Subclasses should implement the internal implementation of the hook. * @param _disputableActionId Identifier of the action to be allowed */ function onDisputableActionAllowed(uint256 _disputableActionId) external onlyAgreement { _onDisputableActionAllowed(_disputableActionId); } /** * @notice Reject disputable action #`_disputableActionId` * @dev This hook must be implemented by Disputable apps. We provide a base implementation to ensure that the `onlyAgreement` modifier * is included. Subclasses should implement the internal implementation of the hook. * @param _disputableActionId Identifier of the action to be rejected */ function onDisputableActionRejected(uint256 _disputableActionId) external onlyAgreement { _onDisputableActionRejected(_disputableActionId); } /** * @notice Void disputable action #`_disputableActionId` * @dev This hook must be implemented by Disputable apps. We provide a base implementation to ensure that the `onlyAgreement` modifier * is included. Subclasses should implement the internal implementation of the hook. * @param _disputableActionId Identifier of the action to be voided */ function onDisputableActionVoided(uint256 _disputableActionId) external onlyAgreement { _onDisputableActionVoided(_disputableActionId); } /** * @notice Set Agreement to `_agreement` * @param _agreement Agreement instance to be set */ function setAgreement(IAgreement _agreement) external auth(SET_AGREEMENT_ROLE) { IAgreement agreement = _getAgreement(); require(agreement == IAgreement(0) && _agreement != IAgreement(0), ERROR_AGREEMENT_STATE_INVALID); AGREEMENT_POSITION.setStorageAddress(address(_agreement)); emit AgreementSet(_agreement); } /** * @dev Tell the linked Agreement * @return Agreement */ function getAgreement() external view returns (IAgreement) { return _getAgreement(); } /** * @dev Query if a contract implements a certain interface * @param _interfaceId The interface identifier being queried, as specified in ERC-165 * @return True if the contract implements the requested interface and if its not 0xffffffff, false otherwise */ function supportsInterface(bytes4 _interfaceId) public pure returns (bool) { return super.supportsInterface(_interfaceId) || _interfaceId == DISPUTABLE_INTERFACE_ID; } /** * @dev Internal implementation of the `onDisputableActionChallenged` hook * @param _disputableActionId Identifier of the action to be challenged * @param _challengeId Identifier of the challenge in the context of the Agreement * @param _challenger Address that submitted the challenge */ function _onDisputableActionChallenged(uint256 _disputableActionId, uint256 _challengeId, address _challenger) internal; /** * @dev Internal implementation of the `onDisputableActionRejected` hook * @param _disputableActionId Identifier of the action to be rejected */ function _onDisputableActionRejected(uint256 _disputableActionId) internal; /** * @dev Internal implementation of the `onDisputableActionAllowed` hook * @param _disputableActionId Identifier of the action to be allowed */ function _onDisputableActionAllowed(uint256 _disputableActionId) internal; /** * @dev Internal implementation of the `onDisputableActionVoided` hook * @param _disputableActionId Identifier of the action to be voided */ function _onDisputableActionVoided(uint256 _disputableActionId) internal; /** * @dev Register a new disputable action in the Agreement * @param _disputableActionId Identifier of the action in the context of the Disputable * @param _context Link to human-readable context for the given action * @param _submitter Address that submitted the action * @return Unique identifier for the created action in the context of the Agreement */ function _registerDisputableAction(uint256 _disputableActionId, bytes _context, address _submitter) internal returns (uint256) { IAgreement agreement = _ensureAgreement(); return agreement.newAction(_disputableActionId, _context, _submitter); } /** * @dev Close disputable action in the Agreement * @param _actionId Identifier of the action in the context of the Agreement */ function _closeDisputableAction(uint256 _actionId) internal { IAgreement agreement = _ensureAgreement(); agreement.closeAction(_actionId); } /** * @dev Tell the linked Agreement * @return Agreement */ function _getAgreement() internal view returns (IAgreement) { return IAgreement(AGREEMENT_POSITION.getStorageAddress()); } /** * @dev Tell the linked Agreement or revert if it has not been set * @return Agreement */ function _ensureAgreement() internal view returns (IAgreement) { IAgreement agreement = _getAgreement(); require(agreement != IAgreement(0), ERROR_AGREEMENT_STATE_INVALID); return agreement; } } // File: @aragon/os/contracts/lib/math/SafeMath.sol // See https://github.com/OpenZeppelin/openzeppelin-solidity/blob/d51e38758e1d985661534534d5c61e27bece5042/contracts/math/SafeMath.sol // Adapted to use pragma ^0.4.24 and satisfy our linter rules pragma solidity ^0.4.24; /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { string private constant ERROR_ADD_OVERFLOW = "MATH_ADD_OVERFLOW"; string private constant ERROR_SUB_UNDERFLOW = "MATH_SUB_UNDERFLOW"; string private constant ERROR_MUL_OVERFLOW = "MATH_MUL_OVERFLOW"; string private constant ERROR_DIV_ZERO = "MATH_DIV_ZERO"; /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 _a, uint256 _b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (_a == 0) { return 0; } uint256 c = _a * _b; require(c / _a == _b, ERROR_MUL_OVERFLOW); return c; } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint256 _a, uint256 _b) internal pure returns (uint256) { require(_b > 0, ERROR_DIV_ZERO); // Solidity only automatically asserts when dividing by 0 uint256 c = _a / _b; // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { require(_b <= _a, ERROR_SUB_UNDERFLOW); uint256 c = _a - _b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 _a, uint256 _b) internal pure returns (uint256) { uint256 c = _a + _b; require(c >= _a, ERROR_ADD_OVERFLOW); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, ERROR_DIV_ZERO); return a % b; } } // File: @aragon/staking/interfaces/IStaking.sol pragma solidity >=0.4 <=0.7; interface IStaking { function allowManager(address _lockManager, uint256 _allowance, bytes _data) external; function allowManagerAndLock(uint256 _amount, address _lockManager, uint256 _allowance, bytes _data) external; function unlockAndRemoveManager(address _account, address _lockManager) external; function increaseLockAllowance(address _lockManager, uint256 _allowance) external; function decreaseLockAllowance(address _account, address _lockManager, uint256 _allowance) external; function lock(address _account, address _lockManager, uint256 _amount) external; function unlock(address _account, address _lockManager, uint256 _amount) external; function setLockManager(address _account, address _newLockManager) external; function transfer(address _to, uint256 _amount) external; function transferAndUnstake(address _to, uint256 _amount) external; function slash(address _account, address _to, uint256 _amount) external; function slashAndUnstake(address _account, address _to, uint256 _amount) external; function getLock(address _account, address _lockManager) external view returns (uint256 _amount, uint256 _allowance); function unlockedBalanceOf(address _account) external view returns (uint256); function lockedBalanceOf(address _user) external view returns (uint256); function getBalancesOf(address _user) external view returns (uint256 staked, uint256 locked); function canUnlock(address _sender, address _account, address _lockManager, uint256 _amount) external view returns (bool); } // File: @aragon/staking/interfaces/IStakingFactory.sol pragma solidity >=0.4 <=0.7; interface IStakingFactory { function existsInstance(/* ERC20 */ address token) external view returns (bool); function getInstance(/* ERC20 */ address token) external view returns (IStaking); function getOrCreateInstance(/* ERC20 */ address token) external returns (IStaking); } // File: @aragon/staking/interfaces/ILockManager.sol pragma solidity >=0.4 <=0.7; interface ILockManager { /** * @notice Check if `_user`'s by `_lockManager` can be unlocked * @param _user Owner of lock * @param _amount Amount of locked tokens to unlock * @return Whether given lock of given owner can be unlocked by given sender */ function canUnlock(address _user, uint256 _amount) external view returns (bool); } // File: contracts/arbitration/IArbitrator.sol pragma solidity ^0.4.24; /** * @title Arbitrator interface * @dev This interface is the one used by `Agreement` as its dispute resolution protocol. * This interface was manually-copied from https://github.com/aragon/aragon-court/blob/v1.2.0/contracts/arbitration/IArbitrator.sol * since we are using different solidity versions. */ interface IArbitrator { /** * @dev Create a dispute over the Arbitrable sender with a number of possible rulings * @param _possibleRulings Number of possible rulings allowed for the dispute * @param _metadata Optional metadata that can be used to provide additional information on the dispute to be created * @return Dispute identifier */ function createDispute(uint256 _possibleRulings, bytes _metadata) external returns (uint256); /** * @dev Close the evidence period of a dispute * @param _disputeId Identifier of the dispute to close its evidence submitting period */ function closeEvidencePeriod(uint256 _disputeId) external; /** * @dev Execute the Arbitrable associated to a dispute based on its final ruling * @param _disputeId Identifier of the dispute to be executed */ function executeRuling(uint256 _disputeId) external; /** * @dev Tell the dispute fees information to create a dispute * @return recipient Address where the corresponding dispute fees must be transferred to * @return feeToken ERC20 token used for the fees * @return feeAmount Total amount of fees that must be allowed to the recipient */ function getDisputeFees() external view returns (address recipient, ERC20 feeToken, uint256 feeAmount); /** * @dev Tell the subscription fees information for a subscriber to be up-to-date * @param _subscriber Address of the account paying the subscription fees for * @return recipient Address where the corresponding subscriptions fees must be transferred to * @return feeToken ERC20 token used for the subscription fees * @return feeAmount Total amount of fees that must be allowed to the recipient */ function getSubscriptionFees(address _subscriber) external view returns (address recipient, ERC20 feeToken, uint256 feeAmount); } // File: contracts/arbitration/IArbitrable.sol pragma solidity ^0.4.24; /** * @title Arbitrable interface * @dev This interface is implemented by `Agreement` so it can be used to submit disputes to an `IArbitrator`. * This interface was manually-copied from https://github.com/aragon/aragon-court/blob/v1.2.0/contracts/arbitration/IArbitrable.sol * since we are using different solidity versions. */ contract IArbitrable is ERC165 { bytes4 internal constant ARBITRABLE_INTERFACE_ID = bytes4(0x88f3ee69); /** * @dev Emitted when an IArbitrable instance's dispute is ruled by an IArbitrator * @param arbitrator IArbitrator instance ruling the dispute * @param disputeId Identifier of the dispute being ruled by the arbitrator * @param ruling Ruling given by the arbitrator */ event Ruled(IArbitrator indexed arbitrator, uint256 indexed disputeId, uint256 ruling); /** * @dev Emitted when new evidence is submitted for the IArbitrable instance's dispute * @param arbitrator IArbitrator submitting the evidence for * @param disputeId Identifier of the dispute receiving new evidence * @param submitter Address of the account submitting the evidence * @param evidence Data submitted for the evidence of the dispute * @param finished Whether or not the submitter has finished submitting evidence */ event EvidenceSubmitted(IArbitrator indexed arbitrator, uint256 indexed disputeId, address indexed submitter, bytes evidence, bool finished); /** * @dev Submit evidence for a dispute * @param _disputeId Id of the dispute in the Court * @param _evidence Data submitted for the evidence related to the dispute * @param _finished Whether or not the submitter has finished submitting evidence */ function submitEvidence(uint256 _disputeId, bytes _evidence, bool _finished) external; /** * @dev Give a ruling for a certain dispute, the account calling it must have rights to rule on the contract * @param _disputeId Identifier of the dispute to be ruled * @param _ruling Ruling given by the arbitrator, where 0 is reserved for "refused to make a decision" */ function rule(uint256 _disputeId, uint256 _ruling) external; /** * @dev Query if a contract implements a certain interface * @param _interfaceId The interface identifier being queried, as specified in ERC-165 * @return True if the contract implements the requested interface and if its not 0xffffffff, false otherwise */ function supportsInterface(bytes4 _interfaceId) public pure returns (bool) { return super.supportsInterface(_interfaceId) || _interfaceId == ARBITRABLE_INTERFACE_ID; } } // File: contracts/arbitration/IAragonAppFeesCashier.sol pragma solidity ^0.4.24; /** * @title AragonAppFeesCashier interface * @dev This interface is derived from the `IArbitrator`'s subscriptions module. * It is used to pay the fees corresponding to the usage of a disputable app. * This interface was manually-copied from https://github.com/aragon/aragon-court/blob/v1.2.0/contracts/subscriptions/IAragonAppFeesCashier.sol * since we are using different solidity versions. */ interface IAragonAppFeesCashier { /** * @dev Emitted when an IAragonAppFeesCashier instance sets a new fee for an app * @param appId App identifier * @param token Token address to be used for the fees * @param amount Fee amount to be charged for the given app */ event AppFeeSet(bytes32 indexed appId, ERC20 token, uint256 amount); /** * @dev Emitted when an IAragonAppFeesCashier instance unsets an app fee * @param appId App identifier */ event AppFeeUnset(bytes32 indexed appId); /** * @dev Emitted when an IAragonAppFeesCashier instance receives a payment for an app * @param by Address paying the fees * @param appId App identifier * @param data Optional data */ event AppFeePaid(address indexed by, bytes32 appId, bytes data); /** * @dev Set the fee amount and token to be used for an app * @param _appId App identifier * @param _token Token address to be used for the fees * @param _amount Fee amount to be charged for the given app */ function setAppFee(bytes32 _appId, ERC20 _token, uint256 _amount) external; /** * @dev Set the fee amount and token to be used for a list of apps * @param _appIds List of app identifiers * @param _tokens List of token addresses to be used for the fees for each app * @param _amounts List of fee amounts to be charged for each app */ function setAppFees(bytes32[] _appIds, ERC20[] _tokens, uint256[] _amounts) external; /** * @dev Remove the fee set for an app * @param _appId App identifier */ function unsetAppFee(bytes32 _appId) external; /** * @dev Remove the fee set for a list of apps * @param _appIds List of app identifiers */ function unsetAppFees(bytes32[] _appIds) external; /** * @dev Pay the fees corresponding to an app * @param _appId App identifier * @param _data Optional data input */ function payAppFees(bytes32 _appId, bytes _data) external payable; /** * @dev Tell the fee token and amount set for a given app * @param _appId Identifier of the app being queried * @return token Fee token address set for the requested app * @return amount Fee token amount set for the requested app */ function getAppFee(bytes32 _appId) external view returns (ERC20 token, uint256 amount); } // File: contracts/Agreement.sol /* * SPDX-License-Identitifer: GPL-3.0-or-later */ pragma solidity 0.4.24; contract Agreement is IArbitrable, ILockManager, IAgreement, IACLOracle, AragonApp { using SafeMath for uint256; using SafeMath64 for uint64; using SafeERC20 for ERC20; /* Arbitrator outcomes constants */ uint256 internal constant DISPUTES_POSSIBLE_OUTCOMES = 2; // Note that Aragon Court treats the possible outcomes as arbitrary numbers, leaving the Arbitrable (us) to define how to understand them. // Some outcomes [0, 1, and 2] are reserved by Aragon Court: "missing", "leaked", and "refused", respectively. // This Arbitrable introduces the concept of the challenger/submitter (a binary outcome) as 3/4. // Note that Aragon Court emits the lowest outcome in the event of a tie, and so for us, we prefer the challenger. uint256 internal constant DISPUTES_RULING_CHALLENGER = 3; uint256 internal constant DISPUTES_RULING_SUBMITTER = 4; /* Validation errors */ string internal constant ERROR_SENDER_NOT_ALLOWED = "AGR_SENDER_NOT_ALLOWED"; string internal constant ERROR_SIGNER_MUST_SIGN = "AGR_SIGNER_MUST_SIGN"; string internal constant ERROR_SIGNER_ALREADY_SIGNED = "AGR_SIGNER_ALREADY_SIGNED"; string internal constant ERROR_INVALID_SIGNING_SETTING = "AGR_INVALID_SIGNING_SETTING"; string internal constant ERROR_INVALID_SETTLEMENT_OFFER = "AGR_INVALID_SETTLEMENT_OFFER"; string internal constant ERROR_ACTION_DOES_NOT_EXIST = "AGR_ACTION_DOES_NOT_EXIST"; string internal constant ERROR_CHALLENGE_DOES_NOT_EXIST = "AGR_CHALLENGE_DOES_NOT_EXIST"; string internal constant ERROR_TOKEN_DEPOSIT_FAILED = "AGR_TOKEN_DEPOSIT_FAILED"; string internal constant ERROR_TOKEN_TRANSFER_FAILED = "AGR_TOKEN_TRANSFER_FAILED"; string internal constant ERROR_TOKEN_APPROVAL_FAILED = "AGR_TOKEN_APPROVAL_FAILED"; string internal constant ERROR_TOKEN_NOT_CONTRACT = "AGR_TOKEN_NOT_CONTRACT"; string internal constant ERROR_SETTING_DOES_NOT_EXIST = "AGR_SETTING_DOES_NOT_EXIST"; string internal constant ERROR_ARBITRATOR_NOT_CONTRACT = "AGR_ARBITRATOR_NOT_CONTRACT"; string internal constant ERROR_STAKING_FACTORY_NOT_CONTRACT = "AGR_STAKING_FACTORY_NOT_CONTRACT"; string internal constant ERROR_ACL_ORACLE_SIGNER_MISSING = "AGR_ACL_ORACLE_SIGNER_MISSING"; string internal constant ERROR_ACL_ORACLE_SIGNER_NOT_ADDRESS = "AGR_ACL_ORACLE_SIGNER_NOT_ADDR"; /* Disputable related errors */ string internal constant ERROR_SENDER_CANNOT_CHALLENGE_ACTION = "AGR_SENDER_CANT_CHALLENGE_ACTION"; string internal constant ERROR_DISPUTABLE_NOT_CONTRACT = "AGR_DISPUTABLE_NOT_CONTRACT"; string internal constant ERROR_DISPUTABLE_NOT_ACTIVE = "AGR_DISPUTABLE_NOT_ACTIVE"; string internal constant ERROR_DISPUTABLE_ALREADY_ACTIVE = "AGR_DISPUTABLE_ALREADY_ACTIVE"; string internal constant ERROR_COLLATERAL_REQUIREMENT_DOES_NOT_EXIST = "AGR_COL_REQ_DOES_NOT_EXIST"; /* Action related errors */ string internal constant ERROR_CANNOT_CHALLENGE_ACTION = "AGR_CANNOT_CHALLENGE_ACTION"; string internal constant ERROR_CANNOT_CLOSE_ACTION = "AGR_CANNOT_CLOSE_ACTION"; string internal constant ERROR_CANNOT_SETTLE_ACTION = "AGR_CANNOT_SETTLE_ACTION"; string internal constant ERROR_CANNOT_DISPUTE_ACTION = "AGR_CANNOT_DISPUTE_ACTION"; string internal constant ERROR_CANNOT_RULE_ACTION = "AGR_CANNOT_RULE_ACTION"; string internal constant ERROR_CANNOT_SUBMIT_EVIDENCE = "AGR_CANNOT_SUBMIT_EVIDENCE"; string internal constant ERROR_CANNOT_CLOSE_EVIDENCE_PERIOD = "AGR_CANNOT_CLOSE_EVIDENCE_PERIOD"; // This role will be checked against the Disputable app when users try to challenge actions. // It is expected to be configured per Disputable app. For reference, see `canPerformChallenge()`. // bytes32 public constant CHALLENGE_ROLE = keccak256("CHALLENGE_ROLE"); bytes32 public constant CHALLENGE_ROLE = 0xef025787d7cd1a96d9014b8dc7b44899b8c1350859fb9e1e05f5a546dd65158d; // bytes32 public constant CHANGE_AGREEMENT_ROLE = keccak256("CHANGE_AGREEMENT_ROLE"); bytes32 public constant CHANGE_AGREEMENT_ROLE = 0x07813bca4905795fa22783885acd0167950db28f2d7a40b70f666f429e19f1d9; // bytes32 public constant MANAGE_DISPUTABLE_ROLE = keccak256("MANAGE_DISPUTABLE_ROLE"); bytes32 public constant MANAGE_DISPUTABLE_ROLE = 0x2309a8cbbd5c3f18649f3b7ac47a0e7b99756c2ac146dda1ffc80d3f80827be6; event Signed(address indexed signer, uint256 settingId); event SettingChanged(uint256 settingId); event AppFeesCashierSynced(IAragonAppFeesCashier newAppFeesCashier); event DisputableAppActivated(address indexed disputable); event DisputableAppDeactivated(address indexed disputable); event CollateralRequirementChanged(address indexed disputable, uint256 collateralRequirementId); struct Setting { IArbitrator arbitrator; IAragonAppFeesCashier aragonAppFeesCashier; // Fees cashier to deposit action fees (linked to the selected arbitrator) string title; bytes content; } struct CollateralRequirement { ERC20 token; // ERC20 token to be used for collateral uint64 challengeDuration; // Challenge duration, during which the submitter can raise a dispute uint256 actionAmount; // Amount of collateral token to be locked from the submitter's staking pool when creating actions uint256 challengeAmount; // Amount of collateral token to be locked from the challenger's own balance when challenging actions IStaking staking; // Staking pool cache for the collateral token -- will never change } struct DisputableInfo { bool activated; // Whether the Disputable app is active uint256 nextCollateralRequirementsId; // Identification number of the next collateral requirement mapping (uint256 => CollateralRequirement) collateralRequirements; // List of collateral requirements indexed by ID } struct Action { DisputableAragonApp disputable; // Disputable app that created the action uint256 disputableActionId; // Identification number of the action on the Disputable app uint256 collateralRequirementId; // Identification number of the collateral requirement applicable to the action uint256 settingId; // Identification number of the agreement setting applicable to the action address submitter; // Address that submitted the action bool closed; // Whether the action is closed (and cannot be challenged anymore) bytes context; // Link to a human-readable context for the given action uint256 lastChallengeId; // Identification number of the action's most recent challenge, if any } struct ArbitratorFees { ERC20 token; // ERC20 token used for the arbitration fees uint256 amount; // Amount of arbitration fees } struct Challenge { uint256 actionId; // Identification number of the action associated to the challenge address challenger; // Address that challenged the action uint64 endDate; // Last date the submitter can raise a dispute against the challenge bytes context; // Link to a human-readable context for the challenge uint256 settlementOffer; // Amount of collateral tokens the challenger would accept without involving the arbitrator ArbitratorFees challengerArbitratorFees; // Arbitration fees paid by the challenger (in advance) ArbitratorFees submitterArbitratorFees; // Arbitration fees paid by the submitter (on dispute creation) ChallengeState state; // Current state of the challenge bool submitterFinishedEvidence; // Whether the action submitter has finished submitting evidence for the raised dispute bool challengerFinishedEvidence; // Whether the action challenger has finished submitting evidence for the raised dispute uint256 disputeId; // Identification number of the dispute on the arbitrator uint256 ruling; // Ruling given from the arbitrator for the dispute } IStakingFactory public stakingFactory; // Staking factory, for finding each collateral token's staking pool uint256 private nextSettingId; mapping (uint256 => Setting) private settings; // List of historic agreement settings indexed by ID (starting at 1) mapping (address => uint256) private lastSettingSignedBy; // Mapping of address => last agreement setting signed mapping (address => DisputableInfo) private disputableInfos; // Mapping of Disputable app => disputable infos uint256 private nextActionId; mapping (uint256 => Action) private actions; // List of actions indexed by ID (starting at 1) uint256 private nextChallengeId; mapping (uint256 => Challenge) private challenges; // List of challenges indexed by ID (starting at 1) mapping (uint256 => uint256) private challengeByDispute; // Mapping of arbitrator's dispute ID => challenge ID /** * @notice Initialize Agreement for "`_title`" and content "`_content`", with arbitrator `_arbitrator` and staking factory `_factory` * @param _arbitrator Address of the IArbitrator that will be used to resolve disputes * @param _setAppFeesCashier Whether to integrate with the IArbitrator's fee cashier * @param _title String indicating a short description * @param _content Link to a human-readable text that describes the initial rules for the Agreement * @param _stakingFactory Staking factory for finding each collateral token's staking pool */ function initialize( IArbitrator _arbitrator, bool _setAppFeesCashier, string _title, bytes _content, IStakingFactory _stakingFactory ) external { initialized(); require(isContract(address(_stakingFactory)), ERROR_STAKING_FACTORY_NOT_CONTRACT); stakingFactory = _stakingFactory; nextSettingId = 1; // Agreement setting ID zero is considered the null agreement setting for further validations nextActionId = 1; // Action ID zero is considered the null action for further validations nextChallengeId = 1; // Challenge ID zero is considered the null challenge for further validations _newSetting(_arbitrator, _setAppFeesCashier, _title, _content); } /** * @notice Update Agreement to title "`_title`" and content "`_content`", with arbitrator `_arbitrator` * @dev Initialization check is implicitly provided by the `auth()` modifier * @param _arbitrator Address of the IArbitrator that will be used to resolve disputes * @param _setAppFeesCashier Whether to integrate with the IArbitrator's fee cashier * @param _title String indicating a short description * @param _content Link to a human-readable text that describes the new rules for the Agreement */ function changeSetting( IArbitrator _arbitrator, bool _setAppFeesCashier, string _title, bytes _content ) external auth(CHANGE_AGREEMENT_ROLE) { _newSetting(_arbitrator, _setAppFeesCashier, _title, _content); } /** * @notice Sync app fees cashier address * @dev The app fees cashier address is being cached in the contract to save gas. * This can be called permission-lessly to allow any account to re-sync the cashier when changed by the arbitrator. * Initialization check is implicitly provided by `_getSetting()`, as valid settings can only be created after initialization. */ function syncAppFeesCashier() external { Setting storage setting = _getSetting(_getCurrentSettingId()); IAragonAppFeesCashier newAppFeesCashier = _getArbitratorFeesCashier(setting.arbitrator); IAragonAppFeesCashier currentAppFeesCashier = setting.aragonAppFeesCashier; // Sync the app fees cashier only if there was one set before and it's different from the arbitrator's current one if (currentAppFeesCashier != IAragonAppFeesCashier(0) && currentAppFeesCashier != newAppFeesCashier) { setting.aragonAppFeesCashier = newAppFeesCashier; emit AppFeesCashierSynced(newAppFeesCashier); } } /** * @notice Activate Disputable app `_disputableAddress` * @dev Initialization check is implicitly provided by the `auth()` modifier * @param _disputableAddress Address of the Disputable app * @param _collateralToken Address of the ERC20 token to be used for collateral * @param _actionAmount Amount of collateral tokens that will be locked every time an action is submitted * @param _challengeAmount Amount of collateral tokens that will be locked every time an action is challenged * @param _challengeDuration Challenge duration, during which the submitter can raise a dispute */ function activate( address _disputableAddress, ERC20 _collateralToken, uint64 _challengeDuration, uint256 _actionAmount, uint256 _challengeAmount ) external auth(MANAGE_DISPUTABLE_ROLE) { require(isContract(_disputableAddress), ERROR_DISPUTABLE_NOT_CONTRACT); DisputableInfo storage disputableInfo = disputableInfos[_disputableAddress]; _ensureInactiveDisputable(disputableInfo); DisputableAragonApp disputable = DisputableAragonApp(_disputableAddress); disputableInfo.activated = true; // If the disputable app is being activated for the first time, then we need to set-up its initial collateral // requirement and set its Agreement reference to here. if (disputable.getAgreement() != IAgreement(this)) { disputable.setAgreement(IAgreement(this)); uint256 nextId = disputableInfo.nextCollateralRequirementsId; disputableInfo.nextCollateralRequirementsId = nextId > 0 ? nextId : 1; } _changeCollateralRequirement(disputable, disputableInfo, _collateralToken, _challengeDuration, _actionAmount, _challengeAmount); emit DisputableAppActivated(disputable); } /** * @notice Deactivate Disputable app `_disputable` * @dev Initialization check is implicitly provided by the `auth()` modifier * @param _disputableAddress Address of the Disputable app to be deactivated */ function deactivate(address _disputableAddress) external auth(MANAGE_DISPUTABLE_ROLE) { DisputableInfo storage disputableInfo = disputableInfos[_disputableAddress]; _ensureActiveDisputable(disputableInfo); disputableInfo.activated = false; emit DisputableAppDeactivated(_disputableAddress); } /** * @notice Change `_disputable`'s collateral requirements * @dev Initialization check is implicitly provided by the `auth()` modifier * @param _disputable Address of the Disputable app * @param _collateralToken Address of the ERC20 token to be used for collateral * @param _actionAmount Amount of collateral tokens that will be locked every time an action is submitted * @param _challengeAmount Amount of collateral tokens that will be locked every time an action is challenged * @param _challengeDuration Challenge duration, during which the submitter can raise a dispute */ function changeCollateralRequirement( DisputableAragonApp _disputable, ERC20 _collateralToken, uint64 _challengeDuration, uint256 _actionAmount, uint256 _challengeAmount ) external auth(MANAGE_DISPUTABLE_ROLE) { DisputableInfo storage disputableInfo = disputableInfos[address(_disputable)]; _ensureActiveDisputable(disputableInfo); _changeCollateralRequirement(_disputable, disputableInfo, _collateralToken, _challengeDuration, _actionAmount, _challengeAmount); } /** * @notice Sign the agreement up-to setting #`_settingId` * @dev Callable by any account; only accounts that have signed the latest version of the agreement can submit new disputable actions. * Initialization check is implicitly provided by `_settingId < nextSettingId`, as valid settings can only be created after initialization. * @param _settingId Last setting ID the user is agreeing with */ function sign(uint256 _settingId) external { uint256 lastSettingIdSigned = lastSettingSignedBy[msg.sender]; require(lastSettingIdSigned < _settingId, ERROR_SIGNER_ALREADY_SIGNED); require(_settingId < nextSettingId, ERROR_INVALID_SIGNING_SETTING); lastSettingSignedBy[msg.sender] = _settingId; emit Signed(msg.sender, _settingId); } /** * @notice Register action #`_disputableActionId` from disputable `msg.sender` for submitter `_submitter` with context `_context` * @dev This function should be called from the Disputable app each time a new disputable action is created. * Each disputable action ID must only be registered once; this is how the Agreement gets notified about each disputable action. * Initialization check is implicitly provided by `_ensureActiveDisputable()` as Disputable apps can only be activated * via `activate()` which already requires initialization. * IMPORTANT: Note the responsibility of the Disputable app in terms of providing the correct `_submitter` parameter. * Users are required to trust that all Disputable apps activated with this Agreement have implemented this correctly, as * otherwise funds could be maliciously locked from the incorrect account on new actions. * @param _disputableActionId Identification number of the action on the Disputable app * @param _context Link to a human-readable context for the given action * @param _submitter Address that submitted the action * @return Unique identification number for the created action on the Agreement */ function newAction(uint256 _disputableActionId, bytes _context, address _submitter) external returns (uint256) { DisputableInfo storage disputableInfo = disputableInfos[msg.sender]; _ensureActiveDisputable(disputableInfo); uint256 currentSettingId = _getCurrentSettingId(); uint256 lastSettingIdSigned = lastSettingSignedBy[_submitter]; require(lastSettingIdSigned >= currentSettingId, ERROR_SIGNER_MUST_SIGN); // An initial collateral requirement is created when disputable apps are activated, thus length is always greater than 0 uint256 currentCollateralRequirementId = disputableInfo.nextCollateralRequirementsId - 1; CollateralRequirement storage requirement = _getCollateralRequirement(disputableInfo, currentCollateralRequirementId); _lockBalance(requirement.staking, _submitter, requirement.actionAmount); // Pay action submission fees Setting storage setting = _getSetting(currentSettingId); DisputableAragonApp disputable = DisputableAragonApp(msg.sender); _payAppFees(setting, disputable, _submitter, id); uint256 id = nextActionId++; Action storage action = actions[id]; action.disputable = disputable; action.disputableActionId = _disputableActionId; action.collateralRequirementId = currentCollateralRequirementId; action.settingId = currentSettingId; action.submitter = _submitter; action.context = _context; emit ActionSubmitted(id, msg.sender); return id; } /** * @notice Close action #`_actionId` * @dev This function closes actions that: * - Are not currently challenged nor disputed, or * - Were previously disputed but ruled in favour of the submitter or voided * Disputable apps may call this method directly at the end of an action, but is also accessible in a permission-less manner * in case the app does not close its own actions automatically (e.g. disputable votes that don't pass). * Can be called multiple times; it does nothing if the action is already closed. * Initialization check is implicitly provided by `_getAction()` as disputable actions can only be created via `newAction()`. * @param _actionId Identification number of the action to be closed */ function closeAction(uint256 _actionId) external { Action storage action = _getAction(_actionId); if (action.closed) { return; } require(_canClose(action), ERROR_CANNOT_CLOSE_ACTION); (, CollateralRequirement storage requirement) = _getDisputableInfoFor(action); _unlockBalance(requirement.staking, action.submitter, requirement.actionAmount); _unsafeCloseAction(_actionId, action); } /** * @notice Challenge action #`_actionId` * @dev This is only callable by those who hold the CHALLENGE_ROLE on the related Disputable app. * Can be called multiple times per action, until a challenge is successful (settled or ruled for challenger). * Initialization check is implicitly provided by `_getAction()` as disputable actions can only be created via `newAction()`. * @param _actionId Identification number of the action to be challenged * @param _settlementOffer Amount of collateral tokens the challenger would accept for resolving the dispute without involving the arbitrator * @param _finishedEvidence Whether the challenger is finished submitting evidence with the challenge context * @param _context Link to a human-readable context for the challenge */ function challengeAction(uint256 _actionId, uint256 _settlementOffer, bool _finishedEvidence, bytes _context) external { Action storage action = _getAction(_actionId); require(_canChallenge(action), ERROR_CANNOT_CHALLENGE_ACTION); (DisputableAragonApp disputable, CollateralRequirement storage requirement) = _getDisputableInfoFor(action); require(_canPerformChallenge(disputable, msg.sender), ERROR_SENDER_CANNOT_CHALLENGE_ACTION); require(_settlementOffer <= requirement.actionAmount, ERROR_INVALID_SETTLEMENT_OFFER); uint256 challengeId = _createChallenge(_actionId, action, msg.sender, requirement, _settlementOffer, _finishedEvidence, _context); action.lastChallengeId = challengeId; disputable.onDisputableActionChallenged(action.disputableActionId, challengeId, msg.sender); emit ActionChallenged(_actionId, challengeId); } /** * @notice Settle challenged action #`_actionId`, accepting the settlement offer * @dev This can be accessed by both the submitter (at any time) or any account (after the settlement period has passed). * Can only be called once (if at all) per opened challenge. * Initialization check is implicitly provided by `_getChallengedAction()` as disputable actions can only be created via `newAction()`. * @param _actionId Identification number of the action to be settled */ function settleAction(uint256 _actionId) external { (Action storage action, Challenge storage challenge, uint256 challengeId) = _getChallengedAction(_actionId); address submitter = action.submitter; if (msg.sender == submitter) { require(_canSettle(challenge), ERROR_CANNOT_SETTLE_ACTION); } else { require(_canClaimSettlement(challenge), ERROR_CANNOT_SETTLE_ACTION); } (DisputableAragonApp disputable, CollateralRequirement storage requirement) = _getDisputableInfoFor(action); uint256 actionCollateral = requirement.actionAmount; uint256 settlementOffer = challenge.settlementOffer; // The settlement offer was already checked to be up-to the collateral amount upon challenge creation // However, we cap it to collateral amount to be safe // With this, we can avoid using SafeMath to calculate `unlockedAmount` uint256 slashedAmount = settlementOffer >= actionCollateral ? actionCollateral : settlementOffer; uint256 unlockedAmount = actionCollateral - slashedAmount; // Unlock and slash action collateral for settlement offer address challenger = challenge.challenger; IStaking staking = requirement.staking; _unlockBalance(staking, submitter, unlockedAmount); _slashBalance(staking, submitter, challenger, slashedAmount); // Transfer challenge collateral and challenger arbitrator fees back to the challenger _transferTo(requirement.token, challenger, requirement.challengeAmount); _transferTo(challenge.challengerArbitratorFees.token, challenger, challenge.challengerArbitratorFees.amount); challenge.state = ChallengeState.Settled; disputable.onDisputableActionRejected(action.disputableActionId); emit ActionSettled(_actionId, challengeId); _unsafeCloseAction(_actionId, action); } /** * @notice Dispute challenged action #`_actionId`, raising it to the arbitrator * @dev Only the action submitter can create a dispute for an action with an open challenge. * Can only be called once (if at all) per opened challenge. * Initialization check is implicitly provided by `_getChallengedAction()` as disputable actions can only be created via `newAction()`. * @param _actionId Identification number of the action to be disputed * @param _submitterFinishedEvidence Whether the submitter was finished submitting evidence with their action context */ function disputeAction(uint256 _actionId, bool _submitterFinishedEvidence) external { (Action storage action, Challenge storage challenge, uint256 challengeId) = _getChallengedAction(_actionId); require(_canDispute(challenge), ERROR_CANNOT_DISPUTE_ACTION); address submitter = action.submitter; require(msg.sender == submitter, ERROR_SENDER_NOT_ALLOWED); IArbitrator arbitrator = _getArbitratorFor(action); bytes memory metadata = abi.encodePacked(appId(), action.lastChallengeId); uint256 disputeId = _createDispute(action, challenge, arbitrator, metadata); _submitEvidence(arbitrator, disputeId, submitter, action.context, _submitterFinishedEvidence); _submitEvidence(arbitrator, disputeId, challenge.challenger, challenge.context, challenge.challengerFinishedEvidence); challenge.state = ChallengeState.Disputed; challenge.submitterFinishedEvidence = _submitterFinishedEvidence; challenge.disputeId = disputeId; challengeByDispute[disputeId] = challengeId; emit ActionDisputed(_actionId, challengeId); } /** * @notice Submit evidence for dispute #`_disputeId` * @dev Only callable by the action submitter or challenger. * Can be called as many times as desired until the dispute is over. * Initialization check is implicitly provided by `_getDisputedAction()` as disputable actions can only be created via `newAction()`. * @param _disputeId Identification number of the dispute on the arbitrator * @param _evidence Evidence data to be submitted * @param _finished Whether the evidence submitter is now finished submitting evidence */ function submitEvidence(uint256 _disputeId, bytes _evidence, bool _finished) external { (, Action storage action, , Challenge storage challenge) = _getDisputedAction(_disputeId); require(_isDisputed(challenge), ERROR_CANNOT_SUBMIT_EVIDENCE); IArbitrator arbitrator = _getArbitratorFor(action); if (msg.sender == action.submitter) { // If the submitter finished submitting evidence earlier, also emit this event as finished bool submitterFinishedEvidence = challenge.submitterFinishedEvidence || _finished; _submitEvidence(arbitrator, _disputeId, msg.sender, _evidence, submitterFinishedEvidence); challenge.submitterFinishedEvidence = submitterFinishedEvidence; } else if (msg.sender == challenge.challenger) { // If the challenger finished submitting evidence earlier, also emit this event as finished bool challengerFinishedEvidence = challenge.challengerFinishedEvidence || _finished; _submitEvidence(arbitrator, _disputeId, msg.sender, _evidence, challengerFinishedEvidence); challenge.challengerFinishedEvidence = challengerFinishedEvidence; } else { revert(ERROR_SENDER_NOT_ALLOWED); } } /** * @notice Close evidence submission period for dispute #`_disputeId` * @dev Callable by any account. * Initialization check is implicitly provided by `_getDisputedAction()` as disputable actions can only be created via `newAction()`. * @param _disputeId Identification number of the dispute on the arbitrator */ function closeEvidencePeriod(uint256 _disputeId) external { (, Action storage action, , Challenge storage challenge) = _getDisputedAction(_disputeId); require(_isDisputed(challenge), ERROR_CANNOT_SUBMIT_EVIDENCE); require(challenge.submitterFinishedEvidence && challenge.challengerFinishedEvidence, ERROR_CANNOT_CLOSE_EVIDENCE_PERIOD); IArbitrator arbitrator = _getArbitratorFor(action); arbitrator.closeEvidencePeriod(_disputeId); } /** * @notice Rule the action associated to dispute #`_disputeId` with ruling `_ruling` * @dev Can only be called once per challenge by the associated abitrator. * Initialization check is implicitly provided by `_getDisputedAction()` as disputable actions can only be created via `newAction()`. * @param _disputeId Identification number of the dispute on the arbitrator * @param _ruling Ruling given by the arbitrator */ function rule(uint256 _disputeId, uint256 _ruling) external { (uint256 actionId, Action storage action, uint256 challengeId, Challenge storage challenge) = _getDisputedAction(_disputeId); require(_isDisputed(challenge), ERROR_CANNOT_RULE_ACTION); IArbitrator arbitrator = _getArbitratorFor(action); require(arbitrator == IArbitrator(msg.sender), ERROR_SENDER_NOT_ALLOWED); challenge.ruling = _ruling; emit Ruled(arbitrator, _disputeId, _ruling); if (_ruling == DISPUTES_RULING_SUBMITTER) { _acceptAction(actionId, action, challengeId, challenge); } else if (_ruling == DISPUTES_RULING_CHALLENGER) { _rejectAction(actionId, action, challengeId, challenge); } else { _voidAction(actionId, action, challengeId, challenge); } } // Getter fns /** * @dev Tell the identification number of the current agreement setting * @return Identification number of the current agreement setting */ function getCurrentSettingId() external view returns (uint256) { return _getCurrentSettingId(); } /** * @dev Tell the information related to an agreement setting * @param _settingId Identification number of the agreement setting * @return arbitrator Address of the IArbitrator that will be used to resolve disputes * @return aragonAppFeesCashier Address of the fees cashier to deposit action fees (linked to the selected arbitrator) * @return title String indicating a short description * @return content Link to a human-readable text that describes the current rules for the Agreement */ function getSetting(uint256 _settingId) external view returns (IArbitrator arbitrator, IAragonAppFeesCashier aragonAppFeesCashier, string title, bytes content) { Setting storage setting = _getSetting(_settingId); arbitrator = setting.arbitrator; aragonAppFeesCashier = setting.aragonAppFeesCashier; title = setting.title; content = setting.content; } /** * @dev Tell the information related to a Disputable app * @param _disputable Address of the Disputable app * @return activated Whether the Disputable app is active * @return currentCollateralRequirementId Identification number of the current collateral requirement */ function getDisputableInfo(address _disputable) external view returns (bool activated, uint256 currentCollateralRequirementId) { DisputableInfo storage disputableInfo = disputableInfos[_disputable]; activated = disputableInfo.activated; uint256 nextId = disputableInfo.nextCollateralRequirementsId; // Since `nextCollateralRequirementsId` is initialized to 1 when disputable apps are activated, it is safe to consider the // current collateral requirement ID of a disputable app as 0 if it has not been set yet, which means it was not activated yet. currentCollateralRequirementId = nextId == 0 ? 0 : nextId - 1; } /** * @dev Tell the information related to a collateral requirement of a Disputable app * @param _disputable Address of the Disputable app * @param _collateralRequirementId Identification number of the collateral requirement * @return collateralToken Address of the ERC20 token to be used for collateral * @return actionAmount Amount of collateral tokens that will be locked every time an action is created * @return challengeAmount Amount of collateral tokens that will be locked every time an action is challenged * @return challengeDuration Challenge duration, during which the submitter can raise a dispute */ function getCollateralRequirement(address _disputable, uint256 _collateralRequirementId) external view returns ( ERC20 collateralToken, uint64 challengeDuration, uint256 actionAmount, uint256 challengeAmount ) { DisputableInfo storage disputableInfo = disputableInfos[_disputable]; CollateralRequirement storage collateral = _getCollateralRequirement(disputableInfo, _collateralRequirementId); collateralToken = collateral.token; actionAmount = collateral.actionAmount; challengeAmount = collateral.challengeAmount; challengeDuration = collateral.challengeDuration; } /** * @dev Tell the information related to a signer * @param _signer Address of signer * @return lastSettingIdSigned Identification number of the last agreement setting signed by the signer * @return mustSign Whether the requested signer needs to sign the current agreement setting before submitting an action */ function getSigner(address _signer) external view returns (uint256 lastSettingIdSigned, bool mustSign) { (lastSettingIdSigned, mustSign) = _getSigner(_signer); } /** * @dev Tell the information related to an action * @param _actionId Identification number of the action * @return disputable Address of the Disputable app that created the action * @return disputableActionId Identification number of the action on the Disputable app * @return collateralRequirementId Identification number of the collateral requirement applicable to the action * @return settingId Identification number of the agreement setting applicable to the action * @return submitter Address that submitted the action * @return closed Whether the action is closed * @return context Link to a human-readable context for the action * @return lastChallengeId Identification number of the action's most recent challenge, if any * @return lastChallengeActive Whether the action's most recent challenge is still ongoing */ function getAction(uint256 _actionId) external view returns ( address disputable, uint256 disputableActionId, uint256 collateralRequirementId, uint256 settingId, address submitter, bool closed, bytes context, uint256 lastChallengeId, bool lastChallengeActive ) { Action storage action = _getAction(_actionId); disputable = action.disputable; disputableActionId = action.disputableActionId; collateralRequirementId = action.collateralRequirementId; settingId = action.settingId; submitter = action.submitter; closed = action.closed; context = action.context; lastChallengeId = action.lastChallengeId; if (lastChallengeId > 0) { (, Challenge storage challenge, ) = _getChallengedAction(_actionId); lastChallengeActive = _isWaitingChallengeAnswer(challenge) || _isDisputed(challenge); } } /** * @dev Tell the information related to an action challenge * @param _challengeId Identification number of the challenge * @return actionId Identification number of the action associated to the challenge * @return challenger Address that challenged the action * @return endDate Datetime of the last date the submitter can raise a dispute against the challenge * @return context Link to a human-readable context for the challenge * @return settlementOffer Amount of collateral tokens the challenger would accept for resolving the dispute without involving the arbitrator * @return state Current state of the challenge * @return submitterFinishedEvidence Whether the action submitter has finished submitting evidence for the associated dispute * @return challengerFinishedEvidence Whether the action challenger has finished submitting evidence for the associated dispute * @return disputeId Identification number of the associated dispute on the arbitrator * @return ruling Ruling given from the arbitrator for the dispute */ function getChallenge(uint256 _challengeId) external view returns ( uint256 actionId, address challenger, uint64 endDate, bytes context, uint256 settlementOffer, ChallengeState state, bool submitterFinishedEvidence, bool challengerFinishedEvidence, uint256 disputeId, uint256 ruling ) { Challenge storage challenge = _getChallenge(_challengeId); actionId = challenge.actionId; challenger = challenge.challenger; endDate = challenge.endDate; context = challenge.context; settlementOffer = challenge.settlementOffer; state = challenge.state; submitterFinishedEvidence = challenge.submitterFinishedEvidence; challengerFinishedEvidence = challenge.challengerFinishedEvidence; disputeId = challenge.disputeId; ruling = challenge.ruling; } /** * @dev Tell the arbitration fees paid for an action challenge * Split from `getChallenge()` due to “stack too deep issues” * @param _challengeId Identification number of the challenge * @return submitterArbitratorFeesToken ERC20 token used for the arbitration fees paid by the submitter (on dispute creation) * @return submitterArbitratorFeesAmount Amount of arbitration fees paid by the submitter (on dispute creation) * @return challengerArbitratorFeesToken ERC20 token used for the arbitration fees paid by the challenger (in advance) * @return challengerArbitratorFeesAmount Amount of arbitration fees paid by the challenger (in advance) */ function getChallengeArbitratorFees(uint256 _challengeId) external view returns ( ERC20 submitterArbitratorFeesToken, uint256 submitterArbitratorFeesAmount, ERC20 challengerArbitratorFeesToken, uint256 challengerArbitratorFeesAmount ) { Challenge storage challenge = _getChallenge(_challengeId); submitterArbitratorFeesToken = challenge.submitterArbitratorFees.token; submitterArbitratorFeesAmount = challenge.submitterArbitratorFees.amount; challengerArbitratorFeesToken = challenge.challengerArbitratorFees.token; challengerArbitratorFeesAmount = challenge.challengerArbitratorFees.amount; } /** * @dev Tell whether an action can be challenged * @param _actionId Identification number of the action * @return True if the action can be challenged, false otherwise */ function canChallenge(uint256 _actionId) external view returns (bool) { Action storage action = _getAction(_actionId); return _canChallenge(action); } /** * @dev Tell whether an action can be manually closed. * An action can be closed if it is allowed to: * - Proceed in the context of this Agreement (see `_canProceed()`), and * - Be closed in the context of the originating Disputable app * @param _actionId Identification number of the action * @return True if the action can be closed, false otherwise */ function canClose(uint256 _actionId) external view returns (bool) { Action storage action = _getAction(_actionId); return _canClose(action); } /** * @dev Tell whether an action can be settled * @param _actionId Identification number of the action * @return True if the action can be settled, false otherwise */ function canSettle(uint256 _actionId) external view returns (bool) { (, Challenge storage challenge, ) = _getChallengedAction(_actionId); return _canSettle(challenge); } /** * @dev Tell whether an action can be settled by claiming its challenge settlement * @param _actionId Identification number of the action * @return True if the action settlement can be claimed, false otherwise */ function canClaimSettlement(uint256 _actionId) external view returns (bool) { (, Challenge storage challenge, ) = _getChallengedAction(_actionId); return _canClaimSettlement(challenge); } /** * @dev Tell whether an action can be disputed * @param _actionId Identification number of the action * @return True if the action can be disputed, false otherwise */ function canDispute(uint256 _actionId) external view returns (bool) { (, Challenge storage challenge, ) = _getChallengedAction(_actionId); return _canDispute(challenge); } /** * @dev Tell whether an action's dispute can be ruled * @param _actionId Identification number of the action * @return True if the action's dispute can be ruled, false otherwise */ function canRuleDispute(uint256 _actionId) external view returns (bool) { (, Challenge storage challenge, ) = _getChallengedAction(_actionId); return _isDisputed(challenge); } /** * @dev Tell whether an address can challenge an action * @param _actionId Identification number of the action * @param _challenger Address of the challenger * @return True if the challenger can challenge the action, false otherwise */ function canPerformChallenge(uint256 _actionId, address _challenger) external view returns (bool) { Action storage action = _getAction(_actionId); return _canPerformChallenge(action.disputable, _challenger); } /** * @notice Tells whether an address has already signed the Agreement * @dev ACL oracle interface conformance * @return True if a parameterized address has signed the current version of the Agreement, false otherwise */ function canPerform(address /* _grantee */, address /* _where */, bytes32 /* _what */, uint256[] _how) external view returns (bool) { // We currently expect the address as the only permission parameter because an ACL Oracle's `grantee` // argument is not provided with the original sender if the permission is set for ANY_ENTITY. require(_how.length > 0, ERROR_ACL_ORACLE_SIGNER_MISSING); require(_how[0] < 2**160, ERROR_ACL_ORACLE_SIGNER_NOT_ADDRESS); address signer = address(_how[0]); (, bool mustSign) = _getSigner(signer); return !mustSign; } /** * @dev ILockManager conformance. * The Staking contract checks this on each request to unlock an amount managed by this Agreement. * It always returns false to disable owners from unlocking their funds arbitrarily, as we * want to control the release of the locked amount when actions are closed or settled. * @return Whether the request to unlock tokens of a given owner should be allowed */ function canUnlock(address, uint256) external view returns (bool) { return false; } /** * @dev Disable built-in AragonApp token recovery escape hatch. * This app is intended to hold users' funds and we do not want to allow them to be transferred to the default vault. * @return Always false */ function allowRecoverability(address /* _token */) public view returns (bool) { return false; } // Internal fns /** * @dev Change agreement settings * @param _arbitrator Address of the IArbitrator that will be used to resolve disputes * @param _setAppFeesCashier Whether to integrate with the IArbitrator's fee cashier * @param _title String indicating a short description * @param _content Link to a human-readable text that describes the new rules for the Agreement */ function _newSetting(IArbitrator _arbitrator, bool _setAppFeesCashier, string _title, bytes _content) internal { require(isContract(address(_arbitrator)), ERROR_ARBITRATOR_NOT_CONTRACT); uint256 id = nextSettingId++; Setting storage setting = settings[id]; setting.title = _title; setting.content = _content; setting.arbitrator = _arbitrator; // Note that if the Agreement app didn't have an app fees cashier set at the start, then it must be explicitly set later. // Arbitrators must always have at least some sort of subscription module, and having the flexibility to turn this off // on the Agreement side can be useful. setting.aragonAppFeesCashier = _setAppFeesCashier ? _getArbitratorFeesCashier(_arbitrator) : IAragonAppFeesCashier(0); emit SettingChanged(id); } /** * @dev Change the collateral requirements of an active Disputable app * @param _disputable Address of the Disputable app * @param _disputableInfo Disputable info instance for the Disputable app * @param _collateralToken Address of the ERC20 token to be used for collateral * @param _actionAmount Amount of collateral tokens that will be locked every time an action is submitted * @param _challengeAmount Amount of collateral tokens that will be locked every time an action is challenged * @param _challengeDuration Challenge duration, during which the submitter can raise a dispute */ function _changeCollateralRequirement( DisputableAragonApp _disputable, DisputableInfo storage _disputableInfo, ERC20 _collateralToken, uint64 _challengeDuration, uint256 _actionAmount, uint256 _challengeAmount ) internal { require(isContract(address(_collateralToken)), ERROR_TOKEN_NOT_CONTRACT); IStaking staking = stakingFactory.getOrCreateInstance(_collateralToken); uint256 id = _disputableInfo.nextCollateralRequirementsId++; CollateralRequirement storage collateralRequirement = _disputableInfo.collateralRequirements[id]; collateralRequirement.token = _collateralToken; collateralRequirement.challengeDuration = _challengeDuration; collateralRequirement.actionAmount = _actionAmount; collateralRequirement.challengeAmount = _challengeAmount; collateralRequirement.staking = staking; emit CollateralRequirementChanged(_disputable, id); } /** * @dev Pay transactions fees required for new actions * @param _setting Agreement setting instance, used to get Aragon App Fees Cashier * @param _disputable Address of the Disputable app, used to determine fees * @param _submitter Address that submitted the action * @param _actionId Identification number of the action being paid for */ function _payAppFees(Setting storage _setting, DisputableAragonApp _disputable, address _submitter, uint256 _actionId) internal { // Get fees IAragonAppFeesCashier aragonAppFeesCashier = _setting.aragonAppFeesCashier; if (aragonAppFeesCashier == IAragonAppFeesCashier(0)) { return; } bytes32 appId = _disputable.appId(); (ERC20 token, uint256 amount) = aragonAppFeesCashier.getAppFee(appId); if (amount == 0) { return; } // Pull the required amount from the fee token's staking pool and approve them to the cashier IStaking staking = stakingFactory.getOrCreateInstance(token); _lockBalance(staking, _submitter, amount); _slashBalance(staking, _submitter, address(this), amount); _approveFor(token, address(aragonAppFeesCashier), amount); // Pay fees aragonAppFeesCashier.payAppFees(appId, abi.encodePacked(_actionId)); } /** * @dev Close an action * This function does not perform any checks about the action status; callers must have already ensured the action can be closed. * @param _actionId Identification number of the action being closed * @param _action Action instance being closed */ function _unsafeCloseAction(uint256 _actionId, Action storage _action) internal { _action.closed = true; emit ActionClosed(_actionId); } /** * @dev Challenge an action * @param _actionId Identification number of the action being challenged * @param _action Action instance being challenged * @param _challenger Address challenging the action * @param _requirement Collateral requirement instance applicable to the challenge * @param _settlementOffer Amount of collateral tokens the challenger would accept for resolving the dispute without involving the arbitrator * @param _finishedSubmittingEvidence Whether the challenger is finished submitting evidence with the challenge context * @param _context Link to a human-readable context for the challenge * @return Identification number for the created challenge */ function _createChallenge( uint256 _actionId, Action storage _action, address _challenger, CollateralRequirement storage _requirement, uint256 _settlementOffer, bool _finishedSubmittingEvidence, bytes _context ) internal returns (uint256) { // Store challenge uint256 challengeId = nextChallengeId++; Challenge storage challenge = challenges[challengeId]; challenge.actionId = _actionId; challenge.challenger = _challenger; challenge.endDate = getTimestamp64().add(_requirement.challengeDuration); challenge.context = _context; challenge.settlementOffer = _settlementOffer; challenge.challengerFinishedEvidence = _finishedSubmittingEvidence; // Pull challenge collateral _depositFrom(_requirement.token, _challenger, _requirement.challengeAmount); // Pull pre-paid arbitrator fees from challenger IArbitrator arbitrator = _getArbitratorFor(_action); (, ERC20 feeToken, uint256 feeAmount) = arbitrator.getDisputeFees(); challenge.challengerArbitratorFees.token = feeToken; challenge.challengerArbitratorFees.amount = feeAmount; _depositFrom(feeToken, _challenger, feeAmount); return challengeId; } /** * @dev Dispute an action * @param _action Action instance being disputed * @param _challenge Currently open challenge instance for the action * @return _arbitrator Address of the IArbitrator applicable to the action * @return _metadata Metadata content to be used for the dispute * @return Identification number of the dispute created on the arbitrator */ function _createDispute(Action storage _action, Challenge storage _challenge, IArbitrator _arbitrator, bytes memory _metadata) internal returns (uint256) { // Pull arbitration fees from submitter (address disputeFeeRecipient, ERC20 feeToken, uint256 feeAmount) = _arbitrator.getDisputeFees(); _challenge.submitterArbitratorFees.token = feeToken; _challenge.submitterArbitratorFees.amount = feeAmount; address submitter = _action.submitter; _depositFrom(feeToken, submitter, feeAmount); // Create dispute. The arbitrator should pull its arbitration fees (if any) from this Agreement on `createDispute()`. _approveFor(feeToken, disputeFeeRecipient, feeAmount); uint256 disputeId = _arbitrator.createDispute(DISPUTES_POSSIBLE_OUTCOMES, _metadata); return disputeId; } /** * @dev Submit evidence for a dispute on an arbitrator * @param _arbitrator Arbitrator to submit evidence on * @param _disputeId Identification number of the dispute on the arbitrator * @param _submitter Address submitting the evidence * @param _evidence Evidence data to be submitted * @param _finished Whether the submitter is now finished submitting evidence */ function _submitEvidence(IArbitrator _arbitrator, uint256 _disputeId, address _submitter, bytes _evidence, bool _finished) internal { if (_evidence.length > 0) { emit EvidenceSubmitted(_arbitrator, _disputeId, _submitter, _evidence, _finished); } } /** * @dev Reject an action ("accept challenge") * @param _actionId Identification number of the action to be rejected * @param _action Action instance to be rejected * @param _challengeId Current challenge identification number for the action * @param _challenge Current challenge instance for the action */ function _rejectAction(uint256 _actionId, Action storage _action, uint256 _challengeId, Challenge storage _challenge) internal { _challenge.state = ChallengeState.Accepted; address challenger = _challenge.challenger; (DisputableAragonApp disputable, CollateralRequirement storage requirement) = _getDisputableInfoFor(_action); // Transfer action collateral, challenge collateral, and challenger arbitrator fees to the challenger _slashBalance(requirement.staking, _action.submitter, challenger, requirement.actionAmount); _transferTo(requirement.token, challenger, requirement.challengeAmount); _transferTo(_challenge.challengerArbitratorFees.token, challenger, _challenge.challengerArbitratorFees.amount); disputable.onDisputableActionRejected(_action.disputableActionId); emit ActionRejected(_actionId, _challengeId); _unsafeCloseAction(_actionId, _action); } /** * @dev Accept an action ("reject challenge") * @param _actionId Identification number of the action to be accepted * @param _action Action instance to be accepted * @param _challengeId Current challenge identification number for the action * @param _challenge Current challenge instance for the action */ function _acceptAction(uint256 _actionId, Action storage _action, uint256 _challengeId, Challenge storage _challenge) internal { _challenge.state = ChallengeState.Rejected; address submitter = _action.submitter; (DisputableAragonApp disputable, CollateralRequirement storage requirement) = _getDisputableInfoFor(_action); // Transfer challenge collateral and challenger arbitrator fees to the submitter _transferTo(requirement.token, submitter, requirement.challengeAmount); _transferTo(_challenge.challengerArbitratorFees.token, submitter, _challenge.challengerArbitratorFees.amount); disputable.onDisputableActionAllowed(_action.disputableActionId); emit ActionAccepted(_actionId, _challengeId); // Note that the action still continues after this ruling and will be closed at a future date } /** * @dev Void an action ("void challenge") * @param _actionId Identification number of the action to be voided * @param _action Action instance to be voided * @param _challengeId Current challenge identification number for the action * @param _challenge Current challenge instance for the action */ function _voidAction(uint256 _actionId, Action storage _action, uint256 _challengeId, Challenge storage _challenge) internal { _challenge.state = ChallengeState.Voided; (DisputableAragonApp disputable, CollateralRequirement storage requirement) = _getDisputableInfoFor(_action); address challenger = _challenge.challenger; // Return challenge collateral to the challenger, and split the challenger arbitrator fees between the challenger and the submitter _transferTo(requirement.token, challenger, requirement.challengeAmount); ERC20 challengerArbitratorFeesToken = _challenge.challengerArbitratorFees.token; uint256 challengerArbitratorFeesAmount = _challenge.challengerArbitratorFees.amount; uint256 submitterPayBack = challengerArbitratorFeesAmount / 2; // No need for Safemath because of previous computation uint256 challengerPayBack = challengerArbitratorFeesAmount - submitterPayBack; _transferTo(challengerArbitratorFeesToken, _action.submitter, submitterPayBack); _transferTo(challengerArbitratorFeesToken, challenger, challengerPayBack); disputable.onDisputableActionVoided(_action.disputableActionId); emit ActionVoided(_actionId, _challengeId); // Note that the action still continues after this ruling and will be closed at a future date } /** * @dev Lock some tokens in the staking pool for a user * @param _staking Staking pool for the ERC20 token to be locked * @param _user Address of the user to lock tokens for * @param _amount Amount of collateral tokens to be locked */ function _lockBalance(IStaking _staking, address _user, uint256 _amount) internal { if (_amount == 0) { return; } _staking.lock(_user, address(this), _amount); } /** * @dev Unlock some tokens in the staking pool for a user * @param _staking Staking pool for the ERC20 token to be unlocked * @param _user Address of the user to unlock tokens for * @param _amount Amount of collateral tokens to be unlocked */ function _unlockBalance(IStaking _staking, address _user, uint256 _amount) internal { if (_amount == 0) { return; } _staking.unlock(_user, address(this), _amount); } /** * @dev Slash some tokens in the staking pool from a user to a recipient * @param _staking Staking pool for the ERC20 token to be slashed * @param _user Address of the user to be slashed * @param _recipient Address receiving the slashed tokens * @param _amount Amount of collateral tokens to be slashed */ function _slashBalance(IStaking _staking, address _user, address _recipient, uint256 _amount) internal { if (_amount == 0) { return; } _staking.slashAndUnstake(_user, _recipient, _amount); } /** * @dev Transfer tokens to an address * @param _token ERC20 token to be transferred * @param _to Address receiving the tokens * @param _amount Amount of tokens to be transferred */ function _transferTo(ERC20 _token, address _to, uint256 _amount) internal { if (_amount > 0) { require(_token.safeTransfer(_to, _amount), ERROR_TOKEN_TRANSFER_FAILED); } } /** * @dev Deposit tokens from an address to this Agreement * @param _token ERC20 token to be transferred * @param _from Address transferring the tokens * @param _amount Amount of tokens to be transferred */ function _depositFrom(ERC20 _token, address _from, uint256 _amount) internal { if (_amount > 0) { require(_token.safeTransferFrom(_from, address(this), _amount), ERROR_TOKEN_DEPOSIT_FAILED); } } /** * @dev Approve tokens held by this Agreement to another address * @param _token ERC20 token used for the arbitration fees * @param _to Address to be approved * @param _amount Amount of `_arbitrationFeeToken` tokens to be approved */ function _approveFor(ERC20 _token, address _to, uint256 _amount) internal { if (_amount > 0) { // To be safe, we first set the allowance to zero in case there is a remaining approval for the arbitrator. // This is not strictly necessary for ERC20s, but some tokens, e.g. MiniMe (ANT and ANJ), // revert on an approval if an outstanding allowance exists require(_token.safeApprove(_to, 0), ERROR_TOKEN_APPROVAL_FAILED); require(_token.safeApprove(_to, _amount), ERROR_TOKEN_APPROVAL_FAILED); } } /** * @dev Fetch an agreement setting instance by identification number * @param _settingId Identification number of the agreement setting * @return Agreement setting instance associated to the given identification number */ function _getSetting(uint256 _settingId) internal view returns (Setting storage) { require(_settingId > 0 && _settingId < nextSettingId, ERROR_SETTING_DOES_NOT_EXIST); return settings[_settingId]; } /** * @dev Tell the identification number of the current agreement setting * @return Identification number of the current agreement setting */ function _getCurrentSettingId() internal view returns (uint256) { // An initial setting is created during initialization, thus after initialization, length will be always greater than 0 return nextSettingId == 0 ? 0 : nextSettingId - 1; } /** * @dev Tell the arbitrator to be used for an action * @param _action Action instance * @return arbitrator Address of the IArbitrator that will be used to resolve disputes */ function _getArbitratorFor(Action storage _action) internal view returns (IArbitrator) { Setting storage setting = _getSetting(_action.settingId); return setting.arbitrator; } /** * @dev Tell the app fees cashier instance associated to an arbitrator * @param _arbitrator Arbitrator querying the app fees cashier for * @return Address of the app fees cashier associated to the arbitrator */ function _getArbitratorFeesCashier(IArbitrator _arbitrator) internal view returns (IAragonAppFeesCashier) { (address cashier,,) = _arbitrator.getSubscriptionFees(address(this)); return IAragonAppFeesCashier(cashier); } /** * @dev Ensure a Disputable app is activate * @param _disputableInfo Disputable info of the app */ function _ensureActiveDisputable(DisputableInfo storage _disputableInfo) internal view { require(_disputableInfo.activated, ERROR_DISPUTABLE_NOT_ACTIVE); } /** * @dev Ensure a Disputable app is inactive * @param _disputableInfo Disputable info of the app */ function _ensureInactiveDisputable(DisputableInfo storage _disputableInfo) internal view { require(!_disputableInfo.activated, ERROR_DISPUTABLE_ALREADY_ACTIVE); } /** * @dev Tell the disputable-related information about an action * @param _action Action instance * @return disputable Address of the Disputable app associated to the action * @return requirement Collateral requirement instance applicable to the action */ function _getDisputableInfoFor(Action storage _action) internal view returns (DisputableAragonApp disputable, CollateralRequirement storage requirement) { disputable = _action.disputable; DisputableInfo storage disputableInfo = disputableInfos[address(disputable)]; requirement = _getCollateralRequirement(disputableInfo, _action.collateralRequirementId); } /** * @dev Fetch the collateral requirement instance by identification number for a Disputable app * @param _disputableInfo Disputable info instance * @param _collateralRequirementId Identification number of the collateral requirement * @return Collateral requirement instance associated to the given identification number */ function _getCollateralRequirement(DisputableInfo storage _disputableInfo, uint256 _collateralRequirementId) internal view returns (CollateralRequirement storage) { bool exists = _collateralRequirementId > 0 && _collateralRequirementId < _disputableInfo.nextCollateralRequirementsId; require(exists, ERROR_COLLATERAL_REQUIREMENT_DOES_NOT_EXIST); return _disputableInfo.collateralRequirements[_collateralRequirementId]; } /** * @dev Tell the information related to a signer * @param _signer Address of signer * @return lastSettingIdSigned Identification number of the last agreement setting signed by the signer * @return mustSign Whether the signer needs to sign the current agreement setting before submitting an action */ function _getSigner(address _signer) internal view returns (uint256 lastSettingIdSigned, bool mustSign) { lastSettingIdSigned = lastSettingSignedBy[_signer]; mustSign = lastSettingIdSigned < _getCurrentSettingId(); } /** * @dev Fetch an action instance by identification number * @param _actionId Identification number of the action * @return Action instance associated to the given identification number */ function _getAction(uint256 _actionId) internal view returns (Action storage) { require(_actionId > 0 && _actionId < nextActionId, ERROR_ACTION_DOES_NOT_EXIST); return actions[_actionId]; } /** * @dev Fetch a challenge instance by identification number * @param _challengeId Identification number of the challenge * @return Challenge instance associated to the given identification number */ function _getChallenge(uint256 _challengeId) internal view returns (Challenge storage) { require(_existChallenge(_challengeId), ERROR_CHALLENGE_DOES_NOT_EXIST); return challenges[_challengeId]; } /** * @dev Fetch an action instance along with its most recent challenge by identification number * @param _actionId Identification number of the action * @return action Action instance associated to the given identification number * @return challenge Most recent challenge instance associated to the action * @return challengeId Identification number of the most recent challenge associated to the action */ function _getChallengedAction(uint256 _actionId) internal view returns (Action storage action, Challenge storage challenge, uint256 challengeId) { action = _getAction(_actionId); challengeId = action.lastChallengeId; challenge = _getChallenge(challengeId); } /** * @dev Fetch a dispute's associated action and challenge instance * @param _disputeId Identification number of the dispute on the arbitrator * @return actionId Identification number of the action associated to the dispute * @return action Action instance associated to the dispute * @return challengeId Identification number of the challenge associated to the dispute * @return challenge Current challenge instance associated to the dispute */ function _getDisputedAction(uint256 _disputeId) internal view returns (uint256 actionId, Action storage action, uint256 challengeId, Challenge storage challenge) { challengeId = challengeByDispute[_disputeId]; challenge = _getChallenge(challengeId); actionId = challenge.actionId; action = _getAction(actionId); } /** * @dev Tell whether a challenge exists * @param _challengeId Identification number of the challenge * @return True if the requested challenge exists, false otherwise */ function _existChallenge(uint256 _challengeId) internal view returns (bool) { return _challengeId > 0 && _challengeId < nextChallengeId; } /** * @dev Tell whether an action can be manually closed * @param _action Action instance * @return True if the action can be closed, false otherwise */ function _canClose(Action storage _action) internal view returns (bool) { if (!_canProceed(_action)) { return false; } DisputableAragonApp disputable = _action.disputable; // Assume that the Disputable app does not need to be checked if it's the one asking us to close an action return DisputableAragonApp(msg.sender) == disputable || disputable.canClose(_action.disputableActionId); } /** * @dev Tell whether an action can be challenged * @param _action Action instance * @return True if the action can be challenged, false otherwise */ function _canChallenge(Action storage _action) internal view returns (bool) { return _canProceed(_action) && _action.disputable.canChallenge(_action.disputableActionId); } /** * @dev Tell whether an action can proceed to another state. * @dev An action can proceed if it is: * - Not closed * - Not currently challenged or disputed, and * - Not already settled or had a dispute rule in favour of the challenger (the action will have been closed automatically) * @param _action Action instance * @return True if the action can proceed, false otherwise */ function _canProceed(Action storage _action) internal view returns (bool) { // If the action was already closed, return false if (_action.closed) { return false; } uint256 challengeId = _action.lastChallengeId; // If the action has not been challenged yet, return true if (!_existChallenge(challengeId)) { return true; } // If the action was previously challenged but ruled in favour of the submitter or voided, return true Challenge storage challenge = challenges[challengeId]; ChallengeState state = challenge.state; return state == ChallengeState.Rejected || state == ChallengeState.Voided; } /** * @dev Tell whether a challenge can be settled * @param _challenge Challenge instance * @return True if the challenge can be settled, false otherwise */ function _canSettle(Challenge storage _challenge) internal view returns (bool) { return _isWaitingChallengeAnswer(_challenge); } /** * @dev Tell whether a challenge settlement can be claimed * @param _challenge Challenge instance * @return True if the challenge settlement can be claimed, false otherwise */ function _canClaimSettlement(Challenge storage _challenge) internal view returns (bool) { return _isWaitingChallengeAnswer(_challenge) && getTimestamp() >= uint256(_challenge.endDate); } /** * @dev Tell whether a challenge can be disputed * @param _challenge Challenge instance * @return True if the challenge can be disputed, false otherwise */ function _canDispute(Challenge storage _challenge) internal view returns (bool) { return _isWaitingChallengeAnswer(_challenge) && uint256(_challenge.endDate) > getTimestamp(); } /** * @dev Tell whether a challenge is waiting to be answered * @param _challenge Challenge instance * @return True if the challenge is waiting to be answered, false otherwise */ function _isWaitingChallengeAnswer(Challenge storage _challenge) internal view returns (bool) { return _challenge.state == ChallengeState.Waiting; } /** * @dev Tell whether a challenge is disputed * @param _challenge Challenge instance * @return True if the challenge is disputed, false otherwise */ function _isDisputed(Challenge storage _challenge) internal view returns (bool) { return _challenge.state == ChallengeState.Disputed; } /** * @dev Tell whether an address has permission to challenge actions on a specific Disputable app * @param _disputable Address of the Disputable app * @param _challenger Address of the challenger * @return True if the challenger can challenge actions on the Disputable app, false otherwise */ function _canPerformChallenge(DisputableAragonApp _disputable, address _challenger) internal view returns (bool) { IKernel currentKernel = kernel(); if (currentKernel == IKernel(0)) { return false; } // To make sure the challenger address is reachable by ACL oracles, we need to pass it as the first argument. // Permissions set with ANY_ENTITY do not provide the original sender's address into the ACL Oracle's `grantee` argument. bytes memory params = ConversionHelpers.dangerouslyCastUintArrayToBytes(arr(_challenger)); return currentKernel.hasPermission(_challenger, address(_disputable), CHALLENGE_ROLE, params); } }
* @title Arbitrable interface @dev This interface is implemented by `Agreement` so it can be used to submit disputes to an `IArbitrator`. since we are using different solidity versions./
contract IArbitrable is ERC165 { bytes4 internal constant ARBITRABLE_INTERFACE_ID = bytes4(0x88f3ee69); event Ruled(IArbitrator indexed arbitrator, uint256 indexed disputeId, uint256 ruling); event EvidenceSubmitted(IArbitrator indexed arbitrator, uint256 indexed disputeId, address indexed submitter, bytes evidence, bool finished); function submitEvidence(uint256 _disputeId, bytes _evidence, bool _finished) external; function rule(uint256 _disputeId, uint256 _ruling) external; } function supportsInterface(bytes4 _interfaceId) public pure returns (bool) { return super.supportsInterface(_interfaceId) || _interfaceId == ARBITRABLE_INTERFACE_ID; } }
10,762,546
[ 1, 686, 3682, 354, 7119, 1560, 225, 1220, 1560, 353, 8249, 635, 1375, 17420, 68, 1427, 518, 848, 506, 1399, 358, 4879, 1015, 458, 281, 358, 392, 1375, 45, 686, 3682, 86, 639, 8338, 1377, 3241, 732, 854, 1450, 3775, 18035, 560, 5244, 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, 16351, 467, 686, 3682, 354, 7119, 353, 4232, 39, 28275, 288, 203, 565, 1731, 24, 2713, 5381, 6052, 15650, 54, 2782, 67, 18865, 67, 734, 273, 1731, 24, 12, 20, 92, 5482, 74, 23, 1340, 8148, 1769, 203, 203, 565, 871, 6781, 72, 12, 45, 686, 3682, 86, 639, 8808, 10056, 86, 639, 16, 2254, 5034, 8808, 1015, 2507, 548, 16, 2254, 5034, 436, 332, 310, 1769, 203, 203, 565, 871, 512, 9526, 28882, 12, 45, 686, 3682, 86, 639, 8808, 10056, 86, 639, 16, 2254, 5034, 8808, 1015, 2507, 548, 16, 1758, 8808, 4879, 387, 16, 1731, 14481, 16, 1426, 6708, 1769, 203, 203, 565, 445, 4879, 30465, 12, 11890, 5034, 389, 2251, 2507, 548, 16, 1731, 389, 23431, 16, 1426, 389, 13527, 13, 3903, 31, 203, 203, 565, 445, 1720, 12, 11890, 5034, 389, 2251, 2507, 548, 16, 2254, 5034, 389, 86, 332, 310, 13, 3903, 31, 203, 203, 97, 203, 203, 565, 445, 6146, 1358, 12, 3890, 24, 389, 5831, 548, 13, 1071, 16618, 1135, 261, 6430, 13, 288, 203, 3639, 327, 2240, 18, 28064, 1358, 24899, 5831, 548, 13, 747, 389, 5831, 548, 422, 6052, 15650, 54, 2782, 67, 18865, 67, 734, 31, 203, 565, 289, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/43114/0xAf41a65F786339e7911F4acDAD6BD49426F2Dc6b/sources/contracts/meta/MetaSwapUtils.sol
* @notice Calculates the expected return amount from swapping between the pooled tokens and the underlying tokens of the base Swap pool. @param self Swap struct to read from @param metaSwapStorage MetaSwap struct from the same contract @param tokenIndexFrom the token to sell @param tokenIndexTo the token to buy @param dx the number of tokens to sell. If the token charges a fee on transfers, use the amount that gets transferred after the fee. @return dy the number of tokens the user will get/ tokenFrom is from this pool tokenFrom is from the base pool both from and to are from the base pool tokenTo is from this pool tokenTo is from the base pool
function calculateSwapUnderlying( SwapUtils.Swap storage self, MetaSwap storage metaSwapStorage, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view returns (uint256) { CalculateSwapUnderlyingInfo memory v = CalculateSwapUnderlyingInfo( _getBaseVirtualPrice(metaSwapStorage), metaSwapStorage.baseSwap, 0, uint8(metaSwapStorage.baseTokens.length), 0, 0, 0 ); uint256[] memory xp = _xp(self, v.baseVirtualPrice); v.baseLPTokenIndex = uint8(xp.length.sub(1)); { uint8 maxRange = v.baseLPTokenIndex + v.baseTokensLength; require( tokenIndexFrom < maxRange && tokenIndexTo < maxRange, "Token index out of range" ); } if (tokenIndexFrom < v.baseLPTokenIndex) { v.x = xp[tokenIndexFrom].add( dx.mul(self.tokenPrecisionMultipliers[tokenIndexFrom]) ); tokenIndexFrom = tokenIndexFrom - v.baseLPTokenIndex; if (tokenIndexTo < v.baseLPTokenIndex) { uint256[] memory baseInputs = new uint256[](v.baseTokensLength); baseInputs[tokenIndexFrom] = dx; v.x = v .baseSwap .calculateTokenAmount(baseInputs, true) .mul(v.baseVirtualPrice) .div(BASE_VIRTUAL_PRICE_PRECISION) .add(xp[v.baseLPTokenIndex]); return v.baseSwap.calculateSwap( tokenIndexFrom, tokenIndexTo - v.baseLPTokenIndex, dx ); } tokenIndexFrom = v.baseLPTokenIndex; } v.metaIndexTo = v.baseLPTokenIndex; if (tokenIndexTo < v.baseLPTokenIndex) { v.metaIndexTo = tokenIndexTo; } { uint256 y = SwapUtils.getY( self._getAPrecise(), tokenIndexFrom, v.metaIndexTo, v.x, xp ); v.dy = xp[v.metaIndexTo].sub(y).sub(1); uint256 dyFee = v.dy.mul(self.swapFee).div(FEE_DENOMINATOR); v.dy = v.dy.sub(dyFee); } if (tokenIndexTo < v.baseLPTokenIndex) { v.dy = v.dy.div(self.tokenPrecisionMultipliers[v.metaIndexTo]); v.dy = v.baseSwap.calculateRemoveLiquidityOneToken( v.dy.mul(BASE_VIRTUAL_PRICE_PRECISION).div(v.baseVirtualPrice), tokenIndexTo - v.baseLPTokenIndex ); } return v.dy; }
4,644,675
[ 1, 10587, 326, 2665, 327, 3844, 628, 7720, 1382, 3086, 326, 25007, 2430, 471, 326, 6808, 2430, 434, 326, 1026, 12738, 2845, 18, 225, 365, 12738, 1958, 358, 855, 628, 225, 2191, 12521, 3245, 6565, 12521, 1958, 628, 326, 1967, 6835, 225, 1147, 1016, 1265, 326, 1147, 358, 357, 80, 225, 1147, 1016, 774, 326, 1147, 358, 30143, 225, 6633, 326, 1300, 434, 2430, 358, 357, 80, 18, 971, 326, 1147, 1149, 2852, 279, 14036, 603, 29375, 16, 999, 326, 3844, 716, 5571, 906, 4193, 1839, 326, 14036, 18, 327, 7732, 326, 1300, 434, 2430, 326, 729, 903, 336, 19, 1147, 1265, 353, 628, 333, 2845, 1147, 1265, 353, 628, 326, 1026, 2845, 3937, 628, 471, 358, 854, 628, 326, 1026, 2845, 1147, 774, 353, 628, 333, 2845, 1147, 774, 353, 628, 326, 1026, 2845, 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, 4604, 12521, 14655, 6291, 12, 203, 3639, 12738, 1989, 18, 12521, 2502, 365, 16, 203, 3639, 6565, 12521, 2502, 2191, 12521, 3245, 16, 203, 3639, 2254, 28, 1147, 1016, 1265, 16, 203, 3639, 2254, 28, 1147, 1016, 774, 16, 203, 3639, 2254, 5034, 6633, 203, 565, 262, 3903, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 9029, 12521, 14655, 6291, 966, 3778, 331, 273, 203, 5411, 9029, 12521, 14655, 6291, 966, 12, 203, 7734, 389, 588, 2171, 6466, 5147, 12, 3901, 12521, 3245, 3631, 203, 7734, 2191, 12521, 3245, 18, 1969, 12521, 16, 203, 7734, 374, 16, 203, 7734, 2254, 28, 12, 3901, 12521, 3245, 18, 1969, 5157, 18, 2469, 3631, 203, 7734, 374, 16, 203, 7734, 374, 16, 203, 7734, 374, 203, 5411, 11272, 203, 203, 3639, 2254, 5034, 8526, 3778, 13681, 273, 389, 23829, 12, 2890, 16, 331, 18, 1969, 6466, 5147, 1769, 203, 3639, 331, 18, 1969, 14461, 1345, 1016, 273, 2254, 28, 12, 23829, 18, 2469, 18, 1717, 12, 21, 10019, 203, 3639, 288, 203, 5411, 2254, 28, 943, 2655, 273, 331, 18, 1969, 14461, 1345, 1016, 397, 331, 18, 1969, 5157, 1782, 31, 203, 5411, 2583, 12, 203, 7734, 1147, 1016, 1265, 411, 943, 2655, 597, 1147, 1016, 774, 411, 943, 2655, 16, 203, 7734, 315, 1345, 770, 596, 434, 1048, 6, 203, 5411, 11272, 203, 3639, 289, 203, 203, 3639, 309, 261, 2316, 1016, 1265, 411, 331, 18, 1969, 14461, 1345, 1016, 13, 288, 203, 5411, 331, 18, 92, 273, 13681, 63, 2316, 1016, 1265, 2 ]
./partial_match/42/0x4B8F9C9d3D5709ce30Dd911b504Ef7ab4d2b6F93/sources/AErc20.sol
Set initial exchange rate Initialize block number and borrow index (block number mocks depend on controller being set)
constructor( ) public { admin = msg.sender; initialExchangeRateMantissa = uint(200000000000000000000000000); accrualBlockNumber = getBlockNumber(); borrowIndex = mantissaOne; name = string("Artem DAI"); symbol = string("aDAI"); decimals = uint(8); }
8,957,319
[ 1, 694, 2172, 7829, 4993, 9190, 1203, 1300, 471, 29759, 770, 261, 2629, 1300, 15895, 2447, 603, 2596, 3832, 444, 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 ]
[ 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, 3885, 12, 262, 1071, 288, 7010, 3639, 3981, 273, 1234, 18, 15330, 31, 203, 203, 3639, 2172, 11688, 4727, 49, 970, 21269, 273, 2254, 12, 22, 12648, 12648, 2787, 9449, 1769, 203, 203, 3639, 4078, 86, 1462, 1768, 1854, 273, 11902, 1854, 5621, 203, 3639, 29759, 1016, 273, 31340, 3335, 31, 203, 203, 3639, 508, 273, 533, 2932, 686, 874, 463, 18194, 8863, 203, 3639, 3273, 273, 533, 2932, 69, 9793, 45, 8863, 203, 3639, 15105, 273, 2254, 12, 28, 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 ]
pragma solidity ^0.7.1; pragma experimental ABIEncoderV2; library BootDaoLib { bytes32 constant DAO_STORAGE_POSITION = keccak256("diamond.standard.dao.storage"); // @notice Ballot receipt record for a voter struct Receipt { // @notice Whether or not a vote has been cast bool hasVoted; // @notice Whether or not the voter supports the proposal bool support; // @notice The number of votes the voter had, which were cast uint votes; } struct Proposal { // @notice Unique id for looking up a proposal uint id; string description; // @notice Creator of the proposal address proposer; // @notice the ordered list of target addresses for calls to be made address[] targets; // @notice The ordered list of values (i.e. msg.value) to be passed to the calls to be made uint[] values; // @notice The ordered list of function signatures to be called string[] signatures; // @notice The ordered list of calldata to be passed to each call bytes[] calldatas; // @notice The block at which voting begins: holders must delegate their votes prior to this block uint startBlock; // @notice The block at which voting ends: votes must be cast prior to this block uint endBlock; // @notice The timestamp that the proposal will be available for execution, set once the vote succeeds uint unlockTime; // @notice Current number of votes in favor of this proposal uint forVotes; // @notice Current number of votes in opposition to this proposal uint againstVotes; // @notice Flag marking whether the proposal has been canceled bool canceled; // @notice Flag marking whether the proposal has been executed bool executed; // @notice Receipts of ballots for the entire set of voters mapping(address => Receipt) receipts; } struct DaoStorage { string title; address[] members; address genesisAddress; uint proposalCount; mapping(uint => Proposal) proposals; mapping(address => uint) balances; } function daoStorage() internal pure returns (DaoStorage storage ds) { bytes32 position = DAO_STORAGE_POSITION; assembly { ds.slot := position } } function getProposal(uint id) internal view returns (Proposal storage) { DaoStorage storage ds = daoStorage(); return ds.proposals[id]; } }
@notice Whether or not a vote has been cast @notice Whether or not the voter supports the proposal @notice The number of votes the voter had, which were cast
struct Receipt { bool hasVoted; bool support; uint votes; }
6,472,245
[ 1, 18247, 578, 486, 279, 12501, 711, 2118, 4812, 225, 17403, 578, 486, 326, 331, 20005, 6146, 326, 14708, 225, 1021, 1300, 434, 19588, 326, 331, 20005, 9323, 16, 1492, 4591, 4812, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1958, 29787, 288, 203, 3639, 1426, 711, 58, 16474, 31, 203, 203, 3639, 1426, 2865, 31, 203, 203, 3639, 2254, 19588, 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 ]
./full_match/80001/0x523BcdE5d98f3D205D917229a3fea4aA76214F32/sources/diamond/MyDiamond.sol
import {AppStorage} from "./AppStorage.sol";
import "@solidstate/contracts/proxy/diamond/SolidStateDiamond.sol";
9,488,062
[ 1, 5666, 288, 3371, 3245, 97, 628, 25165, 3371, 3245, 18, 18281, 14432, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5666, 8787, 30205, 2019, 19, 16351, 87, 19, 5656, 19, 3211, 301, 1434, 19, 25044, 1119, 14521, 301, 1434, 18, 18281, 14432, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/4/0xE32A88aAc056507F2E40a261ACd99742c377B6b3/sources/contracts/PriceDiscovery.sol
@notice Call to get users BUSD deposit. @param _user Users account @return Recalculated value of deposit
function getTotalDepositedByUser(address _user) public view returns(uint256) { uint256 total; for (uint8 i = 0; i < uint8(Stage.Closed); i++) { total += amountDepositedByUserAndStage[_user][i]; } return total; }
12,470,932
[ 1, 1477, 358, 336, 3677, 605, 3378, 40, 443, 1724, 18, 225, 389, 1355, 12109, 2236, 327, 868, 22113, 460, 434, 443, 1724, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 12831, 758, 1724, 18696, 1299, 12, 2867, 389, 1355, 13, 1071, 1476, 1135, 12, 11890, 5034, 13, 288, 203, 3639, 2254, 5034, 2078, 31, 203, 203, 3639, 364, 261, 11890, 28, 277, 273, 374, 31, 277, 411, 2254, 28, 12, 8755, 18, 7395, 1769, 277, 27245, 288, 203, 5411, 2078, 1011, 3844, 758, 1724, 18696, 1299, 1876, 8755, 63, 67, 1355, 6362, 77, 15533, 203, 3639, 289, 203, 3639, 327, 2078, 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 ]
// SPDX-License-Identifier: MIT pragma solidity =0.8.11; import {BoringOwnable} from "BoringOwnable.sol"; import "UUPSUpgradeable.sol"; import "SafeERC20.sol"; import "ERC20.sol"; import "ReentrancyGuard.sol"; import "ERC20VotesUpgradeable.sol"; import {IVault, IAsset} from "IVault.sol"; import "IWeightedPool.sol"; import "IPriceOracle.sol"; import "ILiquidityGauge.sol"; import "IBalancerMinter.sol"; import "BalancerUtils.sol"; contract sNOTE is ERC20VotesUpgradeable, BoringOwnable, UUPSUpgradeable, ReentrancyGuard { using SafeERC20 for ERC20; IVault public immutable BALANCER_VAULT; ERC20 public immutable NOTE; ERC20 public immutable BALANCER_POOL_TOKEN; ERC20 public immutable WETH; bytes32 public immutable NOTE_ETH_POOL_ID; ILiquidityGauge public immutable LIQUIDITY_GAUGE; address public immutable TREASURY_MANAGER_CONTRACT; IBalancerMinter public immutable BALANCER_MINTER; ERC20 public immutable BALANCER_TOKEN; /// @notice Balancer token indexes /// Balancer requires token addresses to be sorted BAL#102 uint256 public immutable WETH_INDEX; uint256 public immutable NOTE_INDEX; /// @notice Maximum shortfall withdraw of 50% uint256 public constant MAX_SHORTFALL_WITHDRAW = 50; uint256 public constant SHORTFALL_WITHDRAW_COOLDOWN = 7 days; /// @notice Redemption window in seconds uint256 public constant REDEEM_WINDOW_SECONDS = 3 days; uint32 public constant MAXIMUM_COOL_DOWN_PERIOD_SECONDS = 30 days; /// @notice From IPriceOracle.getLargestSafeQueryWindow uint32 public constant MAX_ORACLE_WINDOW_SIZE = 122400; /// @notice Number of seconds that need to pass before sNOTE can be redeemed uint32 public coolDownTimeInSeconds; /// @notice Timestamp of the last time a shortfall was withdrawn uint32 public lastShortfallWithdrawTime; /// @notice Mapping between sNOTE holders and their cool down status mapping(address => uint256) public accountRedeemWindowBegin; /// @notice Window for time weighted oracle price uint32 public votingOracleWindowInSeconds; /// @notice Emitted when a cool down begins event CoolDownStarted( address indexed account, uint256 redeemWindowBegin, uint256 redeemWindowEnd ); /// @notice Emitted when a cool down ends event CoolDownEnded(address indexed account); /// @notice Emitted when cool down time is updated event GlobalCoolDownUpdated(uint256 newCoolDownTimeSeconds); /// @notice Emitted when sNote is minted event SNoteMinted( address indexed account, uint256 wethChangeAmount, uint256 noteChangeAmount, uint256 bptChangeAmount ); /// @notice Emitted when sNote is redeemed event SNoteRedeemed( address indexed account, uint256 wethChangeAmount, uint256 noteChangeAmount, uint256 bptChangeAmount ); event ClaimedBAL(uint256 balAmount); /// @notice Emitted when voting power oracle window is updated event VotingOracleWindowUpdated(uint256 _votingOracleWindowInSeconds); /** Errors **/ error ManagerRequired(address sender); error OwnerOrManagerRequired(address sender); modifier onlyManagerContract() { if (TREASURY_MANAGER_CONTRACT != msg.sender) revert ManagerRequired(msg.sender); _; } modifier ownerOrManagerContract() { if (TREASURY_MANAGER_CONTRACT != msg.sender && owner != msg.sender) revert OwnerOrManagerRequired(msg.sender); _; } /// @notice Constructor sets immutable contract addresses constructor( IVault _balancerVault, bytes32 _noteETHPoolId, uint256 _wethIndex, uint256 _noteIndex, ILiquidityGauge _liquidityGauge, address _treasuryManagerContract, IBalancerMinter _balancerMinter ) initializer { // Validate that the pool exists // prettier-ignore (address poolAddress, /* */) = _balancerVault.getPool(_noteETHPoolId); require(poolAddress != address(0)); WETH_INDEX = _wethIndex; NOTE_INDEX = _noteIndex; // prettier-ignore (address[] memory tokens, /* */, /* */) = _balancerVault.getPoolTokens(_noteETHPoolId); WETH = ERC20(tokens[_wethIndex]); NOTE = ERC20(tokens[_noteIndex]); NOTE_ETH_POOL_ID = _noteETHPoolId; BALANCER_VAULT = _balancerVault; BALANCER_POOL_TOKEN = ERC20(poolAddress); LIQUIDITY_GAUGE = _liquidityGauge; TREASURY_MANAGER_CONTRACT = _treasuryManagerContract; BALANCER_MINTER = _balancerMinter; BALANCER_TOKEN = ERC20(_balancerMinter.getBalancerToken()); } /** Governance Methods **/ /// @notice Authorizes the DAO to upgrade this contract function _authorizeUpgrade( address /* newImplementation */ ) internal override onlyOwner {} /// @notice Updates the required cooldown time to redeem function setCoolDownTime(uint32 _coolDownTimeInSeconds) external onlyOwner { require(_coolDownTimeInSeconds <= MAXIMUM_COOL_DOWN_PERIOD_SECONDS); coolDownTimeInSeconds = _coolDownTimeInSeconds; emit GlobalCoolDownUpdated(_coolDownTimeInSeconds); } /// @notice Updates the voting power oracle window function setVotingOracleWindow(uint32 _votingOracleWindowInSeconds) external onlyOwner { require(_votingOracleWindowInSeconds <= MAX_ORACLE_WINDOW_SIZE); votingOracleWindowInSeconds = _votingOracleWindowInSeconds; emit VotingOracleWindowUpdated(_votingOracleWindowInSeconds); } /// @notice Allows the DAO to extract up to 50% of the BPT tokens during a collateral shortfall event function extractTokensForCollateralShortfall(uint256 requestedWithdraw) external nonReentrant onlyOwner { // Check that the last shortfall withdraw time was not recent uint32 blockTime = _safe32(block.timestamp); require( lastShortfallWithdrawTime + SHORTFALL_WITHDRAW_COOLDOWN < blockTime, "Shortfall Cooldown" ); lastShortfallWithdrawTime = blockTime; uint256 bptBalance = _bptHeld(); uint256 maxBPTWithdraw = (bptBalance * MAX_SHORTFALL_WITHDRAW) / 100; // Do not allow a withdraw of more than the MAX_SHORTFALL_WITHDRAW percentage. Specifically don't // revert here since there may be a delay between when governance issues the token amount and when // the withdraw actually occurs. uint256 bptExitAmount = requestedWithdraw > maxBPTWithdraw ? maxBPTWithdraw : requestedWithdraw; IAsset[] memory assets = new IAsset[](2); assets[WETH_INDEX] = IAsset(address(WETH)); assets[NOTE_INDEX] = IAsset(address(NOTE)); // Accept whatever NOTE/WETH we will receive here, since these // withdraws will be in a timelock it will be difficult to determine // how the pool will be constituted at the time of withdraw _exitPool(assets, new uint256[](2), bptExitAmount); } /// @notice Allows the DAO to set the swap fee on the BPT function setSwapFeePercentage(uint256 swapFeePercentage) external onlyOwner { IWeightedPool(address(BALANCER_POOL_TOKEN)).setSwapFeePercentage( swapFeePercentage ); } /** User Methods **/ /// @notice Mints sNOTE from the underlying BPT token. /// @param bptAmount is the amount of BPT to transfer from the msg.sender. function mintFromBPT(uint256 bptAmount) external nonReentrant { // _mint logic requires that tokens are transferred first if (bptAmount == 0) return; BALANCER_POOL_TOKEN.safeTransferFrom( msg.sender, address(this), bptAmount ); // This will stake BPT into the liquidity gauge _mint(msg.sender, bptAmount); (uint256 wethAmount, uint256 noteAmount) = getTokenClaimForBPT( bptAmount ); emit SNoteMinted(msg.sender, wethAmount, noteAmount, bptAmount); } /// @notice Mints sNOTE from some amount of NOTE and ETH /// @param noteAmount amount of NOTE to transfer into the sNOTE contract /// @param minBPT slippage parameter to prevent front running function mintFromETH(uint256 noteAmount, uint256 minBPT) external payable nonReentrant { // Transfer the NOTE balance into sNOTE first if (noteAmount > 0) NOTE.safeTransferFrom(msg.sender, address(this), noteAmount); IAsset[] memory assets = new IAsset[](2); uint256[] memory maxAmountsIn = new uint256[](2); assets[WETH_INDEX] = IAsset(address(0)); assets[NOTE_INDEX] = IAsset(address(NOTE)); maxAmountsIn[WETH_INDEX] = msg.value; maxAmountsIn[NOTE_INDEX] = noteAmount; _mintFromAssets(assets, maxAmountsIn, minBPT); } /// @notice Mints sNOTE from some amount of NOTE and WETH /// @param noteAmount amount of NOTE to transfer into the sNOTE contract /// @param wethAmount amount of WETH to transfer into the sNOTE contract /// @param minBPT slippage parameter to prevent front running function mintFromWETH( uint256 noteAmount, uint256 wethAmount, uint256 minBPT ) external nonReentrant { // Transfer the NOTE and WETH balance into sNOTE first if (noteAmount > 0) NOTE.safeTransferFrom(msg.sender, address(this), noteAmount); if (wethAmount > 0) WETH.safeTransferFrom(msg.sender, address(this), wethAmount); IAsset[] memory assets = new IAsset[](2); uint256[] memory maxAmountsIn = new uint256[](2); assets[WETH_INDEX] = IAsset(address(WETH)); assets[NOTE_INDEX] = IAsset(address(NOTE)); maxAmountsIn[WETH_INDEX] = wethAmount; maxAmountsIn[NOTE_INDEX] = noteAmount; _mintFromAssets(assets, maxAmountsIn, minBPT); } function _mintFromAssets( IAsset[] memory assets, uint256[] memory maxAmountsIn, uint256 minBPT ) internal { // Don't use _bptHeld here because we are just detecting the change // in BPT tokens from minting uint256 bptBefore = BALANCER_POOL_TOKEN.balanceOf(address(this)); // Set msgValue when joining via ETH uint256 msgValue = assets[WETH_INDEX] == IAsset(address(0)) ? maxAmountsIn[WETH_INDEX] : 0; BALANCER_VAULT.joinPool{value: msgValue}( NOTE_ETH_POOL_ID, address(this), address(this), // sNOTE will receive the BPT IVault.JoinPoolRequest( assets, maxAmountsIn, abi.encode( IVault.JoinKind.EXACT_TOKENS_IN_FOR_BPT_OUT, maxAmountsIn, minBPT ), false // Don't use internal balances ) ); // Don't use _bptHeld here because we are just detecting the change // in BPT tokens from minting uint256 bptAfter = BALANCER_POOL_TOKEN.balanceOf(address(this)); // Balancer pool token amounts must increase uint256 bptChange = bptAfter - bptBefore; // This will stake BPT into the liquidity gauge _mint(msg.sender, bptChange); emit SNoteMinted( msg.sender, maxAmountsIn[WETH_INDEX], maxAmountsIn[NOTE_INDEX], bptChange ); } function _exitPool( IAsset[] memory assets, uint256[] memory minAmountsOut, uint256 bptExitAmount ) internal { // Unstake BPT LIQUIDITY_GAUGE.withdraw(bptExitAmount, false); uint256 wethBefore = address(assets[WETH_INDEX]) == address(0) ? msg.sender.balance : IERC20(address(assets[WETH_INDEX])).balanceOf(msg.sender); uint256 noteBefore = IERC20(address(assets[NOTE_INDEX])).balanceOf( msg.sender ); BALANCER_VAULT.exitPool( NOTE_ETH_POOL_ID, address(this), payable(msg.sender), // Owner will receive the underlying assets IVault.ExitPoolRequest( assets, minAmountsOut, abi.encode( IVault.ExitKind.EXACT_BPT_IN_FOR_TOKENS_OUT, bptExitAmount ), false // Don't use internal balances ) ); uint256 wethAfter = address(assets[WETH_INDEX]) == address(0) ? msg.sender.balance : IERC20(address(assets[WETH_INDEX])).balanceOf(msg.sender); uint256 noteAfter = IERC20(address(assets[NOTE_INDEX])).balanceOf( msg.sender ); emit SNoteRedeemed( msg.sender, wethAfter - wethBefore, noteAfter - noteBefore, bptExitAmount ); } /// @notice Begins a cool down period for the sender, this is required to redeem tokens function startCoolDown() external { // Cannot start a cool down if there is already one in effect _requireAccountNotInCoolDown(msg.sender); uint256 redeemWindowBegin = block.timestamp + coolDownTimeInSeconds; uint256 redeemWindowEnd = redeemWindowBegin + REDEEM_WINDOW_SECONDS; accountRedeemWindowBegin[msg.sender] = redeemWindowBegin; emit CoolDownStarted(msg.sender, redeemWindowBegin, redeemWindowEnd); } /// @notice Stops a cool down for the sender function stopCoolDown() external { // Reset the cool down back to zero so that the account must initiate it again to redeem delete accountRedeemWindowBegin[msg.sender]; emit CoolDownEnded(msg.sender); } /// @notice Redeems some amount of sNOTE to underlying constituent tokens (ETH and NOTE). /// An account must have passed its cool down expiration before they can redeem /// @param sNOTEAmount amount of sNOTE to redeem /// @param minWETH slippage protection for ETH/WETH amount /// @param minNOTE slippage protection for NOTE amount /// @param redeemWETH true if redeeming to WETH to ETH function redeem( uint256 sNOTEAmount, uint256 minWETH, uint256 minNOTE, bool redeemWETH ) external nonReentrant { uint256 redeemWindowBegin = accountRedeemWindowBegin[msg.sender]; uint256 redeemWindowEnd = redeemWindowBegin + REDEEM_WINDOW_SECONDS; require( redeemWindowBegin != 0 && redeemWindowBegin <= block.timestamp && block.timestamp <= redeemWindowEnd, "Not in Redemption Window" ); uint256 bptToRedeem = getPoolTokenShare(sNOTEAmount); // Handles event emission, balance update and total supply update _burn(msg.sender, sNOTEAmount); if (bptToRedeem > 0) { IAsset[] memory assets = new IAsset[](2); uint256[] memory minAmountsOut = new uint256[](2); assets[WETH_INDEX] = redeemWETH ? IAsset(address(0)) : IAsset(address(WETH)); assets[NOTE_INDEX] = IAsset(address(NOTE)); minAmountsOut[WETH_INDEX] = minWETH; minAmountsOut[NOTE_INDEX] = minNOTE; _exitPool(assets, minAmountsOut, bptToRedeem); } } /// @notice Allows the treasury manager contract to claim BAL from the liquidity gauge function claimBAL() external nonReentrant onlyManagerContract { uint256 balBefore = BALANCER_TOKEN.balanceOf(address(this)); BALANCER_MINTER.mint(address(LIQUIDITY_GAUGE)); uint256 balAfter = BALANCER_TOKEN.balanceOf(address(this)); uint256 claimAmount = balAfter - balBefore; BALANCER_TOKEN.safeTransfer(TREASURY_MANAGER_CONTRACT, claimAmount); emit ClaimedBAL(claimAmount); } function _stakeAll() internal { uint256 bptBalance = BALANCER_POOL_TOKEN.balanceOf(address(this)); LIQUIDITY_GAUGE.deposit(bptBalance, address(this), false); } /// @notice Approve and stake all tokens in one transaction function approveAndStakeAll() external nonReentrant onlyOwner { BALANCER_POOL_TOKEN.safeApprove( address(LIQUIDITY_GAUGE), type(uint256).max ); _stakeAll(); } /// @notice Deposits all BPT owned by the sNOTE contract into the liquidity gauge function stakeAll() external nonReentrant ownerOrManagerContract { _stakeAll(); } /// @dev Gets the total BPT held across the LIQUIDITY GAUGE and the contract itself function _bptHeld() internal view returns (uint256) { return (LIQUIDITY_GAUGE.balanceOf(address(this)) + BALANCER_POOL_TOKEN.balanceOf(address(this))); } /** External View Methods **/ /// @notice Returns the WETH and NOTE claim for an amount of sNOTE function getTokenClaim(uint256 sNOTEAmount) public view returns (uint256 wethBalance, uint256 noteBalance) { return getTokenClaimForBPT(getPoolTokenShare(sNOTEAmount)); } /// @notice Returns the WETH and NOTE claim for an address function tokenClaimOf(address account) public view returns (uint256 wethBalance, uint256 noteBalance) { return getTokenClaimForBPT(getPoolTokenShare(balanceOf(account))); } /// @notice Returns the WETH and NOTE claim for an amount of BPT function getTokenClaimForBPT(uint256 bptAmount) public view returns (uint256 wethBalance, uint256 noteBalance) { // prettier-ignore ( /* address[] memory tokens */, uint256[] memory balances, /* uint256 lastChangeBlock */ ) = BALANCER_VAULT.getPoolTokens(NOTE_ETH_POOL_ID); uint256 bptSupply = BALANCER_POOL_TOKEN.totalSupply(); // increase NOTE precision to 1e18 uint256 noteBal = balances[NOTE_INDEX] * 1e10; wethBalance = (balances[WETH_INDEX] * bptAmount) / bptSupply; noteBalance = (noteBal * bptAmount) / bptSupply / 1e10; } /// @notice Returns how many Balancer pool tokens an sNOTE token amount has a claim on function getPoolTokenShare(uint256 sNOTEAmount) public view returns (uint256 bptClaim) { uint256 _totalSupply = totalSupply(); if (_totalSupply == 0) return 0; uint256 bptBalance = _bptHeld(); // BPT and sNOTE are both in 18 decimal precision so no conversion required return (bptBalance * sNOTEAmount) / _totalSupply; } /// @notice Returns the pool token share of a specific account function poolTokenShareOf(address account) public view returns (uint256 bptClaim) { return getPoolTokenShare(balanceOf(account)); } /// @notice Returns the voting power of an account without consulting delegation, /// used for off chain Snapshot voting. function votingPowerWithoutDelegation(address account) public view returns (uint256) { return getVotingPower(balanceOf(account)); } /// @notice Calculates voting power for a given amount of sNOTE /// @param sNOTEAmount amount of sNOTE to calculate voting power for /// @return corresponding NOTE voting power function getVotingPower(uint256 sNOTEAmount) public view returns (uint256) { uint256 _totalSupply = totalSupply(); if (_totalSupply == 0) return 0; // Gets the BPT token price (in ETH) uint256 bptPrice = BalancerUtils.getTimeWeightedOraclePrice( address(BALANCER_POOL_TOKEN), IPriceOracle.Variable.BPT_PRICE, uint256(votingOracleWindowInSeconds) ); // Gets the NOTE token price (in ETH) uint256 notePrice = BalancerUtils.getTimeWeightedOraclePrice( address(BALANCER_POOL_TOKEN), IPriceOracle.Variable.PAIR_PRICE, uint256(votingOracleWindowInSeconds) ); // Since both bptPrice and notePrice are denominated in ETH, we can use // this formula to calculate noteAmount // (bptBalance * 0.8) * bptPrice = notePrice * noteAmount // noteAmount = (bptPrice * bptBalance * 0.8) / notePrice uint256 bptBalance = _bptHeld(); // This calculation is (NOTE tokens are in 8 decimal precision): // (1e18 * 1e18 * 1e2) / (1e18 * 1e2 * 1e10) == 1e8 uint256 noteAmount = (bptPrice * bptBalance * 80) / (notePrice * 100 * 1e10); return (noteAmount * sNOTEAmount) / _totalSupply; } /// @notice Calculates current voting power for a given account /// @param account a given sNOTE holding account /// @return corresponding NOTE voting power function getVotes(address account) public view override returns (uint256) { return getVotingPower(super.getVotes(account)); } /// @notice Calculates voting power for on chain voting (for use with OpenZeppelin Governor) /// @param account a given sNOTE holding account /// @param blockNumber a block number to calculate voting power at /// @return corresponding NOTE voting power function getPastVotes(address account, uint256 blockNumber) public view override returns (uint256) { return getVotingPower(super.getPastVotes(account, blockNumber)); } /** Internal Methods **/ function _requireAccountNotInCoolDown(address account) internal view { uint256 redeemWindowBegin = accountRedeemWindowBegin[account]; uint256 redeemWindowEnd = redeemWindowBegin + REDEEM_WINDOW_SECONDS; // An account is not in cool down if the redeem window is not set (== 0) or // if the window has already passed (redeemWindowEnd < block.timestamp) require( redeemWindowBegin == 0 || redeemWindowEnd < block.timestamp, "Account in Cool Down" ); } /// @notice Mints sNOTE tokens given a bptAmount /// @param account account to mint tokens to /// @param bptAmount the number of BPT tokens being minted by the account function _mint(address account, uint256 bptAmount) internal override { // Stake BPT LIQUIDITY_GAUGE.deposit(bptAmount, address(this), false); // Immediately after minting, we need to satisfy the equality: // (sNOTEToMint * bptBalance) / (totalSupply + sNOTEToMint) == bptAmount // Rearranging to get sNOTEToMint on one side: // (sNOTEToMint * bptBalance) = (totalSupply + sNOTEToMint) * bptAmount // (sNOTEToMint * bptBalance) = totalSupply * bptAmount + sNOTEToMint * bptAmount // (sNOTEToMint * bptBalance) - (sNOTEToMint * bptAmount) = totalSupply * bptAmount // sNOTEToMint * (bptBalance - bptAmount) = totalSupply * bptAmount // sNOTEToMint = (totalSupply * bptAmount) / (bptBalance - bptAmount) // NOTE: at this point the BPT has already been transferred into the sNOTE contract, so this // bptBalance amount includes bptAmount. uint256 bptBalance = _bptHeld(); uint256 _totalSupply = totalSupply(); uint256 sNOTEToMint; if (_totalSupply == 0) { sNOTEToMint = bptAmount; } else { sNOTEToMint = (_totalSupply * bptAmount) / (bptBalance - bptAmount); } // Handles event emission, balance update and total supply update super._mint(account, sNOTEToMint); } function _beforeTokenTransfer( address from, address to, uint256 amount ) internal override { // Cannot send or receive tokens if a cool down is in effect or else accounts // can bypass the cool down. It's not clear if sending tokens can be used to bypass // the cool down but we restrict it here anyway, there's no clear use case for sending // sNOTE tokens during a cool down. if (to != address(0)) { // Run these checks only when we are not burning tokens. (OZ ERC20 does not allow transfers // to address(0), to == address(0) only when _burn is called). // from == address(0) when minting, no need to check cool down if (from != address(0)) _requireAccountNotInCoolDown(from); _requireAccountNotInCoolDown(to); } super._beforeTokenTransfer(from, to, amount); } function _safe32(uint256 x) internal pure returns (uint32) { require(x <= type(uint32).max); return uint32(x); } } // SPDX-License-Identifier: MIT pragma solidity =0.8.11; // Audit on 5-Jan-2021 by Keno and BoringCrypto // Source: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/access/Ownable.sol + Claimable.sol // Edited by BoringCrypto contract BoringOwnableData { address public owner; address public pendingOwner; } contract BoringOwnable is BoringOwnableData { event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /// @notice Transfers ownership to `newOwner`. Either directly or claimable by the new pending owner. /// Can only be invoked by the current `owner`. /// @param newOwner Address of the new owner. /// @param direct True if `newOwner` should be set immediately. False if `newOwner` needs to use `claimOwnership`. /// @param renounce Allows the `newOwner` to be `address(0)` if `direct` and `renounce` is True. Has no effect otherwise. function transferOwnership( address newOwner, bool direct, bool renounce ) external onlyOwner { if (direct) { // Checks require(newOwner != address(0) || renounce, "Ownable: zero address"); // Effects emit OwnershipTransferred(owner, newOwner); owner = newOwner; pendingOwner = address(0); } else { // Effects pendingOwner = newOwner; } } /// @notice Needs to be called by `pendingOwner` to claim ownership. function claimOwnership() external { address _pendingOwner = pendingOwner; // Checks require(msg.sender == _pendingOwner, "Ownable: caller != pending owner"); // Effects emit OwnershipTransferred(owner, _pendingOwner); owner = _pendingOwner; pendingOwner = address(0); } /// @notice Only allows the `owner` to execute the function. modifier onlyOwner() { require(msg.sender == owner, "Ownable: caller is not the owner"); _; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (proxy/utils/UUPSUpgradeable.sol) pragma solidity ^0.8.0; import "draft-IERC1822.sol"; import "ERC1967Upgrade.sol"; /** * @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an * {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy. * * A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is * reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing * `UUPSUpgradeable` with a custom implementation of upgrades. * * The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism. * * _Available since v4.1._ */ abstract contract UUPSUpgradeable is IERC1822Proxiable, ERC1967Upgrade { /// @custom:oz-upgrades-unsafe-allow state-variable-immutable state-variable-assignment address private immutable __self = address(this); /** * @dev Check that the execution is being performed through a delegatecall call and that the execution context is * a proxy contract with an implementation (as defined in ERC1967) pointing to self. This should only be the case * for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a * function through ERC1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to * fail. */ modifier onlyProxy() { require(address(this) != __self, "Function must be called through delegatecall"); require(_getImplementation() == __self, "Function must be called through active proxy"); _; } /** * @dev Check that the execution is not being performed through a delegate call. This allows a function to be * callable on the implementing contract but not through proxies. */ modifier notDelegated() { require(address(this) == __self, "UUPSUpgradeable: must not be called through delegatecall"); _; } /** * @dev Implementation of the ERC1822 {proxiableUUID} function. This returns the storage slot used by the * implementation. It is used to validate that the this implementation remains valid after an upgrade. * * IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks * bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this * function revert if invoked through a proxy. This is guaranteed by the `notDelegated` modifier. */ function proxiableUUID() external view virtual override notDelegated returns (bytes32) { return _IMPLEMENTATION_SLOT; } /** * @dev Upgrade the implementation of the proxy to `newImplementation`. * * Calls {_authorizeUpgrade}. * * Emits an {Upgraded} event. */ function upgradeTo(address newImplementation) external virtual onlyProxy { _authorizeUpgrade(newImplementation); _upgradeToAndCallUUPS(newImplementation, new bytes(0), false); } /** * @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call * encoded in `data`. * * Calls {_authorizeUpgrade}. * * Emits an {Upgraded} event. */ function upgradeToAndCall(address newImplementation, bytes memory data) external payable virtual onlyProxy { _authorizeUpgrade(newImplementation); _upgradeToAndCallUUPS(newImplementation, data, true); } /** * @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by * {upgradeTo} and {upgradeToAndCall}. * * Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}. * * ```solidity * function _authorizeUpgrade(address) internal override onlyOwner {} * ``` */ function _authorizeUpgrade(address newImplementation) internal virtual; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (interfaces/draft-IERC1822.sol) pragma solidity ^0.8.0; /** * @dev ERC1822: Universal Upgradeable Proxy Standard (UUPS) documents a method for upgradeability through a simplified * proxy whose upgrades are fully controlled by the current implementation. */ interface IERC1822Proxiable { /** * @dev Returns the storage slot that the proxiable contract assumes is being used to store the implementation * address. * * IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks * bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this * function revert if invoked through a proxy. */ function proxiableUUID() external view returns (bytes32); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (proxy/ERC1967/ERC1967Upgrade.sol) pragma solidity ^0.8.2; import "IBeacon.sol"; import "draft-IERC1822.sol"; import "Address.sol"; import "StorageSlot.sol"; /** * @dev This abstract contract provides getters and event emitting update functions for * https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots. * * _Available since v4.1._ * * @custom:oz-upgrades-unsafe-allow delegatecall */ abstract contract ERC1967Upgrade { // This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1 bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143; /** * @dev Storage slot with the address of the current implementation. * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; /** * @dev Emitted when the implementation is upgraded. */ event Upgraded(address indexed implementation); /** * @dev Returns the current implementation address. */ function _getImplementation() internal view returns (address) { return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value; } /** * @dev Stores a new address in the EIP1967 implementation slot. */ function _setImplementation(address newImplementation) private { require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract"); StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; } /** * @dev Perform implementation upgrade * * Emits an {Upgraded} event. */ function _upgradeTo(address newImplementation) internal { _setImplementation(newImplementation); emit Upgraded(newImplementation); } /** * @dev Perform implementation upgrade with additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCall( address newImplementation, bytes memory data, bool forceCall ) internal { _upgradeTo(newImplementation); if (data.length > 0 || forceCall) { Address.functionDelegateCall(newImplementation, data); } } /** * @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCallUUPS( address newImplementation, bytes memory data, bool forceCall ) internal { // Upgrades from old implementations will perform a rollback test. This test requires the new // implementation to upgrade back to the old, non-ERC1822 compliant, implementation. Removing // this special case will break upgrade paths from old UUPS implementation to new ones. if (StorageSlot.getBooleanSlot(_ROLLBACK_SLOT).value) { _setImplementation(newImplementation); } else { try IERC1822Proxiable(newImplementation).proxiableUUID() returns (bytes32 slot) { require(slot == _IMPLEMENTATION_SLOT, "ERC1967Upgrade: unsupported proxiableUUID"); } catch { revert("ERC1967Upgrade: new implementation is not UUPS"); } _upgradeToAndCall(newImplementation, data, forceCall); } } /** * @dev Storage slot with the admin of the contract. * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; /** * @dev Emitted when the admin account has changed. */ event AdminChanged(address previousAdmin, address newAdmin); /** * @dev Returns the current admin. */ function _getAdmin() internal view returns (address) { return StorageSlot.getAddressSlot(_ADMIN_SLOT).value; } /** * @dev Stores a new address in the EIP1967 admin slot. */ function _setAdmin(address newAdmin) private { require(newAdmin != address(0), "ERC1967: new admin is the zero address"); StorageSlot.getAddressSlot(_ADMIN_SLOT).value = newAdmin; } /** * @dev Changes the admin of the proxy. * * Emits an {AdminChanged} event. */ function _changeAdmin(address newAdmin) internal { emit AdminChanged(_getAdmin(), newAdmin); _setAdmin(newAdmin); } /** * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy. * This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor. */ bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50; /** * @dev Emitted when the beacon is upgraded. */ event BeaconUpgraded(address indexed beacon); /** * @dev Returns the current beacon. */ function _getBeacon() internal view returns (address) { return StorageSlot.getAddressSlot(_BEACON_SLOT).value; } /** * @dev Stores a new beacon in the EIP1967 beacon slot. */ function _setBeacon(address newBeacon) private { require(Address.isContract(newBeacon), "ERC1967: new beacon is not a contract"); require( Address.isContract(IBeacon(newBeacon).implementation()), "ERC1967: beacon implementation is not a contract" ); StorageSlot.getAddressSlot(_BEACON_SLOT).value = newBeacon; } /** * @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does * not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that). * * Emits a {BeaconUpgraded} event. */ function _upgradeBeaconToAndCall( address newBeacon, bytes memory data, bool forceCall ) internal { _setBeacon(newBeacon); emit BeaconUpgraded(newBeacon); if (data.length > 0 || forceCall) { Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data); } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (proxy/beacon/IBeacon.sol) pragma solidity ^0.8.0; /** * @dev This is the interface that {BeaconProxy} expects of its beacon. */ interface IBeacon { /** * @dev Must return an address that can be used as a delegate call target. * * {BeaconProxy} will check that this address is a contract. */ function implementation() external view returns (address); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/StorageSlot.sol) pragma solidity ^0.8.0; /** * @dev Library for reading and writing primitive types to specific storage slots. * * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts. * This library helps with reading and writing to such slots without the need for inline assembly. * * The functions in this library return Slot structs that contain a `value` member that can be used to read or write. * * Example usage to set ERC1967 implementation slot: * ``` * contract ERC1967 { * bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; * * function _getImplementation() internal view returns (address) { * return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value; * } * * function _setImplementation(address newImplementation) internal { * require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract"); * StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; * } * } * ``` * * _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._ */ library StorageSlot { struct AddressSlot { address value; } struct BooleanSlot { bool value; } struct Bytes32Slot { bytes32 value; } struct Uint256Slot { uint256 value; } /** * @dev Returns an `AddressSlot` with member `value` located at `slot`. */ function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `BooleanSlot` with member `value` located at `slot`. */ function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Bytes32Slot` with member `value` located at `slot`. */ function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Uint256Slot` with member `value` located at `slot`. */ function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) { assembly { r.slot := slot } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol) pragma solidity ^0.8.0; import "IERC20.sol"; import "Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `to`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `from` to `to` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/ERC20.sol) pragma solidity ^0.8.0; import "IERC20.sol"; import "IERC20Metadata.sol"; import "Context.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC20 * applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `to` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address to, uint256 amount) public virtual override returns (bool) { address owner = _msgSender(); _transfer(owner, to, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on * `transferFrom`. This is semantically equivalent to an infinite approval. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { address owner = _msgSender(); _approve(owner, spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * NOTE: Does not update the allowance if the current allowance * is the maximum `uint256`. * * Requirements: * * - `from` and `to` cannot be the zero address. * - `from` must have a balance of at least `amount`. * - the caller must have allowance for ``from``'s tokens of at least * `amount`. */ function transferFrom( address from, address to, uint256 amount ) public virtual override returns (bool) { address spender = _msgSender(); _spendAllowance(from, spender, amount); _transfer(from, to, amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { address owner = _msgSender(); _approve(owner, spender, _allowances[owner][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { address owner = _msgSender(); uint256 currentAllowance = _allowances[owner][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(owner, spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `from` must have a balance of at least `amount`. */ function _transfer( address from, address to, uint256 amount ) internal virtual { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(from, to, amount); uint256 fromBalance = _balances[from]; require(fromBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[from] = fromBalance - amount; } _balances[to] += amount; emit Transfer(from, to, amount); _afterTokenTransfer(from, to, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Spend `amount` form the allowance of `owner` toward `spender`. * * Does not update the allowance amount in case of infinite allowance. * Revert if not enough allowance is available. * * Might emit an {Approval} event. */ function _spendAllowance( address owner, address spender, uint256 amount ) internal virtual { uint256 currentAllowance = allowance(owner, spender); if (currentAllowance != type(uint256).max) { require(currentAllowance >= amount, "ERC20: insufficient allowance"); unchecked { _approve(owner, spender, currentAllowance - amount); } } } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol) pragma solidity ^0.8.0; import "IERC20.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol) pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/extensions/ERC20Votes.sol) pragma solidity ^0.8.0; import "draft-ERC20PermitUpgradeable.sol"; import "MathUpgradeable.sol"; import "IVotesUpgradeable.sol"; import "SafeCastUpgradeable.sol"; import "ECDSAUpgradeable.sol"; import "Initializable.sol"; /** * @dev Extension of ERC20 to support Compound-like voting and delegation. This version is more generic than Compound's, * and supports token supply up to 2^224^ - 1, while COMP is limited to 2^96^ - 1. * * NOTE: If exact COMP compatibility is required, use the {ERC20VotesComp} variant of this module. * * This extension keeps a history (checkpoints) of each account's vote power. Vote power can be delegated either * by calling the {delegate} function directly, or by providing a signature to be used with {delegateBySig}. Voting * power can be queried through the public accessors {getVotes} and {getPastVotes}. * * By default, token balance does not account for voting power. This makes transfers cheaper. The downside is that it * requires users to delegate to themselves in order to activate checkpoints and have their voting power tracked. * * _Available since v4.2._ */ abstract contract ERC20VotesUpgradeable is Initializable, IVotesUpgradeable, ERC20PermitUpgradeable { function __ERC20Votes_init() internal onlyInitializing { } function __ERC20Votes_init_unchained() internal onlyInitializing { } struct Checkpoint { uint32 fromBlock; uint224 votes; } bytes32 private constant _DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); mapping(address => address) private _delegates; mapping(address => Checkpoint[]) private _checkpoints; Checkpoint[] private _totalSupplyCheckpoints; /** * @dev Get the `pos`-th checkpoint for `account`. */ function checkpoints(address account, uint32 pos) public view virtual returns (Checkpoint memory) { return _checkpoints[account][pos]; } /** * @dev Get number of checkpoints for `account`. */ function numCheckpoints(address account) public view virtual returns (uint32) { return SafeCastUpgradeable.toUint32(_checkpoints[account].length); } /** * @dev Get the address `account` is currently delegating to. */ function delegates(address account) public view virtual override returns (address) { return _delegates[account]; } /** * @dev Gets the current votes balance for `account` */ function getVotes(address account) public view virtual override returns (uint256) { uint256 pos = _checkpoints[account].length; return pos == 0 ? 0 : _checkpoints[account][pos - 1].votes; } /** * @dev Retrieve the number of votes for `account` at the end of `blockNumber`. * * Requirements: * * - `blockNumber` must have been already mined */ function getPastVotes(address account, uint256 blockNumber) public view virtual override returns (uint256) { require(blockNumber < block.number, "ERC20Votes: block not yet mined"); return _checkpointsLookup(_checkpoints[account], blockNumber); } /** * @dev Retrieve the `totalSupply` at the end of `blockNumber`. Note, this value is the sum of all balances. * It is but NOT the sum of all the delegated votes! * * Requirements: * * - `blockNumber` must have been already mined */ function getPastTotalSupply(uint256 blockNumber) public view virtual override returns (uint256) { require(blockNumber < block.number, "ERC20Votes: block not yet mined"); return _checkpointsLookup(_totalSupplyCheckpoints, blockNumber); } /** * @dev Lookup a value in a list of (sorted) checkpoints. */ function _checkpointsLookup(Checkpoint[] storage ckpts, uint256 blockNumber) private view returns (uint256) { // We run a binary search to look for the earliest checkpoint taken after `blockNumber`. // // During the loop, the index of the wanted checkpoint remains in the range [low-1, high). // With each iteration, either `low` or `high` is moved towards the middle of the range to maintain the invariant. // - If the middle checkpoint is after `blockNumber`, we look in [low, mid) // - If the middle checkpoint is before or equal to `blockNumber`, we look in [mid+1, high) // Once we reach a single value (when low == high), we've found the right checkpoint at the index high-1, if not // out of bounds (in which case we're looking too far in the past and the result is 0). // Note that if the latest checkpoint available is exactly for `blockNumber`, we end up with an index that is // past the end of the array, so we technically don't find a checkpoint after `blockNumber`, but it works out // the same. uint256 high = ckpts.length; uint256 low = 0; while (low < high) { uint256 mid = MathUpgradeable.average(low, high); if (ckpts[mid].fromBlock > blockNumber) { high = mid; } else { low = mid + 1; } } return high == 0 ? 0 : ckpts[high - 1].votes; } /** * @dev Delegate votes from the sender to `delegatee`. */ function delegate(address delegatee) public virtual override { _delegate(_msgSender(), delegatee); } /** * @dev Delegates votes from signer to `delegatee` */ function delegateBySig( address delegatee, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s ) public virtual override { require(block.timestamp <= expiry, "ERC20Votes: signature expired"); address signer = ECDSAUpgradeable.recover( _hashTypedDataV4(keccak256(abi.encode(_DELEGATION_TYPEHASH, delegatee, nonce, expiry))), v, r, s ); require(nonce == _useNonce(signer), "ERC20Votes: invalid nonce"); _delegate(signer, delegatee); } /** * @dev Maximum token supply. Defaults to `type(uint224).max` (2^224^ - 1). */ function _maxSupply() internal view virtual returns (uint224) { return type(uint224).max; } /** * @dev Snapshots the totalSupply after it has been increased. */ function _mint(address account, uint256 amount) internal virtual override { super._mint(account, amount); require(totalSupply() <= _maxSupply(), "ERC20Votes: total supply risks overflowing votes"); _writeCheckpoint(_totalSupplyCheckpoints, _add, amount); } /** * @dev Snapshots the totalSupply after it has been decreased. */ function _burn(address account, uint256 amount) internal virtual override { super._burn(account, amount); _writeCheckpoint(_totalSupplyCheckpoints, _subtract, amount); } /** * @dev Move voting power when tokens are transferred. * * Emits a {DelegateVotesChanged} event. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual override { super._afterTokenTransfer(from, to, amount); _moveVotingPower(delegates(from), delegates(to), amount); } /** * @dev Change delegation for `delegator` to `delegatee`. * * Emits events {DelegateChanged} and {DelegateVotesChanged}. */ function _delegate(address delegator, address delegatee) internal virtual { address currentDelegate = delegates(delegator); uint256 delegatorBalance = balanceOf(delegator); _delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveVotingPower(currentDelegate, delegatee, delegatorBalance); } function _moveVotingPower( address src, address dst, uint256 amount ) private { if (src != dst && amount > 0) { if (src != address(0)) { (uint256 oldWeight, uint256 newWeight) = _writeCheckpoint(_checkpoints[src], _subtract, amount); emit DelegateVotesChanged(src, oldWeight, newWeight); } if (dst != address(0)) { (uint256 oldWeight, uint256 newWeight) = _writeCheckpoint(_checkpoints[dst], _add, amount); emit DelegateVotesChanged(dst, oldWeight, newWeight); } } } function _writeCheckpoint( Checkpoint[] storage ckpts, function(uint256, uint256) view returns (uint256) op, uint256 delta ) private returns (uint256 oldWeight, uint256 newWeight) { uint256 pos = ckpts.length; oldWeight = pos == 0 ? 0 : ckpts[pos - 1].votes; newWeight = op(oldWeight, delta); if (pos > 0 && ckpts[pos - 1].fromBlock == block.number) { ckpts[pos - 1].votes = SafeCastUpgradeable.toUint224(newWeight); } else { ckpts.push(Checkpoint({fromBlock: SafeCastUpgradeable.toUint32(block.number), votes: SafeCastUpgradeable.toUint224(newWeight)})); } } function _add(uint256 a, uint256 b) private pure returns (uint256) { return a + b; } function _subtract(uint256 a, uint256 b) private pure returns (uint256) { return a - b; } /** * This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[47] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-ERC20Permit.sol) pragma solidity ^0.8.0; import "draft-IERC20PermitUpgradeable.sol"; import "ERC20Upgradeable.sol"; import "draft-EIP712Upgradeable.sol"; import "ECDSAUpgradeable.sol"; import "CountersUpgradeable.sol"; import "Initializable.sol"; /** * @dev Implementation of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. * * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by * presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. * * _Available since v3.4._ */ abstract contract ERC20PermitUpgradeable is Initializable, ERC20Upgradeable, IERC20PermitUpgradeable, EIP712Upgradeable { using CountersUpgradeable for CountersUpgradeable.Counter; mapping(address => CountersUpgradeable.Counter) private _nonces; // solhint-disable-next-line var-name-mixedcase bytes32 private _PERMIT_TYPEHASH; /** * @dev Initializes the {EIP712} domain separator using the `name` parameter, and setting `version` to `"1"`. * * It's a good idea to use the same `name` that is defined as the ERC20 token name. */ function __ERC20Permit_init(string memory name) internal onlyInitializing { __EIP712_init_unchained(name, "1"); __ERC20Permit_init_unchained(name); } function __ERC20Permit_init_unchained(string memory) internal onlyInitializing { _PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");} /** * @dev See {IERC20Permit-permit}. */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public virtual override { require(block.timestamp <= deadline, "ERC20Permit: expired deadline"); bytes32 structHash = keccak256(abi.encode(_PERMIT_TYPEHASH, owner, spender, value, _useNonce(owner), deadline)); bytes32 hash = _hashTypedDataV4(structHash); address signer = ECDSAUpgradeable.recover(hash, v, r, s); require(signer == owner, "ERC20Permit: invalid signature"); _approve(owner, spender, value); } /** * @dev See {IERC20Permit-nonces}. */ function nonces(address owner) public view virtual override returns (uint256) { return _nonces[owner].current(); } /** * @dev See {IERC20Permit-DOMAIN_SEPARATOR}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view override returns (bytes32) { return _domainSeparatorV4(); } /** * @dev "Consume a nonce": return the current value and increment. * * _Available since v4.1._ */ function _useNonce(address owner) internal virtual returns (uint256 current) { CountersUpgradeable.Counter storage nonce = _nonces[owner]; current = nonce.current(); nonce.increment(); } /** * This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[49] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-IERC20Permit.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. * * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. */ interface IERC20PermitUpgradeable { /** * @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: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/ERC20.sol) pragma solidity ^0.8.0; import "IERC20Upgradeable.sol"; import "IERC20MetadataUpgradeable.sol"; import "ContextUpgradeable.sol"; import "Initializable.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin 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 ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable, IERC20MetadataUpgradeable { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ function __ERC20_init(string memory name_, string memory symbol_) internal onlyInitializing { __ERC20_init_unchained(name_, symbol_); } function __ERC20_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing { _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 {} /** * This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[45] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `to`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `from` to `to` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol) pragma solidity ^0.8.0; import "IERC20Upgradeable.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20MetadataUpgradeable is IERC20Upgradeable { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.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 meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal onlyInitializing { } function __Context_init_unchained() internal onlyInitializing { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } /** * This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (proxy/utils/Initializable.sol) pragma solidity ^0.8.0; import "AddressUpgradeable.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. * * [CAUTION] * ==== * Avoid leaving a contract uninitialized. * * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation * contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the * initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed: * * [.hljs-theme-light.nopadding] * ``` * /// @custom:oz-upgrades-unsafe-allow constructor * constructor() initializer {} * ``` * ==== */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { // If the contract is initializing we ignore whether _initialized is set in order to support multiple // inheritance patterns, but we only do this in the context of a constructor, because in other contexts the // contract may have been reentered. require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /** * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the * {initializer} modifier, directly or indirectly. */ modifier onlyInitializing() { require(_initializing, "Initializable: contract is not initializing"); _; } function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/cryptography/draft-EIP712.sol) pragma solidity ^0.8.0; import "ECDSAUpgradeable.sol"; import "Initializable.sol"; /** * @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data. * * The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible, * thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding * they need in their contracts using a combination of `abi.encode` and `keccak256`. * * This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding * scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA * ({_hashTypedDataV4}). * * The implementation of the domain separator was designed to be as efficient as possible while still properly updating * the chain id to protect against replay attacks on an eventual fork of the chain. * * NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method * https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask]. * * _Available since v3.4._ */ abstract contract EIP712Upgradeable is Initializable { /* solhint-disable var-name-mixedcase */ bytes32 private _HASHED_NAME; bytes32 private _HASHED_VERSION; bytes32 private constant _TYPE_HASH = keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"); /* solhint-enable var-name-mixedcase */ /** * @dev Initializes the domain separator and parameter caches. * * The meaning of `name` and `version` is specified in * https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]: * * - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol. * - `version`: the current major version of the signing domain. * * NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart * contract upgrade]. */ function __EIP712_init(string memory name, string memory version) internal onlyInitializing { __EIP712_init_unchained(name, version); } function __EIP712_init_unchained(string memory name, string memory version) internal onlyInitializing { bytes32 hashedName = keccak256(bytes(name)); bytes32 hashedVersion = keccak256(bytes(version)); _HASHED_NAME = hashedName; _HASHED_VERSION = hashedVersion; } /** * @dev Returns the domain separator for the current chain. */ function _domainSeparatorV4() internal view returns (bytes32) { return _buildDomainSeparator(_TYPE_HASH, _EIP712NameHash(), _EIP712VersionHash()); } function _buildDomainSeparator( bytes32 typeHash, bytes32 nameHash, bytes32 versionHash ) private view returns (bytes32) { return keccak256(abi.encode(typeHash, nameHash, versionHash, block.chainid, address(this))); } /** * @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this * function returns the hash of the fully encoded EIP712 message for this domain. * * This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example: * * ```solidity * bytes32 digest = _hashTypedDataV4(keccak256(abi.encode( * keccak256("Mail(address to,string contents)"), * mailTo, * keccak256(bytes(mailContents)) * ))); * address signer = ECDSA.recover(digest, signature); * ``` */ function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) { return ECDSAUpgradeable.toTypedDataHash(_domainSeparatorV4(), structHash); } /** * @dev The hash of the name parameter for the EIP712 domain. * * NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs * are a concern. */ function _EIP712NameHash() internal virtual view returns (bytes32) { return _HASHED_NAME; } /** * @dev The hash of the version parameter for the EIP712 domain. * * NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs * are a concern. */ function _EIP712VersionHash() internal virtual view returns (bytes32) { return _HASHED_VERSION; } /** * This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (utils/cryptography/ECDSA.sol) pragma solidity ^0.8.0; import "StringsUpgradeable.sol"; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSAUpgradeable { enum RecoverError { NoError, InvalidSignature, InvalidSignatureLength, InvalidSignatureS, InvalidSignatureV } function _throwError(RecoverError error) private pure { if (error == RecoverError.NoError) { return; // no error: do nothing } else if (error == RecoverError.InvalidSignature) { revert("ECDSA: invalid signature"); } else if (error == RecoverError.InvalidSignatureLength) { revert("ECDSA: invalid signature length"); } else if (error == RecoverError.InvalidSignatureS) { revert("ECDSA: invalid signature 's' value"); } else if (error == RecoverError.InvalidSignatureV) { revert("ECDSA: invalid signature 'v' value"); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature` or error string. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. * * Documentation for signature generation: * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js] * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers] * * _Available since v4.3._ */ function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) { // Check the signature length // - case 65: r,s,v signature (standard) // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._ if (signature.length == 65) { bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return tryRecover(hash, v, r, s); } else if (signature.length == 64) { bytes32 r; bytes32 vs; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) vs := mload(add(signature, 0x40)) } return tryRecover(hash, r, vs); } else { return (address(0), RecoverError.InvalidSignatureLength); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, signature); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately. * * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures] * * _Available since v4.3._ */ function tryRecover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address, RecoverError) { bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff); uint8 v = uint8((uint256(vs) >> 255) + 27); return tryRecover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately. * * _Available since v4.2._ */ function recover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, r, vs); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `v`, * `r` and `s` signature fields separately. * * _Available since v4.3._ */ function tryRecover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address, RecoverError) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return (address(0), RecoverError.InvalidSignatureS); } if (v != 27 && v != 28) { return (address(0), RecoverError.InvalidSignatureV); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); if (signer == address(0)) { return (address(0), RecoverError.InvalidSignature); } return (signer, RecoverError.NoError); } /** * @dev Overload of {ECDSA-recover} that receives the `v`, * `r` and `s` signature fields separately. */ function recover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, v, r, s); _throwError(error); return recovered; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } /** * @dev Returns an Ethereum Signed Message, created from `s`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", StringsUpgradeable.toString(s.length), s)); } /** * @dev Returns an Ethereum Signed Typed Data, created from a * `domainSeparator` and a `structHash`. This produces hash corresponding * to the one signed with the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] * JSON-RPC method as part of EIP-712. * * See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library StringsUpgradeable { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Counters.sol) pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library CountersUpgradeable { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (utils/math/Math.sol) pragma solidity ^0.8.0; /** * @dev Standard math utilities missing in the Solidity language. */ library MathUpgradeable { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow. return (a & b) + (a ^ b) / 2; } /** * @dev Returns the ceiling of the division of two numbers. * * This differs from standard division with `/` in that it rounds up instead * of rounding down. */ function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b - 1) / b can overflow on addition, so we distribute. return a / b + (a % b == 0 ? 0 : 1); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (governance/utils/IVotes.sol) pragma solidity ^0.8.0; /** * @dev Common interface for {ERC20Votes}, {ERC721Votes}, and other {Votes}-enabled contracts. * * _Available since v4.5._ */ interface IVotesUpgradeable { /** * @dev Emitted when an account changes their delegate. */ event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /** * @dev Emitted when a token transfer or delegate change results in changes to a delegate's number of votes. */ event DelegateVotesChanged(address indexed delegate, uint256 previousBalance, uint256 newBalance); /** * @dev Returns the current amount of votes that `account` has. */ function getVotes(address account) external view returns (uint256); /** * @dev Returns the amount of votes that `account` had at the end of a past block (`blockNumber`). */ function getPastVotes(address account, uint256 blockNumber) external view returns (uint256); /** * @dev Returns the total supply of votes available at the end of a past block (`blockNumber`). * * NOTE: This value is the sum of all available votes, which is not necessarily the sum of all delegated votes. * Votes that have not been delegated are still part of total supply, even though they would not participate in a * vote. */ function getPastTotalSupply(uint256 blockNumber) external view returns (uint256); /** * @dev Returns the delegate that `account` has chosen. */ function delegates(address account) external view returns (address); /** * @dev Delegates votes from the sender to `delegatee`. */ function delegate(address delegatee) external; /** * @dev Delegates votes from signer to `delegatee`. */ function delegateBySig( address delegatee, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/math/SafeCast.sol) pragma solidity ^0.8.0; /** * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow * checks. * * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can * easily result in undesired exploitation or bugs, since developers usually * assume that overflows raise errors. `SafeCast` restores this intuition by * reverting the transaction when such an operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. * * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing * all math on `uint256` and `int256` and then downcasting. */ library SafeCastUpgradeable { /** * @dev Returns the downcasted uint224 from uint256, reverting on * overflow (when the input is greater than largest uint224). * * Counterpart to Solidity's `uint224` operator. * * Requirements: * * - input must fit into 224 bits */ function toUint224(uint256 value) internal pure returns (uint224) { require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits"); return uint224(value); } /** * @dev Returns the downcasted uint128 from uint256, reverting on * overflow (when the input is greater than largest uint128). * * Counterpart to Solidity's `uint128` operator. * * Requirements: * * - input must fit into 128 bits */ function toUint128(uint256 value) internal pure returns (uint128) { require(value <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits"); return uint128(value); } /** * @dev Returns the downcasted uint96 from uint256, reverting on * overflow (when the input is greater than largest uint96). * * Counterpart to Solidity's `uint96` operator. * * Requirements: * * - input must fit into 96 bits */ function toUint96(uint256 value) internal pure returns (uint96) { require(value <= type(uint96).max, "SafeCast: value doesn't fit in 96 bits"); return uint96(value); } /** * @dev Returns the downcasted uint64 from uint256, reverting on * overflow (when the input is greater than largest uint64). * * Counterpart to Solidity's `uint64` operator. * * Requirements: * * - input must fit into 64 bits */ function toUint64(uint256 value) internal pure returns (uint64) { require(value <= type(uint64).max, "SafeCast: value doesn't fit in 64 bits"); return uint64(value); } /** * @dev Returns the downcasted uint32 from uint256, reverting on * overflow (when the input is greater than largest uint32). * * Counterpart to Solidity's `uint32` operator. * * Requirements: * * - input must fit into 32 bits */ function toUint32(uint256 value) internal pure returns (uint32) { require(value <= type(uint32).max, "SafeCast: value doesn't fit in 32 bits"); return uint32(value); } /** * @dev Returns the downcasted uint16 from uint256, reverting on * overflow (when the input is greater than largest uint16). * * Counterpart to Solidity's `uint16` operator. * * Requirements: * * - input must fit into 16 bits */ function toUint16(uint256 value) internal pure returns (uint16) { require(value <= type(uint16).max, "SafeCast: value doesn't fit in 16 bits"); return uint16(value); } /** * @dev Returns the downcasted uint8 from uint256, reverting on * overflow (when the input is greater than largest uint8). * * Counterpart to Solidity's `uint8` operator. * * Requirements: * * - input must fit into 8 bits. */ function toUint8(uint256 value) internal pure returns (uint8) { require(value <= type(uint8).max, "SafeCast: value doesn't fit in 8 bits"); return uint8(value); } /** * @dev Converts a signed int256 into an unsigned uint256. * * Requirements: * * - input must be greater than or equal to 0. */ function toUint256(int256 value) internal pure returns (uint256) { require(value >= 0, "SafeCast: value must be positive"); return uint256(value); } /** * @dev Returns the downcasted int128 from int256, reverting on * overflow (when the input is less than smallest int128 or * greater than largest int128). * * Counterpart to Solidity's `int128` operator. * * Requirements: * * - input must fit into 128 bits * * _Available since v3.1._ */ function toInt128(int256 value) internal pure returns (int128) { require(value >= type(int128).min && value <= type(int128).max, "SafeCast: value doesn't fit in 128 bits"); return int128(value); } /** * @dev Returns the downcasted int64 from int256, reverting on * overflow (when the input is less than smallest int64 or * greater than largest int64). * * Counterpart to Solidity's `int64` operator. * * Requirements: * * - input must fit into 64 bits * * _Available since v3.1._ */ function toInt64(int256 value) internal pure returns (int64) { require(value >= type(int64).min && value <= type(int64).max, "SafeCast: value doesn't fit in 64 bits"); return int64(value); } /** * @dev Returns the downcasted int32 from int256, reverting on * overflow (when the input is less than smallest int32 or * greater than largest int32). * * Counterpart to Solidity's `int32` operator. * * Requirements: * * - input must fit into 32 bits * * _Available since v3.1._ */ function toInt32(int256 value) internal pure returns (int32) { require(value >= type(int32).min && value <= type(int32).max, "SafeCast: value doesn't fit in 32 bits"); return int32(value); } /** * @dev Returns the downcasted int16 from int256, reverting on * overflow (when the input is less than smallest int16 or * greater than largest int16). * * Counterpart to Solidity's `int16` operator. * * Requirements: * * - input must fit into 16 bits * * _Available since v3.1._ */ function toInt16(int256 value) internal pure returns (int16) { require(value >= type(int16).min && value <= type(int16).max, "SafeCast: value doesn't fit in 16 bits"); return int16(value); } /** * @dev Returns the downcasted int8 from int256, reverting on * overflow (when the input is less than smallest int8 or * greater than largest int8). * * Counterpart to Solidity's `int8` operator. * * Requirements: * * - input must fit into 8 bits. * * _Available since v3.1._ */ function toInt8(int256 value) internal pure returns (int8) { require(value >= type(int8).min && value <= type(int8).max, "SafeCast: value doesn't fit in 8 bits"); return int8(value); } /** * @dev Converts an unsigned uint256 into a signed int256. * * Requirements: * * - input must be less than or equal to maxInt256. */ function toInt256(uint256 value) internal pure returns (int256) { // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive require(value <= uint256(type(int256).max), "SafeCast: value doesn't fit in an int256"); return int256(value); } } pragma solidity =0.8.11; interface IAsset { // solhint-disable-previous-line no-empty-blocks } interface IVault { enum PoolSpecialization { GENERAL, MINIMAL_SWAP_INFO, TWO_TOKEN } enum JoinKind { INIT, EXACT_TOKENS_IN_FOR_BPT_OUT, TOKEN_IN_FOR_EXACT_BPT_OUT, ALL_TOKENS_IN_FOR_EXACT_BPT_OUT } enum ExitKind { EXACT_BPT_IN_FOR_ONE_TOKEN_OUT, EXACT_BPT_IN_FOR_TOKENS_OUT, BPT_IN_FOR_EXACT_TOKENS_OUT, MANAGEMENT_FEE_TOKENS_OUT // for ManagedPool } /** * @dev Returns a Pool's contract address and specialization setting. */ function getPool(bytes32 poolId) external view returns (address, PoolSpecialization); function joinPool( bytes32 poolId, address sender, address recipient, JoinPoolRequest memory request ) external payable; struct JoinPoolRequest { IAsset[] assets; uint256[] maxAmountsIn; bytes userData; bool fromInternalBalance; } function exitPool( bytes32 poolId, address sender, address payable recipient, ExitPoolRequest memory request ) external; struct ExitPoolRequest { IAsset[] assets; uint256[] minAmountsOut; bytes userData; bool toInternalBalance; } enum SwapKind { GIVEN_IN, GIVEN_OUT } struct SingleSwap { bytes32 poolId; SwapKind kind; IAsset assetIn; IAsset assetOut; uint256 amount; bytes userData; } struct FundManagement { address sender; bool fromInternalBalance; address payable recipient; bool toInternalBalance; } function swap( SingleSwap memory singleSwap, FundManagement memory funds, uint256 limit, uint256 deadline ) external payable returns (uint256); function getPoolTokens(bytes32 poolId) external view returns ( address[] memory tokens, uint256[] memory balances, uint256 lastChangeBlock ); } pragma solidity =0.8.11; interface IWeightedPool { function setSwapFeePercentage(uint256 swapFeePercentage) external; } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity =0.8.11; pragma abicoder v2; /** * @dev Interface for querying historical data from a Pool that can be used as a Price Oracle. * * This lets third parties retrieve average prices of tokens held by a Pool over a given period of time, as well as the * price of the Pool share token (BPT) and invariant. Since the invariant is a sensible measure of Pool liquidity, it * can be used to compare two different price sources, and choose the most liquid one. * * Once the oracle is fully initialized, all queries are guaranteed to succeed as long as they require no data that * is not older than the largest safe query window. */ interface IPriceOracle { // The three values that can be queried: // // - PAIR_PRICE: the price of the tokens in the Pool, expressed as the price of the second token in units of the // first token. For example, if token A is worth $2, and token B is worth $4, the pair price will be 2.0. // Note that the price is computed *including* the tokens decimals. This means that the pair price of a Pool with // DAI and USDC will be close to 1.0, despite DAI having 18 decimals and USDC 6. // // - BPT_PRICE: the price of the Pool share token (BPT), in units of the first token. // Note that the price is computed *including* the tokens decimals. This means that the BPT price of a Pool with // USDC in which BPT is worth $5 will be 5.0, despite the BPT having 18 decimals and USDC 6. // // - INVARIANT: the value of the Pool's invariant, which serves as a measure of its liquidity. enum Variable { PAIR_PRICE, BPT_PRICE, INVARIANT } /** * @dev Returns the time average weighted price corresponding to each of `queries`. Prices are represented as 18 * decimal fixed point values. */ function getTimeWeightedAverage(OracleAverageQuery[] memory queries) external view returns (uint256[] memory results); /** * @dev Returns latest sample of `variable`. Prices are represented as 18 decimal fixed point values. */ function getLatest(Variable variable) external view returns (uint256); /** * @dev Information for a Time Weighted Average query. * * Each query computes the average over a window of duration `secs` seconds that ended `ago` seconds ago. For * example, the average over the past 30 minutes is computed by settings secs to 1800 and ago to 0. If secs is 1800 * and ago is 1800 as well, the average between 60 and 30 minutes ago is computed instead. */ struct OracleAverageQuery { Variable variable; uint256 secs; uint256 ago; } /** * @dev Returns largest time window that can be safely queried, where 'safely' means the Oracle is guaranteed to be * able to produce a result and not revert. * * If a query has a non-zero `ago` value, then `secs + ago` (the oldest point in time) must be smaller than this * value for 'safe' queries. */ function getLargestSafeQueryWindow() external view returns (uint256); /** * @dev Returns the accumulators corresponding to each of `queries`. */ function getPastAccumulators(OracleAccumulatorQuery[] memory queries) external view returns (int256[] memory results); /** * @dev Information for an Accumulator query. * * Each query estimates the accumulator at a time `ago` seconds ago. */ struct OracleAccumulatorQuery { Variable variable; uint256 ago; } } pragma solidity =0.8.11; import "IERC20.sol"; interface ILiquidityGauge is IERC20 { function deposit(uint256 _value, address _addr, bool _claim_rewards) external; function withdraw(uint256 _value, bool _claim_rewards) external; } pragma solidity =0.8.11; interface IBalancerMinter { function mint(address gauge) external; function getBalancerToken() external returns (address); } // SPDX-License-Identifier: MIT pragma solidity =0.8.11; import "IPriceOracle.sol"; library BalancerUtils { function getTimeWeightedOraclePrice( address pool, IPriceOracle.Variable variable, uint256 secs ) internal view returns (uint256) { IPriceOracle.OracleAverageQuery[] memory queries = new IPriceOracle.OracleAverageQuery[](1); queries[0].variable = variable; queries[0].secs = secs; queries[0].ago = 0; // now // Gets the balancer time weighted average price denominated in ETH return IPriceOracle(pool).getTimeWeightedAverage(queries)[0]; } }
Validate that the pool exists prettier-ignore prettier-ignore
) initializer { (address poolAddress, /* */) = _balancerVault.getPool(_noteETHPoolId); require(poolAddress != address(0)); WETH_INDEX = _wethIndex; NOTE_INDEX = _noteIndex; (address[] memory tokens, /* */, /* */) = _balancerVault.getPoolTokens(_noteETHPoolId); WETH = ERC20(tokens[_wethIndex]); NOTE = ERC20(tokens[_noteIndex]); NOTE_ETH_POOL_ID = _noteETHPoolId; BALANCER_VAULT = _balancerVault; BALANCER_POOL_TOKEN = ERC20(poolAddress); LIQUIDITY_GAUGE = _liquidityGauge; TREASURY_MANAGER_CONTRACT = _treasuryManagerContract; BALANCER_MINTER = _balancerMinter; BALANCER_TOKEN = ERC20(_balancerMinter.getBalancerToken()); }
1,382,058
[ 1, 4270, 716, 326, 2845, 1704, 675, 748, 2453, 17, 6185, 675, 748, 2453, 17, 6185, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 262, 12562, 288, 203, 3639, 261, 2867, 2845, 1887, 16, 1748, 1195, 13, 273, 389, 18770, 12003, 18, 588, 2864, 24899, 7652, 1584, 2500, 1371, 548, 1769, 203, 3639, 2583, 12, 6011, 1887, 480, 1758, 12, 20, 10019, 203, 203, 3639, 678, 1584, 44, 67, 9199, 273, 389, 91, 546, 1016, 31, 203, 3639, 5219, 67, 9199, 273, 389, 7652, 1016, 31, 203, 203, 3639, 261, 2867, 8526, 3778, 2430, 16, 1748, 1195, 16, 1748, 1195, 13, 273, 389, 18770, 12003, 18, 588, 2864, 5157, 24899, 7652, 1584, 2500, 1371, 548, 1769, 203, 203, 3639, 678, 1584, 44, 273, 4232, 39, 3462, 12, 7860, 63, 67, 91, 546, 1016, 19226, 203, 3639, 5219, 273, 4232, 39, 3462, 12, 7860, 63, 67, 7652, 1016, 19226, 203, 3639, 5219, 67, 1584, 44, 67, 20339, 67, 734, 273, 389, 7652, 1584, 2500, 1371, 548, 31, 203, 3639, 605, 1013, 1258, 39, 654, 67, 27722, 2274, 273, 389, 18770, 12003, 31, 203, 3639, 605, 1013, 1258, 39, 654, 67, 20339, 67, 8412, 273, 4232, 39, 3462, 12, 6011, 1887, 1769, 203, 3639, 8961, 53, 3060, 4107, 67, 43, 27738, 273, 389, 549, 372, 24237, 18941, 31, 203, 3639, 399, 862, 3033, 1099, 61, 67, 19402, 67, 6067, 2849, 1268, 273, 389, 27427, 345, 22498, 1318, 8924, 31, 203, 3639, 605, 1013, 1258, 39, 654, 67, 6236, 2560, 273, 389, 18770, 49, 2761, 31, 203, 3639, 605, 1013, 1258, 39, 654, 67, 8412, 273, 4232, 39, 3462, 24899, 18770, 49, 2761, 18, 588, 6444, 1345, 10663, 203, 565, 2 ]
./full_match/1/0xfD58BD69C7aEB8e0c73bFb0F20f38F1f8225e4F6/sources/contracts/CryptaSubscription.sol
Change operator wallet address @param signer/
function setAdmin(address wallet) external onlyOwner validAddress(wallet) { _admin = wallet; }
16,454,286
[ 1, 3043, 3726, 9230, 1758, 225, 10363, 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, 4446, 12, 2867, 9230, 13, 3903, 1338, 5541, 923, 1887, 12, 19177, 13, 288, 203, 3639, 389, 3666, 273, 9230, 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 ]
// SPDX-License-Identifier: CC-BY-NC-4.0 // email "licensing [at] pyxelchain.com" for licensing information // Pyxelchain Technologies v1.0.0 (NFTGrid.sol) pragma solidity =0.8.7; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; // import "hardhat/console.sol"; /** * @title Billion Pyxel Project * @author Nik Cimino @ncimino * * @dev the 1 billion pixels are arranged in a 32768 x 32768 = 1,073,741,824 pixel matrix * to address all 1 billion pixels we break them into 256 pixel tiles which are 16 pixels x 16 pixels * this infers a grid based addressing sytem of dimensions: 32768 / 16 = 2048 x 2048 = 4,194,304 tiles * * @custom:websites https://billionpyxelproject.com https://billionpixelproject.net * * @notice to _significantly_ reduce gas we require that purchases are some increment of the layers defined above * * @notice this cotnract does not make use of ERC721Enumerable as the tokenIDs are not sequential */ /* * this contract is not concerned with the individual pixels, but with the tiles that can be addressed and sold * each tile is represented as an NFT, but each NFT can be different dimensions in layer 1 they are 1 tile each, but in layer 4 they are 16 tiles each * layer 1: 1 x 1 = 1 tile / index * layer 2: 2 x 2 = 4 tiles / index * layer 3: 4 x 4 = 16 tiles / index * layer 4: 8 x 8 = 64 tiles / index * layer 5: 16 x 16 = 256 tiles / index * layer 6: 32 x 32 = 1,024 tiles / index * layer 7: 64 x 64 = 4,096 tiles / index * layer 8: 128 x 128 = 16,384 tiles / index * layer 9: 256 x 256 = 65,536 tiles / index * layer 10: 512 x 512 = 262,144 tiles / index * layer 11: 1024 x 1024 = 1,048,576 tiles / index * layer 12: 2048 x 2048 = 4,194,304 tiles / index * * quad alignment: * * layer 11 layer 12 * ____N___ ________ * / / / / / * W/---+---/E / / * /___/___/ /_______/ * S */ contract NFTGrid is ERC721, Ownable, ReentrancyGuard { using Strings for uint256; using Counters for Counters.Counter; using SafeERC20 for IERC20; //// TYPES & STRUCTS /** * @dev symetric: should be kept up-to-date with JS implementation * @notice layers enum interger value is used as 2 ^ Layer e.g. 2 ^ (x4=2) = 5, 2 ^ (x16=4) = 16 * there are a total of 12 sizes (0-11) * @dev these enums are uint256 / correct? */ enum Size { X1, X2, X4, X8, X16, X32, X64, X128, X256, X512, X1024, X2048 } // 2048 = 2^11 = 1 << 11 /** * @notice we model our grid system in the same what that the front-end displays are modeled, this is with 0,0 in the top left corner * x increases as we move to the right, but y increases as we move done * @dev max x and y is 2048 = 2 ^ 11 which can fit in a uint16, and since we need 4 values using 64 bits packs them all tight * @dev we model this so that we have logical coherency between our internal logic and the display systems of this logic * @dev x & y are the center of the quad */ struct Rectangle { uint16 x; uint16 y; uint16 w; uint16 h; } /** * @notice a quad cannot be owned after it has been divided * @dev the quads are the tokenIds which are an encoding of x,y,w,h */ struct QuadTree { uint64 northeast; // quads max index is 2 ^ 64 = 18,446,744,073,709,551,616 uint64 northwest; // however, this allows us to pack all 4 into a 256 bit slot uint64 southeast; uint64 southwest; Rectangle boundary; // 16 * 4 = 64 bits address owner; // address are 20 bytes = 160 bits bool divided; // bools are 1 byte = 8 bits ... should also pack into a 256 bit slot, right? so 2 total? uint24 ownedCount; // need 22 bits to represent full 2048x2048 count - total number of grid tiles owned under this quad (recursively) } struct PurchaseToken { bool enabled; uint256 pricePerPixel; } //// EVENTS event ETHPriceChanged ( uint256 oldPrice, uint256 newPrice ); event TokenUpdated ( address indexed tokenAddress, uint256 indexed tokenPrice, bool enabled ); event BuyCreditWithETH ( address indexed buyer, address indexed receiver, uint256 amountETH, uint256 amountPixels ); event BuyCreditWithToken ( address indexed buyer, address indexed token, address indexed receiver, uint256 amountToken, uint256 amountPixels ); event TransferCredit ( address indexed sender, address indexed receiver, uint256 amount ); //// MODIFIERS modifier placementNotLocked() { require(!placementLocked, "NFTG: placement locked"); _; } modifier reserveNotLocked() { require(!reserveLocked, "NFTG: reserve locked"); _; } //// MEMBERS uint16 constant public GRID_W = 2048; uint16 constant public GRID_H = 2048; uint256 constant public PIXELS_PER_TILE = 256; bool public placementLocked; bool public reserveLocked; bool public permanentlyAllowCustomURIs; bool public allowCustomURIs = true; uint64 immutable public rootTokenId; uint256 public pricePerPixelInETH = 0.00004 ether; address[] public receivedAddresses; mapping (address => PurchaseToken) public tokens;// e.g. USDC can be passed in @ $0.10/pixel = $25.60 per tile mapping (uint64 => QuadTree) public qtrees; mapping (address => bool) public addressExists; mapping (address => uint256) public pixelCredits; mapping (address => uint256) public ownedPixels; mapping (uint256 => string) public tokenURIs; string public defaultURI; uint256 public totalPixelsOwned; //// CONTRACT /** * @dev the list of initially support token addresses and token prices are privded at deployment * @param _tokenAddresses is an array of token addresses to support purchases with * @param _tokenPrices is an array of token prices and indesxes correlate with the token addresses also provided here */ constructor(address[] memory _tokenAddresses, uint256[] memory _tokenPrices) ERC721("Billion Pyxel Project", "BPP") { require(_tokenAddresses.length == _tokenPrices.length, "NFTG: array length mismatch"); for (uint256 i = 0; i < _tokenAddresses.length; i++) { updateToken(_tokenAddresses[i], _tokenPrices[i], true); } uint64 qtreeTokenId = _createQTNode(address(0x0), GRID_W/2-1, GRID_H/2-1, GRID_W, GRID_H); rootTokenId = qtreeTokenId; _subdivideQTNode(qtreeTokenId); } /** * @notice get a tokens price and if it is enabled * @param _tokenAddress is the address of the token to be looked up * @return pricePerPixel is the price per pixel given the current token address * @return enabled is indicating if the current token is enabled */ function getToken(address _tokenAddress) external view returns(uint256 pricePerPixel, bool enabled) { PurchaseToken memory purchaseToken = tokens[_tokenAddress]; pricePerPixel = purchaseToken.pricePerPixel; enabled = purchaseToken.enabled; } /** * @notice let each token have an independent URI as these will be owned and controlled by their owner * @param _tokenId is the token ID to look-up the URI for * @return uri is the URI for the provided token ID */ function tokenURI(uint256 _tokenId) public view virtual override returns(string memory uri) { require(_exists(_tokenId), "NFTG: non-existant token"); if (!allowCustomURIs) { uri = _getDefaultURI(_tokenId); } else { uri = tokenURIs[_tokenId]; if (bytes(uri).length == 0) { uri = _getDefaultURI(_tokenId); } } } /** * @notice returns the default URI given a token ID * @param _tokenId the token ID to lookup the default URI for * @return uri the URI of the token ID, which appends the token ID to the end of the default URI string */ function _getDefaultURI(uint256 _tokenId) private view returns(string memory uri) { uri = bytes(defaultURI).length > 0 ? string(abi.encodePacked(defaultURI, _tokenId.toString())) : ""; } /** * @notice allow the contract owner to set the default URI for the NFTs, the token ID will be appended to the end of this URI * @param _uri is the default base URI that is used if custom are disabled or if none has been specified for the current token */ function setDefaultURI(string memory _uri) external onlyOwner { defaultURI = _uri; } /** * @notice allow the NFT owner to set a custom URI for this NFT, the token ID will _not_ be appended to the end of this URI * (it can be explicitly added to the end when set if needed as this is on a per NFT basis) * @param _tokenId the NFT token ID that the URI will be updated for * @param _tokenUri the new URI for the given token ID */ function setTokenURI(uint256 _tokenId, string calldata _tokenUri) external virtual { require(_exists(_tokenId), "NFTG: non-existant token"); require(allowCustomURIs, "NFTG: custom URIs disabled"); QuadTree storage qtree = qtrees[uint64(_tokenId)]; require(qtree.owner == msg.sender, "NFTG: only owner can set URI"); tokenURIs[_tokenId] = _tokenUri; } /** * @notice add a new, disable an existing, or change the price of a token * @notice token price must account for the ERC20 decimals value e.g. for USDC 6 decimals, setting this value to 100000 equals: $0.10/pixel * @param _tokenAddress the address of the token to update * @param _tokenPrice the price per pixel of the token * @param _enabled used to enable or disable the token */ function updateToken(address _tokenAddress, uint256 _tokenPrice, bool _enabled) public onlyOwner { require(_tokenPrice != 0, "NFTG: token price 0"); require(_tokenAddress != address(0), "NFTG: token address 0"); PurchaseToken storage newToken = tokens[_tokenAddress]; newToken.enabled = _enabled; newToken.pricePerPixel = _tokenPrice; emit TokenUpdated(_tokenAddress, _tokenPrice, _enabled); } /** * @notice controls ability of placement */ function togglePlacementLock() external onlyOwner { placementLocked = !placementLocked; } /** * @notice controls ability of users to reserve pixels */ function toggleReserveLock() external onlyOwner { reserveLocked = !reserveLocked; } /** * @notice controls ability of users to set their own URI */ function toggleCustomURIs() external onlyOwner { require(!permanentlyAllowCustomURIs, "NFTG: permanently enabled"); allowCustomURIs = !allowCustomURIs; } /** * @notice controls ability of users to set their own URI, once called custom URIs can never be disabled again */ function permanentlyEnableCustomURIs() external onlyOwner { permanentlyAllowCustomURIs = true; allowCustomURIs = true; } /** * @notice set the price per pixel in ETH * @param _pricePerPixel is the price per pixel in ETH */ function setETHPrice(uint256 _pricePerPixel) external onlyOwner { emit ETHPriceChanged(pricePerPixelInETH, _pricePerPixel); require(_pricePerPixel > 0, "NFTG: price is 0"); pricePerPixelInETH = _pricePerPixel; } /** * @notice returns a subset of the arrays of pixel credit receivers and their current balances - can be used to export credit balances * @param _start the starting index of accounts/balances to start looking out * @param _count the number of indexes to look through from the _start forward * */ function getPixelCredits(uint256 _start, uint256 _count) external view returns(address[] memory addresses, uint256[] memory balances) { require(_count > 0, "NFTG: count is 0"); require(_start < receivedAddresses.length, "NFTG: start too high"); uint256 stop = _start + _count; stop = (stop > receivedAddresses.length) ? receivedAddresses.length : stop; uint256 actualCount = stop - _start; addresses = new address[](actualCount); balances = new uint256[](actualCount); for (uint256 i = _start; i < stop; i++) { address current = receivedAddresses[i]; addresses[i - _start] = current; balances[i - _start] = pixelCredits[current]; } } /** * @notice transfer some credits from the current owner to a new owner * @param _receiver the account receiving the credits * @param _amount the amount of credits to transfer from one account to another */ function transferCredits(address _receiver, uint256 _amount) external reserveNotLocked { require(pixelCredits[msg.sender] >= _amount, "NFTG: not enough credit"); require(_receiver != address(0), "NFTG: address 0"); emit TransferCredit(msg.sender, _receiver, _amount); pixelCredits[msg.sender] -= _amount; pixelCredits[_receiver] += _amount; } /** * @notice purchases enough credit for and places/mints the token ID in a single operation using a token * @param _tokenAddress the token address to use to make the purchase * @param _tokenId the tokenId of the quad to buy using Tokens */ function buyWithToken(address _tokenAddress, uint64 _tokenId) external nonReentrant placementNotLocked { _buyWithToken(_tokenAddress, _tokenId); } /** * @param _tokenAddress the token address to use to make the purchase * @param _tokenIds the token IDs of the quads to buy using Tokens */ function multiBuyWithToken(address _tokenAddress, uint64[] calldata _tokenIds) external nonReentrant placementNotLocked { for(uint i = 0; i < _tokenIds.length; i++) { _buyWithToken(_tokenAddress, _tokenIds[i]); } } /** * @notice buys a specific token ID using an ERC20 token, will convert token to credits and then mint/place the NFT * @param _tokenAddress is the address of the token to be used to make the purchase * @param _tokenId is the token ID to purchase */ function _buyWithToken(address _tokenAddress, uint64 _tokenId) private { PurchaseToken memory token = tokens[_tokenAddress]; require(token.enabled, "NFTG: token not supported"); Rectangle memory range = getRangeFromTokenId(_tokenId); uint256 price = _price(token.pricePerPixel, range); _buyCreditWithToken(_tokenAddress, msg.sender, price); _placeQTNode(_tokenId); } /** * @notice purchases enough credit for and places/mints the token ID in a single operation using ETH * @param _tokenId the tokenId of the quad to buy using ETH */ function buyWithETH(uint64 _tokenId) external payable nonReentrant placementNotLocked { _buyCreditWithETH(msg.sender); _placeQTNode(_tokenId); } /** * @param _tokenIds the tokenIds of the quads to buy using ETH */ function multiBuyWithETH(uint64[] calldata _tokenIds) external payable nonReentrant placementNotLocked { _buyCreditWithETH(msg.sender); for(uint i = 0; i < _tokenIds.length; i++) { _placeQTNode(_tokenIds[i]); } } /** * @notice places the specified token ID via minting the NFT * @param _tokenId is the ID of the token to be placed/minted */ function _placeQTNode(uint64 _tokenId) private { Rectangle memory range = getRangeFromTokenId(_tokenId); uint256 pixelsToPlace = uint256(range.w) * uint256(range.h) * PIXELS_PER_TILE; uint256 pixelBalance = pixelCredits[msg.sender]; require(pixelsToPlace <= pixelBalance, "NFTG: not enough credit"); pixelCredits[msg.sender] -= pixelsToPlace; _mintQTNode(_tokenId); } /** * @notice the amount of {msg.value} is what will be used to convert into pixel credits * @param _receiveAddress is the address receiving the pixel credits */ // slither-disable-next-line reentrancy-events function buyCreditWithETH(address _receiveAddress) external payable nonReentrant reserveNotLocked { _buyCreditWithETH(_receiveAddress); } function _buyCreditWithETH(address _receiveAddress) private { uint256 credit = msg.value / pricePerPixelInETH; require(credit > 0, "NFTG: not enough ETH sent"); emit BuyCreditWithETH(msg.sender, _receiveAddress, msg.value, credit); pixelCredits[_receiveAddress] += credit; ownedPixels[_receiveAddress] += credit; totalPixelsOwned += credit; if (!addressExists[_receiveAddress]) { receivedAddresses.push(_receiveAddress); addressExists[_receiveAddress] = true; } Address.sendValue(payable(owner()), msg.value); } /** * @param _tokenAddress is the address of the token being used to purchase the pixels * @param _receiveAddress is the address receiving the pixel credits * @param _amount is the amount in tokens - if using a stable like USDC, then this represent dollar value in wei */ function buyCreditWithToken(address _tokenAddress, address _receiveAddress, uint256 _amount) external nonReentrant reserveNotLocked { _buyCreditWithToken(_tokenAddress, _receiveAddress, _amount); } /** * @notice buy credit with tokens * @param _tokenAddress is the token (ERC20) address being used to do the purchase * @param _receiveAddress is the account receiving the credits * @param _amount is the amount of tokens to use to do the purchase */ function _buyCreditWithToken(address _tokenAddress, address _receiveAddress, uint256 _amount) private { PurchaseToken memory token = tokens[_tokenAddress]; require(token.enabled, "NFTG: token not supported"); uint256 credit = _amount / token.pricePerPixel; require(credit > 0, "NFTG: not enough tokens sent"); emit BuyCreditWithToken(msg.sender, _tokenAddress, _receiveAddress, _amount, credit); pixelCredits[_receiveAddress] += credit; ownedPixels[_receiveAddress] += credit; totalPixelsOwned += credit; if (!addressExists[_receiveAddress]) { receivedAddresses.push(_receiveAddress); addressExists[_receiveAddress] = true; } IERC20(_tokenAddress).safeTransferFrom(msg.sender, owner(), _amount); } /** * @notice allows already purchased pixels to be allocated to specific token IDs * @dev will fail if pixel balance is insufficient * @param _tokenIds the tokenIds of the quads to place */ function placePixels(uint64[] calldata _tokenIds) external nonReentrant placementNotLocked { for(uint i = 0; i < _tokenIds.length; i++) { _placeQTNode(_tokenIds[i]); } } /** * @notice mints the QuadTree node for the provided token ID and ownership goes to the caller * @dev only the unowned leafs can be purchased * @dev quads are only divided via subdivde or buyWith* * @param _tokenId is the token ID being minted */ function _mintQTNode(uint64 _tokenId) private { QuadTree storage qtree = qtrees[uint64(_tokenId)]; require(!qtree.divided, "NFTG: cannot buy if divided"); require(qtree.owner == address(0x0), "NFTG: already owned"); revertIfParentOwned(_tokenId); _revertIfChildOwned(qtree); // needed if burning Rectangle memory range = getRangeFromTokenId(_tokenId); uint24 increaseCount = uint24(range.w) * uint24(range.h); _divideAndCount(getParentTokenId(_tokenId), increaseCount); qtree.owner = msg.sender; qtree.ownedCount = increaseCount; _safeMint(msg.sender, _tokenId); } /** * @notice given the price and size calculate the price of a rectangle * @param _pricePerPixel is the price per pixel * @param _rect is the rectangle we are calculating the price of * @return price is the price of this rectangle */ function _price(uint256 _pricePerPixel, Rectangle memory _rect) private pure returns(uint256 price) { price = _pricePerPixel * PIXELS_PER_TILE * uint256(_rect.w) * uint256(_rect.h); } /** * @notice override the ERC720 function so that we can update user credits * @dev this logic only executes if pixels are being transferred from one user to another * @dev this contract doesn't support burning of QuadTrees so we don't need to subtract on burn (_to == 0), burning only happens on subdivide * @dev this contract increases the owned count on reserve not on minting (_from == 0) we ignore those as they are already added */ function _beforeTokenTransfer(address _from, address _to, uint256 _tokenId) internal virtual override { if ((_from != address(0)) && (_to != address(0))) { Rectangle memory range = getRangeFromTokenId(uint64(_tokenId)); uint256 credit = uint256(range.w) * uint256(range.h) * PIXELS_PER_TILE; ownedPixels[_from] -= credit; ownedPixels[_to] += credit; } } /** * @notice calculates the price of a quad in ETH * @param _tokenId the tokenId of the quad to get the ETH price of * @return price the price of the token ID in ETH */ function getETHPrice(uint64 _tokenId) external view returns(uint price) { Rectangle memory range = getRangeFromTokenId(_tokenId); price = _price(pricePerPixelInETH, range); } /** * @notice calculates the price of a quad in tokens * @param _tokenAddress the token address to look up the price for * @param _tokenId the token ID of the quad to get the token price of * @return price the price of the token ID in tokens */ function getTokenPrice(address _tokenAddress, uint64 _tokenId) external view returns(uint price) { PurchaseToken memory token = tokens[_tokenAddress]; require(token.enabled, "NFTG: token not supported"); Rectangle memory range = getRangeFromTokenId(_tokenId); price = _price(token.pricePerPixel, range); } /** * @notice this starts at the given node and goes up the QuadTree graph to the root, from there every node is subdivide and the amount of tiles purchased are added * @dev don't need to check the qtree of the root token ID (X2048) as it was divided in the ctor * @param _tokenId is the token ID to be divided and have count incremented on * @param _increaseBy is the count of the tiles (X1) currently placed under that quad - X2048 or the root node will always have the full number of placed tiles */ function _divideAndCount(uint64 _tokenId, uint24 _increaseBy) private { QuadTree storage qtree = qtrees[_tokenId]; if (_tokenId != rootTokenId) { uint64 parentTokenId = getParentTokenId(_tokenId); _divideAndCount(parentTokenId, _increaseBy); } if (!qtree.divided) { _subdivideQTNode(_tokenId); } qtree.ownedCount += _increaseBy; } /** * @notice useful for checking if any child is owned * @param _tokenId is the token ID to check if any child below it is owned */ function revertIfChildOwned(uint64 _tokenId) external view { QuadTree memory qtree = qtrees[_tokenId]; _revertIfChildOwned(qtree); } /** * @notice checks if any child tile is owned, since the QuadTree nodes track this for all children it is a simple query of the owned count * @param _qtree is the QuadTree node object to check */ function _revertIfChildOwned(QuadTree memory _qtree) private pure { require(_qtree.ownedCount == 0, "NFTG: child owned"); } /** * @notice useful for checking if any parent is owned - if it doesn't revert, then no body owns above it * @param _tokenId is the token ID to check if any parent above it is owned */ function revertIfParentOwned(uint64 _tokenId) public view { uint64 parentTokenId = _tokenId; while (parentTokenId != rootTokenId) { // NOTE: don't need to check the parent of X2048 parentTokenId = getParentTokenId(parentTokenId); QuadTree memory parent = qtrees[parentTokenId]; require(parent.owner == address(0x0), "NFTG: parent owned"); } } /** * @notice calculates a parent tile tokenId from a child - it is known that the parents w/h will be 2x the child, * and from that we can determine the quad using it's x/y * @dev symetric: should be kept up-to-date with JS implementation * @param _tokenId the tokenId of the quad to get the parent range of */ function getParentRange(uint64 _tokenId) public pure returns(Rectangle memory parent) { // parent is child until assignment (to save gas)... parent = getRangeFromTokenId(_tokenId); uint16 width = 2 * parent.w; uint16 height = 2 * parent.h; uint16 tileIndexX = calculateIndex(parent.x, parent.w); uint16 tileIndexY = calculateIndex(parent.y, parent.h); // slither-disable-next-line divide-before-multiply parent.x = tileIndexX / 2 * width + width / 2 - 1; // note: division here truncates and this is intended when going to indexes // slither-disable-next-line divide-before-multiply parent.y = tileIndexY / 2 * height + height / 2 - 1; parent.w = width; parent.h = height; validate(parent); } /** * index layout: * layer 11 layer 12 * _0___1__ ____0___ * 0 / / / / / * /---+---/ 0/ / * 1 /___/___/ /_______/ * x=127+256,y=127 w=256 x=0,y=0 w=1 special case for dimension of 1 since we move up and left * x=w/2-1+index*w x=index*w * index*w=x-w/2+1 * index=(x-w/2+1)/w */ /** * @notice calculate the index of a token given an x or y (_value) and a corresponding size (w or h as _dimension) * @dev this function does not check values - it is presumed that the values have already passed 'validate' * @param _value is x or y * @param _dimension is w or h (respectively) * @return index is the index starting at 0 and going to w/GRID_W - 1 or h/GRID_H - 1 * the indexes of the tiles are the tokenId of the column or row of that tile (based on dimension) */ function calculateIndex(uint16 _value, uint16 _dimension) public pure returns(uint16 index) { index = (_dimension == 1) ? (_value / _dimension) : ((_value + 1 - _dimension/2) / _dimension); } /** * @notice derive the parent token ID given one of it's child token IDs * @dev symetric: should be kept up-to-date with JS implementation * @notice calculates a parent tile tokenId from a child * @param _tokenId the tokenId of the quad to get the parent range of */ function getParentTokenId(uint64 _tokenId) public pure returns(uint64 parentTokenId) { parentTokenId = _getTokenIdFromRangeNoCheck(getParentRange(_tokenId)); } /** * @notice splits a tile into a quarter (a.k.a. quad) * @dev there are ne, nw, se, sw quads on the QuadTrees * @notice the quads are stored as tokenIds here not actual other QuadTrees */ function subdivide(uint256 _tokenId) external placementNotLocked { QuadTree memory qtree = qtrees[uint64(_tokenId)]; require(!qtree.divided, "NFTG: already divided"); require(qtree.owner == msg.sender, "NFTG: only owner can subdivide"); _subdivideQTNode(uint64(_tokenId)); } /** * @notice this function subdivides the QuadTree node into 4 child QuadTree nodes * @notice quad coordinates are at the center of the quad - this makes dividing coords relative... * for root: x=1023, y=1023, w=2048, h=2048 * wChild = wParent/2 = 1024 * currently: xParent + wChild/2 = xParent + wParent/4 > 1023 + 512 = 1535 * @dev special care was taken when writing this function so that this function does not transfer any ownership! */ function _subdivideQTNode(uint64 _tokenId) private { QuadTree storage qtree = qtrees[_tokenId]; uint16 x = qtree.boundary.x; uint16 y = qtree.boundary.y; uint16 w = qtree.boundary.w; uint16 h = qtree.boundary.h; require(w > 1 && h > 1, "NFTG: cannot divide"); // cannot divide w or h=1 and 0 is not expected if (qtree.owner != address(0x0)) { _burn(uint256(_tokenId)); } // special case for w|h=2 // X2:0,0:x,y = 1,0 & 0,0 & 1,1 & 0,1 // X2:1,0:x,y = 2,0 & 2,0 & 2,2 & 0,2 // X2:1,1:x,y = 2,1 & 1,1 & 2,2 & 1,2 // X2:2,2:x,y = 4,3 & 3,3 & 4,4 & 3,4 if ((w == 2) || (h==2)) { qtree.northeast = _createQTNode(qtree.owner, x + 1, y - 0, w/2, h/2); qtree.northwest = _createQTNode(qtree.owner, x - 0, y - 0, w/2, h/2); qtree.southeast = _createQTNode(qtree.owner, x + 1, y + 1, w/2, h/2); qtree.southwest = _createQTNode(qtree.owner, x - 0, y + 1, w/2, h/2); } else { qtree.northeast = _createQTNode(qtree.owner, x + w/4, y - h/4, w/2, h/2); qtree.northwest = _createQTNode(qtree.owner, x - w/4, y - h/4, w/2, h/2); qtree.southeast = _createQTNode(qtree.owner, x + w/4, y + h/4, w/2, h/2); qtree.southwest = _createQTNode(qtree.owner, x - w/4, y + h/4, w/2, h/2); } qtree.divided = true; qtree.owner = address(0x0); } /** * @notice creates a QuadTree node - which is placement of pixels as well as mints the NFT as long as there is an actual owner * @param _owner is who the owner of the QuadTree and the NFT will be, this can be zero and if so then the QuadTree node is not owned and the NFT is not minted * @param _x is the x location * @param _y is the y location * @param _w is the width * @param _h is the height * @return tokenId the tokenId of the quad */ function _createQTNode(address _owner, uint16 _x, uint16 _y, uint16 _w, uint16 _h) private returns(uint64 tokenId) { Rectangle memory boundary = Rectangle(_x, _y, _w, _h); // console.log("_x", _x, "_y", _y); // console.log("_w", _w, "_h", _h); tokenId = getTokenIdFromRange(boundary); QuadTree storage qtree = qtrees[tokenId]; qtree.boundary = boundary; qtree.owner = _owner; if (_owner != address(0)) { _safeMint(_owner, tokenId); } } /** * @notice decodes the token ID into a rectangle * @dev symetric: should be kept up-to-date with JS implementation * entokenIdd tokenId: 0x<X:2 bytes>_<Y:2 bytes>_<W:2 bytes>_wers of 2 are 0x1 = 1, 0x10 = 2, 0x100 = 4, etc. * 4: 0x100 & (0x100 - 1) = 0x100 & 0x011 = 0x000 * negative tests: * 7: 0x111 & (0x111 - 1) = 0x111 & 0x110 = 0x110 * 5: 0x101 & (0x101 - 1) = 0x101 & 0x100 = 0x100 * @dev for the x & y validation, these values are always in the middle of the first tile (0.5 * w, 0.5 * h) and are then at increments of w & h * therefor we can use the modulo operator and check that the remainder is precisely the offset: * @dev we offset x & y left one and up one so that for X1 the w=1/h=1 has x=0/y=0 and just as well for X2 w=2/h=2 has x=0,y=0 * the x & y values range from 0:w-1 and 0:h-1 * special care should be taken around w=1 and w=2 as the first tile for both is at x=0 and y=0 and * for w=1 max x&y=2047 for w=2 max x&y=2046 *<H:2 bytes> = 8 bytes = 64 bits (4 hex represent 2 bytes) * to get x we right shift by 6 bytes: 0x0000_0000_0000_<X:2 bytes> * to get y we right shift by 4 bytes & 0xFFFF: 0x0000_0000_<X:2 bytes>_<Y:2 bytes> & 0xFFFF = 0x0000_0000_0000_<Y:2 bytes> * @param _tokenId is the token ID to get the range of * @return range is the rectangle/range decoded from the NFTs token ID */ function getRangeFromTokenId(uint64 _tokenId) public pure returns(Rectangle memory range) { uint16 mask = 0xFFFF; range.x = uint16((_tokenId >> 6 * 8) & mask); range.y = uint16((_tokenId >> 4 * 8) & mask); range.w = uint16((_tokenId >> 2 * 8) & mask); range.h = uint16(_tokenId & mask); validate(range); } /** * @notice encodes a rectangle into a token ID * @dev symetric: should be kept up-to-date with JS implementation * @dev tokenId: 0x<X:2 bytes><Y:2 bytes><W:2 bytes><H:2 bytes> = 8 bytes = 64 bits * @param _range is the rectangle to encode * @return tokenId is the token ID encoded from the rectangle */ function getTokenIdFromRange(Rectangle memory _range) public pure returns(uint64 tokenId) { validate(_range); tokenId = _getTokenIdFromRangeNoCheck(_range); } /** * @notice performs an unchecked encoding of a rectable into a token ID (used where validate was already run) * @param _range is the rectangle to encode * @return tokenId is the token ID encoded from the rectangle */ function _getTokenIdFromRangeNoCheck(Rectangle memory _range) private pure returns(uint64 tokenId) { tokenId = (uint64(_range.x) << 6 * 8) + (uint64(_range.y) << 4 * 8) + (uint64(_range.w) << 2 * 8) + uint64(_range.h); } /** * @notice validates a rectangle to make sure it conforms to the x & y placement rules as well as w & h follow the sizing rules, reverts if any rule is broken * @dev symetric: should be kept up-to-date with JS implementation * @dev the w and h must be a power of 2 and instead of comparing to all of the values in the enum, we just check it using: * N & (N - 1) this works because all powers of 2 are 0x1 = 1, 0x10 = 2, 0x100 = 4, etc. * 4: 0x100 & (0x100 - 1) = 0x100 & 0x011 = 0x000 * negative tests: * 7: 0x111 & (0x111 - 1) = 0x111 & 0x110 = 0x110 * 5: 0x101 & (0x101 - 1) = 0x101 & 0x100 = 0x100 * @dev for the x & y validation, these values are always in the middle of the first tile (0.5 * w, 0.5 * h) and are then at increments of w & h * there for we can use the modulo operator and check that the remainder is precisely the offset: * @dev we offset x & y left one and up one so that for X1 the w=1/h=1 has x=0/y=0 and just as well for X2 w=2/h=2 has x=0,y=0 * the x & y values range from 0:w-1 and 0:h-1 * special care should be taken around w=1 and w=2 as the first tile for both is at x=0 and y=0 and * for w=1 max x&y=2047 for w=2 max x&y=2046 * @param _range is the rectangle to validate */ function validate(Rectangle memory _range) public pure { require((_range.x <= GRID_W - 1), "NFTG: x is out-of-bounds"); require((_range.y <= GRID_H - 1), "NFTG: y is out-of-bounds"); require((_range.w > 0), "NFTG: w must be greater than 0"); require((_range.h > 0), "NFTG: h must be greater than 0"); require((_range.w <= GRID_W), "NFTG: w is too large"); require((_range.h <= GRID_H), "NFTG: h is too large"); require((_range.w & (_range.w - 1) == 0), "NFTG: w is not a power of 2"); require((_range.h & (_range.h - 1) == 0), "NFTG: h is not a power of 2"); uint16 xMidOffset = _range.w / 2; // for w=1 xmid=0, w=2 xmid=1, w=4 xmid=2, etc. uint16 yMidOffset = _range.h / 2; // for w=1 and x=2047: (2047+1)%1=0, w=2 and x=1023: (1023+1)%2=0, w=4 and x=255: (255+1)%4=0 require(((_range.x + 1) % _range.w) == xMidOffset, "NFTG: x is not a multiple of w"); require(((_range.y + 1) % _range.h) == yMidOffset, "NFTG: y is not a multiple of h"); } //// BOILERPLATE /** * @notice receive ETH with no calldata * @dev see: https://blog.soliditylang.org/2020/03/26/fallback-receive-split/ */ // solhint-disable-next-line no-empty-blocks receive() external payable {} /** * @notice receive ETH with no function match */ fallback() external payable {} /** * @notice allow withdraw of any ETH sent directly to the contract */ function withdraw() external onlyOwner { address payable owner = payable(owner()); owner.transfer(address(this).balance); } /** * @notice allow withdraw of any ERC20 sent directly to the contract * @param _token the address of the token to use for withdraw * @param _amount the amount of the token to withdraw */ function withdrawToken(address _token, uint _amount) external onlyOwner { IERC20(_token).safeTransfer(owner(), _amount); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Counters.sol) pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library Counters { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol) pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `to`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `from` to `to` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/ERC721.sol) pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); _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 {} } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol) pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); }
* @notice validates a rectangle to make sure it conforms to the x & y placement rules as well as w & h follow the sizing rules, reverts if any rule is broken @dev symetric: should be kept up-to-date with JS implementation @dev the w and h must be a power of 2 and instead of comparing to all of the values in the enum, we just check it using: N & (N - 1) this works because all powers of 2 are 0x1 = 1, 0x10 = 2, 0x100 = 4, etc. 4: 0x100 & (0x100 - 1) = 0x100 & 0x011 = 0x000 negative tests: 7: 0x111 & (0x111 - 1) = 0x111 & 0x110 = 0x110 5: 0x101 & (0x101 - 1) = 0x101 & 0x100 = 0x100 @dev for the x & y validation, these values are always in the middle of the first tile (0.5 w, 0.5 h) and are then at increments of w & h there for we can use the modulo operator and check that the remainder is precisely the offset: @dev we offset x & y left one and up one so that for X1 the w=1/h=1 has x=0/y=0 and just as well for X2 w=2/h=2 has x=0,y=0 the x & y values range from 0:w-1 and 0:h-1 special care should be taken around w=1 and w=2 as the first tile for both is at x=0 and y=0 and for w=1 max x&y=2047 for w=2 max x&y=2046 @param _range is the rectangle to validate/ for w=1 and x=2047: (2047+1)%1=0, w=2 and x=1023: (1023+1)%2=0, w=4 and x=255: (255+1)%4=0
function validate(Rectangle memory _range) public pure { require((_range.x <= GRID_W - 1), "NFTG: x is out-of-bounds"); require((_range.y <= GRID_H - 1), "NFTG: y is out-of-bounds"); require((_range.w > 0), "NFTG: w must be greater than 0"); require((_range.h > 0), "NFTG: h must be greater than 0"); require((_range.w <= GRID_W), "NFTG: w is too large"); require((_range.h <= GRID_H), "NFTG: h is too large"); require((_range.w & (_range.w - 1) == 0), "NFTG: w is not a power of 2"); require((_range.h & (_range.h - 1) == 0), "NFTG: h is not a power of 2"); uint16 yMidOffset = _range.h / 2; require(((_range.x + 1) % _range.w) == xMidOffset, "NFTG: x is not a multiple of w"); require(((_range.y + 1) % _range.h) == yMidOffset, "NFTG: y is not a multiple of h"); }
265,549
[ 1, 877, 815, 279, 11845, 358, 1221, 3071, 518, 356, 9741, 358, 326, 619, 473, 677, 12607, 2931, 487, 5492, 487, 341, 473, 366, 2805, 326, 272, 6894, 2931, 16, 15226, 87, 309, 1281, 1720, 353, 12933, 225, 5382, 1591, 30, 1410, 506, 16555, 731, 17, 869, 17, 712, 598, 6756, 4471, 225, 326, 341, 471, 366, 1297, 506, 279, 7212, 434, 576, 471, 3560, 434, 17553, 358, 777, 434, 326, 924, 316, 326, 2792, 16, 732, 2537, 866, 518, 1450, 30, 565, 423, 473, 261, 50, 300, 404, 13, 225, 333, 6330, 2724, 777, 7602, 414, 434, 576, 854, 374, 92, 21, 273, 404, 16, 374, 92, 2163, 273, 576, 16, 374, 92, 6625, 273, 1059, 16, 5527, 18, 565, 1059, 30, 374, 92, 6625, 473, 261, 20, 92, 6625, 300, 404, 13, 273, 374, 92, 6625, 473, 374, 92, 1611, 21, 273, 374, 92, 3784, 6092, 7434, 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, 1954, 12, 19463, 3778, 389, 3676, 13, 1071, 16618, 288, 203, 3639, 2583, 12443, 67, 3676, 18, 92, 1648, 15228, 734, 67, 59, 300, 404, 3631, 315, 50, 4464, 43, 30, 619, 353, 596, 17, 792, 17, 10576, 8863, 203, 3639, 2583, 12443, 67, 3676, 18, 93, 1648, 15228, 734, 67, 44, 300, 404, 3631, 315, 50, 4464, 43, 30, 677, 353, 596, 17, 792, 17, 10576, 8863, 203, 3639, 2583, 12443, 67, 3676, 18, 91, 405, 374, 3631, 315, 50, 4464, 43, 30, 341, 1297, 506, 6802, 2353, 374, 8863, 203, 3639, 2583, 12443, 67, 3676, 18, 76, 405, 374, 3631, 315, 50, 4464, 43, 30, 366, 1297, 506, 6802, 2353, 374, 8863, 203, 3639, 2583, 12443, 67, 3676, 18, 91, 1648, 15228, 734, 67, 59, 3631, 315, 50, 4464, 43, 30, 341, 353, 4885, 7876, 8863, 203, 3639, 2583, 12443, 67, 3676, 18, 76, 1648, 15228, 734, 67, 44, 3631, 315, 50, 4464, 43, 30, 366, 353, 4885, 7876, 8863, 203, 3639, 2583, 12443, 67, 3676, 18, 91, 473, 261, 67, 3676, 18, 91, 300, 404, 13, 422, 374, 3631, 315, 50, 4464, 43, 30, 341, 353, 486, 279, 7212, 434, 576, 8863, 7010, 3639, 2583, 12443, 67, 3676, 18, 76, 473, 261, 67, 3676, 18, 76, 300, 404, 13, 422, 374, 3631, 315, 50, 4464, 43, 30, 366, 353, 486, 279, 7212, 434, 576, 8863, 203, 3639, 2254, 2313, 677, 20711, 2335, 273, 389, 3676, 18, 76, 342, 576, 31, 203, 3639, 2583, 12443, 24899, 3676, 18, 92, 397, 2 ]
//Address: 0xdae1baf249964bc4b6ac98c3122f0e3e785fd279 //Contract name: TokiaToken //Balance: 0 Ether //Verification Date: 12/28/2017 //Transacion Count: 4964 // CODE STARTS HERE pragma solidity 0.4.18; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; require(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) public balances; /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { function safeTransfer(ERC20Basic token, address to, uint256 value) internal { assert(token.transfer(to, value)); } function safeTransferFrom(ERC20 token, address from, address to, uint256 value) internal { assert(token.transferFrom(from, to, value)); } function safeApprove(ERC20 token, address spender, uint256 value) internal { assert(token.approve(spender, value)); } } /** * @title TokenTimelock * @dev TokenTimelock is a token holder contract that will allow a * beneficiary to extract the tokens after a given release time */ contract TokenTimelock { using SafeERC20 for ERC20Basic; // ERC20 basic token contract being held ERC20Basic public token; // beneficiary of tokens after they are released address public beneficiary; // timestamp when token release is enabled uint64 public releaseTime; function TokenTimelock(ERC20Basic _token, address _beneficiary, uint64 _releaseTime) public { require(_releaseTime > uint64(block.timestamp)); token = _token; beneficiary = _beneficiary; releaseTime = _releaseTime; } /** * @notice Transfers tokens held by timelock to beneficiary. */ function release() public { require(uint64(block.timestamp) >= releaseTime); uint256 amount = token.balanceOf(this); require(amount > 0); token.safeTransfer(beneficiary, amount); } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256 remaining) { return allowed[_owner][_spender]; } /** * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol */ function increaseApproval (address _spender, uint _addedValue) public returns (bool success) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval (address _spender, uint _subtractedValue) public returns (bool success) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } contract Owned { address public owner; function Owned() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } } contract TokiaToken is StandardToken, Owned { string public constant name = "TokiaToken"; string public constant symbol = "TKA"; uint8 public constant decimals = 18; /// Maximum tokens to be allocated. uint256 public constant HARD_CAP = 62500000 * 10**uint256(decimals); /// Maximum tokens to be allocated on the sale (75% of the hard cap) uint256 public constant TOKENS_SALE_HARD_CAP = 50000000 * 10**uint256(decimals); /// Base exchange rate is set to 1 ETH = 714 TKA. uint256 public constant BASE_RATE = 714; /// seconds since 01.01.1970 to 04.12.2017 (both 00:00:00 o'clock UTC) /// presale start time uint64 private constant date04Dec2017 = 1512345600; /// presale end time; round 1 start time uint64 private constant date01Jan2018 = 1514764800; /// round 1 end time; round 2 start time uint64 private constant date01Feb2018 = 1517443200; /// round 2 end time; round 3 start time uint64 private constant date15Feb2018 = 1518652800; /// round 3 end time; round 4 start time uint64 private constant date01Mar2018 = 1519862400; /// round 4 end time; closing token sale uint64 private constant date15Mar2018 = 1521072000; /// team tokens are locked until this date (01.01.2019) uint64 private constant date01Jan2019 = 1546300800; /// token trading opening time (01.05.2018) uint64 private constant date01May2018 = 1525219199; /// no tokens can be ever issued when this is set to "true" bool public tokenSaleClosed = false; /// contract to be called to release the Tokia team tokens address public timelockContractAddress; /// Issue event index starting from 0. uint64 public issueIndex = 0; /// Emitted for each sucuessful token purchase. event Issue(uint64 issueIndex, address addr, uint256 tokenAmount); modifier inProgress { require(totalSupply < TOKENS_SALE_HARD_CAP && !tokenSaleClosed); _; } /// Allow the closing to happen only once modifier beforeEnd { require(!tokenSaleClosed); _; } /// Require that the end of the sale has passed (time is 01 May 2018 or later) modifier tradingOpen { require(uint64(block.timestamp) > date01May2018); _; } function TokiaToken() public { } /// @dev This default function allows token to be purchased by directly /// sending ether to this smart contract. function () public payable { purchaseTokens(msg.sender); } /// @dev Issue token based on Ether received. /// @param _beneficiary Address that newly issued token will be sent to. function purchaseTokens(address _beneficiary) public payable inProgress { // only accept a minimum amount of ETH? require(msg.value >= 0.01 ether); uint256 tokens = computeTokenAmount(msg.value); doIssueTokens(_beneficiary, tokens); /// forward the raised funds to the contract creator owner.transfer(this.balance); } /// @dev Batch issue tokens on the presale /// @param _addresses addresses that the presale tokens will be sent to. /// @param _addresses the amounts of tokens, with decimals expanded (full). function issueTokensMulti(address[] _addresses, uint256[] _tokens) public onlyOwner inProgress { require(_addresses.length == _tokens.length); require(_addresses.length <= 100); for (uint256 i = 0; i < _tokens.length; i = i.add(1)) { doIssueTokens(_addresses[i], _tokens[i].mul(10**uint256(decimals))); } } /// @dev Issue tokens for a single buyer on the presale /// @param _beneficiary addresses that the presale tokens will be sent to. /// @param _tokens the amount of tokens, with decimals expanded (full). function issueTokens(address _beneficiary, uint256 _tokens) public onlyOwner inProgress { doIssueTokens(_beneficiary, _tokens.mul(10**uint256(decimals))); } /// @dev issue tokens for a single buyer /// @param _beneficiary addresses that the tokens will be sent to. /// @param _tokens the amount of tokens, with decimals expanded (full). function doIssueTokens(address _beneficiary, uint256 _tokens) internal { require(_beneficiary != address(0)); // compute without actually increasing it uint256 increasedTotalSupply = totalSupply.add(_tokens); // roll back if hard cap reached require(increasedTotalSupply <= TOKENS_SALE_HARD_CAP); // increase token total supply totalSupply = increasedTotalSupply; // update the beneficiary balance to number of tokens sent balances[_beneficiary] = balances[_beneficiary].add(_tokens); // event is fired when tokens issued Issue( issueIndex++, _beneficiary, _tokens ); } /// @dev Returns the current price. function price() public view returns (uint256 tokens) { return computeTokenAmount(1 ether); } /// @dev Compute the amount of TKA token that can be purchased. /// @param ethAmount Amount of Ether to purchase TKA. /// @return Amount of TKA token to purchase function computeTokenAmount(uint256 ethAmount) internal view returns (uint256 tokens) { uint256 tokenBase = ethAmount.mul(BASE_RATE); uint8[5] memory roundDiscountPercentages = [47, 35, 25, 15, 5]; uint8 roundDiscountPercentage = roundDiscountPercentages[currentRoundIndex()]; uint8 amountDiscountPercentage = getAmountDiscountPercentage(tokenBase); tokens = tokenBase.mul(100).div(100 - (roundDiscountPercentage + amountDiscountPercentage)); } /// @dev Compute the additional discount for the purchaed amount of TKA /// @param tokenBase the base tokens amount computed only against the base rate /// @return integer representing the percentage discount function getAmountDiscountPercentage(uint256 tokenBase) internal pure returns (uint8) { if(tokenBase >= 1500 * 10**uint256(decimals)) return 9; if(tokenBase >= 1000 * 10**uint256(decimals)) return 5; if(tokenBase >= 500 * 10**uint256(decimals)) return 3; return 0; } /// @dev Determine the current sale round /// @return integer representing the index of the current sale round function currentRoundIndex() internal view returns (uint8 roundNum) { roundNum = currentRoundIndexByDate(); /// token caps for each round uint256[5] memory roundCaps = [ 10000000 * 10**uint256(decimals), 22500000 * 10**uint256(decimals), // + round 1 35000000 * 10**uint256(decimals), // + round 2 40000000 * 10**uint256(decimals), // + round 3 50000000 * 10**uint256(decimals) // + round 4 ]; /// round determined by conjunction of both time and total sold tokens while(roundNum < 4 && totalSupply > roundCaps[roundNum]) { roundNum++; } } /// @dev Determine the current sale tier. /// @return the index of the current sale tier by date. function currentRoundIndexByDate() internal view returns (uint8 roundNum) { uint64 _now = uint64(block.timestamp); require(_now <= date15Mar2018); roundNum = 0; if(_now > date01Mar2018) roundNum = 4; if(_now > date15Feb2018) roundNum = 3; if(_now > date01Feb2018) roundNum = 2; if(_now > date01Jan2018) roundNum = 1; return roundNum; } /// @dev Closes the sale, issues the team tokens and burns the unsold function close() public onlyOwner beforeEnd { /// team tokens are equal to 25% of the sold tokens uint256 teamTokens = totalSupply.mul(25).div(100); /// check for rounding errors when cap is reached if(totalSupply.add(teamTokens) > HARD_CAP) { teamTokens = HARD_CAP.sub(totalSupply); } /// team tokens are locked until this date (01.01.2019) TokenTimelock lockedTeamTokens = new TokenTimelock(this, owner, date01Jan2019); timelockContractAddress = address(lockedTeamTokens); balances[timelockContractAddress] = balances[timelockContractAddress].add(teamTokens); /// increase token total supply totalSupply = totalSupply.add(teamTokens); /// fire event when tokens issued Issue( issueIndex++, timelockContractAddress, teamTokens ); /// burn the unallocated tokens - no more tokens can be issued after this line tokenSaleClosed = true; /// forward the raised funds to the contract creator owner.transfer(this.balance); } /// Transfer limited by the tradingOpen modifier (time is 01 May 2018 or later) function transferFrom(address _from, address _to, uint256 _value) public tradingOpen returns (bool) { return super.transferFrom(_from, _to, _value); } /// Transfer limited by the tradingOpen modifier (time is 01 May 2018 or later) function transfer(address _to, uint256 _value) public tradingOpen returns (bool) { return super.transfer(_to, _value); } }
@dev Compute the amount of TKA token that can be purchased. @param ethAmount Amount of Ether to purchase TKA. @return Amount of TKA token to purchase
function computeTokenAmount(uint256 ethAmount) internal view returns (uint256 tokens) { uint256 tokenBase = ethAmount.mul(BASE_RATE); uint8[5] memory roundDiscountPercentages = [47, 35, 25, 15, 5]; uint8 roundDiscountPercentage = roundDiscountPercentages[currentRoundIndex()]; uint8 amountDiscountPercentage = getAmountDiscountPercentage(tokenBase); tokens = tokenBase.mul(100).div(100 - (roundDiscountPercentage + amountDiscountPercentage)); }
1,837,170
[ 1, 7018, 326, 3844, 434, 399, 47, 37, 1147, 716, 848, 506, 5405, 343, 8905, 18, 225, 13750, 6275, 16811, 434, 512, 1136, 358, 23701, 399, 47, 37, 18, 327, 16811, 434, 399, 47, 37, 1147, 358, 23701, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 3671, 1345, 6275, 12, 11890, 5034, 13750, 6275, 13, 2713, 1476, 1135, 261, 11890, 5034, 2430, 13, 288, 203, 3639, 2254, 5034, 1147, 2171, 273, 13750, 6275, 18, 16411, 12, 8369, 67, 24062, 1769, 203, 3639, 2254, 28, 63, 25, 65, 3778, 3643, 9866, 8410, 1023, 273, 306, 9462, 16, 13191, 16, 6969, 16, 4711, 16, 1381, 15533, 203, 203, 3639, 2254, 28, 3643, 9866, 16397, 273, 3643, 9866, 8410, 1023, 63, 2972, 11066, 1016, 1435, 15533, 203, 3639, 2254, 28, 3844, 9866, 16397, 273, 24418, 9866, 16397, 12, 2316, 2171, 1769, 203, 203, 3639, 2430, 273, 1147, 2171, 18, 16411, 12, 6625, 2934, 2892, 12, 6625, 300, 261, 2260, 9866, 16397, 397, 3844, 9866, 16397, 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 ]
./full_match/1287/0xC7C8F57C273c59476f67c614192296dEBcFE9229/sources/project_/contracts/RecordsVotingContract.sol
@dev This struct holds the data for new record version request @param recordData Data for the new record @param governanceToken New token data for governance token @param communityToken New token data for community token @param requester Owner of the request @param oldVersionId Record id of old version @param tokenId id of the token which will be used for voting @param ballotId Id of the voting ballot @param isPresent This is to check if the request with id is present or not @param isAccepted The is the status of record that is accepted or not
struct NewVersionRequest { RecordsContract.RecordStruct recordData; NewVersionTokenStruct governanceToken; NewVersionTokenStruct communityToken; uint256[] contributionIds; address requester; uint256 oldVersionId; uint256 tokenId; uint256 ballotId; bool isPresent; bool isAccepted; } uint256 requestId, RecordsContract.RecordStruct recordData, NewVersionTokenStruct governanceToken, NewVersionTokenStruct communityToken, uint256[] contributionIds, address requester, uint256 oldVersionId, uint256 tokenId, uint256 ballotId ); address voter, uint256 versionRequestId, uint256 ballotId, bool vote ); event NewVersionVotingBallotCreated( address requester, uint256 versionRequestId, uint256 ballotId, uint256 createdAt ); uint256 versionReqId, uint256 tokenId, uint256 ballotId, bool result, bool minTurnOut, uint256 newRecordId );
7,096,739
[ 1, 2503, 1958, 14798, 326, 501, 364, 394, 1409, 1177, 590, 225, 23065, 1910, 364, 326, 394, 1409, 225, 314, 1643, 82, 1359, 1345, 1166, 1147, 501, 364, 314, 1643, 82, 1359, 1147, 225, 19833, 1345, 1166, 1147, 501, 364, 19833, 1147, 225, 19961, 16837, 434, 326, 590, 225, 1592, 28039, 5059, 612, 434, 1592, 1177, 225, 1147, 548, 612, 434, 326, 1147, 1492, 903, 506, 1399, 364, 331, 17128, 225, 26503, 352, 548, 3124, 434, 326, 331, 17128, 26503, 352, 225, 12469, 1220, 353, 358, 866, 309, 326, 590, 598, 612, 353, 3430, 578, 486, 225, 353, 18047, 1021, 353, 326, 1267, 434, 1409, 716, 353, 8494, 578, 486, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 1958, 1166, 27604, 288, 203, 3639, 27390, 8924, 18, 2115, 3823, 23065, 31, 203, 3639, 1166, 1444, 1345, 3823, 314, 1643, 82, 1359, 1345, 31, 203, 3639, 1166, 1444, 1345, 3823, 19833, 1345, 31, 203, 3639, 2254, 5034, 8526, 24880, 2673, 31, 203, 3639, 1758, 19961, 31, 203, 3639, 2254, 5034, 1592, 28039, 31, 203, 3639, 2254, 5034, 1147, 548, 31, 203, 3639, 2254, 5034, 26503, 352, 548, 31, 203, 3639, 1426, 12469, 31, 203, 3639, 1426, 353, 18047, 31, 203, 565, 289, 203, 203, 3639, 2254, 5034, 14459, 16, 203, 3639, 27390, 8924, 18, 2115, 3823, 23065, 16, 203, 3639, 1166, 1444, 1345, 3823, 314, 1643, 82, 1359, 1345, 16, 203, 3639, 1166, 1444, 1345, 3823, 19833, 1345, 16, 203, 3639, 2254, 5034, 8526, 24880, 2673, 16, 203, 3639, 1758, 19961, 16, 203, 3639, 2254, 5034, 1592, 28039, 16, 203, 3639, 2254, 5034, 1147, 548, 16, 203, 3639, 2254, 5034, 26503, 352, 548, 203, 565, 11272, 203, 203, 3639, 1758, 331, 20005, 16, 203, 3639, 2254, 5034, 1177, 15493, 16, 203, 3639, 2254, 5034, 26503, 352, 548, 16, 203, 3639, 1426, 12501, 203, 565, 11272, 203, 203, 565, 871, 1166, 1444, 58, 17128, 38, 454, 352, 6119, 12, 203, 3639, 1758, 19961, 16, 203, 3639, 2254, 5034, 1177, 15493, 16, 203, 3639, 2254, 5034, 26503, 352, 548, 16, 203, 3639, 2254, 5034, 26083, 203, 565, 11272, 203, 203, 3639, 2254, 5034, 1177, 6113, 548, 16, 203, 3639, 2254, 5034, 1147, 548, 16, 203, 3639, 2254, 5034, 26503, 352, 548, 16, 203, 3639, 2 ]
./partial_match/1/0x0a783B98fdAc271Efd3804b129a5Af15e88093d5/sources/Token.sol
1 K2G = 23,8894 CPT
uint tokens = (_valueCPT * 10000) / 238894;
2,866,510
[ 1, 21, 1475, 22, 43, 273, 10213, 16, 5482, 11290, 385, 1856, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2254, 2430, 273, 261, 67, 1132, 39, 1856, 380, 12619, 13, 342, 10213, 5482, 11290, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/80001/0x12d8a7fB94b9D57da2F2C04bFBBD3558Fa138646/sources/project_/contracts/ERC20/USDC/Context/Context.sol
@dev Provides information about the current execution context, including the sender of the transaction and its data. While these are generally available via msg.sender and msg.data, they should not be accessed in such a direct manner, since when dealing with GSN meta-transactions the account sending and paying for execution may not be the actual sender (as far as an application is concerned). This contract is only required for intermediate, library-like contracts./
abstract contract Context { function _msgSender() internal virtual view returns (address payable) { return msg.sender; } function _msgData() internal virtual view returns (bytes memory) { return msg.data; } }
865,548
[ 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, 611, 13653, 2191, 17, 20376, 326, 2236, 5431, 471, 8843, 310, 364, 4588, 2026, 486, 506, 326, 3214, 5793, 261, 345, 10247, 487, 392, 2521, 353, 356, 2750, 11748, 2934, 1220, 6835, 353, 1338, 1931, 364, 12110, 16, 5313, 17, 5625, 20092, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 17801, 6835, 1772, 288, 203, 203, 203, 565, 445, 389, 3576, 12021, 1435, 2713, 5024, 1476, 1135, 261, 2867, 8843, 429, 13, 288, 203, 3639, 327, 1234, 18, 15330, 31, 203, 565, 289, 203, 203, 565, 445, 389, 3576, 751, 1435, 2713, 5024, 1476, 1135, 261, 3890, 3778, 13, 288, 203, 3639, 327, 1234, 18, 892, 31, 203, 565, 289, 203, 97, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.0; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "./interface/IUniswapFactory.sol"; import "./interface/IKyberNetworkProxy.sol"; import "./interface/IKyberUniswapReserve.sol"; import "./interface/IKyberOasisReserve.sol"; import "./interface/IKyberBancorReserve.sol"; import "./interface/IBancorNetwork.sol"; import "./interface/IBancorContractRegistry.sol"; //import "./interface/IBancorNetworkPathFinder.sol"; import "./interface/IBancorConverterRegistry.sol"; import "./interface/IBancorEtherToken.sol"; import "./interface/IOasisExchange.sol"; import "./interface/IWETH.sol"; import "./interface/ICurve.sol"; import "./interface/IChai.sol"; import "./interface/ICompound.sol"; import "./interface/IAaveToken.sol"; import "./interface/IMooniswap.sol"; import "./interface/IUniswapV2Factory.sol"; import "./interface/IDForceSwap.sol"; import "./interface/IShell.sol"; import "./IOneSplit.sol"; import "./UniversalERC20.sol"; contract IOneSplitView is IOneSplitConsts { function getExpectedReturn( IERC20 fromToken, IERC20 toToken, uint256 amount, uint256 parts, uint256 flags ) public view returns( uint256 returnAmount, uint256[] memory distribution ); } library DisableFlags { function check(uint256 flags, uint256 flag) internal pure returns(bool) { return (flags & flag) != 0; } } contract OneSplitRoot { using SafeMath for uint256; using DisableFlags for uint256; using UniversalERC20 for IERC20; using UniversalERC20 for IWETH; using UniversalERC20 for IBancorEtherToken; using UniswapV2ExchangeLib for IUniswapV2Exchange; using ChaiHelper for IChai; uint256 constant public DEXES_COUNT = 22; IERC20 constant public ETH_ADDRESS = IERC20(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE); IERC20 constant public dai = IERC20(0x6B175474E89094C44Da98b954EedeAC495271d0F); IERC20 constant public bnt = IERC20(0x1F573D6Fb3F13d689FF844B4cE37794d79a7FF1C); IERC20 constant public usdc = IERC20(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48); IERC20 constant public usdt = IERC20(0xdAC17F958D2ee523a2206206994597C13D831ec7); IERC20 constant public tusd = IERC20(0x0000000000085d4780B73119b644AE5ecd22b376); IERC20 constant public busd = IERC20(0x4Fabb145d64652a948d72533023f6E7A623C7C53); IERC20 constant public susd = IERC20(0x57Ab1ec28D129707052df4dF418D58a2D46d5f51); IERC20 constant public pax = IERC20(0x8E870D67F660D95d5be530380D0eC0bd388289E1); IWETH constant public weth = IWETH(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); IBancorEtherToken constant public bancorEtherToken = IBancorEtherToken(0xc0829421C1d260BD3cB3E0F06cfE2D52db2cE315); IChai constant public chai = IChai(0x06AF07097C9Eeb7fD685c692751D5C66dB49c215); IERC20 constant public renbtc = IERC20(0xEB4C2781e4ebA804CE9a9803C67d0893436bB27D); IERC20 constant public wbtc = IERC20(0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599); IERC20 constant public tbtc = IERC20(0x1bBE271d15Bb64dF0bc6CD28Df9Ff322F2eBD847); IERC20 constant public hbtc = IERC20(0x0316EB71485b0Ab14103307bf65a021042c6d380); IKyberNetworkProxy constant public kyberNetworkProxy = IKyberNetworkProxy(0x818E6FECD516Ecc3849DAf6845e3EC868087B755); IUniswapFactory constant public uniswapFactory = IUniswapFactory(0xc0a47dFe034B400B47bDaD5FecDa2621de6c4d95); IBancorContractRegistry constant public bancorContractRegistry = IBancorContractRegistry(0x52Ae12ABe5D8BD778BD5397F99cA900624CfADD4); //IBancorNetworkPathFinder constant public bancorNetworkPathFinder = IBancorNetworkPathFinder(0x6F0cD8C4f6F06eAB664C7E3031909452b4B72861); IBancorConverterRegistry constant public bancorConverterRegistry = IBancorConverterRegistry(0xf6E2D7F616B67E46D708e4410746E9AAb3a4C518); IOasisExchange constant public oasisExchange = IOasisExchange(0x794e6e91555438aFc3ccF1c5076A74F42133d08D); ICurve constant public curveCompound = ICurve(0xA2B47E3D5c44877cca798226B7B8118F9BFb7A56); ICurve constant public curveUsdt = ICurve(0x52EA46506B9CC5Ef470C5bf89f17Dc28bB35D85C); ICurve constant public curveY = ICurve(0x45F783CCE6B7FF23B2ab2D70e416cdb7D6055f51); ICurve constant public curveBinance = ICurve(0x79a8C46DeA5aDa233ABaFFD40F3A0A2B1e5A4F27); ICurve constant public curveSynthetix = ICurve(0xA5407eAE9Ba41422680e2e00537571bcC53efBfD); ICurve constant public curvePax = ICurve(0x06364f10B501e868329afBc005b3492902d6C763); ICurve constant public curveRenBtc = ICurve(0x93054188d876f558f4a66B2EF1d97d16eDf0895B); ICurve constant public curveTBtc = ICurve(0x9726e9314eF1b96E45f40056bEd61A088897313E); IShell constant public shell = IShell(0xA8253a440Be331dC4a7395B73948cCa6F19Dc97D); IAaveLendingPool constant public aave = IAaveLendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); ICompound constant public compound = ICompound(0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B); ICompoundEther constant public cETH = ICompoundEther(0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5); IMooniswapRegistry constant public mooniswapRegistry = IMooniswapRegistry(0x7079E8517594e5b21d2B9a0D17cb33F5FE2bca70); IUniswapV2Factory constant public uniswapV2 = IUniswapV2Factory(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f); IDForceSwap constant public dforceSwap = IDForceSwap(0x03eF3f37856bD08eb47E2dE7ABc4Ddd2c19B60F2); function _buildBancorPath( IERC20 fromToken, IERC20 toToken ) internal view returns(address[] memory path) { if (fromToken == toToken) { return new address[](0); } if (fromToken.isETH()) { fromToken = bancorEtherToken; } if (toToken.isETH()) { toToken = bancorEtherToken; } if (fromToken == bnt || toToken == bnt) { path = new address[](3); } else { path = new address[](5); } address fromConverter; address toConverter; if (fromToken != bnt) { (bool success, bytes memory data) = address(bancorConverterRegistry).staticcall.gas(10000)(abi.encodeWithSelector( bancorConverterRegistry.getConvertibleTokenSmartToken.selector, fromToken.isETH() ? bnt : fromToken, 0 )); if (!success) { return new address[](0); } fromConverter = abi.decode(data, (address)); if (fromConverter == address(0)) { return new address[](0); } } if (toToken != bnt) { (bool success, bytes memory data) = address(bancorConverterRegistry).staticcall.gas(10000)(abi.encodeWithSelector( bancorConverterRegistry.getConvertibleTokenSmartToken.selector, toToken.isETH() ? bnt : toToken, 0 )); if (!success) { return new address[](0); } toConverter = abi.decode(data, (address)); if (toConverter == address(0)) { return new address[](0); } } if (toToken == bnt) { path[0] = address(fromToken); path[1] = fromConverter; path[2] = address(bnt); return path; } if (fromToken == bnt) { path[0] = address(bnt); path[1] = toConverter; path[2] = address(toToken); return path; } path[0] = address(fromToken); path[1] = fromConverter; path[2] = address(bnt); path[3] = toConverter; path[4] = address(toToken); return path; } function _getCompoundToken(IERC20 token) internal pure returns(ICompoundToken) { if (token.isETH()) { // ETH return ICompoundToken(0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5); } if (token == IERC20(0x6B175474E89094C44Da98b954EedeAC495271d0F)) { // DAI return ICompoundToken(0x5d3a536E4D6DbD6114cc1Ead35777bAB948E3643); } if (token == IERC20(0x0D8775F648430679A709E98d2b0Cb6250d2887EF)) { // BAT return ICompoundToken(0x6C8c6b02E7b2BE14d4fA6022Dfd6d75921D90E4E); } if (token == IERC20(0x1985365e9f78359a9B6AD760e32412f4a445E862)) { // REP return ICompoundToken(0x158079Ee67Fce2f58472A96584A73C7Ab9AC95c1); } if (token == IERC20(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48)) { // USDC return ICompoundToken(0x39AA39c021dfbaE8faC545936693aC917d5E7563); } if (token == IERC20(0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599)) { // WBTC return ICompoundToken(0xC11b1268C1A384e55C48c2391d8d480264A3A7F4); } if (token == IERC20(0xE41d2489571d322189246DaFA5ebDe1F4699F498)) { // ZRX return ICompoundToken(0xB3319f5D18Bc0D84dD1b4825Dcde5d5f7266d407); } if (token == IERC20(0xdAC17F958D2ee523a2206206994597C13D831ec7)) { // USDT return ICompoundToken(0xf650C3d88D12dB855b8bf7D11Be6C55A4e07dCC9); } return ICompoundToken(0); } function _getAaveToken(IERC20 token) internal pure returns(IAaveToken) { if (token.isETH()) { // ETH return IAaveToken(0x3a3A65aAb0dd2A17E3F1947bA16138cd37d08c04); } if (token == IERC20(0x6B175474E89094C44Da98b954EedeAC495271d0F)) { // DAI return IAaveToken(0xfC1E690f61EFd961294b3e1Ce3313fBD8aa4f85d); } if (token == IERC20(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48)) { // USDC return IAaveToken(0x9bA00D6856a4eDF4665BcA2C2309936572473B7E); } if (token == IERC20(0x57Ab1ec28D129707052df4dF418D58a2D46d5f51)) { // SUSD return IAaveToken(0x625aE63000f46200499120B906716420bd059240); } if (token == IERC20(0x4Fabb145d64652a948d72533023f6E7A623C7C53)) { // BUSD return IAaveToken(0x6Ee0f7BB50a54AB5253dA0667B0Dc2ee526C30a8); } if (token == IERC20(0x0000000000085d4780B73119b644AE5ecd22b376)) { // TUSD return IAaveToken(0x4DA9b813057D04BAef4e5800E36083717b4a0341); } if (token == IERC20(0xdAC17F958D2ee523a2206206994597C13D831ec7)) { // USDT return IAaveToken(0x71fc860F7D3A592A4a98740e39dB31d25db65ae8); } if (token == IERC20(0x0D8775F648430679A709E98d2b0Cb6250d2887EF)) { // BAT return IAaveToken(0xE1BA0FB44CCb0D11b80F92f4f8Ed94CA3fF51D00); } if (token == IERC20(0xdd974D5C2e2928deA5F71b9825b8b646686BD200)) { // KNC return IAaveToken(0x9D91BE44C06d373a8a226E1f3b146956083803eB); } if (token == IERC20(0x80fB784B7eD66730e8b1DBd9820aFD29931aab03)) { // LEND return IAaveToken(0x7D2D3688Df45Ce7C552E19c27e007673da9204B8); } if (token == IERC20(0x514910771AF9Ca656af840dff83E8264EcF986CA)) { // LINK return IAaveToken(0xA64BD6C70Cb9051F6A9ba1F163Fdc07E0DfB5F84); } if (token == IERC20(0x0F5D2fB29fb7d3CFeE444a200298f468908cC942)) { // MANA return IAaveToken(0x6FCE4A401B6B80ACe52baAefE4421Bd188e76F6f); } if (token == IERC20(0x9f8F72aA9304c8B593d555F12eF6589cC3A579A2)) { // MKR return IAaveToken(0x7deB5e830be29F91E298ba5FF1356BB7f8146998); } if (token == IERC20(0x1985365e9f78359a9B6AD760e32412f4a445E862)) { // REP return IAaveToken(0x71010A9D003445aC60C4e6A7017c1E89A477B438); } if (token == IERC20(0xC011a73ee8576Fb46F5E1c5751cA3B9Fe0af2a6F)) { // SNX return IAaveToken(0x328C4c80BC7aCa0834Db37e6600A6c49E12Da4DE); } if (token == IERC20(0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599)) { // WBTC return IAaveToken(0xFC4B8ED459e00e5400be803A9BB3954234FD50e3); } if (token == IERC20(0xE41d2489571d322189246DaFA5ebDe1F4699F498)) { // ZRX return IAaveToken(0x6Fb0855c404E09c47C3fBCA25f08d4E41f9F062f); } return IAaveToken(0); } function _infiniteApproveIfNeeded(IERC20 token, address to) internal { if (!token.isETH()) { if ((token.allowance(address(this), to) >> 255) == 0) { token.universalApprove(to, uint256(- 1)); } } } } contract OneSplitViewWrapBase is IOneSplitView, OneSplitRoot { function getExpectedReturn( IERC20 fromToken, IERC20 toToken, uint256 amount, uint256 parts, uint256 flags // See constants in IOneSplit.sol ) public view returns( uint256 returnAmount, uint256[] memory distribution ) { return _getExpectedReturnFloor( fromToken, toToken, amount, parts, flags ); } function _getExpectedReturnFloor( IERC20 fromToken, IERC20 toToken, uint256 amount, uint256 parts, uint256 flags // See constants in IOneSplit.sol ) internal view returns( uint256 returnAmount, uint256[] memory distribution ); } contract OneSplitView is IOneSplitView, OneSplitRoot { function log(uint256) external view { } function getExchangeName(uint256 i) public pure returns(string memory) { return [ "Uniswap", "Kyber", "Bancor", "Oasis", "Curve Compound", "Curve USDT", "Curve Y", "Curve Binance", "CurveSynthetix", "Uniswap Compound", "Uniswap CHAI", "Uniswap Aave", "Mooniswap", "Uniswap V2", "Uniswap V2 (ETH)", "Uniswap V2 (DAI)", "Uniswap V2 (USDC)", "Curve Pax", "Curve RenBTC", "Curve tBTC", "Dforce XSwap", "Shell" ][i]; } function getExpectedReturn( IERC20 fromToken, IERC20 toToken, uint256 amount, uint256 parts, uint256 flags // See constants in IOneSplit.sol ) public view returns( uint256 returnAmount, uint256[] memory distribution ) { distribution = new uint256[](DEXES_COUNT); if (fromToken == toToken) { return (amount, distribution); } bool invert = flags.check(FLAG_DISABLE_ALL_SPLIT_SOURCES); function(IERC20,IERC20,uint256,uint256) view returns(uint256)[DEXES_COUNT] memory reserves = [ invert != flags.check(FLAG_DISABLE_UNISWAP) ? _calculateNoReturn : calculateUniswapReturn, invert != flags.check(FLAG_DISABLE_KYBER) ? _calculateNoReturn : calculateKyberReturn, invert != flags.check(FLAG_DISABLE_BANCOR) ? _calculateNoReturn : calculateBancorReturn, invert != flags.check(FLAG_DISABLE_OASIS) ? _calculateNoReturn : calculateOasisReturn, invert != flags.check(FLAG_DISABLE_CURVE_COMPOUND) ? _calculateNoReturn : calculateCurveCompound, invert != flags.check(FLAG_DISABLE_CURVE_USDT) ? _calculateNoReturn : calculateCurveUsdt, invert != flags.check(FLAG_DISABLE_CURVE_Y) ? _calculateNoReturn : calculateCurveY, invert != flags.check(FLAG_DISABLE_CURVE_BINANCE) ? _calculateNoReturn : calculateCurveBinance, invert != flags.check(FLAG_DISABLE_CURVE_SYNTHETIX) ? _calculateNoReturn : calculateCurveSynthetix, (true) != flags.check(FLAG_ENABLE_UNISWAP_COMPOUND) ? _calculateNoReturn : calculateUniswapCompound, (true) != flags.check(FLAG_ENABLE_UNISWAP_CHAI) ? _calculateNoReturn : calculateUniswapChai, (true) != flags.check(FLAG_ENABLE_UNISWAP_AAVE) ? _calculateNoReturn : calculateUniswapAave, invert != flags.check(FLAG_DISABLE_MOONISWAP) ? _calculateNoReturn : calculateMooniswap, invert != flags.check(FLAG_DISABLE_UNISWAP_V2) ? _calculateNoReturn : calculateUniswapV2, invert != flags.check(FLAG_DISABLE_UNISWAP_V2_ETH) ? _calculateNoReturn : calculateUniswapV2ETH, invert != flags.check(FLAG_DISABLE_UNISWAP_V2_DAI) ? _calculateNoReturn : calculateUniswapV2DAI, invert != flags.check(FLAG_DISABLE_UNISWAP_V2_USDC) ? _calculateNoReturn : calculateUniswapV2USDC, invert != flags.check(FLAG_DISABLE_CURVE_PAX) ? _calculateNoReturn : calculateCurvePax, invert != flags.check(FLAG_DISABLE_CURVE_RENBTC) ? _calculateNoReturn : calculateCurveRenBtc, invert != flags.check(FLAG_DISABLE_CURVE_TBTC) ? _calculateNoReturn : calculateCurveTBtc, invert != flags.check(FLAG_DISABLE_DFORCE_SWAP) ? _calculateNoReturn : calculateDforceSwap, invert != flags.check(FLAG_DISABLE_SHELL) ? _calculateNoReturn : calculateShell ]; uint256[DEXES_COUNT] memory rates; uint256[DEXES_COUNT] memory fullRates; for (uint i = 0; i < rates.length; i++) { rates[i] = reserves[i](fromToken, toToken, amount.div(parts), flags); this.log(rates[i]); fullRates[i] = rates[i]; } for (uint j = 0; j < parts; j++) { // Find best part uint256 bestIndex = 0; for (uint i = 1; i < rates.length; i++) { if (rates[i] > rates[bestIndex]) { bestIndex = i; } } // Add best part returnAmount = returnAmount.add(rates[bestIndex]); distribution[bestIndex]++; // Avoid CompilerError: Stack too deep uint256 srcAmount = amount; // Recalc part if needed if (j + 1 < parts) { uint256 newRate = reserves[bestIndex]( fromToken, toToken, srcAmount.mul(distribution[bestIndex] + 1).div(parts), flags ); if (newRate > fullRates[bestIndex]) { rates[bestIndex] = newRate.sub(fullRates[bestIndex]); } else { rates[bestIndex] = 0; } this.log(rates[bestIndex]); fullRates[bestIndex] = newRate; } } } // View Helpers function calculateCurveCompound( IERC20 fromToken, IERC20 destToken, uint256 amount, uint256 /*flags*/ ) public view returns(uint256) { int128 i = (fromToken == dai ? 1 : 0) + (fromToken == usdc ? 2 : 0); int128 j = (destToken == dai ? 1 : 0) + (destToken == usdc ? 2 : 0); if (i == 0 || j == 0) { return 0; } return curveCompound.get_dy_underlying(i - 1, j - 1, amount); } function calculateCurveUsdt( IERC20 fromToken, IERC20 destToken, uint256 amount, uint256 /*flags*/ ) public view returns(uint256) { int128 i = (fromToken == dai ? 1 : 0) + (fromToken == usdc ? 2 : 0) + (fromToken == usdt ? 3 : 0); int128 j = (destToken == dai ? 1 : 0) + (destToken == usdc ? 2 : 0) + (destToken == usdt ? 3 : 0); if (i == 0 || j == 0) { return 0; } return curveUsdt.get_dy_underlying(i - 1, j - 1, amount); } function calculateCurveY( IERC20 fromToken, IERC20 destToken, uint256 amount, uint256 /*flags*/ ) public view returns(uint256) { int128 i = (fromToken == dai ? 1 : 0) + (fromToken == usdc ? 2 : 0) + (fromToken == usdt ? 3 : 0) + (fromToken == tusd ? 4 : 0); int128 j = (destToken == dai ? 1 : 0) + (destToken == usdc ? 2 : 0) + (destToken == usdt ? 3 : 0) + (destToken == tusd ? 4 : 0); if (i == 0 || j == 0) { return 0; } return curveY.get_dy_underlying(i - 1, j - 1, amount); } function calculateCurveBinance( IERC20 fromToken, IERC20 destToken, uint256 amount, uint256 /*flags*/ ) public view returns(uint256) { int128 i = (fromToken == dai ? 1 : 0) + (fromToken == usdc ? 2 : 0) + (fromToken == usdt ? 3 : 0) + (fromToken == busd ? 4 : 0); int128 j = (destToken == dai ? 1 : 0) + (destToken == usdc ? 2 : 0) + (destToken == usdt ? 3 : 0) + (destToken == busd ? 4 : 0); if (i == 0 || j == 0) { return 0; } return curveBinance.get_dy_underlying(i - 1, j - 1, amount); } function calculateCurveSynthetix( IERC20 fromToken, IERC20 destToken, uint256 amount, uint256 /*flags*/ ) public view returns(uint256) { int128 i = (fromToken == dai ? 1 : 0) + (fromToken == usdc ? 2 : 0) + (fromToken == usdt ? 3 : 0) + (fromToken == susd ? 4 : 0); int128 j = (destToken == dai ? 1 : 0) + (destToken == usdc ? 2 : 0) + (destToken == usdt ? 3 : 0) + (destToken == susd ? 4 : 0); if (i == 0 || j == 0) { return 0; } return curveSynthetix.get_dy_underlying(i - 1, j - 1, amount); } function calculateCurvePax( IERC20 fromToken, IERC20 destToken, uint256 amount, uint256 /*flags*/ ) public view returns(uint256) { int128 i = (fromToken == dai ? 1 : 0) + (fromToken == usdc ? 2 : 0) + (fromToken == usdt ? 3 : 0) + (fromToken == pax ? 4 : 0); int128 j = (destToken == dai ? 1 : 0) + (destToken == usdc ? 2 : 0) + (destToken == usdt ? 3 : 0) + (destToken == pax ? 4 : 0); if (i == 0 || j == 0) { return 0; } return curvePax.get_dy_underlying(i - 1, j - 1, amount); } function calculateCurveRenBtc( IERC20 fromToken, IERC20 destToken, uint256 amount, uint256 /*flags*/ ) public view returns(uint256) { int128 i = (fromToken == renbtc ? 1 : 0) + (fromToken == wbtc ? 2 : 0); int128 j = (destToken == renbtc ? 1 : 0) + (destToken == wbtc ? 2 : 0); if (i == 0 || j == 0) { return 0; } return curveRenBtc.get_dy(i - 1, j - 1, amount); } function calculateCurveTBtc( IERC20 fromToken, IERC20 destToken, uint256 amount, uint256 /*flags*/ ) public view returns(uint256) { int128 i = (fromToken == tbtc ? 1 : 0) + (fromToken == wbtc ? 2 : 0) + (fromToken == hbtc ? 3 : 0); int128 j = (destToken == tbtc ? 1 : 0) + (destToken == wbtc ? 2 : 0) + (destToken == hbtc ? 3 : 0); if (i == 0 || j == 0) { return 0; } return curveTBtc.get_dy(i - 1, j - 1, amount); } function calculateShell( IERC20 fromToken, IERC20 destToken, uint256 amount, uint256 /*flags*/ ) public view returns (uint256) { (bool success, bytes memory data) = address(shell).staticcall(abi.encodeWithSelector( shell.viewOriginTrade.selector, fromToken, destToken, amount )); if (!success || data.length == 0) { return 0; } return abi.decode(data, (uint256)); } function calculateDforceSwap( IERC20 fromToken, IERC20 destToken, uint256 amount, uint256 /*flags*/ ) public view returns(uint256) { (bool success, bytes memory data) = address(dforceSwap).staticcall( abi.encodeWithSelector( dforceSwap.getAmountByInput.selector, fromToken, destToken, amount ) ); if (!success || data.length == 0) { return 0; } uint256 result = abi.decode(data, (uint256)); uint256 available = destToken.universalBalanceOf(address(dforceSwap)); if (result > available) { return 0; } return result; } function calculateUniswapReturn( IERC20 fromToken, IERC20 toToken, uint256 amount, uint256 /*flags*/ ) public view returns(uint256) { uint256 returnAmount = amount; if (!fromToken.isETH()) { IUniswapExchange fromExchange = uniswapFactory.getExchange(fromToken); if (fromExchange != IUniswapExchange(0)) { (bool success, bytes memory data) = address(fromExchange).staticcall.gas(200000)( abi.encodeWithSelector( fromExchange.getTokenToEthInputPrice.selector, returnAmount ) ); if (success) { returnAmount = abi.decode(data, (uint256)); } else { returnAmount = 0; } } else { returnAmount = 0; } } if (!toToken.isETH()) { IUniswapExchange toExchange = uniswapFactory.getExchange(toToken); if (toExchange != IUniswapExchange(0)) { (bool success, bytes memory data) = address(toExchange).staticcall.gas(200000)( abi.encodeWithSelector( toExchange.getEthToTokenInputPrice.selector, returnAmount ) ); if (success) { returnAmount = abi.decode(data, (uint256)); } else { returnAmount = 0; } } else { returnAmount = 0; } } return returnAmount; } function calculateUniswapCompound( IERC20 fromToken, IERC20 toToken, uint256 amount, uint256 flags ) public view returns(uint256) { if (!fromToken.isETH() && !toToken.isETH()) { return 0; } if (!fromToken.isETH()) { ICompoundToken fromCompound = _getCompoundToken(fromToken); if (fromCompound != ICompoundToken(0)) { return calculateUniswapReturn( fromCompound, toToken, amount.mul(1e18).div(fromCompound.exchangeRateStored()), flags ); } } else { ICompoundToken toCompound = _getCompoundToken(toToken); if (toCompound != ICompoundToken(0)) { return calculateUniswapReturn( fromToken, toCompound, amount, flags ).mul(toCompound.exchangeRateStored()).div(1e18); } } return 0; } function calculateUniswapChai( IERC20 fromToken, IERC20 toToken, uint256 amount, uint256 flags ) public view returns(uint256) { if (fromToken == dai && toToken.isETH()) { return calculateUniswapReturn( chai, toToken, chai.daiToChai(amount), flags ); } if (fromToken.isETH() && toToken == dai) { return chai.chaiToDai(calculateUniswapReturn( fromToken, chai, amount, flags )); } return 0; } function calculateUniswapAave( IERC20 fromToken, IERC20 toToken, uint256 amount, uint256 flags ) public view returns(uint256) { if (!fromToken.isETH() && !toToken.isETH()) { return 0; } if (!fromToken.isETH()) { IAaveToken fromAave = _getAaveToken(fromToken); if (fromAave != IAaveToken(0)) { return calculateUniswapReturn( fromAave, toToken, amount, flags ); } } else { IAaveToken toAave = _getAaveToken(toToken); if (toAave != IAaveToken(0)) { return calculateUniswapReturn( fromToken, toAave, amount, flags ); } } return 0; } function calculateKyberReturn( IERC20 fromToken, IERC20 toToken, uint256 amount, uint256 flags ) public view returns(uint256) { (bool success, bytes memory data) = address(kyberNetworkProxy).staticcall.gas(2300)(abi.encodeWithSelector( kyberNetworkProxy.kyberNetworkContract.selector )); if (!success) { return 0; } IKyberNetworkContract kyberNetworkContract = IKyberNetworkContract(abi.decode(data, (address))); if (fromToken.isETH() || toToken.isETH()) { return _calculateKyberReturnWithEth(kyberNetworkContract, fromToken, toToken, amount, flags); } uint256 value = _calculateKyberReturnWithEth(kyberNetworkContract, fromToken, ETH_ADDRESS, amount, flags); if (value == 0) { return 0; } return _calculateKyberReturnWithEth(kyberNetworkContract, ETH_ADDRESS, toToken, value, flags); } function _calculateKyberReturnWithEth( IKyberNetworkContract kyberNetworkContract, IERC20 fromToken, IERC20 toToken, uint256 amount, uint256 flags ) public view returns(uint256) { require(fromToken.isETH() || toToken.isETH(), "One of the tokens should be ETH"); (bool success, bytes memory data) = address(kyberNetworkContract).staticcall.gas(1500000)(abi.encodeWithSelector( kyberNetworkContract.searchBestRate.selector, fromToken.isETH() ? ETH_ADDRESS : fromToken, toToken.isETH() ? ETH_ADDRESS : toToken, amount, true )); if (!success) { return 0; } (address reserve, uint256 rate) = abi.decode(data, (address,uint256)); if (rate == 0) { return 0; } if ((reserve == 0x31E085Afd48a1d6e51Cc193153d625e8f0514C7F && !flags.check(FLAG_ENABLE_KYBER_UNISWAP_RESERVE)) || (reserve == 0x1E158c0e93c30d24e918Ef83d1e0bE23595C3c0f && !flags.check(FLAG_ENABLE_KYBER_OASIS_RESERVE)) || (reserve == 0x053AA84FCC676113a57e0EbB0bD1913839874bE4 && !flags.check(FLAG_ENABLE_KYBER_BANCOR_RESERVE))) { return 0; } if (!flags.check(FLAG_ENABLE_KYBER_UNISWAP_RESERVE)) { (success,) = reserve.staticcall.gas(2300)(abi.encodeWithSelector( IKyberUniswapReserve(reserve).uniswapFactory.selector )); if (success) { return 0; } } if (!flags.check(FLAG_ENABLE_KYBER_OASIS_RESERVE)) { (success,) = reserve.staticcall.gas(2300)(abi.encodeWithSelector( IKyberOasisReserve(reserve).otc.selector )); if (success) { return 0; } } if (!flags.check(FLAG_ENABLE_KYBER_BANCOR_RESERVE)) { (success,) = reserve.staticcall.gas(2300)(abi.encodeWithSelector( IKyberBancorReserve(reserve).bancorEth.selector )); if (success) { return 0; } } return rate.mul(amount) .mul(10 ** IERC20(toToken).universalDecimals()) .div(10 ** IERC20(fromToken).universalDecimals()) .div(1e18); } function calculateBancorReturn( IERC20 fromToken, IERC20 toToken, uint256 amount, uint256 /*flags*/ ) public view returns(uint256) { IBancorNetwork bancorNetwork = IBancorNetwork(bancorContractRegistry.addressOf("BancorNetwork")); address[] memory path = _buildBancorPath(fromToken, toToken); (bool success, bytes memory data) = address(bancorNetwork).staticcall.gas(500000)( abi.encodeWithSelector( bancorNetwork.getReturnByPath.selector, path, amount ) ); if (!success) { return 0; } (uint256 returnAmount,) = abi.decode(data, (uint256,uint256)); return returnAmount; } function calculateOasisReturn( IERC20 fromToken, IERC20 toToken, uint256 amount, uint256 /*flags*/ ) public view returns(uint256) { (bool success, bytes memory data) = address(oasisExchange).staticcall.gas(500000)( abi.encodeWithSelector( oasisExchange.getBuyAmount.selector, toToken.isETH() ? weth : toToken, fromToken.isETH() ? weth : fromToken, amount ) ); if (!success) { return 0; } return abi.decode(data, (uint256)); } function calculateMooniswap( IERC20 fromToken, IERC20 toToken, uint256 amount, uint256 /*flags*/ ) public view returns(uint256) { IMooniswap mooniswap = mooniswapRegistry.target(); (bool success, bytes memory data) = address(mooniswap).staticcall.gas(1000000)( abi.encodeWithSelector( mooniswap.getReturn.selector, fromToken, toToken, amount ) ); if (!success) { return 0; } return abi.decode(data, (uint256)); } function calculateUniswapV2( IERC20 fromToken, IERC20 toToken, uint256 amount, uint256 /*flags*/ ) public view returns(uint256) { IERC20 fromTokenReal = fromToken.isETH() ? weth : fromToken; IERC20 toTokenReal = toToken.isETH() ? weth : toToken; IUniswapV2Exchange fromExchange = uniswapV2.getPair(fromTokenReal, toTokenReal); if (fromExchange != IUniswapV2Exchange(0)) { return fromExchange.getReturn(fromTokenReal, toTokenReal, amount); } } function calculateUniswapV2ETH( IERC20 fromToken, IERC20 toToken, uint256 amount, uint256 flags ) public view returns(uint256) { if (fromToken.isETH() || fromToken == weth || toToken.isETH() || toToken == weth) { return 0; } return calculateUniswapV2OverMidToken( fromToken, weth, toToken, amount, flags ); } function calculateUniswapV2DAI( IERC20 fromToken, IERC20 toToken, uint256 amount, uint256 flags ) public view returns(uint256) { if (fromToken == dai || toToken == dai) { return 0; } return calculateUniswapV2OverMidToken( fromToken, dai, toToken, amount, flags ); } function calculateUniswapV2USDC( IERC20 fromToken, IERC20 toToken, uint256 amount, uint256 flags ) public view returns(uint256) { if (fromToken == usdc || toToken == usdc) { return 0; } return calculateUniswapV2OverMidToken( fromToken, usdc, toToken, amount, flags ); } function calculateUniswapV2OverMidToken( IERC20 fromToken, IERC20 midToken, IERC20 toToken, uint256 amount, uint256 flags ) public view returns(uint256) { return calculateUniswapV2( midToken, toToken, calculateUniswapV2(fromToken, midToken, amount, flags), flags ); } function _calculateNoReturn( IERC20 /*fromToken*/, IERC20 /*toToken*/, uint256 /*amount*/, uint256 /*flags*/ ) internal view returns(uint256) { this; } } contract OneSplitBaseWrap is IOneSplit, OneSplitRoot { function _swap( IERC20 fromToken, IERC20 toToken, uint256 amount, uint256[] memory distribution, uint256 flags // See constants in IOneSplit.sol ) internal { if (fromToken == toToken) { return; } _swapFloor( fromToken, toToken, amount, distribution, flags ); } function _swapFloor( IERC20 fromToken, IERC20 toToken, uint256 amount, uint256[] memory distribution, uint256 /*flags*/ // See constants in IOneSplit.sol ) internal; } contract OneSplit is IOneSplit, OneSplitRoot { IOneSplitView public oneSplitView; constructor(IOneSplitView _oneSplitView) public { oneSplitView = _oneSplitView; } function() external payable { // solium-disable-next-line security/no-tx-origin require(msg.sender != tx.origin); } function getExpectedReturn( IERC20 fromToken, IERC20 toToken, uint256 amount, uint256 parts, uint256 flags ) public view returns( uint256 returnAmount, uint256[] memory distribution ) { return oneSplitView.getExpectedReturn( fromToken, toToken, amount, parts, flags ); } function swap( IERC20 fromToken, IERC20 toToken, uint256 amount, uint256 /*minReturn*/, uint256[] memory distribution, uint256 /*flags*/ // See constants in IOneSplit.sol ) public payable returns(uint256 returnAmount) { if (fromToken == toToken) { return amount; } function(IERC20,IERC20,uint256) returns(uint256)[DEXES_COUNT] memory reserves = [ _swapOnUniswap, _swapOnKyber, _swapOnBancor, _swapOnOasis, _swapOnCurveCompound, _swapOnCurveUsdt, _swapOnCurveY, _swapOnCurveBinance, _swapOnCurveSynthetix, _swapOnUniswapCompound, _swapOnUniswapChai, _swapOnUniswapAave, _swapOnMooniswap, _swapOnUniswapV2, _swapOnUniswapV2ETH, _swapOnUniswapV2DAI, _swapOnUniswapV2USDC, _swapOnCurvePax, _swapOnCurveRenBtc, _swapOnCurveTBtc, _swapOnDforceSwap, _swapOnShell ]; require(distribution.length <= reserves.length, "OneSplit: Distribution array should not exceed reserves array size"); uint256 parts = 0; uint256 lastNonZeroIndex = 0; for (uint i = 0; i < distribution.length; i++) { if (distribution[i] > 0) { parts = parts.add(distribution[i]); lastNonZeroIndex = i; } } require(parts > 0, "OneSplit: distribution should contain non-zeros"); uint256 remainingAmount = amount; for (uint i = 0; i < distribution.length; i++) { if (distribution[i] == 0) { continue; } uint256 swapAmount = amount.mul(distribution[i]).div(parts); if (i == lastNonZeroIndex) { swapAmount = remainingAmount; } remainingAmount -= swapAmount; reserves[i](fromToken, toToken, swapAmount); } returnAmount = toToken.universalBalanceOf(address(this)); } // Swap helpers function _swapOnCurveCompound( IERC20 fromToken, IERC20 destToken, uint256 amount ) internal returns(uint256) { int128 i = (fromToken == dai ? 1 : 0) + (fromToken == usdc ? 2 : 0); int128 j = (destToken == dai ? 1 : 0) + (destToken == usdc ? 2 : 0); if (i == 0 || j == 0) { return 0; } _infiniteApproveIfNeeded(fromToken, address(curveCompound)); curveCompound.exchange_underlying(i - 1, j - 1, amount, 0); } function _swapOnCurveUsdt( IERC20 fromToken, IERC20 destToken, uint256 amount ) internal returns(uint256) { int128 i = (fromToken == dai ? 1 : 0) + (fromToken == usdc ? 2 : 0) + (fromToken == usdt ? 3 : 0); int128 j = (destToken == dai ? 1 : 0) + (destToken == usdc ? 2 : 0) + (destToken == usdt ? 3 : 0); if (i == 0 || j == 0) { return 0; } _infiniteApproveIfNeeded(fromToken, address(curveUsdt)); curveUsdt.exchange_underlying(i - 1, j - 1, amount, 0); } function _swapOnCurveY( IERC20 fromToken, IERC20 destToken, uint256 amount ) internal returns(uint256) { int128 i = (fromToken == dai ? 1 : 0) + (fromToken == usdc ? 2 : 0) + (fromToken == usdt ? 3 : 0) + (fromToken == tusd ? 4 : 0); int128 j = (destToken == dai ? 1 : 0) + (destToken == usdc ? 2 : 0) + (destToken == usdt ? 3 : 0) + (destToken == tusd ? 4 : 0); if (i == 0 || j == 0) { return 0; } _infiniteApproveIfNeeded(fromToken, address(curveY)); curveY.exchange_underlying(i - 1, j - 1, amount, 0); } function _swapOnCurveBinance( IERC20 fromToken, IERC20 destToken, uint256 amount ) internal returns(uint256) { int128 i = (fromToken == dai ? 1 : 0) + (fromToken == usdc ? 2 : 0) + (fromToken == usdt ? 3 : 0) + (fromToken == busd ? 4 : 0); int128 j = (destToken == dai ? 1 : 0) + (destToken == usdc ? 2 : 0) + (destToken == usdt ? 3 : 0) + (destToken == busd ? 4 : 0); if (i == 0 || j == 0) { return 0; } _infiniteApproveIfNeeded(fromToken, address(curveBinance)); curveBinance.exchange_underlying(i - 1, j - 1, amount, 0); } function _swapOnCurveSynthetix( IERC20 fromToken, IERC20 destToken, uint256 amount ) internal returns(uint256) { int128 i = (fromToken == dai ? 1 : 0) + (fromToken == usdc ? 2 : 0) + (fromToken == usdt ? 3 : 0) + (fromToken == susd ? 4 : 0); int128 j = (destToken == dai ? 1 : 0) + (destToken == usdc ? 2 : 0) + (destToken == usdt ? 3 : 0) + (destToken == susd ? 4 : 0); if (i == 0 || j == 0) { return 0; } _infiniteApproveIfNeeded(fromToken, address(curveSynthetix)); curveSynthetix.exchange_underlying(i - 1, j - 1, amount, 0); } function _swapOnCurvePax( IERC20 fromToken, IERC20 destToken, uint256 amount ) internal returns(uint256) { int128 i = (fromToken == dai ? 1 : 0) + (fromToken == usdc ? 2 : 0) + (fromToken == usdt ? 3 : 0) + (fromToken == pax ? 4 : 0); int128 j = (destToken == dai ? 1 : 0) + (destToken == usdc ? 2 : 0) + (destToken == usdt ? 3 : 0) + (destToken == pax ? 4 : 0); if (i == 0 || j == 0) { return 0; } _infiniteApproveIfNeeded(fromToken, address(curvePax)); curvePax.exchange_underlying(i - 1, j - 1, amount, 0); } function _swapOnShell( IERC20 fromToken, IERC20 toToken, uint256 amount ) internal returns (uint256) { _infiniteApproveIfNeeded(fromToken, address(shell)); return shell.swapByOrigin( address(fromToken), address(toToken), amount, 0, now + 50 ); } function _swapOnCurveRenBtc( IERC20 fromToken, IERC20 destToken, uint256 amount ) internal returns(uint256) { int128 i = (fromToken == renbtc ? 1 : 0) + (fromToken == wbtc ? 2 : 0); int128 j = (destToken == renbtc ? 1 : 0) + (destToken == wbtc ? 2 : 0); if (i == 0 || j == 0) { return 0; } _infiniteApproveIfNeeded(fromToken, address(curveRenBtc)); curveRenBtc.exchange(i - 1, j - 1, amount, 0); } function _swapOnCurveTBtc( IERC20 fromToken, IERC20 destToken, uint256 amount ) internal returns(uint256) { int128 i = (fromToken == tbtc ? 1 : 0) + (fromToken == wbtc ? 2 : 0) + (fromToken == hbtc ? 3 : 0); int128 j = (destToken == tbtc ? 1 : 0) + (destToken == wbtc ? 2 : 0) + (destToken == hbtc ? 3 : 0); if (i == 0 || j == 0) { return 0; } _infiniteApproveIfNeeded(fromToken, address(curveTBtc)); curveTBtc.exchange(i - 1, j - 1, amount, 0); } function _swapOnDforceSwap( IERC20 fromToken, IERC20 destToken, uint256 amount ) internal returns(uint256) { _infiniteApproveIfNeeded(fromToken, address(dforceSwap)); dforceSwap.swap(fromToken, destToken, amount); } function _swapOnUniswap( IERC20 fromToken, IERC20 toToken, uint256 amount ) internal returns(uint256) { uint256 returnAmount = amount; if (!fromToken.isETH()) { IUniswapExchange fromExchange = uniswapFactory.getExchange(fromToken); if (fromExchange != IUniswapExchange(0)) { _infiniteApproveIfNeeded(fromToken, address(fromExchange)); returnAmount = fromExchange.tokenToEthSwapInput(returnAmount, 1, now); } } if (!toToken.isETH()) { IUniswapExchange toExchange = uniswapFactory.getExchange(toToken); if (toExchange != IUniswapExchange(0)) { returnAmount = toExchange.ethToTokenSwapInput.value(returnAmount)(1, now); } } return returnAmount; } function _swapOnUniswapCompound( IERC20 fromToken, IERC20 toToken, uint256 amount ) internal returns(uint256) { if (!fromToken.isETH()) { ICompoundToken fromCompound = _getCompoundToken(fromToken); _infiniteApproveIfNeeded(fromToken, address(fromCompound)); fromCompound.mint(amount); return _swapOnUniswap(IERC20(fromCompound), toToken, IERC20(fromCompound).universalBalanceOf(address(this))); } if (!toToken.isETH()) { ICompoundToken toCompound = _getCompoundToken(toToken); uint256 compoundAmount = _swapOnUniswap(fromToken, IERC20(toCompound), amount); toCompound.redeem(compoundAmount); return toToken.universalBalanceOf(address(this)); } return 0; } function _swapOnUniswapChai( IERC20 fromToken, IERC20 toToken, uint256 amount ) internal returns(uint256) { if (fromToken == dai) { _infiniteApproveIfNeeded(fromToken, address(chai)); chai.join(address(this), amount); return _swapOnUniswap(IERC20(chai), toToken, IERC20(chai).universalBalanceOf(address(this))); } if (toToken == dai) { uint256 chaiAmount = _swapOnUniswap(fromToken, IERC20(chai), amount); chai.exit(address(this), chaiAmount); return toToken.universalBalanceOf(address(this)); } return 0; } function _swapOnUniswapAave( IERC20 fromToken, IERC20 toToken, uint256 amount ) internal returns(uint256) { if (!fromToken.isETH()) { IAaveToken fromAave = _getAaveToken(fromToken); _infiniteApproveIfNeeded(fromToken, aave.core()); aave.deposit(fromToken, amount, 1101); return _swapOnUniswap(IERC20(fromAave), toToken, IERC20(fromAave).universalBalanceOf(address(this))); } if (!toToken.isETH()) { IAaveToken toAave = _getAaveToken(toToken); uint256 aaveAmount = _swapOnUniswap(fromToken, IERC20(toAave), amount); toAave.redeem(aaveAmount); return aaveAmount; } return 0; } function _swapOnMooniswap( IERC20 fromToken, IERC20 toToken, uint256 amount ) internal returns(uint256) { IMooniswap mooniswap = mooniswapRegistry.target(); _infiniteApproveIfNeeded(fromToken, address(mooniswap)); return mooniswap.swap.value(fromToken.isETH() ? amount : 0)( fromToken, toToken, amount, 0 ); } function _swapOnKyber( IERC20 fromToken, IERC20 toToken, uint256 amount ) internal returns(uint256) { _infiniteApproveIfNeeded(fromToken, address(kyberNetworkProxy)); return kyberNetworkProxy.tradeWithHint.value(fromToken.isETH() ? amount : 0)( fromToken.isETH() ? ETH_ADDRESS : fromToken, amount, toToken.isETH() ? ETH_ADDRESS : toToken, address(this), 1 << 255, 0, 0x4D37f28D2db99e8d35A6C725a5f1749A085850a3, "" ); } function _swapOnBancor( IERC20 fromToken, IERC20 toToken, uint256 amount ) internal returns(uint256) { if (fromToken.isETH()) { bancorEtherToken.deposit.value(amount)(); } IBancorNetwork bancorNetwork = IBancorNetwork(bancorContractRegistry.addressOf("BancorNetwork")); address[] memory path = _buildBancorPath(fromToken, toToken); _infiniteApproveIfNeeded(fromToken.isETH() ? bancorEtherToken : fromToken, address(bancorNetwork)); uint256 returnAmount = bancorNetwork.claimAndConvert(path, amount, 1); if (toToken.isETH()) { bancorEtherToken.withdraw(bancorEtherToken.balanceOf(address(this))); } return returnAmount; } function _swapOnOasis( IERC20 fromToken, IERC20 toToken, uint256 amount ) internal returns(uint256) { if (fromToken.isETH()) { weth.deposit.value(amount)(); } _infiniteApproveIfNeeded(fromToken.isETH() ? weth : fromToken, address(oasisExchange)); uint256 returnAmount = oasisExchange.sellAllAmount( fromToken.isETH() ? weth : fromToken, amount, toToken.isETH() ? weth : toToken, 1 ); if (toToken.isETH()) { weth.withdraw(weth.balanceOf(address(this))); } return returnAmount; } function _swapOnUniswapV2Internal( IERC20 fromToken, IERC20 toToken, uint256 amount ) internal returns(uint256 returnAmount) { if (fromToken.isETH()) { weth.deposit.value(amount)(); } IERC20 fromTokenReal = fromToken.isETH() ? weth : fromToken; IERC20 toTokenReal = toToken.isETH() ? weth : toToken; IUniswapV2Exchange exchange = uniswapV2.getPair(fromTokenReal, toTokenReal); returnAmount = exchange.getReturn(fromTokenReal, toTokenReal, amount); fromTokenReal.universalTransfer(address(exchange), amount); if (uint256(address(fromTokenReal)) < uint256(address(toTokenReal))) { exchange.swap(0, returnAmount, address(this), ""); } else { exchange.swap(returnAmount, 0, address(this), ""); } if (toToken.isETH()) { weth.withdraw(weth.balanceOf(address(this))); } } function _swapOnUniswapV2OverMid( IERC20 fromToken, IERC20 midToken, IERC20 toToken, uint256 amount ) internal returns(uint256) { return _swapOnUniswapV2Internal( midToken, toToken, _swapOnUniswapV2Internal( fromToken, midToken, amount ) ); } function _swapOnUniswapV2( IERC20 fromToken, IERC20 toToken, uint256 amount ) internal returns(uint256) { return _swapOnUniswapV2Internal( fromToken, toToken, amount ); } function _swapOnUniswapV2ETH( IERC20 fromToken, IERC20 toToken, uint256 amount ) internal returns(uint256) { return _swapOnUniswapV2OverMid( fromToken, weth, toToken, amount ); } function _swapOnUniswapV2DAI( IERC20 fromToken, IERC20 toToken, uint256 amount ) internal returns(uint256) { return _swapOnUniswapV2OverMid( fromToken, dai, toToken, amount ); } function _swapOnUniswapV2USDC( IERC20 fromToken, IERC20 toToken, uint256 amount ) internal returns(uint256) { return _swapOnUniswapV2OverMid( fromToken, usdc, toToken, amount ); } }
IBancorNetworkPathFinder constant public bancorNetworkPathFinder = IBancorNetworkPathFinder(0x6F0cD8C4f6F06eAB664C7E3031909452b4B72861);
contract OneSplitRoot { using SafeMath for uint256; using DisableFlags for uint256; using UniversalERC20 for IERC20; using UniversalERC20 for IWETH; using UniversalERC20 for IBancorEtherToken; using UniswapV2ExchangeLib for IUniswapV2Exchange; using ChaiHelper for IChai; uint256 constant public DEXES_COUNT = 22; IERC20 constant public ETH_ADDRESS = IERC20(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE); IERC20 constant public dai = IERC20(0x6B175474E89094C44Da98b954EedeAC495271d0F); IERC20 constant public bnt = IERC20(0x1F573D6Fb3F13d689FF844B4cE37794d79a7FF1C); IERC20 constant public usdc = IERC20(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48); IERC20 constant public usdt = IERC20(0xdAC17F958D2ee523a2206206994597C13D831ec7); IERC20 constant public tusd = IERC20(0x0000000000085d4780B73119b644AE5ecd22b376); IERC20 constant public busd = IERC20(0x4Fabb145d64652a948d72533023f6E7A623C7C53); IERC20 constant public susd = IERC20(0x57Ab1ec28D129707052df4dF418D58a2D46d5f51); IERC20 constant public pax = IERC20(0x8E870D67F660D95d5be530380D0eC0bd388289E1); IWETH constant public weth = IWETH(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); IBancorEtherToken constant public bancorEtherToken = IBancorEtherToken(0xc0829421C1d260BD3cB3E0F06cfE2D52db2cE315); IChai constant public chai = IChai(0x06AF07097C9Eeb7fD685c692751D5C66dB49c215); IERC20 constant public renbtc = IERC20(0xEB4C2781e4ebA804CE9a9803C67d0893436bB27D); IERC20 constant public wbtc = IERC20(0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599); IERC20 constant public tbtc = IERC20(0x1bBE271d15Bb64dF0bc6CD28Df9Ff322F2eBD847); IERC20 constant public hbtc = IERC20(0x0316EB71485b0Ab14103307bf65a021042c6d380); IKyberNetworkProxy constant public kyberNetworkProxy = IKyberNetworkProxy(0x818E6FECD516Ecc3849DAf6845e3EC868087B755); IUniswapFactory constant public uniswapFactory = IUniswapFactory(0xc0a47dFe034B400B47bDaD5FecDa2621de6c4d95); IBancorContractRegistry constant public bancorContractRegistry = IBancorContractRegistry(0x52Ae12ABe5D8BD778BD5397F99cA900624CfADD4); IBancorConverterRegistry constant public bancorConverterRegistry = IBancorConverterRegistry(0xf6E2D7F616B67E46D708e4410746E9AAb3a4C518); IOasisExchange constant public oasisExchange = IOasisExchange(0x794e6e91555438aFc3ccF1c5076A74F42133d08D); ICurve constant public curveCompound = ICurve(0xA2B47E3D5c44877cca798226B7B8118F9BFb7A56); ICurve constant public curveUsdt = ICurve(0x52EA46506B9CC5Ef470C5bf89f17Dc28bB35D85C); ICurve constant public curveY = ICurve(0x45F783CCE6B7FF23B2ab2D70e416cdb7D6055f51); ICurve constant public curveBinance = ICurve(0x79a8C46DeA5aDa233ABaFFD40F3A0A2B1e5A4F27); ICurve constant public curveSynthetix = ICurve(0xA5407eAE9Ba41422680e2e00537571bcC53efBfD); ICurve constant public curvePax = ICurve(0x06364f10B501e868329afBc005b3492902d6C763); ICurve constant public curveRenBtc = ICurve(0x93054188d876f558f4a66B2EF1d97d16eDf0895B); ICurve constant public curveTBtc = ICurve(0x9726e9314eF1b96E45f40056bEd61A088897313E); IShell constant public shell = IShell(0xA8253a440Be331dC4a7395B73948cCa6F19Dc97D); IAaveLendingPool constant public aave = IAaveLendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); ICompound constant public compound = ICompound(0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B); ICompoundEther constant public cETH = ICompoundEther(0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5); IMooniswapRegistry constant public mooniswapRegistry = IMooniswapRegistry(0x7079E8517594e5b21d2B9a0D17cb33F5FE2bca70); IUniswapV2Factory constant public uniswapV2 = IUniswapV2Factory(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f); IDForceSwap constant public dforceSwap = IDForceSwap(0x03eF3f37856bD08eb47E2dE7ABc4Ddd2c19B60F2); function _buildBancorPath( IERC20 fromToken, IERC20 toToken ) internal view returns(address[] memory path) { if (fromToken == toToken) { return new address[](0); } if (fromToken.isETH()) { fromToken = bancorEtherToken; } if (toToken.isETH()) { toToken = bancorEtherToken; } if (fromToken == bnt || toToken == bnt) { path = new address[](3); path = new address[](5); } address fromConverter; address toConverter; if (fromToken != bnt) { (bool success, bytes memory data) = address(bancorConverterRegistry).staticcall.gas(10000)(abi.encodeWithSelector( bancorConverterRegistry.getConvertibleTokenSmartToken.selector, fromToken.isETH() ? bnt : fromToken, 0 )); if (!success) { return new address[](0); } fromConverter = abi.decode(data, (address)); if (fromConverter == address(0)) { return new address[](0); } } if (toToken != bnt) { (bool success, bytes memory data) = address(bancorConverterRegistry).staticcall.gas(10000)(abi.encodeWithSelector( bancorConverterRegistry.getConvertibleTokenSmartToken.selector, toToken.isETH() ? bnt : toToken, 0 )); if (!success) { return new address[](0); } toConverter = abi.decode(data, (address)); if (toConverter == address(0)) { return new address[](0); } } if (toToken == bnt) { path[0] = address(fromToken); path[1] = fromConverter; path[2] = address(bnt); return path; } if (fromToken == bnt) { path[0] = address(bnt); path[1] = toConverter; path[2] = address(toToken); return path; } path[0] = address(fromToken); path[1] = fromConverter; path[2] = address(bnt); path[3] = toConverter; path[4] = address(toToken); return path; } ) internal view returns(address[] memory path) { if (fromToken == toToken) { return new address[](0); } if (fromToken.isETH()) { fromToken = bancorEtherToken; } if (toToken.isETH()) { toToken = bancorEtherToken; } if (fromToken == bnt || toToken == bnt) { path = new address[](3); path = new address[](5); } address fromConverter; address toConverter; if (fromToken != bnt) { (bool success, bytes memory data) = address(bancorConverterRegistry).staticcall.gas(10000)(abi.encodeWithSelector( bancorConverterRegistry.getConvertibleTokenSmartToken.selector, fromToken.isETH() ? bnt : fromToken, 0 )); if (!success) { return new address[](0); } fromConverter = abi.decode(data, (address)); if (fromConverter == address(0)) { return new address[](0); } } if (toToken != bnt) { (bool success, bytes memory data) = address(bancorConverterRegistry).staticcall.gas(10000)(abi.encodeWithSelector( bancorConverterRegistry.getConvertibleTokenSmartToken.selector, toToken.isETH() ? bnt : toToken, 0 )); if (!success) { return new address[](0); } toConverter = abi.decode(data, (address)); if (toConverter == address(0)) { return new address[](0); } } if (toToken == bnt) { path[0] = address(fromToken); path[1] = fromConverter; path[2] = address(bnt); return path; } if (fromToken == bnt) { path[0] = address(bnt); path[1] = toConverter; path[2] = address(toToken); return path; } path[0] = address(fromToken); path[1] = fromConverter; path[2] = address(bnt); path[3] = toConverter; path[4] = address(toToken); return path; } ) internal view returns(address[] memory path) { if (fromToken == toToken) { return new address[](0); } if (fromToken.isETH()) { fromToken = bancorEtherToken; } if (toToken.isETH()) { toToken = bancorEtherToken; } if (fromToken == bnt || toToken == bnt) { path = new address[](3); path = new address[](5); } address fromConverter; address toConverter; if (fromToken != bnt) { (bool success, bytes memory data) = address(bancorConverterRegistry).staticcall.gas(10000)(abi.encodeWithSelector( bancorConverterRegistry.getConvertibleTokenSmartToken.selector, fromToken.isETH() ? bnt : fromToken, 0 )); if (!success) { return new address[](0); } fromConverter = abi.decode(data, (address)); if (fromConverter == address(0)) { return new address[](0); } } if (toToken != bnt) { (bool success, bytes memory data) = address(bancorConverterRegistry).staticcall.gas(10000)(abi.encodeWithSelector( bancorConverterRegistry.getConvertibleTokenSmartToken.selector, toToken.isETH() ? bnt : toToken, 0 )); if (!success) { return new address[](0); } toConverter = abi.decode(data, (address)); if (toConverter == address(0)) { return new address[](0); } } if (toToken == bnt) { path[0] = address(fromToken); path[1] = fromConverter; path[2] = address(bnt); return path; } if (fromToken == bnt) { path[0] = address(bnt); path[1] = toConverter; path[2] = address(toToken); return path; } path[0] = address(fromToken); path[1] = fromConverter; path[2] = address(bnt); path[3] = toConverter; path[4] = address(toToken); return path; } ) internal view returns(address[] memory path) { if (fromToken == toToken) { return new address[](0); } if (fromToken.isETH()) { fromToken = bancorEtherToken; } if (toToken.isETH()) { toToken = bancorEtherToken; } if (fromToken == bnt || toToken == bnt) { path = new address[](3); path = new address[](5); } address fromConverter; address toConverter; if (fromToken != bnt) { (bool success, bytes memory data) = address(bancorConverterRegistry).staticcall.gas(10000)(abi.encodeWithSelector( bancorConverterRegistry.getConvertibleTokenSmartToken.selector, fromToken.isETH() ? bnt : fromToken, 0 )); if (!success) { return new address[](0); } fromConverter = abi.decode(data, (address)); if (fromConverter == address(0)) { return new address[](0); } } if (toToken != bnt) { (bool success, bytes memory data) = address(bancorConverterRegistry).staticcall.gas(10000)(abi.encodeWithSelector( bancorConverterRegistry.getConvertibleTokenSmartToken.selector, toToken.isETH() ? bnt : toToken, 0 )); if (!success) { return new address[](0); } toConverter = abi.decode(data, (address)); if (toConverter == address(0)) { return new address[](0); } } if (toToken == bnt) { path[0] = address(fromToken); path[1] = fromConverter; path[2] = address(bnt); return path; } if (fromToken == bnt) { path[0] = address(bnt); path[1] = toConverter; path[2] = address(toToken); return path; } path[0] = address(fromToken); path[1] = fromConverter; path[2] = address(bnt); path[3] = toConverter; path[4] = address(toToken); return path; } ) internal view returns(address[] memory path) { if (fromToken == toToken) { return new address[](0); } if (fromToken.isETH()) { fromToken = bancorEtherToken; } if (toToken.isETH()) { toToken = bancorEtherToken; } if (fromToken == bnt || toToken == bnt) { path = new address[](3); path = new address[](5); } address fromConverter; address toConverter; if (fromToken != bnt) { (bool success, bytes memory data) = address(bancorConverterRegistry).staticcall.gas(10000)(abi.encodeWithSelector( bancorConverterRegistry.getConvertibleTokenSmartToken.selector, fromToken.isETH() ? bnt : fromToken, 0 )); if (!success) { return new address[](0); } fromConverter = abi.decode(data, (address)); if (fromConverter == address(0)) { return new address[](0); } } if (toToken != bnt) { (bool success, bytes memory data) = address(bancorConverterRegistry).staticcall.gas(10000)(abi.encodeWithSelector( bancorConverterRegistry.getConvertibleTokenSmartToken.selector, toToken.isETH() ? bnt : toToken, 0 )); if (!success) { return new address[](0); } toConverter = abi.decode(data, (address)); if (toConverter == address(0)) { return new address[](0); } } if (toToken == bnt) { path[0] = address(fromToken); path[1] = fromConverter; path[2] = address(bnt); return path; } if (fromToken == bnt) { path[0] = address(bnt); path[1] = toConverter; path[2] = address(toToken); return path; } path[0] = address(fromToken); path[1] = fromConverter; path[2] = address(bnt); path[3] = toConverter; path[4] = address(toToken); return path; } } else { ) internal view returns(address[] memory path) { if (fromToken == toToken) { return new address[](0); } if (fromToken.isETH()) { fromToken = bancorEtherToken; } if (toToken.isETH()) { toToken = bancorEtherToken; } if (fromToken == bnt || toToken == bnt) { path = new address[](3); path = new address[](5); } address fromConverter; address toConverter; if (fromToken != bnt) { (bool success, bytes memory data) = address(bancorConverterRegistry).staticcall.gas(10000)(abi.encodeWithSelector( bancorConverterRegistry.getConvertibleTokenSmartToken.selector, fromToken.isETH() ? bnt : fromToken, 0 )); if (!success) { return new address[](0); } fromConverter = abi.decode(data, (address)); if (fromConverter == address(0)) { return new address[](0); } } if (toToken != bnt) { (bool success, bytes memory data) = address(bancorConverterRegistry).staticcall.gas(10000)(abi.encodeWithSelector( bancorConverterRegistry.getConvertibleTokenSmartToken.selector, toToken.isETH() ? bnt : toToken, 0 )); if (!success) { return new address[](0); } toConverter = abi.decode(data, (address)); if (toConverter == address(0)) { return new address[](0); } } if (toToken == bnt) { path[0] = address(fromToken); path[1] = fromConverter; path[2] = address(bnt); return path; } if (fromToken == bnt) { path[0] = address(bnt); path[1] = toConverter; path[2] = address(toToken); return path; } path[0] = address(fromToken); path[1] = fromConverter; path[2] = address(bnt); path[3] = toConverter; path[4] = address(toToken); return path; } ) internal view returns(address[] memory path) { if (fromToken == toToken) { return new address[](0); } if (fromToken.isETH()) { fromToken = bancorEtherToken; } if (toToken.isETH()) { toToken = bancorEtherToken; } if (fromToken == bnt || toToken == bnt) { path = new address[](3); path = new address[](5); } address fromConverter; address toConverter; if (fromToken != bnt) { (bool success, bytes memory data) = address(bancorConverterRegistry).staticcall.gas(10000)(abi.encodeWithSelector( bancorConverterRegistry.getConvertibleTokenSmartToken.selector, fromToken.isETH() ? bnt : fromToken, 0 )); if (!success) { return new address[](0); } fromConverter = abi.decode(data, (address)); if (fromConverter == address(0)) { return new address[](0); } } if (toToken != bnt) { (bool success, bytes memory data) = address(bancorConverterRegistry).staticcall.gas(10000)(abi.encodeWithSelector( bancorConverterRegistry.getConvertibleTokenSmartToken.selector, toToken.isETH() ? bnt : toToken, 0 )); if (!success) { return new address[](0); } toConverter = abi.decode(data, (address)); if (toConverter == address(0)) { return new address[](0); } } if (toToken == bnt) { path[0] = address(fromToken); path[1] = fromConverter; path[2] = address(bnt); return path; } if (fromToken == bnt) { path[0] = address(bnt); path[1] = toConverter; path[2] = address(toToken); return path; } path[0] = address(fromToken); path[1] = fromConverter; path[2] = address(bnt); path[3] = toConverter; path[4] = address(toToken); return path; } ) internal view returns(address[] memory path) { if (fromToken == toToken) { return new address[](0); } if (fromToken.isETH()) { fromToken = bancorEtherToken; } if (toToken.isETH()) { toToken = bancorEtherToken; } if (fromToken == bnt || toToken == bnt) { path = new address[](3); path = new address[](5); } address fromConverter; address toConverter; if (fromToken != bnt) { (bool success, bytes memory data) = address(bancorConverterRegistry).staticcall.gas(10000)(abi.encodeWithSelector( bancorConverterRegistry.getConvertibleTokenSmartToken.selector, fromToken.isETH() ? bnt : fromToken, 0 )); if (!success) { return new address[](0); } fromConverter = abi.decode(data, (address)); if (fromConverter == address(0)) { return new address[](0); } } if (toToken != bnt) { (bool success, bytes memory data) = address(bancorConverterRegistry).staticcall.gas(10000)(abi.encodeWithSelector( bancorConverterRegistry.getConvertibleTokenSmartToken.selector, toToken.isETH() ? bnt : toToken, 0 )); if (!success) { return new address[](0); } toConverter = abi.decode(data, (address)); if (toConverter == address(0)) { return new address[](0); } } if (toToken == bnt) { path[0] = address(fromToken); path[1] = fromConverter; path[2] = address(bnt); return path; } if (fromToken == bnt) { path[0] = address(bnt); path[1] = toConverter; path[2] = address(toToken); return path; } path[0] = address(fromToken); path[1] = fromConverter; path[2] = address(bnt); path[3] = toConverter; path[4] = address(toToken); return path; } ) internal view returns(address[] memory path) { if (fromToken == toToken) { return new address[](0); } if (fromToken.isETH()) { fromToken = bancorEtherToken; } if (toToken.isETH()) { toToken = bancorEtherToken; } if (fromToken == bnt || toToken == bnt) { path = new address[](3); path = new address[](5); } address fromConverter; address toConverter; if (fromToken != bnt) { (bool success, bytes memory data) = address(bancorConverterRegistry).staticcall.gas(10000)(abi.encodeWithSelector( bancorConverterRegistry.getConvertibleTokenSmartToken.selector, fromToken.isETH() ? bnt : fromToken, 0 )); if (!success) { return new address[](0); } fromConverter = abi.decode(data, (address)); if (fromConverter == address(0)) { return new address[](0); } } if (toToken != bnt) { (bool success, bytes memory data) = address(bancorConverterRegistry).staticcall.gas(10000)(abi.encodeWithSelector( bancorConverterRegistry.getConvertibleTokenSmartToken.selector, toToken.isETH() ? bnt : toToken, 0 )); if (!success) { return new address[](0); } toConverter = abi.decode(data, (address)); if (toConverter == address(0)) { return new address[](0); } } if (toToken == bnt) { path[0] = address(fromToken); path[1] = fromConverter; path[2] = address(bnt); return path; } if (fromToken == bnt) { path[0] = address(bnt); path[1] = toConverter; path[2] = address(toToken); return path; } path[0] = address(fromToken); path[1] = fromConverter; path[2] = address(bnt); path[3] = toConverter; path[4] = address(toToken); return path; } ) internal view returns(address[] memory path) { if (fromToken == toToken) { return new address[](0); } if (fromToken.isETH()) { fromToken = bancorEtherToken; } if (toToken.isETH()) { toToken = bancorEtherToken; } if (fromToken == bnt || toToken == bnt) { path = new address[](3); path = new address[](5); } address fromConverter; address toConverter; if (fromToken != bnt) { (bool success, bytes memory data) = address(bancorConverterRegistry).staticcall.gas(10000)(abi.encodeWithSelector( bancorConverterRegistry.getConvertibleTokenSmartToken.selector, fromToken.isETH() ? bnt : fromToken, 0 )); if (!success) { return new address[](0); } fromConverter = abi.decode(data, (address)); if (fromConverter == address(0)) { return new address[](0); } } if (toToken != bnt) { (bool success, bytes memory data) = address(bancorConverterRegistry).staticcall.gas(10000)(abi.encodeWithSelector( bancorConverterRegistry.getConvertibleTokenSmartToken.selector, toToken.isETH() ? bnt : toToken, 0 )); if (!success) { return new address[](0); } toConverter = abi.decode(data, (address)); if (toConverter == address(0)) { return new address[](0); } } if (toToken == bnt) { path[0] = address(fromToken); path[1] = fromConverter; path[2] = address(bnt); return path; } if (fromToken == bnt) { path[0] = address(bnt); path[1] = toConverter; path[2] = address(toToken); return path; } path[0] = address(fromToken); path[1] = fromConverter; path[2] = address(bnt); path[3] = toConverter; path[4] = address(toToken); return path; } ) internal view returns(address[] memory path) { if (fromToken == toToken) { return new address[](0); } if (fromToken.isETH()) { fromToken = bancorEtherToken; } if (toToken.isETH()) { toToken = bancorEtherToken; } if (fromToken == bnt || toToken == bnt) { path = new address[](3); path = new address[](5); } address fromConverter; address toConverter; if (fromToken != bnt) { (bool success, bytes memory data) = address(bancorConverterRegistry).staticcall.gas(10000)(abi.encodeWithSelector( bancorConverterRegistry.getConvertibleTokenSmartToken.selector, fromToken.isETH() ? bnt : fromToken, 0 )); if (!success) { return new address[](0); } fromConverter = abi.decode(data, (address)); if (fromConverter == address(0)) { return new address[](0); } } if (toToken != bnt) { (bool success, bytes memory data) = address(bancorConverterRegistry).staticcall.gas(10000)(abi.encodeWithSelector( bancorConverterRegistry.getConvertibleTokenSmartToken.selector, toToken.isETH() ? bnt : toToken, 0 )); if (!success) { return new address[](0); } toConverter = abi.decode(data, (address)); if (toConverter == address(0)) { return new address[](0); } } if (toToken == bnt) { path[0] = address(fromToken); path[1] = fromConverter; path[2] = address(bnt); return path; } if (fromToken == bnt) { path[0] = address(bnt); path[1] = toConverter; path[2] = address(toToken); return path; } path[0] = address(fromToken); path[1] = fromConverter; path[2] = address(bnt); path[3] = toConverter; path[4] = address(toToken); return path; } ) internal view returns(address[] memory path) { if (fromToken == toToken) { return new address[](0); } if (fromToken.isETH()) { fromToken = bancorEtherToken; } if (toToken.isETH()) { toToken = bancorEtherToken; } if (fromToken == bnt || toToken == bnt) { path = new address[](3); path = new address[](5); } address fromConverter; address toConverter; if (fromToken != bnt) { (bool success, bytes memory data) = address(bancorConverterRegistry).staticcall.gas(10000)(abi.encodeWithSelector( bancorConverterRegistry.getConvertibleTokenSmartToken.selector, fromToken.isETH() ? bnt : fromToken, 0 )); if (!success) { return new address[](0); } fromConverter = abi.decode(data, (address)); if (fromConverter == address(0)) { return new address[](0); } } if (toToken != bnt) { (bool success, bytes memory data) = address(bancorConverterRegistry).staticcall.gas(10000)(abi.encodeWithSelector( bancorConverterRegistry.getConvertibleTokenSmartToken.selector, toToken.isETH() ? bnt : toToken, 0 )); if (!success) { return new address[](0); } toConverter = abi.decode(data, (address)); if (toConverter == address(0)) { return new address[](0); } } if (toToken == bnt) { path[0] = address(fromToken); path[1] = fromConverter; path[2] = address(bnt); return path; } if (fromToken == bnt) { path[0] = address(bnt); path[1] = toConverter; path[2] = address(toToken); return path; } path[0] = address(fromToken); path[1] = fromConverter; path[2] = address(bnt); path[3] = toConverter; path[4] = address(toToken); return path; } ) internal view returns(address[] memory path) { if (fromToken == toToken) { return new address[](0); } if (fromToken.isETH()) { fromToken = bancorEtherToken; } if (toToken.isETH()) { toToken = bancorEtherToken; } if (fromToken == bnt || toToken == bnt) { path = new address[](3); path = new address[](5); } address fromConverter; address toConverter; if (fromToken != bnt) { (bool success, bytes memory data) = address(bancorConverterRegistry).staticcall.gas(10000)(abi.encodeWithSelector( bancorConverterRegistry.getConvertibleTokenSmartToken.selector, fromToken.isETH() ? bnt : fromToken, 0 )); if (!success) { return new address[](0); } fromConverter = abi.decode(data, (address)); if (fromConverter == address(0)) { return new address[](0); } } if (toToken != bnt) { (bool success, bytes memory data) = address(bancorConverterRegistry).staticcall.gas(10000)(abi.encodeWithSelector( bancorConverterRegistry.getConvertibleTokenSmartToken.selector, toToken.isETH() ? bnt : toToken, 0 )); if (!success) { return new address[](0); } toConverter = abi.decode(data, (address)); if (toConverter == address(0)) { return new address[](0); } } if (toToken == bnt) { path[0] = address(fromToken); path[1] = fromConverter; path[2] = address(bnt); return path; } if (fromToken == bnt) { path[0] = address(bnt); path[1] = toConverter; path[2] = address(toToken); return path; } path[0] = address(fromToken); path[1] = fromConverter; path[2] = address(bnt); path[3] = toConverter; path[4] = address(toToken); return path; } function _getCompoundToken(IERC20 token) internal pure returns(ICompoundToken) { return ICompoundToken(0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5); } return ICompoundToken(0x5d3a536E4D6DbD6114cc1Ead35777bAB948E3643); }
5,499,029
[ 1, 13450, 304, 3850, 3906, 743, 8441, 5381, 1071, 25732, 3850, 3906, 743, 8441, 273, 23450, 304, 3850, 3906, 743, 8441, 12, 20, 92, 26, 42, 20, 71, 40, 28, 39, 24, 74, 26, 42, 7677, 73, 2090, 26, 1105, 39, 27, 41, 23, 4630, 3657, 5908, 7950, 22, 70, 24, 38, 9060, 5292, 21, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 6942, 5521, 2375, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 565, 1450, 10639, 5094, 364, 2254, 5034, 31, 203, 203, 565, 1450, 27705, 654, 39, 3462, 364, 467, 654, 39, 3462, 31, 203, 565, 1450, 27705, 654, 39, 3462, 364, 467, 59, 1584, 44, 31, 203, 565, 1450, 27705, 654, 39, 3462, 364, 23450, 304, 3850, 41, 1136, 1345, 31, 203, 565, 1450, 1351, 291, 91, 438, 58, 22, 11688, 5664, 364, 467, 984, 291, 91, 438, 58, 22, 11688, 31, 203, 565, 1450, 1680, 10658, 2276, 364, 467, 782, 10658, 31, 203, 203, 565, 2254, 5034, 5381, 1071, 2030, 60, 3991, 67, 7240, 273, 11201, 31, 203, 565, 467, 654, 39, 3462, 5381, 1071, 512, 2455, 67, 15140, 273, 467, 654, 39, 3462, 12, 20, 17432, 1340, 1340, 41, 1340, 73, 41, 73, 41, 1340, 41, 73, 41, 73, 41, 1340, 9383, 41, 1340, 1340, 41, 1340, 1340, 1340, 73, 9383, 73, 41, 1769, 203, 203, 565, 467, 654, 39, 3462, 5381, 1071, 5248, 77, 273, 467, 654, 39, 3462, 12, 20, 92, 26, 38, 4033, 6564, 5608, 41, 6675, 5908, 24, 39, 6334, 40, 69, 10689, 70, 29, 6564, 41, 73, 323, 2226, 7616, 25, 5324, 21, 72, 20, 42, 1769, 203, 565, 467, 654, 39, 3462, 5381, 1071, 324, 496, 273, 467, 654, 39, 3462, 12, 20, 92, 21, 42, 25, 9036, 40, 26, 42, 70, 23, 42, 3437, 72, 26, 6675, 2246, 5193, 24, 38, 24, 71, 41, 23, 4700, 11290, 72, 7235, 69, 27, 2 ]
./partial_match/1/0x0e82FD54eD2221c1594Cb9Cc96862B587a206047/sources/b9a8sbduIANSJD.sol
* Constructor function Initializes contract with initial supply tokens to the creator of the contract/
) public { interface tokenRecipient/*SD9B8adnjkjenQDS98W9BNDUHWEND*/ { /*SD9B8adnjkjenQDS98W9BNDUHWEND*/function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) external; } uint256 public totalSupply; mapping (address => uint256) public balanceOf; event Transfer(address indexed from, address indexed to, uint256 value); event Burn(address indexed from, uint256 value); }
15,595,117
[ 1, 6293, 445, 10188, 3128, 6835, 598, 2172, 14467, 2430, 358, 326, 11784, 434, 326, 6835, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 262, 1071, 288, 203, 5831, 1147, 18241, 20308, 9903, 29, 38, 28, 361, 82, 26921, 78, 275, 53, 3948, 10689, 59, 29, 38, 2908, 57, 44, 59, 4415, 5549, 288, 1748, 9903, 29, 38, 28, 361, 82, 26921, 78, 275, 53, 3948, 10689, 59, 29, 38, 2908, 57, 44, 59, 4415, 5549, 915, 6798, 23461, 12, 2867, 389, 2080, 16, 2254, 5034, 389, 1132, 16, 1758, 389, 2316, 16, 1731, 389, 7763, 751, 13, 3903, 31, 289, 203, 565, 2254, 5034, 1071, 2078, 3088, 1283, 31, 203, 565, 2874, 261, 2867, 516, 2254, 5034, 13, 1071, 11013, 951, 31, 203, 565, 871, 12279, 12, 2867, 8808, 628, 16, 1758, 8808, 358, 16, 2254, 5034, 460, 1769, 203, 565, 871, 605, 321, 12, 2867, 8808, 628, 16, 2254, 5034, 460, 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 ]
pragma solidity ^0.5.0; pragma experimental ABIEncoderV2; // solium-disable-line no-experimental // ---------------------------------------------------------------------------- // Copyright (c) 2018,2019 OAX Foundation. // https://www.oax.org/ // See LICENSE file for license details. // ---------------------------------------------------------------------------- import "./openzeppelin/SafeMath.sol"; import "./openzeppelin/ECRecovery.sol"; import "./openzeppelin/IERC20.sol"; /** * @title Mediator */ contract Mediator { using SafeMath for uint256; // // Events // event TokenRegistered( address tokenAddress ); event DepositCompleted( uint256 round, address indexed tokenAddress, address indexed clientAddress, uint256 amount ); event WithdrawalInitiated( uint256 round, address indexed tokenAddress, address indexed clientAddress, uint256 amount ); event WithdrawalConfirmed( uint256 round, address indexed tokenAddress, address indexed clientAddress, uint256 amount ); event WithdrawalCancelled( uint256 round, address indexed tokenAddress, address indexed clientAddress, uint256 amount ); event CommitCompleted( uint256 round, address indexed tokenAddress ); event DisputeOpened( uint256 disputeId, uint256 round, address indexed clientAddress ); event DisputeClosed( uint256 disputeId, uint256 round, address indexed clientAddress ); event Halted( uint256 round, uint256 quarter ); // // Structures // struct RootInfo { bytes32 content; uint256 height; uint256 width; } struct Proof { uint256 clientOpeningBalance; address tokenAddress; address clientAddress; bytes32[] hashes; uint256[] sums; uint256 height; uint256 width; uint256 round; } struct Approval { uint256 approvalId; uint256 round; uint256 buyAmount; address buyAsset; uint256 sellAmount; address sellAsset; bool intent; // true: buy, false: sell address instanceId; } struct Fill { uint256 fillId; uint256 approvalId; uint256 round; uint256 buyAmount; address buyAsset; uint256 sellAmount; address sellAsset; address clientAddress; address instanceId; } struct WithdrawalRequest { uint256 amount; uint256 openingBalance; } struct Dispute { uint256 disputeId; uint256 quarter; uint256 round; uint256[] openingBalances; uint256 fillCount; bool open; } struct AuthorizationMessage { uint256 round; address clientAddress; bytes sig; } // // Fields - General // // Address of the operator. address public operatorAddress; // Number of blocks inside a round. uint256 public roundSize; // Number of blocks inside a quarter. uint256 public quarterSize; // Block number of when the mediator contract was initially deployed. uint256 public blockNumberAtCreation; // Map of round => tokenAddress => clientAddress => deposit amount. mapping(uint256 => mapping(address => mapping(address => uint256))) public clientDeposits; // Map of round => tokenAddress => deposit amount. mapping(uint256 => mapping(address => uint256)) public totalDeposits; // Map of round => tokenAddress => amount. mapping(uint256 => mapping(address => uint256)) public openingBalances; // Map of round => tokenAddress => total requested withdrawal amount. mapping(uint256 => mapping (address => uint256)) public totalRequestedWithdrawals; // Map of round => tokenAddress => clientAddress => requested withdrawal amount. mapping(uint256 => mapping(address => mapping (address => WithdrawalRequest))) public clientRequestedWithdrawals; // Map of tokenAddress => clientAddress => round when withdrawal request was initiated. mapping(address => mapping(address => uint256)) public activeWithdrawalRounds; // Keeps count of the number of fully committed rounds. A round is fully // committed if all assets in the round have been successfully committed. uint256 public committedRounds; // Map of round => total number of commits. mapping(uint256 => uint256) public commitCounters; // Map of round => tokenAddress => commit root. mapping(uint256 => mapping(address => bytes32)) public commits; // // Fields - Tokens // // Number of tokens that have been registered. uint256 public tokenCount; // Map of tokens that have been registered. mapping(address => bool) public registeredTokens; // Map of tokenAddress => arrayIndex for array computations. mapping(address => uint256) public registeredTokensIndex; // Map of arrayIndex => tokenAddress. mapping(uint256 => address) public registeredTokensAddresses; // // Fields - Disputes // // Whether the contract is in HALTED mode or not. bool public halted; // Round number when the Mediator entered HALTED mode. uint256 public haltedRound; // Quarter number when the Mediator entered HALTED mode. uint256 public haltedQuarter; // Total number of disputes ever opened. uint256 public totalDisputes; // Map of round => number of open disputes. mapping(uint256 => uint256) public openDisputeCounters; // Map of clientAddress => dispute info. mapping(address => Dispute) public disputes; // Map disputeId => fillId => fill, used for active disputes. mapping(uint256 => mapping(uint256 => Fill)) public disputeFills; // Map disputeId => approvalId => bool, used to check approvals for duplicates. mapping(uint256 => mapping(uint256 => bool)) public disputeApprovals; // Map of tokenAddress => clientAddress => whether funds have been recovered. mapping(address => mapping(address => bool)) public recovered; // // Modifiers // modifier onlyBy(address _account) { require(msg.sender == _account); _; } modifier notHalted() { updateHaltedState(); require(halted == false); _; } // // Constructor // /** * Constructor for the Mediator smart contract. * @param _roundSize Number of blocks corresponding to one round. * @param _operatorAddress Address of the operator. */ constructor( uint256 _roundSize, address _operatorAddress ) public { require(_roundSize > 0); require(_roundSize % 4 == 0); require(_operatorAddress != address(0)); roundSize = _roundSize; quarterSize = roundSize / 4; operatorAddress = _operatorAddress; blockNumberAtCreation = getCurrentBlockNumber(); halted = false; } // // Public Functions // /** * Direct deposit of ether is not supported. * In order to deposit it is required to invoke depositTokens. */ function() external payable { revert("Not supported"); } /** * Enables the operator to register a token. * @dev Make sure that the token has been properly audited and * can be trusted before adding it. * @param tokenAddress Address of the token to be registered. */ function registerToken(address tokenAddress) public notHalted() onlyBy(operatorAddress) returns (bool) { require(tokenAddress != address(0)); require(tokenAddress != address(this)); // It is only possible to register tokens during round 0, quarter 0 require(getCurrentRound() == 0 && getCurrentQuarter() == 0); if (registeredTokens[tokenAddress]) { return false; } registeredTokens[tokenAddress] = true; registeredTokensIndex[tokenAddress] = tokenCount; registeredTokensAddresses[tokenCount] = tokenAddress; tokenCount = tokenCount.add(1); emit TokenRegistered(tokenAddress); return true; } /** * Enables a client to deposit tokens. * @dev The token must have been registered and must have approval for * the specified amount before calling depositToken. * @param tokenAddress Address of the token. * @param amount Amount of tokens to deposit. */ function depositTokens(address tokenAddress, uint256 amount) public notHalted() returns (bool) { require(registeredTokens[tokenAddress]); require(amount > 0); address clientAddress = msg.sender; require(transferTokenFromClient(tokenAddress, clientAddress, amount)); uint256 currentRound = getCurrentRound(); clientDeposits[currentRound][tokenAddress][clientAddress] = clientDeposits[currentRound][tokenAddress][clientAddress].add(amount); totalDeposits[currentRound][tokenAddress] = totalDeposits[currentRound][tokenAddress].add(amount); emit DepositCompleted( currentRound, tokenAddress, clientAddress, amount ); return true; } /** * Enables a client to initiate a withdrawal request. * @param proof A balance proof for the current last committed round. * @param amount Amount the client wants to withdraw. */ function initiateWithdrawal( Proof memory proof, uint256 amount ) public notHalted() returns (bool) { require(amount > 0); // Make sure we are at round > 0 to initiate any withdrawal. uint256 currentRound = getCurrentRound(); require(currentRound > 0); // Client can only initiate withdrawal for themselves. address clientAddress = proof.clientAddress; require(clientAddress == msg.sender); // Checks that the proof is valid and that the client has funds. // This also checks that the token address in the proof is ok. require(isProofValid(proof, currentRound - 1)); address tokenAddress = proof.tokenAddress; require(activeWithdrawalRounds[tokenAddress][clientAddress] == 0); // Check that there is no existing pending withdrawal. require(amount <= proof.clientOpeningBalance); // Withdrawal amount needs to be <= that the current openingBalance. WithdrawalRequest storage requested = clientRequestedWithdrawals[currentRound][tokenAddress][clientAddress]; requested.amount = amount; requested.openingBalance = proof.clientOpeningBalance; totalRequestedWithdrawals[currentRound][tokenAddress] = totalRequestedWithdrawals[currentRound][tokenAddress].add(amount); activeWithdrawalRounds[tokenAddress][clientAddress] = currentRound; emit WithdrawalInitiated( currentRound, tokenAddress, clientAddress, amount ); return true; } /** * Enables a client to confirm a withdrawal after enough time has passed since * the withdrawal request. * @param tokenAddress Address of the token to be withdrawn. */ function confirmWithdrawal(address tokenAddress) public returns (bool) { // We need to check whether we are in HALTED mode or not. updateHaltedState(); address clientAddress = msg.sender; uint256 roundOfRequest = activeWithdrawalRounds[tokenAddress][clientAddress]; require(roundOfRequest > 0); uint256 currentRound = getCurrentRound(); uint256 currentQuarter = getCurrentQuarter(); uint256 lastConfirmedRoundForWithdrawals; if (currentQuarter == 0 || halted) { lastConfirmedRoundForWithdrawals = currentRound.sub(3); } else { lastConfirmedRoundForWithdrawals = currentRound.sub(2); } require(roundOfRequest <= lastConfirmedRoundForWithdrawals); // Too early to claim funds. activeWithdrawalRounds[tokenAddress][clientAddress] = 0; uint256 amount = clientRequestedWithdrawals[roundOfRequest][tokenAddress][clientAddress].amount; // Transfer the tokens back to the client. require(transferTokenToClient(tokenAddress, clientAddress, amount)); emit WithdrawalConfirmed( currentRound, tokenAddress, clientAddress, amount ); return true; } /** * Enables the operator to cancel a withdrawal. * @param approvals Approvals to sell asset by client. * @param sigs Signatures for the approvals. * @param tokenAddress Address of the token corresponding to the withdrawal. * @param clientAddress Address of the client who made the withdrawal request. */ function cancelWithdrawal( Approval[] memory approvals, bytes[] memory sigs, address tokenAddress, address clientAddress ) public onlyBy(operatorAddress) notHalted() returns (bool) { require(approvals.length == sigs.length); uint256 roundOfRequest = activeWithdrawalRounds[tokenAddress][clientAddress]; require(roundOfRequest > 0); uint256 currentRound = getCurrentRound(); require(canCancelWithdrawal(currentRound, roundOfRequest, tokenAddress)); WithdrawalRequest memory withdrawal = clientRequestedWithdrawals[roundOfRequest][tokenAddress][clientAddress]; if (approvals.length > 1) { for (uint256 i = 0; i < approvals.length - 1; i++) { require(approvals[i].approvalId < approvals[i + 1].approvalId); } } // Check that approvals are valid uint256 roundOfProof = roundOfRequest.sub(1); for (uint256 i = 0; i < approvals.length; i++) { // Check round require(approvals[i].round == roundOfProof || approvals[i].round == roundOfRequest); // Check single approval checkApprovalSig(approvals[i], sigs[i], clientAddress); } uint256 reserved = 0; for (uint256 i = 0; i < approvals.length; i++) { Approval memory approval = approvals[i]; if (approval.sellAsset == tokenAddress) { reserved = reserved.add(approval.sellAmount); } } uint256 requested = withdrawal.amount; uint256 available = withdrawal.openingBalance.sub(reserved); require(requested > available); // Not overwithdrawing so abort cancelWithdrawal. // Cancel the withdrawal clientRequestedWithdrawals[roundOfRequest][tokenAddress][clientAddress].amount = 0; totalRequestedWithdrawals[roundOfRequest][tokenAddress] = totalRequestedWithdrawals[roundOfRequest][tokenAddress].sub(requested); activeWithdrawalRounds[tokenAddress][clientAddress] = 0; emit WithdrawalCancelled( currentRound, tokenAddress, clientAddress, requested ); return true; } /** * Enables the operator to commit a new root for the current round. * @param rootInfo Contains the root content before padding along with the height and width of the tree. * @param tokenAddress Address of the token for this commit. */ function commit( RootInfo memory rootInfo, address tokenAddress ) public onlyBy(operatorAddress) notHalted() returns (bool) { uint256 currentRound = getCurrentRound(); require(currentRound > 0); // Committing a new root is not allowed at round 0. uint256 currentQuarter = getCurrentQuarter(); require(currentQuarter == 0); // Committing is only allowed during quarter 0. require(registeredTokens[tokenAddress]); // The token must be registered. require(commits[currentRound][tokenAddress] == ""); // Make sure nothing has been committed for this round. uint256 previousRound = currentRound.sub(1); uint256 previousOpeningBalance = openingBalances[previousRound][tokenAddress]; uint256 previousTotalDeposits = totalDeposits[previousRound][tokenAddress]; uint256 previousTotalWithdrawals = totalRequestedWithdrawals[previousRound][tokenAddress]; uint256 previousClosingBalance = previousOpeningBalance.add(previousTotalDeposits).sub(previousTotalWithdrawals); bytes32 rootBeforePadding = keccak256(abi.encodePacked(rootInfo.content, previousClosingBalance)); bytes32 root = keccak256(abi.encodePacked(rootBeforePadding, rootInfo.height, rootInfo.width)); openingBalances[currentRound][tokenAddress] = previousClosingBalance; commits[currentRound][tokenAddress] = root; commitCounters[currentRound] = commitCounters[currentRound].add(1); if (commitCounters[currentRound] == tokenCount) { // Operator has satisfied all commit requirements for this round. committedRounds = committedRounds.add(1); } emit CommitCompleted( currentRound, tokenAddress ); return true; } /** * Enables a client to open a dispute. * @param proofs Proofs for each asset. * @param fills Array of fills. * @param sigs Array containing the signatures of the fills. * @param authorizationMessage Signed message from the operator. */ function openDispute( Proof[] memory proofs, Fill[] memory fills, bytes[] memory sigs, AuthorizationMessage memory authorizationMessage ) public notHalted() returns (bool) { require(fills.length == sigs.length); address clientAddress = msg.sender; if (disputes[clientAddress].open) { return false; } uint256 currentRound = getCurrentRound(); uint256 currentQuarter = getCurrentQuarter(); require(currentRound > 0 /* The client must not be allowed to open a dispute during round 0 */); uint256[] memory openingBalancesClient = new uint256[](tokenCount); if (proofs.length > 0) { require(isProofArrayValid(proofs, clientAddress, currentRound - 1)); for (uint256 i = 0; i < proofs.length; i++) { openingBalancesClient[i] = proofs[i].clientOpeningBalance; } } else { require(verifyAuthorizationMessage(clientAddress, authorizationMessage)); } uint256 disputeId = totalDisputes.add(1); if (fills.length > 0) { for (uint256 i = 0; i < fills.length; i++) { require(fills[i].round == currentRound - 1); require(fills[i].clientAddress == clientAddress/*, "The fill must be assigned to the client."*/); checkFillSig(fills[i], sigs[i]); // Put the fill in storage as it will be needed by closeDispute. disputeFills[disputeId][fills[i].fillId] = fills[i]; } // Check if all fills are ordered and unique. for (uint256 i = 0; i < fills.length - 1; i++) { require(fills[i].fillId < fills[i + 1].fillId); } } disputes[clientAddress] = Dispute( disputeId, currentQuarter, currentRound, openingBalancesClient, fills.length, true ); totalDisputes = disputeId; openDisputeCounters[currentRound] = openDisputeCounters[currentRound].add(1); emit DisputeOpened(disputeId, currentRound, clientAddress); return true; } /** * Checks whether the dispute needs to be handled by the operator. * @dev This code was extracted from closeDispute to reduce compiler stack size. * @param dispute Dispute object from storage. * @param currentRound Current round. */ function hasValidOpenDispute(Dispute memory dispute, uint256 currentRound) public view returns (bool) { require(dispute.open); // Check it is the right moment to close the dispute uint256 currentQuarter = getCurrentQuarter(); uint256 elapsedQuarters = (4 * currentRound + currentQuarter) - (4 * dispute.round + dispute.quarter); require(elapsedQuarters <= 1/*, "Deadline to close dispute expired."*/); return true; } /** * Enables the operator to close a dispute. * @param proofs Proofs of balances for each asset for the dispute round. * @param approvals Array of approvals generated during the round previous to the dispute. * @param sigApprovals Signatures on the approvals by the client. * @param fills Fills produced by the operator based on the approvals. * @param sigFills Signatures for the fills. * @param clientAddress Address of the client that opened the dispute. */ function closeDispute( Proof[] memory proofs, Approval[] memory approvals, bytes[] memory sigApprovals, Fill[] memory fills, bytes[] memory sigFills, address clientAddress ) public notHalted() onlyBy(operatorAddress) { uint256 currentRound = getCurrentRound(); Dispute storage dispute = disputes[clientAddress]; require(hasValidOpenDispute(dispute, currentRound)); // Check the proofs require(isProofArrayValid(proofs, clientAddress, dispute.round)); // Check that all fills are unique. if (fills.length > 1) { for (uint256 i = 0; i < fills.length - 1; i++) { require(fills[i].fillId < fills[i + 1].fillId); } } // Check all the fills of dispute are included. uint256 fillCount = 0; for (uint256 i = 0; i < fills.length; i++) { if (areFillsEqual(fills[i], disputeFills[dispute.disputeId][fills[i].fillId])) { fillCount += 1; } } require(fillCount == dispute.fillCount); // Check that all the approvals are valid. uint256 disputedRound = dispute.round.sub(1); for (uint256 i = 0; i < approvals.length; i++) { checkApprovalSig(approvals[i], sigApprovals[i], clientAddress); require(approvals[i].round == disputedRound); } // Check that all the fills are valid for (uint256 i = 0; i < fills.length; i++) { checkFillSig(fills[i], sigFills[i]); require(fills[i].round == disputedRound); require(fills[i].clientAddress == clientAddress); } checkFillWithApproval(approvals, fills); checkDisputeAccounting( clientAddress, proofs, approvals, fills, dispute.disputeId, dispute.round ); // Close the dispute dispute.open = false; openDisputeCounters[dispute.round] = openDisputeCounters[dispute.round].sub(1); emit DisputeClosed( dispute.disputeId, currentRound, clientAddress ); } /** * Enables a client to recover all his funds using a proof from round r - 2. * Only works when the contract is halted. * @param proof Proof of the client balances for round r - 2. */ function recoverAllFunds(Proof memory proof) public returns (bool) { updateHaltedState(); require(halted); address clientAddress = msg.sender; address tokenAddress = proof.tokenAddress; require(proof.clientAddress == clientAddress); require(recovered[tokenAddress][clientAddress] == false); uint256 currentRound = getCurrentRound(); require(isProofValid(proof, currentRound - 2)); uint256 openingBalanceTwoRoundsAgo = proof.clientOpeningBalance; uint256 fundsToRecover = openingBalanceTwoRoundsAgo; fundsToRecover = fundsToRecover.add(clientDeposits[currentRound][tokenAddress][clientAddress]); fundsToRecover = fundsToRecover.add(clientDeposits[currentRound - 1][tokenAddress][clientAddress]); fundsToRecover = fundsToRecover.add(clientDeposits[currentRound - 2][tokenAddress][clientAddress]); recovered[tokenAddress][clientAddress] = true; require(transferTokenToClient(tokenAddress, clientAddress, fundsToRecover)); return true; } /** * Enables a client to recover his funds on chain. * Only works when the contract is halted. * @param tokenAddress Address of the token to recover balance from. */ function recoverOnChainFundsOnly(address tokenAddress) public returns (bool) { updateHaltedState(); require(halted); address clientAddress = msg.sender; require(recovered[tokenAddress][clientAddress] == false); uint256 currentRound = getCurrentRound(); uint256 fundsToRecover = clientDeposits[currentRound][tokenAddress][clientAddress]; if (currentRound >= 1) { fundsToRecover = fundsToRecover.add(clientDeposits[currentRound - 1][tokenAddress][clientAddress]); } if (currentRound >= 2) { fundsToRecover = fundsToRecover.add(clientDeposits[currentRound - 2][tokenAddress][clientAddress]); } recovered[tokenAddress][clientAddress] = true; require(transferTokenToClient(tokenAddress, clientAddress, fundsToRecover)); return true; } /** * Updates the halted state. */ function updateHaltedState() public returns (bool) { if (halted) { return true; } uint256 currentRound = getCurrentRound(); uint256 currentQuarter = getCurrentQuarter(); // If in round 0, it's too early to update the halted state. if (currentRound == 0) { return false; } uint256 previousRound = currentRound.sub(1); bool isMissingCommits; bool hasOpenDisputes; if (currentQuarter == 0) { // Check for missing commits corresponding to r - 2 activity. isMissingCommits = (committedRounds < previousRound); // Check for open disputes during round r - 2 if (previousRound > 0) { hasOpenDisputes = (openDisputeCounters[previousRound - 1] > 0); } } else { // Quarter in [ 1, 2, 3 ]. Check for round r - 1. isMissingCommits = (committedRounds < currentRound); hasOpenDisputes = (openDisputeCounters[currentRound - 1] > 0); } bool hasTokensRegistered = (tokenCount > 0); if (!hasTokensRegistered || isMissingCommits || hasOpenDisputes) { halted = true; haltedRound = currentRound; haltedQuarter = currentQuarter; emit Halted(haltedRound, haltedQuarter); return true; } return false; } // // Utility Functions // /** * Returns the current block number. */ function getCurrentBlockNumber() public view returns (uint256) { return block.number; } /** * Returns the current round based on the block number. */ function getCurrentRound() public view returns (uint256) { if (halted) { return haltedRound; } else { return ((getCurrentBlockNumber() - blockNumberAtCreation) / roundSize); } } /** * Returns the current quarter based on the block number. */ function getCurrentQuarter() public view returns (uint256) { if (halted) { return haltedQuarter; } else { uint256 indexInRound = (getCurrentBlockNumber() - blockNumberAtCreation) % roundSize; return indexInRound / quarterSize; } } /** * Validates a merkle proof for a user, corresponding to the root of the given round. * @param proof Proof to check against the root of the tree. * @param round Round corresponding to the commit against which we want to verify the proof. */ function isProofValid( Proof memory proof, uint256 round ) public view returns (bool) { bytes32 root = commits[round][proof.tokenAddress]; // The root must have been initialized. if (root == 0) { return false; } // The round must be correct if (proof.round != round) { return false; } // We need to check that the clientAddress and clientOpeningBalance correspond to the leaf // for which we want to validate a merkle path to the root. bytes32 leaf = keccak256(abi.encodePacked(proof.clientOpeningBalance, proof.clientAddress, proof.round)); // Validate the proof against the current committed root. return isMerkleProofValid( proof.hashes, proof.sums, root, leaf, proof.clientOpeningBalance, proof.height, proof.width ); } /** * Verifies a Merkle proof proving the existence of a leaf in a Merkle tree. Assumes that each pair of leaves * and each pair of pre-images are sorted. * @dev The merkle proof part of the verification is based on: * https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/cryptography/MerkleProof.sol * @param hashes Merkle proof containing sibling hashes on the branch from the leaf to the root of the Merkle tree. * @param root Merkle root. * @param leaf Leaf of Merkle tree. * @param sum Balance for the leaf we want to check. * @param height Height of the tree. * @param width Width of the tree. */ function isMerkleProofValid( bytes32[] memory hashes, uint256[] memory sums, bytes32 root, bytes32 leaf, uint256 sum, uint256 height, uint256 width ) public pure returns (bool) { bytes32 computedHash = leaf; uint256 computedSum = sum; for (uint256 i = 0; i < hashes.length; i++) { bytes32 proofElement = hashes[i]; computedSum = computedSum.add(sums[i]); if (computedHash < proofElement) { // Hash(current computed hash + current element of the proof). computedHash = keccak256(abi.encodePacked(computedSum, computedHash, proofElement)); } else { // Hash(current element of the proof + current computed hash). computedHash = keccak256(abi.encodePacked(computedSum, proofElement, computedHash)); } } computedHash = keccak256(abi.encodePacked(computedHash, computedSum)); computedHash = keccak256(abi.encodePacked(computedHash, height, width)); // Check if the computed hash (root) is equal to the provided root. return computedHash == root; } /** * Validates an authorization message. * @param clientAddress Address of the client. * @param authorization Signature of message clientAddress and round by the operator. */ function verifyAuthorizationMessage( address clientAddress, AuthorizationMessage memory authorization ) public view returns (bool) { uint256 currentRound = getCurrentRound(); if (authorization.clientAddress != clientAddress) { return false; } if (authorization.round != currentRound - 1) { return false; } bytes32 hash = keccak256( abi.encodePacked( authorization.clientAddress, authorization.round ) ); bytes32 normalizedHash = ECRecovery.toEthSignedMessageHash(hash); address signerAddress = ECRecovery.recover(normalizedHash, authorization.sig); return (signerAddress == operatorAddress); } /** * Validates a signature on an approval and that the instance of the approval is correct. * @param approval Approval signed by the Client. * @param sig Signature on the approval. * @param clientAddress Address of the Client. */ function checkApprovalSig( Approval memory approval, bytes memory sig, address clientAddress ) public view returns (bool) { // InstanceId should match the mediator contract address. require(approval.instanceId == address(this)); // Check the signature bytes32 hash = keccak256( abi.encodePacked( approval.approvalId, approval.round, approval.buyAmount, approval.buyAsset, approval.sellAmount, approval.sellAsset, approval.intent, approval.instanceId ) ); bytes32 normalizedHash = ECRecovery.toEthSignedMessageHash(hash); address signerAddress = ECRecovery.recover(normalizedHash, sig); require(signerAddress == clientAddress); return true; } /** * Validates a fill (signature and instance identifier). * @param fill Approval signed by the operator. * @param sig Signature on the fill. */ function checkFillSig( Fill memory fill, bytes memory sig ) public view returns (bool) { require(fill.instanceId == address(this)); // Signature bytes32 hash = keccak256( abi.encodePacked( fill.fillId, fill.approvalId, fill.round, fill.buyAmount, fill.buyAsset, fill.sellAmount, fill.sellAsset, fill.clientAddress, fill.instanceId ) ); bytes32 normalizedHash = ECRecovery.toEthSignedMessageHash(hash); address signerAddress = ECRecovery.recover(normalizedHash, sig); require(signerAddress == operatorAddress); return true; } /** * Check if it is a good time to cancel a withdrawal. * @param currentRound Round when the function is called. * @param roundOfRequest Round when the withdrawal request was initiated. * @param tokenAddress Address of the token corresponding to the withdrawal request. */ function canCancelWithdrawal(uint256 currentRound, uint256 roundOfRequest, address tokenAddress) public view returns (bool) { return (currentRound == roundOfRequest) || ((currentRound == roundOfRequest + 1) && commits[currentRound][tokenAddress] == ""); } /** * Checks if two fills contain the same values. * @param fill1 First fill. * @param fill2 Second fill. * @return true Iff both fills contain the same values. */ function areFillsEqual(Fill memory fill1, Fill memory fill2) public pure returns (bool) { return ( fill1.fillId == fill2.fillId && fill1.approvalId == fill2.approvalId && fill1.round == fill2.round && fill1.buyAmount == fill2.buyAmount && fill1.buyAsset == fill2.buyAsset && fill1.sellAmount == fill2.sellAmount && fill1.sellAsset == fill2.sellAsset && fill1.clientAddress == fill2.clientAddress ); } /** * @param fills Array of fills. * @param approvals Array of approvals. */ function checkFillWithApproval( Approval[] memory approvals, Fill[] memory fills ) public pure returns (bool) { require(fills.length == approvals.length); // Check the relation between each approval and fill. for (uint256 i = 0; i < approvals.length; i++) { Approval memory approval = approvals[i]; Fill memory fill = fills[i]; require(fill.approvalId == approval.approvalId); require(fill.buyAsset == approval.buyAsset); require(fill.sellAsset == approval.sellAsset); // Avoid division by zero if buyAmount == 0 which could be a legitimate value, // for instance if the approval is used to pay a fee. // No price restriction. if (approval.buyAmount == 0) { continue; } // If the approval buyAmount is non-zero the fill buyAmount must be non-zero too. require(fill.buyAmount > 0/*, "Approval does not allow zero buy amount."*/); // Safe to divide now. Make sure fill price does not exceed approval price. require((fill.sellAmount * approval.buyAmount) <= (approval.sellAmount * (fill.buyAmount))); } return true; } /** * Checks that the token addresses of a proof array are listed in the * correct order and only once. Also that the client addresses and * the proofs themselves are valid. * @param proofs Array of proofs. */ function isProofArrayValid(Proof[] memory proofs, address clientAddress, uint256 round) public view returns (bool) { if (proofs.length != tokenCount) { return false; } for (uint256 i = 0; i < proofs.length; i++) { if (proofs[i].tokenAddress != registeredTokensAddresses[i]) { return false; } if (proofs[i].clientAddress != clientAddress) { return false; } if (isProofValid(proofs[i], round) != true) { return false; } } return true; } // // Private Functions // /** * Verifies the accounting required in order to close a dispute. * @dev We do the dispute accounting as follow: * @dev 1. Take the initial balances (proofs provided when opening dispute) * @dev 2. Add deposits * @dev 3. Compute all approved buys and sells from approvals * @dev 4. Add/remove balances for actual fills * @dev 5. Substract withdrawals * @dev 6. Check that the resulting final balances matches the final proofs * @param proofs Proofs of balances for each asset for the dispute round. * @param approvals Array of approvals generated during the round previous to the dispute. * @param fills Fills produced by the operator based on the approvals. * @param clientAddress Address of the client that opened the dispute. * @param disputeId Id of the dispute object. * @param disputeRound Round from the dispute object. */ function checkDisputeAccounting( address clientAddress, Proof[] memory proofs, Approval[] memory approvals, Fill[] memory fills, uint256 disputeId, uint256 disputeRound ) private returns (bool) { uint256 disputedRound = disputeRound.sub(1); // #1 - Initial Balances uint256[] memory balances = new uint256[](tokenCount); for (uint256 i = 0; i < disputes[clientAddress].openingBalances.length; i++) { balances[i] = disputes[clientAddress].openingBalances[i]; } // #2 - Deposits for (uint256 i = 0; i < tokenCount; i++) { address token = registeredTokensAddresses[i]; uint256 deposit = clientDeposits[disputedRound][token][clientAddress]; if (deposit > 0) { balances[i] = balances[i].add(deposit); } } // #3 - Approvals uint256[] memory approvedBuys = new uint256[](tokenCount); uint256[] memory approvedSells = new uint256[](tokenCount); if (approvals.length > 0) { for (uint256 i = 0; i < approvals.length; i++) { Approval memory approval = approvals[i]; if (disputeApprovals[disputeId][approval.approvalId] != true) { uint256 buyAsset = registeredTokensIndex[approval.buyAsset]; uint256 sellAsset = registeredTokensIndex[approval.sellAsset]; if (approval.intent) { approvedBuys[buyAsset] = approvedBuys[buyAsset].add(approval.buyAmount); } approvedSells[sellAsset] = approvedSells[sellAsset].add(approval.sellAmount); disputeApprovals[disputeId][approval.approvalId] = true; } } } // #4 - Fills for (uint256 i = 0; i < fills.length; i++) { Fill memory fill = fills[i]; Approval memory approval = approvals[i]; uint256 buyAsset = registeredTokensIndex[fill.buyAsset]; uint256 sellAsset = registeredTokensIndex[fill.sellAsset]; if (approval.intent) { require(fill.buyAmount <= approval.buyAmount); // These will revert if < 0 since we are using checked arithmetic from SafeMath. approvedBuys[buyAsset] = approvedBuys[buyAsset].sub(fill.buyAmount); } else { require(fill.sellAmount <= approval.sellAmount); } // These will revert if < 0 since we are using checked arithmetic from SafeMath. approvedSells[sellAsset] = approvedSells[sellAsset].sub(fill.sellAmount); balances[buyAsset] = balances[buyAsset].add(fill.buyAmount); balances[sellAsset] = balances[sellAsset].sub(fill.sellAmount); } // #5 - Withdrawals for (uint256 i = 0; i < tokenCount; i++) { address token = registeredTokensAddresses[i]; uint256 withdrawal = clientRequestedWithdrawals[disputedRound][token][clientAddress].amount; if (withdrawal > 0) { balances[i] = balances[i].sub(withdrawal); } } // #6 - Final Balances for (uint256 i = 0; i < proofs.length; i++) { require(balances[i] == proofs[i].clientOpeningBalance); } return true; } /** * Transfer tokens from a client to this contract. * @param tokenAddress Address of the token contract. * @param amount Amount of tokens to be transferred. * @param clientAddress Address of the source (sender) of the transfer. */ function transferTokenFromClient(address tokenAddress, address clientAddress, uint256 amount) private returns (bool) { return IERC20(tokenAddress).transferFrom(clientAddress, address(this), amount); } /** * Transfer tokens from this contract to a client. * @param tokenAddress Address of the token contract. * @param amount Amount of tokens to be transferred. * @param clientAddress Address of the destination (recipient) of the transfer. */ function transferTokenToClient(address tokenAddress, address clientAddress, uint256 amount) private returns (bool) { return IERC20(tokenAddress).transfer(clientAddress, amount); } }
* Returns the current quarter based on the block number./
function getCurrentQuarter() public view returns (uint256) { if (halted) { return haltedQuarter; uint256 indexInRound = (getCurrentBlockNumber() - blockNumberAtCreation) % roundSize; return indexInRound / quarterSize; } }
6,459,128
[ 1, 1356, 326, 783, 24821, 2511, 603, 326, 1203, 1300, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 5175, 928, 14153, 1435, 203, 565, 1071, 203, 565, 1476, 203, 565, 1135, 261, 11890, 5034, 13, 203, 565, 288, 203, 3639, 309, 261, 22314, 2344, 13, 288, 203, 5411, 327, 19514, 2344, 928, 14153, 31, 203, 5411, 2254, 5034, 770, 382, 11066, 273, 261, 588, 3935, 1768, 1854, 1435, 300, 1203, 1854, 861, 9906, 13, 738, 3643, 1225, 31, 203, 203, 5411, 327, 770, 382, 11066, 342, 24821, 1225, 31, 203, 3639, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** * Note for the truffle testversion: * DragonKingTest inherits from DragonKing and adds one more function for testing the volcano from truffle. * For deployment on ropsten or mainnet, just deploy the DragonKing contract and remove this comment before verifying on * etherscan. * */ /** * Dragonking is a blockchain game in which players may purchase dragons and knights of different levels and values. * Once every period of time the volcano erupts and wipes a few of them from the board. The value of the killed characters * gets distributed amongst all of the survivors. The dragon king receive a bigger share than the others. * In contrast to dragons, knights need to be teleported to the battlefield first with the use of teleport tokens. * Additionally, they may attack a dragon once per period. * Both character types can be protected from death up to three times. * Take a look at dragonking.io for more detailed information. * @author: Julia Altenried, Yuriy Kashnikov * */ pragma solidity ^0.4.17; contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract mortal is Ownable { address owner; function mortal() { owner = msg.sender; } function kill() internal { suicide(owner); } } contract Token { function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {} function transfer(address _to, uint256 _value) public returns (bool success) {} function balanceOf(address who) public view returns (uint256); } contract DragonKing is mortal { struct Character { uint8 characterType; uint128 value; address owner; uint64 purchaseTimestamp; } /** array holding ids of the curret characters*/ uint32[] public ids; /** the id to be given to the next character **/ uint32 public nextId; /** the id of the oldest character */ uint32 public oldest; /** the character belonging to a given id */ mapping(uint32 => Character) characters; /** teleported knights **/ mapping(uint32 => bool) teleported; /** the cost of each character type */ uint128[] public costs; /** the value of each character type (cost - fee), so it's not necessary to compute it each time*/ uint128[] public values; /** the fee to be paid each time an character is bought in percent*/ uint8 fee; /** the number of dragon types **/ uint8 constant public numDragonTypes = 6; /* the number of balloons types */ uint8 constant public numOfBalloonsTypes = 3; /** constant used to signal that there is no King at the moment **/ uint32 constant public noKing = ~uint32(0); /** total number of characters in the game */ uint16 public numCharacters; /** The maximum of characters allowed in the game */ uint16 public maxCharacters; /** number of characters per type */ mapping(uint8 => uint16) public numCharactersXType; /** the amount of time that should pass since last eruption **/ uint public eruptionThreshold; /** timestampt of the last eruption event **/ uint256 public lastEruptionTimestamp; /** how many characters to kill in %, e.g. 20 will stand for 20%, should be < 100 **/ uint8 public percentageToKill; /** knight cooldown. contains the timestamp of the earliest possible moment to start a fight */ mapping(uint32 => uint) public cooldown; uint256 public constant CooldownThreshold = 1 days; /** fight factor, used to compute extra probability in fight **/ uint8 public fightFactor; /** the teleport token contract used to send knights to the game scene */ Token teleportToken; /** the price for teleportation*/ uint public teleportPrice; /** the neverdue token contract used to purchase protection from eruptions and fights */ Token neverdieToken; /** the price for protection */ uint public protectionPrice; /** tells the number of times a character is protected */ mapping(uint32 => uint8) public protection; /** the SKL token contract **/ Token sklToken; /** the XP token contract **/ Token xperToken; // EVENTS /** is fired when new characters are purchased (who bought how many characters of which type?) */ event NewPurchase(address player, uint8 characterType, uint16 amount, uint32 startId); /** is fired when a player leaves the game */ event NewExit(address player, uint256 totalBalance, uint32[] removedCharacters); /** is fired when an eruption occurs */ event NewEruption(uint32[] hitCharacters, uint128 value, uint128 gasCost); /** is fired when a single character is sold **/ event NewSell(uint32 characterId, address player, uint256 value); /** is fired when a knight fights a dragon **/ event NewFight(uint32 winnerID, uint32 loserID, uint256 value, uint16 probability, uint16 dice); /** is fired when a knight is teleported to the field **/ event NewTeleport(uint32 characterId); /** is fired when a protection is purchased **/ event NewProtection(uint32 characterId, uint8 lifes); /** initializes the contract parameters */ function DragonKing(address teleportTokenAddress, address neverdieTokenAddress, address sklTokenAddress, address xperTokenAddress, uint8 eruptionThresholdInHours, uint8 percentageOfCharactersToKill, uint8 characterFee, uint16[] charactersCosts, uint16[] balloonsCosts) public onlyOwner { fee = characterFee; for (uint8 i = 0; i < charactersCosts.length * 2; i++) { costs.push(uint128(charactersCosts[i % numDragonTypes]) * 1 finney); values.push(costs[i] - costs[i] / 100 * fee); } uint256 balloonsIndex = charactersCosts.length * 2; for (uint8 j = 0; j < balloonsCosts.length; j++) { costs.push(uint128(balloonsCosts[j]) * 1 finney); values.push(costs[balloonsIndex + j] - costs[balloonsIndex + j] / 100 * fee); } eruptionThreshold = eruptionThresholdInHours * 60 * 60; // convert to seconds percentageToKill = percentageOfCharactersToKill; maxCharacters = 600; nextId = 1; teleportToken = Token(teleportTokenAddress); teleportPrice = 1000000000000000000; neverdieToken = Token(neverdieTokenAddress); protectionPrice = 1000000000000000000; fightFactor = 4; sklToken = Token(sklTokenAddress); xperToken = Token(xperTokenAddress); } /** * buys as many characters as possible with the transfered value of the given type * @param characterType the type of the character */ function addCharacters(uint8 characterType) payable public { require(tx.origin == msg.sender); uint16 amount = uint16(msg.value / costs[characterType]); uint16 nchars = numCharacters; if (characterType >= costs.length || msg.value < costs[characterType] || nchars + amount > maxCharacters) revert(); uint32 nid = nextId; //if type exists, enough ether was transferred and there are less than maxCharacters characters in the game if (characterType < numDragonTypes) { //dragons enter the game directly if (oldest == 0 || oldest == noKing) oldest = nid; for (uint8 i = 0; i < amount; i++) { addCharacter(nid + i, nchars + i); characters[nid + i] = Character(characterType, values[characterType], msg.sender, uint64(now)); } numCharactersXType[characterType] += amount; numCharacters += amount; } else { // to enter game knights should be teleported later for (uint8 j = 0; j < amount; j++) { characters[nid + j] = Character(characterType, values[characterType], msg.sender, uint64(now)); } } nextId = nid + amount; NewPurchase(msg.sender, characterType, amount, nid); } /** * adds a single dragon of the given type to the ids array, which is used to iterate over all characters * @param nId the id the character is about to receive * @param nchars the number of characters currently in the game */ function addCharacter(uint32 nId, uint16 nchars) internal { if (nchars < ids.length) ids[nchars] = nId; else ids.push(nId); } /** * leave the game. * pays out the sender's balance and removes him and his characters from the game * */ function exit() public { uint32[] memory removed = new uint32[](50); uint8 count; uint32 lastId; uint playerBalance; uint16 nchars = numCharacters; for (uint16 i = 0; i < nchars; i++) { if (characters[ids[i]].owner == msg.sender && characters[ids[i]].purchaseTimestamp + 1 days < now && characters[ids[i]].characterType < 2*numDragonTypes) { //first delete all characters at the end of the array while (nchars > 0 && characters[ids[nchars - 1]].owner == msg.sender && characters[ids[nchars - 1]].purchaseTimestamp + 1 days < now && characters[ids[nchars - 1]].characterType < 2*numDragonTypes) { nchars--; lastId = ids[nchars]; numCharactersXType[characters[lastId].characterType]--; playerBalance += characters[lastId].value; removed[count] = lastId; count++; if (lastId == oldest) oldest = 0; delete characters[lastId]; } //replace the players character by the last one if (nchars > i + 1) { playerBalance += characters[ids[i]].value; removed[count] = ids[i]; count++; nchars--; replaceCharacter(i, nchars); } } } numCharacters = nchars; NewExit(msg.sender, playerBalance, removed); //fire the event to notify the client msg.sender.transfer(playerBalance); if (oldest == 0) findOldest(); } /** * Replaces the character with the given id with the last character in the array * @param index the index of the character in the id array * @param nchars the number of characters * */ function replaceCharacter(uint16 index, uint16 nchars) internal { uint32 characterId = ids[index]; numCharactersXType[characters[characterId].characterType]--; if (characterId == oldest) oldest = 0; delete characters[characterId]; ids[index] = ids[nchars]; delete ids[nchars]; } /** * The volcano eruption can be triggered by anybody but only if enough time has passed since the last eription. * The volcano hits up to a certain percentage of characters, but at least one. * The percantage is specified in 'percentageToKill' * */ function triggerVolcanoEruption() public { require(now >= lastEruptionTimestamp + eruptionThreshold); require(numCharacters>0); lastEruptionTimestamp = now; uint128 pot; uint128 value; uint16 random; uint32 nextHitId; uint16 nchars = numCharacters; uint32 howmany = nchars * percentageToKill / 100; uint128 neededGas = 80000 + 10000 * uint32(nchars); if(howmany == 0) howmany = 1;//hit at least 1 uint32[] memory hitCharacters = new uint32[](howmany); for (uint8 i = 0; i < howmany; i++) { random = uint16(generateRandomNumber(lastEruptionTimestamp + i) % nchars); nextHitId = ids[random]; hitCharacters[i] = nextHitId; value = hitCharacter(random, nchars); if (value > 0) { nchars--; } pot += value; } uint128 gasCost = uint128(neededGas * tx.gasprice); numCharacters = nchars; if (pot > gasCost){ distribute(pot - gasCost); //distribute the pot minus the oraclize gas costs NewEruption(hitCharacters, pot - gasCost, gasCost); } else NewEruption(hitCharacters, 0, gasCost); } /** * A knight may attack a dragon, but not choose which one. * The value of the loser is transfered to the winner. * @param knightID the ID of the knight to perfrom the attack * @param knightIndex the index of the knight in the ids-array. Just needed to save gas costs. * In case it's unknown or incorrect, the index is looked up in the array. * */ function fight(uint32 knightID, uint16 knightIndex) public { require(tx.origin == msg.sender); if (knightID != ids[knightIndex]) knightIndex = getCharacterIndex(knightID); Character storage knight = characters[knightID]; require(cooldown[knightID] + CooldownThreshold <= now); require(knight.owner == msg.sender); require(knight.characterType < 2*numDragonTypes); // knight is not a balloon require(knight.characterType >= numDragonTypes); uint16 dragonIndex = getRandomDragon(knightID); assert(dragonIndex < maxCharacters); uint32 dragonID = ids[dragonIndex]; Character storage dragon = characters[dragonID]; uint128 value; uint16 base_probability; uint16 dice = uint16(generateRandomNumber(knightID) % 100); uint256 knightPower = sklToken.balanceOf(knight.owner) / 10**15 + xperToken.balanceOf(knight.owner); uint256 dragonPower = sklToken.balanceOf(dragon.owner) / 10**15 + xperToken.balanceOf(dragon.owner); if (knight.value == dragon.value) { base_probability = 50; if (knightPower > dragonPower) { base_probability += uint16(100 / fightFactor); } else if (dragonPower > knightPower) { base_probability -= uint16(100 / fightFactor); } } else if (knight.value > dragon.value) { base_probability = 100; if (dragonPower > knightPower) { base_probability -= uint16((100 * dragon.value) / knight.value / fightFactor); } } else if (knightPower > dragonPower) { base_probability += uint16((100 * knight.value) / dragon.value / fightFactor); } cooldown[knightID] = now; if (dice >= base_probability) { // dragon won value = hitCharacter(knightIndex, numCharacters); if (value > 0) { numCharacters--; } dragon.value += value; NewFight(dragonID, knightID, value, base_probability, dice); } else { // knight won value = hitCharacter(dragonIndex, numCharacters); if (value > 0) { numCharacters--; } knight.value += value; if (oldest == 0) findOldest(); NewFight(knightID, dragonID, value, base_probability, dice); } } /** * pick a random dragon. * @param nonce a nonce to make sure there's not always the same dragon chosen in a single block. * @return the index of a random dragon * */ function getRandomDragon(uint256 nonce) internal view returns(uint16) { uint16 randomIndex = uint16(generateRandomNumber(nonce) % numCharacters); //use 7, 11 or 13 as step size. scales for up to 1000 characters uint16 stepSize = numCharacters % 7 == 0 ? (numCharacters % 11 == 0 ? 13 : 11) : 7; uint16 i = randomIndex; //if the picked character is a knight or belongs to the sender, look at the character + stepSizes ahead in the array (modulo the total number) //will at some point return to the startingPoint if no character is suited do { if (characters[ids[i]].characterType < numDragonTypes && characters[ids[i]].owner != msg.sender) return i; i = (i + stepSize) % numCharacters; } while (i != randomIndex); return maxCharacters + 1; //there is none } /** * generate a random number. * @param nonce a nonce to make sure there's not always the same number returned in a single block. * @return the random number * */ function generateRandomNumber(uint256 nonce) internal view returns(uint) { return uint(keccak256(block.blockhash(block.number - 1), now, numCharacters, nonce)); } /** * Hits the character of the given type at the given index. * @param index the index of the character * @param nchars the number of characters * @return the value gained from hitting the characters (zero is the character was protected) * */ function hitCharacter(uint16 index, uint16 nchars) internal returns(uint128 characterValue) { uint32 id = ids[index]; if (protection[id] > 0) { protection[id]--; return 0; } characterValue = characters[ids[index]].value; nchars--; replaceCharacter(index, nchars); } /** * finds the oldest character * */ function findOldest() public { uint32 newOldest = noKing; for (uint16 i = 0; i < numCharacters; i++) { if (ids[i] < newOldest && characters[ids[i]].characterType < numDragonTypes) newOldest = ids[i]; } oldest = newOldest; } /** * distributes the given amount among the surviving characters * @param totalAmount nthe amount to distribute */ function distribute(uint128 totalAmount) internal { uint128 amount; if (oldest == 0) findOldest(); if (oldest != noKing) { //pay 10% to the oldest dragon characters[oldest].value += totalAmount / 10; amount = totalAmount / 10 * 9; } else { amount = totalAmount; } //distribute the rest according to their type uint128 valueSum; uint8 size = 2 * numDragonTypes; uint128[] memory shares = new uint128[](size); for (uint8 v = 0; v < size; v++) { if (numCharactersXType[v] > 0) valueSum += values[v]; } for (uint8 m = 0; m < size; m++) { if (numCharactersXType[m] > 0) shares[m] = amount * values[m] / valueSum / numCharactersXType[m]; } uint8 cType; for (uint16 i = 0; i < numCharacters; i++) { cType = characters[ids[i]].characterType; if(cType < size) characters[ids[i]].value += shares[characters[ids[i]].characterType]; } } /** * allows the owner to collect the accumulated fees * sends the given amount to the owner's address if the amount does not exceed the * fees (cannot touch the players' balances) minus 100 finney (ensure that oraclize fees can be paid) * @param amount the amount to be collected * */ function collectFees(uint128 amount) public onlyOwner { uint collectedFees = getFees(); if (amount + 100 finney < collectedFees) { owner.transfer(amount); } } /** * withdraw NDC and TPT tokens */ function withdraw() public onlyOwner { uint256 ndcBalance = neverdieToken.balanceOf(this); assert(neverdieToken.transfer(owner, ndcBalance)); uint256 tptBalance = teleportToken.balanceOf(this); assert(teleportToken.transfer(owner, tptBalance)); } /** * pays out the players. * */ function payOut() public onlyOwner { for (uint16 i = 0; i < numCharacters; i++) { characters[ids[i]].owner.transfer(characters[ids[i]].value); delete characters[ids[i]]; } delete ids; numCharacters = 0; } /** * pays out the players and kills the game. * */ function stop() public onlyOwner { withdraw(); payOut(); kill(); } /** * sell the character of the given id * throws an exception in case of a knight not yet teleported to the game * @param characterId the id of the character * */ function sellCharacter(uint32 characterId) public { require(tx.origin == msg.sender); require(msg.sender == characters[characterId].owner); require(characters[characterId].characterType < 2*numDragonTypes); require(characters[characterId].purchaseTimestamp + 1 days < now); uint128 val = characters[characterId].value; numCharacters--; replaceCharacter(getCharacterIndex(characterId), numCharacters); msg.sender.transfer(val); if (oldest == 0) findOldest(); NewSell(characterId, msg.sender, val); } /** * receive approval to spend some tokens. * used for teleport and protection. * @param sender the sender address * @param value the transferred value * @param tokenContract the address of the token contract * @param callData the data passed by the token contract * */ function receiveApproval(address sender, uint256 value, address tokenContract, bytes callData) public { uint32 id; uint256 price; if (msg.sender == address(teleportToken)) { id = toUint32(callData); price = teleportPrice * (characters[id].characterType/numDragonTypes);//double price in case of balloon require(value >= price); assert(teleportToken.transferFrom(sender, this, price)); teleportKnight(id); } else if (msg.sender == address(neverdieToken)) { id = toUint32(callData); // user can purchase extra lifes only right after character purchaes // in other words, user value should be equal the initial value uint8 cType = characters[id].characterType; require(characters[id].value == values[cType]); // calc how many lifes user can actually buy // the formula is the following: uint256 lifePrice; uint8 max; if(cType < 2 * numDragonTypes){ lifePrice = ((cType % numDragonTypes) + 1) * protectionPrice; max = 3; } else { lifePrice = (((cType+3) % numDragonTypes) + 1) * protectionPrice * 2; max = 6; } price = 0; uint8 i = protection[id]; for (i; i < max && value >= price + lifePrice * (i + 1); i++) { price += lifePrice * (i + 1); } assert(neverdieToken.transferFrom(sender, this, price)); protectCharacter(id, i); } else revert(); } /** * knights are only entering the game completely, when they are teleported to the scene * @param id the character id * */ function teleportKnight(uint32 id) internal { // ensure we do not teleport twice require(teleported[id] == false); teleported[id] = true; Character storage knight = characters[id]; require(knight.characterType >= numDragonTypes); //this also makes calls with non-existent ids fail addCharacter(id, numCharacters); numCharacters++; numCharactersXType[knight.characterType]++; NewTeleport(id); } /** * adds protection to a character * @param id the character id * @param lifes the number of protections * */ function protectCharacter(uint32 id, uint8 lifes) internal { protection[id] = lifes; NewProtection(id, lifes); } /****************** GETTERS *************************/ /** * returns the character of the given id * @param characterId the character id * @return the type, value and owner of the character * */ function getCharacter(uint32 characterId) constant public returns(uint8, uint128, address) { return (characters[characterId].characterType, characters[characterId].value, characters[characterId].owner); } /** * returns the index of a character of the given id * @param characterId the character id * @return the character id * */ function getCharacterIndex(uint32 characterId) constant public returns(uint16) { for (uint16 i = 0; i < ids.length; i++) { if (ids[i] == characterId) { return i; } } revert(); } /** * returns 10 characters starting from a certain indey * @param startIndex the index to start from * @return 4 arrays containing the ids, types, values and owners of the characters * */ function get10Characters(uint16 startIndex) constant public returns(uint32[10] characterIds, uint8[10] types, uint128[10] values, address[10] owners) { uint32 endIndex = startIndex + 10 > numCharacters ? numCharacters : startIndex + 10; uint8 j = 0; uint32 id; for (uint16 i = startIndex; i < endIndex; i++) { id = ids[i]; characterIds[j] = id; types[j] = characters[id].characterType; values[j] = characters[id].value; owners[j] = characters[id].owner; j++; } } /** * returns the number of dragons in the game * @return the number of dragons * */ function getNumDragons() constant public returns(uint16 numDragons) { for (uint8 i = 0; i < numDragonTypes; i++) numDragons += numCharactersXType[i]; } /** * returns the number of knights in the game * @return the number of knights * */ function getNumKnights() constant public returns(uint16 numKnights) { for (uint8 i = numDragonTypes; i < 2 * numDragonTypes; i++) numKnights += numCharactersXType[i]; } /** * @return the accumulated fees * */ function getFees() constant public returns(uint) { uint reserved = 0; for (uint16 j = 0; j < numCharacters; j++) reserved += characters[ids[j]].value; return address(this).balance - reserved; } /****************** SETTERS *************************/ /** * sets the prices of the character types * @param prices the prices in finney * */ function setPrices(uint16[] prices) public onlyOwner { for (uint8 i = 0; i < prices.length; i++) { costs[i] = uint128(prices[i]) * 1 finney; values[i] = costs[i] - costs[i] / 100 * fee; } } /** * sets the fight factor * @param _factor the new fight factor * */ function setFightFactor(uint8 _factor) public onlyOwner { fightFactor = _factor; } /** * sets the fee to charge on each purchase * @param _fee the new fee * */ function setFee(uint8 _fee) public onlyOwner { fee = _fee; } /** * sets the maximum number of characters allowed in the game * @param number the new maximum * */ function setMaxCharacters(uint16 number) public onlyOwner { maxCharacters = number; } /** * sets the teleport price * @param price the price in tokens * */ function setTeleportPrice(uint price) public onlyOwner { teleportPrice = price; } /** * sets the protection price * @param price the price in tokens * */ function setProtectionPrice(uint price) public onlyOwner { protectionPrice = price; } /** * sets the eruption threshold * @param et the new eruption threshold in seconds * */ function setEruptionThreshold(uint et) public onlyOwner { eruptionThreshold = et; } function setPercentageToKill(uint8 percentage) public onlyOwner { percentageToKill = percentage; } /************* HELPERS ****************/ /** * only works for bytes of length < 32 * @param b the byte input * @return the uint * */ function toUint32(bytes b) internal pure returns(uint32) { bytes32 newB; assembly { newB: = mload(0x80) } return uint32(newB); } }
* Replaces the character with the given id with the last character in the array @param index the index of the character in the id array @param nchars the number of characters /
function replaceCharacter(uint16 index, uint16 nchars) internal { uint32 characterId = ids[index]; numCharactersXType[characters[characterId].characterType]--; if (characterId == oldest) oldest = 0; delete characters[characterId]; ids[index] = ids[nchars]; delete ids[nchars]; }
1,438,289
[ 1, 15189, 326, 3351, 598, 326, 864, 612, 598, 326, 1142, 3351, 316, 326, 526, 225, 770, 326, 770, 434, 326, 3351, 316, 326, 612, 526, 225, 290, 7549, 326, 1300, 434, 3949, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 202, 915, 1453, 7069, 12, 11890, 2313, 770, 16, 2254, 2313, 290, 7549, 13, 2713, 288, 203, 202, 202, 11890, 1578, 26235, 273, 3258, 63, 1615, 15533, 203, 202, 202, 2107, 11600, 60, 559, 63, 20558, 63, 11560, 548, 8009, 11560, 559, 65, 413, 31, 203, 202, 202, 430, 261, 11560, 548, 422, 17067, 13, 17067, 273, 374, 31, 203, 202, 202, 3733, 3949, 63, 11560, 548, 15533, 203, 202, 202, 2232, 63, 1615, 65, 273, 3258, 63, 82, 7549, 15533, 203, 202, 202, 3733, 3258, 63, 82, 7549, 15533, 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 ]
pragma solidity ^0.5.7; interface CTokenInterface { function redeemUnderlying(uint redeemAmount) external returns (uint); function borrow(uint borrowAmount) external returns (uint); function exchangeRateCurrent() external returns (uint); function borrowBalanceCurrent(address account) external returns (uint); function totalSupply() external view returns (uint256); function balanceOf(address owner) external view returns (uint256 balance); function allowance(address, address) external view returns (uint); function approve(address, uint) external; function transfer(address, uint) external returns (bool); function transferFrom(address, address, uint) external returns (bool); } interface CERC20Interface { function mint(uint mintAmount) external returns (uint); // For ERC20 function repayBorrow(uint repayAmount) external returns (uint); // For ERC20 function borrowBalanceCurrent(address account) external returns (uint); } interface CETHInterface { function mint() external payable; // For ETH function repayBorrow() external payable; // For ETH function borrowBalanceCurrent(address account) external returns (uint); } interface ERC20Interface { function allowance(address, address) external view returns (uint); function balanceOf(address) external view returns (uint); function approve(address, uint) external; function transfer(address, uint) external returns (bool); function transferFrom(address, address, uint) external returns (bool); function deposit() external payable; function withdraw(uint) external; } interface ComptrollerInterface { function enterMarkets(address[] calldata cTokens) external returns (uint[] memory); function getAssetsIn(address account) external view returns (address[] memory); function getAccountLiquidity(address account) external view returns (uint, uint, uint); } interface CompOracleInterface { function getUnderlyingPrice(address) external view returns (uint); } interface KyberInterface { function trade( address src, uint srcAmount, address dest, address destAddress, uint maxDestAmount, uint minConversionRate, address walletId ) external payable returns (uint); } contract DSMath { function add(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x, "math-not-safe"); } function sub(uint x, uint y) internal pure returns (uint z) { z = x - y <= x ? x - y : 0; } function mul(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x, "math-not-safe"); } uint constant WAD = 10 ** 18; 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; } } contract Helpers is DSMath { /** * @dev get ethereum address for trade */ function getAddressETH() public pure returns (address eth) { eth = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; } /** * @dev get ethereum address for trade */ function getAddressWETH() public pure returns (address eth) { eth = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; } /** * @dev get ethereum address for trade */ function getAddressUSDC() public pure returns (address usdc) { usdc = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48; } /** * @dev get ethereum address for trade */ function getAddressZRXExchange() public pure returns (address zrxExchange) { zrxExchange = 0x080bf510FCbF18b91105470639e9561022937712; } /** * @dev get ethereum address for trade */ function getAddressKyberProxy() public pure returns (address kyberProxy) { kyberProxy = 0x818E6FECD516Ecc3849DAf6845e3EC868087B755; } /** * @dev get Compound Comptroller Address */ function getComptrollerAddress() public pure returns (address troller) { troller = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B; } /** * @dev get Compound Comptroller Address */ function getCompOracleAddress() public pure returns (address troller) { troller = 0xe7664229833AE4Abf4E269b8F23a86B657E2338D; } /** * @dev get Compound Comptroller Address */ function getCETHAddress() public pure returns (address cEth) { cEth = 0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5; } /** * @dev get Compound Comptroller Address */ function getCUSDCAddress() public pure returns (address cUsdc) { cUsdc = 0x39AA39c021dfbaE8faC545936693aC917d5E7563; } /** * @dev get Compound Comptroller Address */ function getAddressAdmin() public pure returns (address admin) { admin = 0xa7615CD307F323172331865181DC8b80a2834324; } function enterMarket(address cErc20) internal { ComptrollerInterface troller = ComptrollerInterface(getComptrollerAddress()); address[] memory markets = troller.getAssetsIn(address(this)); bool isEntered = false; for (uint i = 0; i < markets.length; i++) { if (markets[i] == cErc20) { isEntered = true; } } if (!isEntered) { address[] memory toEnter = new address[](1); toEnter[0] = cErc20; troller.enterMarkets(toEnter); } } /** * @dev setting allowance to compound for the "user proxy" if required */ function setApproval(address erc20, uint srcAmt, address to) internal { ERC20Interface erc20Contract = ERC20Interface(erc20); uint tokenAllowance = erc20Contract.allowance(address(this), to); if (srcAmt > tokenAllowance) { erc20Contract.approve(to, 2**255); } } } contract CompoundHelper is Helpers { /** * @dev get users overall details for Compound */ function getCompStats( address user, address[] memory cTokenAddr, uint[] memory cTokenFactor ) public returns (uint totalSupply, uint totalBorrow, uint maxBorrow, uint borrowRemain, uint maxWithdraw, uint ratio) { for (uint i = 0; i < cTokenAddr.length; i++) { address cTokenAdd = cTokenAddr[i]; uint factor = cTokenFactor[i]; (uint supplyInEth, uint borrowInEth) = compSupplyBorrow(cTokenAdd, user); totalSupply += supplyInEth; totalBorrow += borrowInEth; maxBorrow += wmul(supplyInEth, factor); } borrowRemain = sub(maxBorrow, totalBorrow); maxWithdraw = sub(wdiv(borrowRemain, 750000000000000000), 10); // divide it by 0.75 (ETH Factor) uint userEthSupply = getEthSupply(user); maxWithdraw = userEthSupply > maxWithdraw ? maxWithdraw : userEthSupply; ratio = wdiv(totalBorrow, totalSupply); } /** * @dev get user's token supply and borrow in ETH */ function compSupplyBorrow(address cTokenAdd, address user) internal returns(uint supplyInEth, uint borrowInEth) { CTokenInterface cTokenContract = CTokenInterface(cTokenAdd); uint tokenPriceInEth = CompOracleInterface(getCompOracleAddress()).getUnderlyingPrice(cTokenAdd); uint cTokenBal = sub(cTokenContract.balanceOf(user), 1); uint cTokenExchangeRate = cTokenContract.exchangeRateCurrent(); uint tokenSupply = sub(wmul(cTokenBal, cTokenExchangeRate), 1); supplyInEth = sub(wmul(tokenSupply, tokenPriceInEth), 10); uint tokenBorrowed = cTokenContract.borrowBalanceCurrent(user); borrowInEth = add(wmul(tokenBorrowed, tokenPriceInEth), 10); } function getEthSupply(address user) internal returns (uint ethSupply) { CTokenInterface cTokenContract = CTokenInterface(getCETHAddress()); uint cTokenBal = sub(cTokenContract.balanceOf(user), 1); uint cTokenExchangeRate = cTokenContract.exchangeRateCurrent(); ethSupply = wmul(cTokenBal, cTokenExchangeRate); } function usdcBorrowed(address user) internal returns (uint usdcAmt) { CTokenInterface cTokenContract = CTokenInterface(getCUSDCAddress()); usdcAmt = cTokenContract.borrowBalanceCurrent(user); } function getUsdcRemainBorrow(uint usdcInEth) internal view returns (uint usdcAmt) { uint tokenPriceInEth = CompOracleInterface(getCompOracleAddress()).getUnderlyingPrice(getCUSDCAddress()); usdcAmt = sub(wdiv(usdcInEth, tokenPriceInEth), 10); } } contract CompoundResolver is CompoundHelper { event LogMint(address erc20, address cErc20, uint tokenAmt, address owner); event LogRedeem(address erc20, address cErc20, uint tokenAmt, address owner); event LogBorrow(address erc20, address cErc20, uint tokenAmt, address owner); event LogRepay(address erc20, address cErc20, uint tokenAmt, address owner); /** * @dev Deposit ETH/ERC20 and mint Compound Tokens */ function mintCEth(uint tokenAmt) internal { CETHInterface cToken = CETHInterface(getCETHAddress()); cToken.mint.value(tokenAmt)(); emit LogMint( getAddressETH(), getCETHAddress(), tokenAmt, msg.sender ); } /** * @dev Redeem ETH/ERC20 and mint Compound Tokens * @param tokenAmt Amount of token To Redeem */ function redeemEth(uint tokenAmt) internal { CTokenInterface cToken = CTokenInterface(getCETHAddress()); setApproval(getCETHAddress(), 10**30, getCETHAddress()); require(cToken.redeemUnderlying(tokenAmt) == 0, "something went wrong"); emit LogRedeem( getAddressETH(), getCETHAddress(), tokenAmt, address(this) ); } /** * @dev borrow ETH/ERC20 */ function borrow(uint tokenAmt) internal { require(CTokenInterface(getCUSDCAddress()).borrow(tokenAmt) == 0, "got collateral?"); emit LogBorrow( getAddressUSDC(), getCUSDCAddress(), tokenAmt, address(this) ); } /** * @dev Pay Debt ETH/ERC20 */ function repayUsdc(uint tokenAmt) internal { CERC20Interface cToken = CERC20Interface(getCUSDCAddress()); setApproval(getAddressUSDC(), tokenAmt, getCUSDCAddress()); require(cToken.repayBorrow(tokenAmt) == 0, "transfer approved?"); emit LogRepay( getAddressUSDC(), getCUSDCAddress(), tokenAmt, address(this) ); } } contract CompoundSave is CompoundResolver { event LogSaveCompoundUsdc(uint srcETH, uint destDAI); event LogLeverageCompoundUsdc(uint srcDAI,uint destETH); function save( uint ethToFree, uint zrxEthAmt, bytes memory calldataHexString, address[] memory ctokenAddr, uint[] memory ctokenFactor ) public { enterMarket(getCETHAddress()); enterMarket(getCUSDCAddress()); (,,,,uint maxWithdraw,) = getCompStats(address(this), ctokenAddr, ctokenFactor); uint ethToSwap = ethToFree < maxWithdraw ? ethToFree : maxWithdraw; redeemEth(ethToSwap); ERC20Interface wethContract = ERC20Interface(getAddressWETH()); wethContract.deposit.value(zrxEthAmt)(); wethContract.approve(getAddressZRXExchange(), zrxEthAmt); getAddressZRXExchange().call(calldataHexString); if (address(this).balance > 0) { KyberInterface(getAddressKyberProxy()).trade.value(address(this).balance)( getAddressETH(), address(this).balance, getAddressUSDC(), address(this), 2**255, 0, getAddressAdmin() ); } ERC20Interface usdcContract = ERC20Interface(getAddressUSDC()); uint usdcBal = usdcContract.balanceOf(address(this)); repayUsdc(usdcBal); emit LogSaveCompoundUsdc(ethToSwap, usdcBal); } function leverage( uint usdcToBorrow, uint zrxUsdcAmt, bytes memory calldataHexString, address[] memory cTokenAddr, uint[] memory ctokenFactor ) public { enterMarket(getCETHAddress()); enterMarket(getCUSDCAddress()); (,,,uint borrowRemain,,) = getCompStats(address(this), cTokenAddr, ctokenFactor); uint usdcToSwap = getUsdcRemainBorrow(borrowRemain); usdcToSwap = usdcToSwap < usdcToBorrow ? usdcToSwap : usdcToBorrow; borrow(usdcToSwap); ERC20Interface usdcContract = ERC20Interface(getAddressUSDC()); usdcContract.approve(getAddressZRXExchange(), zrxUsdcAmt); getAddressZRXExchange().call(calldataHexString); uint usdcBal = usdcContract.balanceOf(address(this)); if (usdcBal > 0) { usdcContract.approve(getAddressKyberProxy(), usdcBal); KyberInterface(getAddressKyberProxy()).trade.value(address(this).balance)( getAddressUSDC(), address(this).balance, getAddressETH(), address(this), 2**255, 0, getAddressAdmin() ); } ERC20Interface wethContract = ERC20Interface(getAddressWETH()); uint wethBal = wethContract.balanceOf(address(this)); wethContract.approve(getAddressWETH(), wethBal); wethContract.withdraw(wethBal); mintCEth(address(this).balance); emit LogLeverageCompoundUsdc(usdcToSwap, address(this).balance); } } contract InstaCompSave is CompoundSave { uint public version; /** * @dev setting up variables on deployment * 1...2...3 versioning in each subsequent deployments */ constructor(uint _version) public { version = _version; } function() external payable {} }
* @dev get ethereum address for trade/
function getAddressKyberProxy() public pure returns (address kyberProxy) { kyberProxy = 0x818E6FECD516Ecc3849DAf6845e3EC868087B755; }
12,815,447
[ 1, 588, 13750, 822, 379, 1758, 364, 18542, 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, 14808, 47, 93, 744, 3886, 1435, 1071, 16618, 1135, 261, 2867, 417, 93, 744, 3886, 13, 288, 203, 3639, 417, 93, 744, 3886, 273, 374, 92, 28, 2643, 41, 26, 42, 7228, 40, 25, 2313, 41, 952, 17295, 29, 9793, 74, 26, 5193, 25, 73, 23, 7228, 5292, 3672, 11035, 38, 21761, 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 ]
./partial_match/1/0x74B7639503bb632FfE86382af7C5a3121a41613a/sources/PendleAccumulator.sol
OpenZeppelin Contracts (last updated v4.9.0) (utils/Address.sol)* @dev Collection of functions related to the address type/
library Address { function deposit_reward_token(address _rewardToken, uint256 _amount) external; function claim_rewards_for(address _user, address _recipient) external; function working_balances(address _address) external view returns (uint256); function deposit(uint256 _value, address _addr) external; function reward_tokens(uint256 _i) external view returns (address); function reward_data(address _tokenReward) external view returns (Reward memory); function balanceOf(address) external returns (uint256); function claimable_reward(address _user, address _reward_token) external view returns (uint256); function claimable_tokens(address _user) external returns (uint256); function user_checkpoint(address _user) external returns (bool); function commit_transfer_ownership(address) external; function claim_rewards(address) external; function add_reward(address, address) external; function set_claimer(address) external; function admin() external view returns (address); function set_reward_distributor(address _rewardToken, address _newDistrib) external; function initialize( address staking_token, address admin, address SDT, address voting_escrow, address veBoost_proxy, address distributor ) external; } } } } function isContract(address account) internal view returns (bool) { return account.code.length > 0; } function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); require(success, "Address: unable to send value, recipient may have reverted"); } (bool success, ) = recipient.call{value: amount}(""); function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, "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 verifyCallResultFromTarget(target, success, returndata, errorMessage); } (bool success, bytes memory returndata) = target.call{value: value}(data); function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResultFromTarget(target, success, returndata, errorMessage); } function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResultFromTarget(target, success, returndata, errorMessage); } function verifyCallResultFromTarget( address target, bool success, bytes memory returndata, string memory errorMessage ) internal view returns (bytes memory) { if (success) { if (returndata.length == 0) { require(isContract(target), "Address: call to non-contract"); } return returndata; _revert(returndata, errorMessage); } } function verifyCallResultFromTarget( address target, bool success, bytes memory returndata, string memory errorMessage ) internal view returns (bytes memory) { if (success) { if (returndata.length == 0) { require(isContract(target), "Address: call to non-contract"); } return returndata; _revert(returndata, errorMessage); } } function verifyCallResultFromTarget( address target, bool success, bytes memory returndata, string memory errorMessage ) internal view returns (bytes memory) { if (success) { if (returndata.length == 0) { require(isContract(target), "Address: call to non-contract"); } return returndata; _revert(returndata, errorMessage); } } } else { function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; _revert(returndata, errorMessage); } } function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; _revert(returndata, errorMessage); } } } else { function _revert(bytes memory returndata, string memory errorMessage) private pure { if (returndata.length > 0) { assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } revert(errorMessage); } } function _revert(bytes memory returndata, string memory errorMessage) private pure { if (returndata.length > 0) { assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } revert(errorMessage); } } function _revert(bytes memory returndata, string memory errorMessage) private pure { if (returndata.length > 0) { assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } revert(errorMessage); } } } else { }
15,611,752
[ 1, 3678, 62, 881, 84, 292, 267, 30131, 261, 2722, 3526, 331, 24, 18, 29, 18, 20, 13, 261, 5471, 19, 1887, 18, 18281, 13, 225, 2200, 434, 4186, 3746, 358, 326, 1758, 618, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 12083, 5267, 288, 203, 565, 445, 443, 1724, 67, 266, 2913, 67, 2316, 12, 2867, 389, 266, 2913, 1345, 16, 2254, 5034, 389, 8949, 13, 3903, 31, 203, 203, 565, 445, 7516, 67, 266, 6397, 67, 1884, 12, 2867, 389, 1355, 16, 1758, 389, 20367, 13, 3903, 31, 203, 203, 565, 445, 5960, 67, 70, 26488, 12, 2867, 389, 2867, 13, 3903, 1476, 1135, 261, 11890, 5034, 1769, 203, 203, 203, 565, 445, 443, 1724, 12, 11890, 5034, 389, 1132, 16, 1758, 389, 4793, 13, 3903, 31, 203, 203, 565, 445, 19890, 67, 7860, 12, 11890, 5034, 389, 77, 13, 3903, 1476, 1135, 261, 2867, 1769, 203, 203, 565, 445, 19890, 67, 892, 12, 2867, 389, 2316, 17631, 1060, 13, 3903, 1476, 1135, 261, 17631, 1060, 3778, 1769, 203, 203, 565, 445, 11013, 951, 12, 2867, 13, 3903, 1135, 261, 11890, 5034, 1769, 203, 203, 565, 445, 7516, 429, 67, 266, 2913, 12, 2867, 389, 1355, 16, 1758, 389, 266, 2913, 67, 2316, 13, 3903, 1476, 1135, 261, 11890, 5034, 1769, 203, 203, 565, 445, 7516, 429, 67, 7860, 12, 2867, 389, 1355, 13, 3903, 1135, 261, 11890, 5034, 1769, 203, 203, 565, 445, 729, 67, 25414, 12, 2867, 389, 1355, 13, 3903, 1135, 261, 6430, 1769, 203, 203, 565, 445, 3294, 67, 13866, 67, 995, 12565, 12, 2867, 13, 3903, 31, 203, 203, 565, 445, 7516, 67, 266, 6397, 12, 2867, 13, 3903, 31, 203, 203, 565, 445, 527, 67, 266, 2913, 12, 2867, 16, 1758, 13, 3903, 31, 203, 203, 565, 445, 2 ]
./full_match/44787/0xf69D5d34A46BF60996449FED26B86ae3A0f24596/sources/contracts/StarFarm.sol
Withdraw Star NFT from STAKING.
function leaveStakingNFT(uint256 _tokenId) public { PoolInfo storage pool = poolInfo[0]; UserInfo storage user = userInfo[0][_msgSender()]; SlotInfo memory slot; require(userNFTs[_msgSender()].length > 0, "no NFT"); updatePool(0,2); (slot._selfGain, slot._parentGain) = starNode.nodeGain(_msgSender()); slot._self_parentGain = slot._selfGain.add(slot._parentGain); slot._nftAmountGain = user.nftAmount.add(user.nftAmount.mul(slot._self_parentGain).div(100)); slot.accStarPerShare = pool.accStarPerShare; if (block.number > pool.lastRewardBlock && pool.lpSupply != 0) { slot.multiplier = getMultiplier(pool.lastRewardBlock, block.number); slot.starReward = slot.multiplier.mul(starPerBlock).mul(pool.allocPoint).div(totalAllocPoint); slot.accStarPerShare = slot.starReward.mul(1e12).div(pool.lpSupply); } if(user.nftAmount > 0){ uint256 _nftAmountpendingStar = slot._nftAmountGain.mul(slot.accStarPerShare).div(1e12); user.nftReward = user.nftReward.add(_nftAmountpendingStar); } uint256 pending = user.nftReward; if(pending > 0) { starToken.safeTransfer(lockAddr,pending.mul(lockRatio).div(100)); starToken.safeTransfer(teamAddr,pending.mul(teamRatio).div(100)); pending = pending.sub(pending.mul(lockRatio.add(teamRatio)).div(100)); starToken.safeTransfer(rewardAddr,pending.mul(rewardRatio).div(100)); pending = pending.sub(pending.mul(rewardRatio).div(100)); pending = pending.mul(100).div(slot._self_parentGain.add(100)); if (user.lastDeposit > block.timestamp.sub(604800)) { starToken.safeTransfer(_msgSender(), pending.mul(slot._selfGain.add(100)).div(100).sub(pending.mul(pool.fee).div(10000))); starNode.settleNode(_msgSender(), pending.mul(slot._parentGain).div(100)); user.nftRewardDebt = user.nftRewardDebt.add(pending.mul(slot._selfGain.add(100)).div(100).sub(pending.mul(pool.fee).div(10000))); pending = pending.mul(pool.fee).div(10000); starToken.safeTransfer(bonusAddr, pending.mul(70).div(100)); starToken.safeTransfer(lockAddr, pending.mul(30).div(100)); starToken.safeTransfer(_msgSender(), pending); starNode.settleNode(_msgSender(), pending.mul(slot._parentGain).div(100)); user.nftRewardDebt = user.nftRewardDebt.add(pending); } user.nftReward = 0; pool.accStarPerShare = slot.accStarPerShare; } if (_tokenId > 0) { uint256[] storage _userNFTs = userNFTs[_msgSender()]; for (slot.i = 0; slot.i < _userNFTs.length; slot.i ++) { if(_userNFTs[slot.i] == _tokenId) { (, , uint256 _price, uint256 _multi) = nftLogic.starMeta(_tokenId); slot._amount = _price.mul(_multi).div(100); if(slot._amount > 0) { uint256 _extraAmount = slot._amount.add(slot._amount.mul(slot._self_parentGain).div(100)); pool.extraAmount = pool.extraAmount.sub(_extraAmount); pool.lpSupply = pool.lpSupply.sub(slot._amount); user.nftAmount = user.nftAmount.sub(slot._amount); _userNFTs[slot.i] = _userNFTs[_userNFTs.length - 1]; _userNFTs.pop(); } starNFT.transferFrom(address(this), _msgSender(), _tokenId); slot._nftAmountGain = user.nftAmount.add(user.nftAmount.mul(slot._selfGain).div(100)); user.nftRewardDebt = slot._nftAmountGain.mul(pool.accStarPerShare).div(1e12); emit Withdraw(_msgSender(), 0, _price.mul(_multi).div(100), isNodeUser[_msgSender()]); break; } } } }
13,265,460
[ 1, 1190, 9446, 934, 297, 423, 4464, 628, 2347, 14607, 1360, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 8851, 510, 6159, 50, 4464, 12, 11890, 5034, 389, 2316, 548, 13, 1071, 288, 203, 3639, 8828, 966, 2502, 2845, 273, 2845, 966, 63, 20, 15533, 203, 3639, 25003, 2502, 729, 273, 16753, 63, 20, 6362, 67, 3576, 12021, 1435, 15533, 203, 202, 202, 8764, 966, 3778, 4694, 31, 203, 3639, 2583, 12, 1355, 50, 4464, 87, 63, 67, 3576, 12021, 1435, 8009, 2469, 405, 374, 16, 315, 2135, 423, 4464, 8863, 203, 3639, 1089, 2864, 12, 20, 16, 22, 1769, 203, 203, 3639, 261, 14194, 6315, 2890, 43, 530, 16, 4694, 6315, 2938, 43, 530, 13, 273, 10443, 907, 18, 2159, 43, 530, 24899, 3576, 12021, 10663, 203, 3639, 4694, 6315, 2890, 67, 2938, 43, 530, 273, 4694, 6315, 2890, 43, 530, 18, 1289, 12, 14194, 6315, 2938, 43, 530, 1769, 203, 3639, 4694, 6315, 82, 1222, 6275, 43, 530, 273, 729, 18, 82, 1222, 6275, 18, 1289, 12, 1355, 18, 82, 1222, 6275, 18, 16411, 12, 14194, 6315, 2890, 67, 2938, 43, 530, 2934, 2892, 12, 6625, 10019, 203, 3639, 4694, 18, 8981, 18379, 2173, 9535, 273, 2845, 18, 8981, 18379, 2173, 9535, 31, 203, 3639, 309, 261, 2629, 18, 2696, 405, 2845, 18, 2722, 17631, 1060, 1768, 597, 2845, 18, 9953, 3088, 1283, 480, 374, 13, 288, 203, 5411, 4694, 18, 20538, 273, 31863, 5742, 12, 6011, 18, 2722, 17631, 1060, 1768, 16, 1203, 18, 2696, 1769, 203, 5411, 4694, 18, 10983, 17631, 1060, 273, 4694, 18, 20538, 18, 16411, 12, 10983, 2173, 1768, 2934, 16411, 12, 6011, 18, 2 ]
./full_match/5/0x96d2740CCB82F7B9Bf37f1De51004b06926C2B52/sources/TimeLock.sol
* @dev Returns the dividends multiplier for `duration` expressed as a fraction of 1e18./
function getDividendsMultiplier(uint32 duration) public view returns (uint256 multiplier) { require(duration >= minLockDuration && duration <= maxLockDuration, "OOB"); uint256 durationRange = maxLockDuration - minLockDuration; uint32 overMinimum = duration - minLockDuration; uint256 multiplier = uint256(1e18).add( maxDividendsBonusMultiplier.mul(overMinimum) / durationRange ); uint256 maxMultiplier = uint256(1e18).add( maxDividendsBonusMultiplier ); uint256 normalisedMultiplier = multiplier.mul(1e18) / (maxMultiplier); return normalisedMultiplier; } constructor( address depositToken_, ERC20NonTransferableDividendsOwned dividendsToken_, uint32 minLockDuration_, uint32 maxLockDuration_, uint256 maxDividendsBonusMultiplier_, uint256 minLockAmount_
7,080,607
[ 1, 1356, 326, 3739, 350, 5839, 15027, 364, 1375, 8760, 68, 26863, 487, 279, 8330, 434, 404, 73, 2643, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 2343, 427, 350, 5839, 23365, 12, 11890, 1578, 3734, 13, 1071, 1476, 1135, 261, 11890, 5034, 15027, 13, 288, 203, 565, 2583, 12, 8760, 1545, 1131, 2531, 5326, 597, 3734, 1648, 943, 2531, 5326, 16, 315, 51, 5704, 8863, 203, 565, 2254, 5034, 3734, 2655, 273, 943, 2531, 5326, 300, 1131, 2531, 5326, 31, 203, 565, 2254, 1578, 1879, 13042, 273, 3734, 300, 1131, 2531, 5326, 31, 203, 203, 565, 2254, 5034, 15027, 273, 2254, 5034, 12, 21, 73, 2643, 2934, 1289, 12, 203, 1377, 943, 7244, 350, 5839, 38, 22889, 23365, 18, 16411, 12, 1643, 13042, 13, 342, 3734, 2655, 203, 565, 11272, 203, 203, 565, 2254, 5034, 943, 23365, 273, 2254, 5034, 12, 21, 73, 2643, 2934, 1289, 12, 203, 1377, 943, 7244, 350, 5839, 38, 22889, 23365, 203, 565, 11272, 203, 203, 565, 2254, 5034, 2212, 5918, 23365, 273, 15027, 18, 16411, 12, 21, 73, 2643, 13, 342, 261, 1896, 23365, 1769, 203, 565, 327, 2212, 5918, 23365, 31, 203, 225, 289, 203, 203, 225, 3885, 12, 203, 565, 1758, 443, 1724, 1345, 67, 16, 203, 565, 4232, 39, 3462, 3989, 5912, 429, 7244, 350, 5839, 5460, 329, 3739, 350, 5839, 1345, 67, 16, 203, 565, 2254, 1578, 1131, 2531, 5326, 67, 16, 203, 565, 2254, 1578, 943, 2531, 5326, 67, 16, 203, 565, 2254, 5034, 943, 7244, 350, 5839, 38, 22889, 23365, 67, 16, 203, 565, 2254, 5034, 1131, 2531, 6275, 67, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.13; /** * Math operations with safety checks */ library SafeMath { function mul(uint a, uint b) internal returns (uint) { uint c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint a, uint b) internal returns (uint) { return a / b; } function sub(uint a, uint b) internal returns (uint) { assert(b <= a); return a - b; } function add(uint a, uint b) internal returns (uint) { uint c = a + b; assert(c >= a); return c; } function max64(uint64 a, uint64 b) internal constant returns (uint64) { return a >= b ? a : b; } function min64(uint64 a, uint64 b) internal constant returns (uint64) { return a < b ? a : b; } function max256(uint256 a, uint256 b) internal constant returns (uint256) { return a >= b ? a : b; } function min256(uint256 a, uint256 b) internal constant returns (uint256) { return a < b ? a : b; } function assertTrue(bool val) internal { assert(val); } function assertFalse(bool val) internal { assert(!val); } } /* * Ownable * * Base contract with an owner. * * Provides onlyOwner modifier, which prevents function from running * if it is called by anyone other than the owner. */ contract Ownable { address public owner; function Ownable() { owner = msg.sender; } modifier onlyOwner() { if (msg.sender != owner) { revert(); } _; } function transferOwnership(address newOwner) onlyOwner { if (newOwner != address(0)) { owner = newOwner; } } } /* * Haltable * * Abstract contract that allows children to implement a halt mechanism. */ contract Haltable is Ownable { bool public halted; modifier revertIfHalted { if (halted) revert(); _; } modifier onlyIfHalted { if (!halted) revert(); _; } function halt() external onlyOwner { halted = true; } function unhalt() external onlyOwner onlyIfHalted { halted = false; } } /** * Forward ETH payments associated with the Provide (PRVD) * token sale and track them with an event. * * Associates purchasers who made payment for token issuance with an identifier. * Enables the ability to make a purchase on behalf of another address. * * Allows the sale to be halted upon completion. */ contract ProvideSale is Haltable { using SafeMath for uint; /** Multisig to which all ETH is forwarded. */ address public multisig; /** Total ETH raised (in wei). */ uint public totalTransferred; /** Total number of distinct purchasers. */ uint public purchaserCount; /** Total incoming ETH (in wei) per centrally tracked purchaser. */ mapping (uint128 => uint) public paymentsByPurchaser; /** Total incoming ETH (in wei) per benefactor address. */ mapping (address => uint) public paymentsByBenefactor; /** Emitted when a purchase is made; benefactor is the address where the tokens will be ultimately issued. */ event PaymentForwarded(address source, uint amount, uint128 identifier, address benefactor); /** * @param _owner Owner is able to pause and resume crowdsale * @param _multisig Multisig to which all ETH is forwarded */ function ProvideSale(address _owner, address _multisig) { owner = _owner; multisig = _multisig; } /** * Purchase on a behalf of a benefactor. * * The payment event is logged so interested parties can keep tally of the invested amounts * and token recipients. * * The actual payment is forwarded to the multisig. * * @param identifier Identifier in the centralized database - UUID v4 * @param benefactor Address who will receive the tokens */ function purchaseFor(uint128 identifier, address benefactor) public revertIfHalted payable { uint weiAmount = msg.value; if (weiAmount == 0) { revert(); // no invalid payments } if (benefactor == 0) { revert(); // bad payment address } PaymentForwarded(msg.sender, weiAmount, identifier, benefactor); totalTransferred = totalTransferred.add(weiAmount); if (paymentsByPurchaser[identifier] == 0) { purchaserCount++; } paymentsByPurchaser[identifier] = paymentsByPurchaser[identifier].add(weiAmount); paymentsByBenefactor[benefactor] = paymentsByBenefactor[benefactor].add(weiAmount); if (!multisig.send(weiAmount)) revert(); // may run out of gas } /** * Purchase on a behalf of the sender. * * @param identifier Identifier of the purchaser - UUID v4 */ function purchase(uint128 identifier) public payable { purchaseFor(identifier, msg.sender); } /** * Purchase on a behalf of the sender, but uses a nil identifier. */ function() public payable { purchase(0); } }
* Purchase on a behalf of a benefactor. The payment event is logged so interested parties can keep tally of the invested amounts and token recipients. The actual payment is forwarded to the multisig. @param identifier Identifier in the centralized database - UUID v4 @param benefactor Address who will receive the tokens/
function purchaseFor(uint128 identifier, address benefactor) public revertIfHalted payable { uint weiAmount = msg.value; if (weiAmount == 0) { } if (benefactor == 0) { } PaymentForwarded(msg.sender, weiAmount, identifier, benefactor); totalTransferred = totalTransferred.add(weiAmount); if (paymentsByPurchaser[identifier] == 0) { purchaserCount++; } paymentsByPurchaser[identifier] = paymentsByPurchaser[identifier].add(weiAmount); paymentsByBenefactor[benefactor] = paymentsByBenefactor[benefactor].add(weiAmount); }
14,056,973
[ 1, 23164, 603, 279, 12433, 6186, 434, 279, 27641, 6812, 18, 1021, 5184, 871, 353, 7545, 1427, 20506, 1087, 606, 848, 3455, 268, 1230, 434, 326, 2198, 3149, 30980, 471, 1147, 12045, 18, 1021, 3214, 5184, 353, 19683, 358, 326, 22945, 360, 18, 225, 2756, 10333, 316, 326, 18291, 1235, 2063, 300, 5866, 331, 24, 225, 27641, 6812, 5267, 10354, 903, 6798, 326, 2430, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 225, 445, 23701, 1290, 12, 11890, 10392, 2756, 16, 1758, 27641, 6812, 13, 1071, 15226, 2047, 44, 287, 2344, 8843, 429, 288, 203, 565, 2254, 732, 77, 6275, 273, 1234, 18, 1132, 31, 203, 203, 565, 309, 261, 1814, 77, 6275, 422, 374, 13, 288, 203, 565, 289, 203, 203, 565, 309, 261, 70, 4009, 6812, 422, 374, 13, 288, 203, 565, 289, 203, 203, 565, 12022, 22915, 12, 3576, 18, 15330, 16, 732, 77, 6275, 16, 2756, 16, 27641, 6812, 1769, 203, 203, 565, 2078, 1429, 4193, 273, 2078, 1429, 4193, 18, 1289, 12, 1814, 77, 6275, 1769, 203, 203, 565, 309, 261, 10239, 1346, 858, 10262, 343, 14558, 63, 5644, 65, 422, 374, 13, 288, 203, 1377, 5405, 343, 14558, 1380, 9904, 31, 203, 565, 289, 203, 203, 565, 25754, 858, 10262, 343, 14558, 63, 5644, 65, 273, 25754, 858, 10262, 343, 14558, 63, 5644, 8009, 1289, 12, 1814, 77, 6275, 1769, 203, 565, 25754, 858, 38, 4009, 6812, 63, 70, 4009, 6812, 65, 273, 25754, 858, 38, 4009, 6812, 63, 70, 4009, 6812, 8009, 1289, 12, 1814, 77, 6275, 1769, 203, 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 ]
./full_match/77/0x5bfc4dEE19CcaCBE765C9a36fAe59F590a5a27DB/sources/project_/contracts/BaseToken.sol
get the address of the offer this user is cashing out
IOffer offer = mapOffers[nNextCashoutIndex];
5,047,185
[ 1, 588, 326, 1758, 434, 326, 10067, 333, 729, 353, 276, 961, 310, 596, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 467, 10513, 10067, 273, 852, 7210, 414, 63, 82, 2134, 39, 961, 659, 1016, 15533, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0xB385fED7b283F0bc713c19B122E001956121f204/sources/contracts/AutoStake.sol
Not Including fees
uint public totalWithdrawn = 0;
1,897,011
[ 1, 1248, 657, 18596, 1656, 281, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 1071, 2078, 1190, 9446, 82, 273, 374, 31, 282, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.6.0; import "../governance/Operator.sol"; import "../interface/IUserRegistry.sol"; /** * @title UserRegistry * @dev UserRegistry contract * Configure and manage users_ * Extended may be used externaly to store data within a user context * * @author Cyril Lapinte - <[email protected]> * * Error messages * UR01: UserId is invalid * UR02: WalletOwner is already known * UR03: Users length does not match with addresses * UR04: WalletOwner is unknown * UR05: Sender is not the wallet owner * UR06: User is already suspended * UR07: User is not suspended */ contract UserRegistry is IUserRegistry, Operator { struct User { uint256 validUntilTime; bool suspended; mapping(uint256 => uint256) extended; } mapping(uint256 => User) public users_; mapping(address => uint256) public walletOwners_; uint256 public userCount_; /** * @dev contructor **/ constructor(address[] memory _addresses, uint256 _validUntilTime) public { for (uint256 i = 0; i < _addresses.length; i++) { _registerUserInternal(_addresses[i], _validUntilTime); } } /** * @dev number of user registered */ function userCount() override public view returns (uint256) { return userCount_; } /** * @dev the userId associated to the provided address */ function userId(address _address) override public view returns (uint256) { return walletOwners_[_address]; } /** * @dev the userId associated to the provided address if the user is valid */ function validUserId(address _address) override public view returns (uint256) { uint256 addressUserId = walletOwners_[_address]; if (_isValidInternal(users_[addressUserId])) { return addressUserId; } return 0; } /** * @dev returns the time at which user validity ends */ function validUntilTime(uint256 _userId) override public view returns (uint256) { return users_[_userId].validUntilTime; } /** * @dev is the user suspended */ function suspended(uint256 _userId) override public view returns (bool) { return users_[_userId].suspended; } /** * @dev access to extended user data */ function extended(uint256 _userId, uint256 _key) override public view returns (uint256) { return users_[_userId].extended[_key]; } /** * @dev validity of the current user */ function isAddressValid(address _address) override public view returns (bool) { return _isValidInternal(users_[walletOwners_[_address]]); } /** * @dev validity of the current user */ function isValid(uint256 _userId) override public view returns (bool) { return _isValidInternal(users_[_userId]); } /** * @dev register a user */ function registerUser(address _address, uint256 _validUntilTime) override public onlyOperator { _registerUserInternal(_address, _validUntilTime); } /** * @dev register many users_ */ function registerManyUsers(address[] memory _addresses, uint256 _validUntilTime) override public onlyOperator { for (uint256 i = 0; i < _addresses.length; i++) { _registerUserInternal(_addresses[i], _validUntilTime); } } /** * @dev attach an address with a user */ function attachAddress(uint256 _userId, address _address) override public onlyOperator { require(_userId > 0 && _userId <= userCount_, "UR01"); require(walletOwners_[_address] == 0, "UR02"); walletOwners_[_address] = _userId; emit AddressAttached(_userId, _address); } /** * @dev attach many addresses to many users_ */ function attachManyAddresses(uint256[] memory _userIds, address[] memory _addresses) override public onlyOperator { require(_addresses.length == _userIds.length, "UR03"); for (uint256 i = 0; i < _addresses.length; i++) { attachAddress(_userIds[i], _addresses[i]); } } /** * @dev detach the association between an address and its user */ function detachAddress(address _address) override public onlyOperator { _detachAddressInternal(_address); } /** * @dev detach many addresses association between addresses and their respective users_ */ function detachManyAddresses(address[] memory _addresses) override public onlyOperator { for (uint256 i = 0; i < _addresses.length; i++) { _detachAddressInternal(_addresses[i]); } } /** * @dev detach the association between an address and its user */ function detachSelf() override public { _detachAddressInternal(msg.sender); } /** * @dev detach the association between an address and its user */ function detachSelfAddress(address _address) override public { uint256 senderUserId = walletOwners_[msg.sender]; require(walletOwners_[_address] == senderUserId, "UR05"); _detachAddressInternal(_address); } /** * @dev suspend a user */ function suspendUser(uint256 _userId) override public onlyOperator { require(_userId > 0 && _userId <= userCount_, "UR01"); require(!users_[_userId].suspended, "UR06"); users_[_userId].suspended = true; } /** * @dev unsuspend a user */ function unsuspendUser(uint256 _userId) override public onlyOperator { require(_userId > 0 && _userId <= userCount_, "UR01"); require(users_[_userId].suspended, "UR07"); users_[_userId].suspended = false; } /** * @dev suspend many users_ */ function suspendManyUsers(uint256[] memory _userIds) override public onlyOperator { for (uint256 i = 0; i < _userIds.length; i++) { suspendUser(_userIds[i]); } } /** * @dev unsuspend many users_ */ function unsuspendManyUsers(uint256[] memory _userIds) override public onlyOperator { for (uint256 i = 0; i < _userIds.length; i++) { unsuspendUser(_userIds[i]); } } /** * @dev update a user */ function updateUser( uint256 _userId, uint256 _validUntilTime, bool _suspended) override public onlyOperator { require(_userId > 0 && _userId <= userCount_, "UR01"); users_[_userId].validUntilTime = _validUntilTime; users_[_userId].suspended = _suspended; } /** * @dev update many users_ */ function updateManyUsers( uint256[] memory _userIds, uint256 _validUntilTime, bool _suspended) override public onlyOperator { for (uint256 i = 0; i < _userIds.length; i++) { updateUser(_userIds[i], _validUntilTime, _suspended); } } /** * @dev update user extended information */ function updateUserExtended(uint256 _userId, uint256 _key, uint256 _value) override public onlyOperator { require(_userId > 0 && _userId <= userCount_, "UR01"); users_[_userId].extended[_key] = _value; } /** * @dev update many user extended informations */ function updateManyUsersExtended( uint256[] memory _userIds, uint256 _key, uint256 _value) override public onlyOperator { for (uint256 i = 0; i < _userIds.length; i++) { updateUserExtended(_userIds[i], _key, _value); } } /** * @dev register a user */ function _registerUserInternal(address _address, uint256 _validUntilTime) internal { require(walletOwners_[_address] == 0, "UR03"); users_[++userCount_] = User(_validUntilTime, false); walletOwners_[_address] = userCount_; emit UserRegistered(userCount_); emit AddressAttached(userCount_, _address); } /** * @dev detach the association between an address and its user */ function _detachAddressInternal(address _address) internal { uint256 addressUserId = walletOwners_[_address]; require(addressUserId != 0, "UR04"); emit AddressDetached(addressUserId, _address); delete walletOwners_[_address]; } /** * @dev validity of the current user */ function _isValidInternal(User storage user) internal view returns (bool) { // solhint-disable-next-line not-rely-on-time return !user.suspended && user.validUntilTime > now; } }
* @dev update many users_/
function updateManyUsers( uint256[] memory _userIds, uint256 _validUntilTime, bool _suspended) override public onlyOperator { for (uint256 i = 0; i < _userIds.length; i++) { updateUser(_userIds[i], _validUntilTime, _suspended); } }
12,676,375
[ 1, 2725, 4906, 3677, 67, 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, 225, 445, 1089, 5594, 6588, 12, 203, 565, 2254, 5034, 8526, 3778, 389, 1355, 2673, 16, 203, 565, 2254, 5034, 389, 877, 9716, 950, 16, 203, 565, 1426, 389, 87, 22942, 13, 3849, 1071, 1338, 5592, 203, 225, 288, 203, 565, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 389, 1355, 2673, 18, 2469, 31, 277, 27245, 288, 203, 1377, 28213, 24899, 1355, 2673, 63, 77, 6487, 389, 877, 9716, 950, 16, 389, 87, 22942, 1769, 203, 565, 289, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1313161554/0x617b2E3c10325C546533Ecae277bcf9964aB3373/sources/BlacklistAndTimeFilter.sol
exclusiveDepositAddress is 0 if deposits can come from anywhere
contract BlacklistAndTimeFilter is Ownable, ApprovalInterface { mapping (address => bool) public blocked; uint public minDays; bool public swapsAllowed; bool public depositsAllowed; ClipperPool public theExchange; address public exclusiveDepositAddress; modifier anySigner() { require(msg.sender==theExchange.owner() || msg.sender==theExchange.triage(), "Clipper: Only owner or triage"); _; } modifier onlyPoolOwner(){ require(msg.sender==theExchange.owner(), "Clipper: Only owner"); _; } constructor() { swapsAllowed = true; depositsAllowed = true; blocked[address(0x1da5821544e25c636c1417Ba96Ade4Cf6D2f9B5A)] = true; blocked[address(0x72a5843cc08275C8171E582972Aa4fDa8C397B2A)] = true; blocked[address(0x7Db418b5D567A4e0E8c59Ad71BE1FcE48f3E6107)] = true; blocked[address(0x7F19720A857F834887FC9A7bC0a0fBe7Fc7f8102)] = true; blocked[address(0x7F367cC41522cE07553e823bf3be79A889DEbe1B)] = true; blocked[address(0x8576aCC5C05D6Ce88f4e49bf65BdF0C62F91353C)] = true; blocked[address(0x901bb9583b24D97e995513C6778dc6888AB6870e)] = true; blocked[address(0x9F4cda013E354b8fC285BF4b9A60460cEe7f7Ea9)] = true; blocked[address(0xA7e5d5A720f06526557c513402f2e6B5fA20b008)] = true; blocked[address(0xd882cFc20F52f2599D84b8e8D58C7FB62cfE344b)] = true; } function setPoolAddress(address payable poolAddress) external onlyOwner { theExchange = ClipperPool(poolAddress); renounceOwnership(); } function approveSwap(address recipient) external override view returns (bool){ return swapsAllowed && !blocked[recipient]; } function _exclusiveDepositAddressNotSet() internal view returns (bool) { return exclusiveDepositAddress == address(0); } function _depositSenderAllowed(address depositor) internal view returns (bool) { return _exclusiveDepositAddressNotSet() || (exclusiveDepositAddress==depositor); } function depositAddressAllowed(address depositor) internal view returns (bool) { return depositsAllowed && !blocked[depositor] && _depositSenderAllowed(depositor); } function approveDeposit(address depositor, uint nDays) external override view returns (bool){ return depositAddressAllowed(depositor) && (nDays >= minDays); } function allowSwaps() external onlyPoolOwner { swapsAllowed = true; } function denySwaps() external anySigner { swapsAllowed = false; } function setExclusiveDepositAddress(address newAddress) external onlyPoolOwner { exclusiveDepositAddress = newAddress; } function allowDeposits() external onlyPoolOwner { depositsAllowed = true; } function denyDeposits() external onlyPoolOwner { depositsAllowed = false; } function blockAddress(address blockMe) external onlyPoolOwner { blocked[blockMe] = true; } function unblockAddress(address unblockMe) external onlyPoolOwner { delete blocked[unblockMe]; } function modifyMinDays(uint newMinDays) external onlyPoolOwner { minDays = newMinDays; } }
13,232,217
[ 1, 23792, 758, 1724, 1887, 353, 374, 309, 443, 917, 1282, 848, 12404, 628, 25651, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 22467, 1098, 1876, 950, 1586, 353, 14223, 6914, 16, 1716, 685, 1125, 1358, 288, 203, 203, 565, 2874, 261, 2867, 516, 1426, 13, 1071, 14547, 31, 203, 565, 2254, 1071, 1131, 9384, 31, 203, 565, 1426, 1071, 1352, 6679, 5042, 31, 203, 565, 1426, 1071, 443, 917, 1282, 5042, 31, 203, 203, 565, 385, 3169, 457, 2864, 1071, 326, 11688, 31, 203, 203, 565, 1758, 1071, 12060, 758, 1724, 1887, 31, 203, 203, 565, 9606, 1281, 15647, 1435, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 631, 5787, 11688, 18, 8443, 1435, 747, 1234, 18, 15330, 631, 5787, 11688, 18, 16857, 410, 9334, 315, 15339, 457, 30, 5098, 3410, 578, 6882, 410, 8863, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 565, 9606, 1338, 2864, 5541, 1435, 95, 203, 3639, 2583, 12, 3576, 18, 15330, 631, 5787, 11688, 18, 8443, 9334, 315, 15339, 457, 30, 5098, 3410, 8863, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 565, 3885, 1435, 288, 203, 3639, 1352, 6679, 5042, 273, 638, 31, 203, 3639, 443, 917, 1282, 5042, 273, 638, 31, 203, 3639, 14547, 63, 2867, 12, 20, 92, 21, 2414, 8204, 22, 3600, 6334, 73, 2947, 71, 4449, 26, 71, 3461, 4033, 38, 69, 10525, 37, 323, 24, 39, 74, 26, 40, 22, 74, 29, 38, 25, 37, 25887, 273, 638, 31, 203, 3639, 14547, 63, 2867, 12, 20, 92, 9060, 69, 25, 5193, 23, 952, 6840, 5324, 25, 39, 28, 4033, 21, 41, 8204, 5540, 9060, 37, 69, 24, 74, 40, 69, 28, 2 ]
/* Copyright 2018 HydroProtocol. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.4.24; contract ERC20 { 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); } contract Exchange { function fillOrder(address[5], uint[6], uint, bool, uint8, bytes32, bytes32) public returns (uint); } contract WETH { function deposit() public payable; function withdraw(uint) public; } contract HydroSwap { address exchangeAddress; address tokenProxyAddress; address wethAddress; uint256 constant MAX_UINT = 2 ** 256 - 1; event LogSwapSuccess(bytes32 indexed id); constructor(address _exchangeAddress, address _tokenProxyAddress, address _wethAddress) public { exchangeAddress = _exchangeAddress; tokenProxyAddress = _tokenProxyAddress; wethAddress = _wethAddress; } function swap( bytes32 id, address[5] orderAddresses, uint[6] orderValues, uint8 v, bytes32 r, bytes32 s) external payable returns (uint256 takerTokenFilledAmount) { address makerTokenAddress = orderAddresses[2]; address takerTokenAddress = orderAddresses[3]; uint makerTokenAmount = orderValues[0]; uint takerTokenAmount = orderValues[1]; if (takerTokenAddress == wethAddress) { require(takerTokenAmount == msg.value, "WRONG_ETH_AMOUNT"); WETH(wethAddress).deposit.value(takerTokenAmount)(); } else { require(ERC20(takerTokenAddress).transferFrom(msg.sender, this, takerTokenAmount), "TOKEN_TRANSFER_FROM_ERROR"); } require(ERC20(takerTokenAddress).approve(tokenProxyAddress, takerTokenAmount), "TOKEN_APPROVE_ERROR"); require( Exchange(exchangeAddress).fillOrder(orderAddresses, orderValues, takerTokenAmount, true, v, r, s) == takerTokenAmount, "FILL_ORDER_ERROR" ); if (makerTokenAddress == wethAddress) { WETH(wethAddress).withdraw(makerTokenAmount); msg.sender.transfer(makerTokenAmount); } else { require(ERC20(makerTokenAddress).transfer(msg.sender, makerTokenAmount), "TOKEN_TRANSFER_ERROR"); } emit LogSwapSuccess(id); return takerTokenAmount; } // Need payable fallback function to accept the WETH withdraw funds. function() public payable {} }
Need payable fallback function to accept the WETH withdraw funds.
function() public payable {}
14,705,079
[ 1, 14112, 8843, 429, 5922, 445, 358, 2791, 326, 678, 1584, 44, 598, 9446, 284, 19156, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1435, 1071, 8843, 429, 2618, 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, -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 "../PriceOracleAdapter.sol"; import "../CErc20.sol"; interface V1PriceOracleInterface { function assetPrices(address asset) external view returns (uint256); } contract PriceOracleAdapterCompound is PriceOracleAdapter { /// @notice Address of the guardian address public guardian; /// @notice Event oracle key updateed event PriceOracleKeyUpdated( address oldAddress, address newAddress, address cTokenAddress ); /// @notice The price oracle, which will continue to serve prices of compound V1PriceOracleInterface public priceProviderInterface; // mapping(addressCtoken => addressKeyOracle); mapping(address => address) public oracleKeyAddress; /// @notice Frozen SAI price (or 0 if not set yet) uint256 public saiPrice; constructor(address guardian_) public { guardian = guardian_; } /** * @notice Get the price * @param cTokenAddress address of cToken * @return The price */ function assetPrices(address cTokenAddress) public view returns (uint256) { //get keyAddress or undlerlyingAddress address asset = (oracleKeyAddress[cTokenAddress] != address(0)) ? address(oracleKeyAddress[cTokenAddress]) : address(CErc20(cTokenAddress).underlying()); return priceProviderInterface.assetPrices(asset); } /** * @notice Set the address of price provider * @param priceProviderAddress address of price provider */ function setPriceProvider(address priceProviderAddress) public { require( msg.sender == guardian, "PriceOracleAdapterCompound: only guardian may set the address" ); require( priceProviderAddress != address(0), "PriceOracleAdapterCompound: address could not be 0" ); //set old address address oldBtcPriceProviderAddress = address(priceProviderInterface); //update interface address priceProviderInterface = V1PriceOracleInterface(priceProviderAddress); //emit event emit PriceOracleAdapterUpdated( oldBtcPriceProviderAddress, address(priceProviderInterface) ); } /** * @notice Set the key oracle address of cToken address * @param cTokenAddress address of key ctoken * @param keyOracle address of key oracle */ function setKeyOracle(address cTokenAddress, address keyOracle) public { require( msg.sender == guardian, "PriceOracleAdapterCompound: only guardian may set the address" ); require( cTokenAddress != address(0), "PriceOracleAdapterCompound: cTokenAddress could not be 0" ); require( keyOracle != address(0), "PriceOracleAdapterCompound: keyOracle could not be 0" ); //set old address address oldBtcPriceProviderAddress = address( oracleKeyAddress[cTokenAddress] ); //update key address oracleKeyAddress[cTokenAddress] = keyOracle; //emit event emit PriceOracleKeyUpdated( oldBtcPriceProviderAddress, address(oracleKeyAddress[cTokenAddress]), cTokenAddress ); } /** * @notice Set the price of SAI, permanently * @param price The price for SAI */ function setSaiPrice(uint256 price) public { require(msg.sender == guardian, "only guardian may set the SAI price"); require(saiPrice == 0, "SAI price may only be set once"); require(price < 0.1e18, "SAI price must be < 0.1 ETH"); saiPrice = price; } }
* @notice Set the price of SAI, permanently @param price The price for SAI/
function setSaiPrice(uint256 price) public { require(msg.sender == guardian, "only guardian may set the SAI price"); require(saiPrice == 0, "SAI price may only be set once"); require(price < 0.1e18, "SAI price must be < 0.1 ETH"); saiPrice = price; }
15,858,500
[ 1, 694, 326, 6205, 434, 17127, 45, 16, 16866, 715, 225, 6205, 1021, 6205, 364, 17127, 45, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 13928, 10658, 5147, 12, 11890, 5034, 6205, 13, 1071, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 11026, 2779, 16, 315, 3700, 11026, 2779, 2026, 444, 326, 17127, 45, 6205, 8863, 203, 3639, 2583, 12, 87, 10658, 5147, 422, 374, 16, 315, 5233, 45, 6205, 2026, 1338, 506, 444, 3647, 8863, 203, 3639, 2583, 12, 8694, 411, 374, 18, 21, 73, 2643, 16, 315, 5233, 45, 6205, 1297, 506, 411, 374, 18, 21, 512, 2455, 8863, 203, 3639, 7864, 77, 5147, 273, 6205, 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 ]
// SPDX-License-Identifier: Apache-2.0 pragma solidity >=0.6.4 <0.8.0; pragma experimental ABIEncoderV2; //import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.3.0/contracts/math/SafeMath.sol"; //import "https://github.com/vigilance91/solidarity/libraries/bytes/BytesConstraints.sol"; import "https://github.com/vigilance91/solidarity/libraries/bytes32/Bytes32Logic.sol"; import "https://github.com/vigilance91/solidarity/libraries/bytes32/Bytes32Constraints.sol"; //import "https://github.com/vigilance91/solidarity/libraries/string/stringLogic.sol"; import "https://github.com/vigilance91/solidarity/libraries/string/stringUtilities.sol"; //import "https://github.com/vigilance91/solidarity/libraries/address/AddressConstraints.sol"; //import "https://github.com/vigilance91/solidarity/libraries/unsigned/uint256Logic.sol"; import "https://github.com/vigilance91/solidarity/libraries/unsigned/uint256Constraints.sol"; import "https://github.com/vigilance91/solidarity/libraries/unsigned/uint256ToString.sol"; /// /// @title mixinChainId /// @author Tyler R. Drury <[email protected]> (www.twitter.com/StudiosVigil) - copyright 16/9/2021, All Rights Reserved /// @dev ChainID mixin implementation /// library mixinChainId { using LogicConstraints for bool; //using SafeMath for uint256; using Bytes32Logic for bytes32; using Bytes32Constraints for bytes32; using uint256Logic for uint256; using uint256Constraints for uint256; using uint256ToString for uint256; using StringLogic for string; using StringConstraints for string; using stringUtilities for string; //using BytesLogic for bytes; //using BytesConstraints for bytes; struct ChainIdStorage{ uint256 id; bytes32 rawHash; //hash of packed binary encoded chainId bytes32 idHash; //hash of the decimal string of this chainId bytes bytesPacked; //binary encoded uint256 value of chainid string idString; //decimal string of chainId (used in combination with salting nonces and contract address hashes) } bytes32 internal constant STORAGE_SLOT = keccak256("solidarity.mixin.CHAIN_ID.STORAGE_SLOT"); /// ///getters /// function storageChainId( )internal pure returns( ChainIdStorage storage ret ){ bytes32 slot = STORAGE_SLOT; assembly { ret_slot := slot } } function chainId( )internal pure returns( uint256 chain ){ assembly { chain := chainid() } } //function chainId( //bytes32 slot //)internal view returns( //bytes32 //){ //return storageChainId().chainId; //} function rawHash( )internal view returns( bytes32 ){ return storageChainId().rawHash; } function idHash( )internal view returns( bytes32 ){ return storageChainId().idHash; } function idString( )internal view returns( string memory ){ return storageChainId().idString; } /// ///logic /// function chainIdEqual( uint256 id )public pure returns( bool ){ return chainId().equal(id); } //function chainIdNotEqual( //uint256 id //)public pure returns( //bool //){ //return chainId().notEqual(id); //} // function idStringEqual( string memory id )internal view returns( bool ){ return idString().equal(id); } //function idStringNotEqual( //string memory id //)internal view returns( //bool //){ //return idString().notEqual(id); //} // function chainHashEqual( bytes32 hash )internal view returns( bool ){ return idHash().equal(hash); } //function chainHashNotEqual( //bytes32 hash //)internal view returns( //bool //){ //return idHash().notEqual(hash); //} function requireVerifyRawHash( )internal view { ChainIdStorage storage SCID = storageChainId(); // //SCID.bytesPacked.requireNotEmpty(); SCID.rawHash.requireNotEmpty(); //Null(); // SCID.rawHash.requireEqual( keccak256(SCID.bytesPacked) ); } function requireVerifyHash( )internal view { ChainIdStorage storage SCID = storageChainId(); // //SCID.idString.requireNotEmpty(); SCID.idHash.requireNotEmpty(); //Null(); SCID.idHash.requireEqual( SCID.idString.hash() ); } /// ///setters /// function isSet( )internal view returns( bool ){ ChainIdStorage storage SCID = storageChainId(); return (SCID.id.greaterThanZero() && SCID.rawHash.notEmpty() && SCID.idHash.notEmpty() && // //SCID.bytesPacked.requireNotEmpty() && SCID.idString.notEmpty() ); } function setChainId( )internal { isSet().requireFalse(); ChainIdStorage storage SCID = storageChainId(); //SCID.id.requireIsZero(); //SCID.rawHash.requireEmpty(); //requireNull(); //SCID.idHash.requireEmpty(); //requireNull(); // //SCID.bytesPack.requireEmpty(); //SCID.idString.requireEmpty(); SCID.id = chainId(); SCID.id.requireGreaterThanZero(); SCID.bytesPacked = abi.encodePacked(SCID.id); SCID.rawHash = keccak256(SCID.bytesPacked); // SCID.idString = SCID.id.decimal(); SCID.idHash = SCID.idString.hash(); } function unsetChainId( )internal { isSet().requireTrue(); ChainIdStorage storage SCID = storageChainId(); delete SCID.id; // delete SCID.bytesPacked; delete SCID.rawHash; // delete SCID.idString; delete SCID.idHash; } } //library mixinChainIdList //{ //using SafeMath for uint256; //using bytes32Constraints for bytes32; //using uint256Constraints for unit256; //using uint256ToString for uint256; //using stringUtilities for string; //struct ChainIdListStorage{ //mapping(string=>mixinChainId.ChainIdStorage) namedMap; //mixinChainId.ChainIdStorage[] list; //} //} //abstract contract ChainListABC //{ //} //contract EthereumChainList is ChainListABC //{ //constructor( //mixinChainId. [] memory //)public //ChainIdListABC( //({name:'mainnet', chainInfo:mixinChainId.()}), // //({name:'ropsten', chainInfo:mixinChainId.()}), //({name:'kovan', chainInfo:mixinChainId.()}), //({name:'rinkeby', chainInfo:mixinChainId.()}), //({name:'goeril', chainInfo:mixinChainId.()}), //... //) //} //contract EthereumPolygonChainList is EthereumChainList //{ //constructor( //mixinChainId. [] memory //)public //EthereumChainIdList( //mixinChainId.() //){ //} //} //contract EthereumBSCChainList is EthereumChainList //{ //constructor( //mixinChainId. [] memory //)public //EthereumChainIdList( //mixinChainId.() //){ //} //} ////contract EthereumTOMOChainList is EthereumChainList ////{ ////constructor( ////mixinChainId. [] memory ////)public ////EthereumChainIdList( ////mixinChainId.() ////){ // ////} ////} //contract EthereumTronChainList is EthereumChainList //{ //constructor( //mixinChainId. [] memory //)public //EthereumChainIdList( //mixinChainId.() //){ //} //} //contract EthereumXDAIChainList is EthereumChainList //{ //constructor( //mixinChainId. [] memory //)public //EthereumChainIdList( //mixinChainId.() //){ //} //} //contract EthereumArbitrumChainList is EthereumChainList //{ //constructor( //mixinChainId. [] memory //)public //EthereumChainIdList( //mixinChainId.() //){ //} //} //contract EthereumOptimismChainList is EthereumChainList //{ //constructor( //mixinChainId. [] memory //)public //EthereumChainIdList( //mixinChainId.() //){ //} //} //contract AllChainList is EthereumChainList //{ //constructor( //)public //EthereumChainIdList( //({name:'polygon', chainInfo:mixinChainId.()}), //({name:'bsc', chainInfo:mixinChainId.()}), // //({name:'tomo', chainInfo:mixinChainId.()}), //({name:'tron', chainInfo:mixinChainId.()}), // //({name:'xdai', chainInfo:mixinChainId.()}), // //({name:'arbitrum',chainInfo:mixinChainId.()}), //({name:'optimism',chainInfo:mixinChainId.()}), // //({name:'avalanche',chainInfo:mixinChainId.()}), //({name:'fantom',chainInfo:mixinChainId.()}), // //({name:'harmony',chainInfo:mixinChainId.()}), ////({name:'ht',chainInfo:mixinChainId.()}) //){ //} //}
decimal string of chainId (used in combination with salting nonces and contract address hashes)
string idString;
15,814,632
[ 1, 12586, 533, 434, 2687, 548, 261, 3668, 316, 10702, 598, 12814, 1787, 1661, 764, 471, 6835, 1758, 9869, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 533, 612, 780, 31, 377, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// Sources flattened with hardhat v2.6.8 https://hardhat.org // File contracts/IERC165.sol // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /* Fully commented standard ERC721 Distilled from OpenZeppelin Docs Base for Building ERC721 by Martin McConnell All the utility without the fluff. */ interface IERC165 { function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File contracts/IERC721.sol pragma solidity ^0.8.0; 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`. 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/IERC721Receiver.sol pragma solidity ^0.8.0; interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4); } // File contracts/IERC721Metadata.sol pragma solidity ^0.8.0; interface IERC721Metadata is IERC721 { //@dev Returns the token collection name. function name() external view returns (string memory); //@dev Returns the token collection symbol. function symbol() external view returns (string memory); //@dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. function tokenURI(uint256 tokenId) external view returns (string memory); } // File contracts/Context.sol pragma solidity ^0.8.0; abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File contracts/Ownable.sol pragma solidity ^0.8.0; abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File contracts/Functional.sol pragma solidity ^0.8.0; abstract contract Functional { 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); } bool private _reentryKey = false; modifier reentryLock { require(!_reentryKey, "attempt to reenter a locked function"); _reentryKey = true; _; _reentryKey = false; } } // File contracts/Address.sol pragma solidity ^0.8.0; library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) private pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File contracts/ControlledAccess.sol pragma solidity ^0.8.0; /* @title ControlledAccess * @dev The ControlledAccess contract allows function to be restricted to users * that possess a signed authorization from the owner of the contract. This signed * message includes the user to give permission to and the contract address to prevent * reusing the same authorization message on different contract with same owner. */ contract ControlledAccess is Ownable { address public signerAddress; /* * @dev Requires msg.sender to have valid access message. * @param _v ECDSA signature parameter v. * @param _r ECDSA signature parameters r. * @param _s ECDSA signature parameters s. */ modifier onlyValidAccess( bytes32 _r, bytes32 _s, uint8 _v ) { require(isValidAccessMessage(msg.sender, _r, _s, _v)); _; } function setSignerAddress(address newAddress) external onlyOwner { signerAddress = newAddress; } /* * @dev Verifies if message was signed by owner to give access to _add for this contract. * Assumes Geth signature prefix. * @param _add Address of agent with access * @param _v ECDSA signature parameter v. * @param _r ECDSA signature parameters r. * @param _s ECDSA signature parameters s. * @return Validity of access message for a given address. */ function isValidAccessMessage( address _add, bytes32 _r, bytes32 _s, uint8 _v ) public view returns (bool) { bytes32 hash = keccak256(abi.encode(owner(), _add)); bytes32 message = keccak256( abi.encodePacked("\x19Ethereum Signed Message:\n32", hash) ); address sig = ecrecover(message, _v, _r, _s); require(signerAddress == sig, "Signature does not match"); return signerAddress == sig; } } // File contracts/SODA.sol // ****************************************************************************************************************************** // ************************************************** Start of Main Contract *************************************************** // ****************************************************************************************************************************** pragma solidity ^0.8.0; contract SODA is IERC721, Ownable, Functional, ControlledAccess { using Address for address; // Token name string private _name; // Token symbol string private _symbol; // URI Root Location for Json Files string private _baseURI; // Provenance hash proving random distribution string public provenanceHash; // 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; // Specific Functionality bool public mintActive; bool public presaleActive; uint256 public price; uint256 public totalTokens; uint256 public numberMinted; uint256 public maxPerWallet; uint256 public maxPerTx; uint256 public reservedTokens; uint256 public startingIndex; uint256 public startingIndexBlock; mapping(address => uint256) private _tokensMintedby; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor() { _name = "Society of Derivative Apes"; _symbol = "SODA"; mintActive = false; presaleActive = false; totalTokens = 9999; // 0-9998 price = 0.04 ether; maxPerWallet = 6; maxPerTx = 3; reservedTokens = 100; // reserved for giveaways and such } //@dev See {IERC165-supportsInterface}. Interfaces Supported by this Standard function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || interfaceId == type(IERC165).interfaceId || interfaceId == SODA.onERC721Received.selector; } // Standard Withdraw function for the owner to pull the contract function withdraw() external onlyOwner { uint256 sendAmount = address(this).balance; address founders = payable(0x62F9ACbD11350FB05B3215507dD1f6e05ed27aF5); address liam = payable(0x3C31abE4b91c9e8bD39fB505CD98c59fc78cD8E6); address drew = payable(0x30A8Bac5AED69b9fF46d4fC04A48388cDe5D3A59); address yeti = payable(0xDF808192A2cb234e276eEF4551228e422a5b6B1A); address community = payable(0x9fcDD9A89C0a5F8933659077b0Caf2c1EF20ac21); bool success; (success, ) = founders.call{value: ((sendAmount * 51)/100)}(""); require(success, "Transaction Unsuccessful"); (success, ) = liam.call{value: ((sendAmount * 13)/100)}(""); require(success, "Transaction Unsuccessful"); (success, ) = drew.call{value: ((sendAmount * 13)/100)}(""); require(success, "Transaction Unsuccessful"); (success, ) = yeti.call{value: ((sendAmount * 13)/100)}(""); require(success, "Transaction Unsuccessful"); (success, ) = community.call{value: ((sendAmount * 10)/100)}(""); require(success, "Transaction Unsuccessful"); } function airDrop(address[] memory _to) external onlyOwner { uint256 qty = _to.length; require((numberMinted + qty) > numberMinted, "Math overflow error"); require((numberMinted + qty) < totalTokens, "Cannot fill order"); uint256 mintSeedValue = numberMinted; if (reservedTokens >= qty) { reservedTokens -= qty; } else { reservedTokens = 0; } for(uint256 i = 0; i < qty; i++) { _safeMint(_to[i], mintSeedValue + i); numberMinted ++; //reservedTokens can be reset, numberMinted can not } } function mint(uint256 qty) external payable reentryLock { require(mintActive); require((qty + reservedTokens + numberMinted) < totalTokens, "Mint: Not enough availability"); require(qty <= maxPerTx, "Mint: Max tokens per transaction exceeded"); require((_tokensMintedby[_msgSender()] + qty) <= maxPerWallet, "Mint: Max tokens per wallet exceeded"); require(msg.value >= qty * price, "Mint: Insufficient Funds"); uint256 mintSeedValue = numberMinted; //Store the starting value of the mint batch //Handle ETH transactions uint256 cashIn = msg.value; uint256 cashChange = cashIn - (qty * price); //send tokens for(uint256 i = 0; i < qty; i++) { _safeMint(_msgSender(), mintSeedValue + i); numberMinted ++; _tokensMintedby[_msgSender()] ++; } if (cashChange > 0){ (bool success, ) = msg.sender.call{value: cashChange}(""); require(success, "Mint: unable to send change to user"); } } function presaleMint(uint256 qty, bytes32 _r, bytes32 _s, uint8 _v ) external payable onlyValidAccess(_r, _s, _v) reentryLock { require(presaleActive); require((_tokensMintedby[_msgSender()] + qty) <= maxPerTx, "Presale Mint: Max tokens during presale exceeded"); require((qty + reservedTokens + numberMinted) < totalTokens, "Mint: Not enough availability"); require(msg.value >= qty * price, "Mint: Insufficient Funds"); uint256 mintSeedValue = numberMinted; //Store the starting value of the mint batch //Handle ETH transactions uint256 cashIn = msg.value; uint256 cashChange = cashIn - (qty * price); //send tokens for(uint256 i = 0; i < qty; i++) { _safeMint(_msgSender(), mintSeedValue + i); numberMinted ++; _tokensMintedby[_msgSender()] ++; } if (cashChange > 0){ (bool success, ) = msg.sender.call{value: cashChange}(""); require(success, "Mint: unable to send change to user"); } } // allows holders to burn their own tokens if desired /* function burn(uint256 tokenID) external { require(_msgSender() == ownerOf(tokenID)); _burn(tokenID); } */ ////////////////////////////////////////////////////////////// //////////////////// Setters and Getters ///////////////////// ////////////////////////////////////////////////////////////// function setMaxPerWallet(uint256 maxWallet) external onlyOwner { maxPerWallet = maxWallet; } function setMaxPerTx(uint256 newMax) external onlyOwner { maxPerTx = newMax; } function setBaseURI(string memory newURI) public onlyOwner { _baseURI = newURI; } function activateMint() public onlyOwner { mintActive = true; } function activatePresale() public onlyOwner { presaleActive = true; } function deactivateMint() public onlyOwner { mintActive = false; } function deactivatePresale() public onlyOwner { presaleActive = false; } function setPrice(uint256 newPrice) public onlyOwner { price = newPrice; } function setTotalTokens(uint256 numTokens) public onlyOwner { totalTokens = numTokens; } function totalSupply() external view returns (uint256) { return numberMinted; } function getBalance(address tokenAddress) view external returns (uint256) { return _balances[tokenAddress]; } /** * @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 {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( msg.sender == owner || isApprovedForAll(owner, msg.sender), "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 != msg.sender, "ERC721: approve to caller"); _operatorApprovals[msg.sender][operator] = approved; emit ApprovalForAll(msg.sender, 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(msg.sender, 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(msg.sender, 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 = 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 = 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(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(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(msg.sender, from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } // *********************** ERC721 Token Receiver ********************** /** * @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) { //InterfaceID=0x150b7a02 return this.onERC721Received.selector; } /** * @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 {} // **************************************** Metadata Standard Functions ********** //@dev Returns the token collection name. function name() external view returns (string memory){ return _name; } //@dev Returns the token collection symbol. function symbol() external view returns (string memory){ return _symbol; } //@dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. function tokenURI(uint256 tokenId) external view returns (string memory){ require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); return string(abi.encodePacked(_baseURI, toString(tokenId), ".json")); /// 0.json 135.json } function contractURI() public view returns (string memory) { return string(abi.encodePacked(_baseURI,"contract.json")); } function setProvenanceHash(string calldata hash) public onlyOwner { provenanceHash = hash; } /** * Set the starting index for the collection */ function setStartingIndex() public onlyOwner { require(startingIndex == 0, "Starting index is already set"); require(startingIndexBlock != 0, "Starting index block must be set"); startingIndex = uint256(blockhash(startingIndexBlock)) % totalTokens; // Just a sanity case in the worst case if this function is called late (EVM only stores last 256 block hashes) if (block.number % startingIndexBlock > 255) { startingIndex = uint256(blockhash(block.number - 1)) % totalTokens; } // Prevent default sequence if (startingIndex == 0) { startingIndex = startingIndex + 1; } } /** * Set the starting index block for the collection, essentially unblocking * setting starting index */ function setStartingIndexBlock() public onlyOwner { require(startingIndex == 0, "Starting index is already set"); startingIndexBlock = block.number; } receive() external payable {} fallback() external payable {} }
Handle ETH transactionssend tokens
function mint(uint256 qty) external payable reentryLock { require(mintActive); require((qty + reservedTokens + numberMinted) < totalTokens, "Mint: Not enough availability"); require(qty <= maxPerTx, "Mint: Max tokens per transaction exceeded"); require((_tokensMintedby[_msgSender()] + qty) <= maxPerWallet, "Mint: Max tokens per wallet exceeded"); require(msg.value >= qty * price, "Mint: Insufficient Funds"); uint256 cashIn = msg.value; uint256 cashChange = cashIn - (qty * price); for(uint256 i = 0; i < qty; i++) { _safeMint(_msgSender(), mintSeedValue + i); numberMinted ++; _tokensMintedby[_msgSender()] ++; } if (cashChange > 0){ require(success, "Mint: unable to send change to user"); } }
315,880
[ 1, 3259, 512, 2455, 2492, 1049, 409, 2430, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 26667, 13, 3903, 8843, 429, 283, 4099, 2531, 288, 203, 3639, 2583, 12, 81, 474, 3896, 1769, 203, 3639, 2583, 12443, 85, 4098, 397, 8735, 5157, 397, 1300, 49, 474, 329, 13, 411, 2078, 5157, 16, 315, 49, 474, 30, 2288, 7304, 13395, 8863, 203, 3639, 2583, 12, 85, 4098, 1648, 943, 2173, 4188, 16, 315, 49, 474, 30, 4238, 2430, 1534, 2492, 12428, 8863, 203, 3639, 2583, 12443, 67, 7860, 49, 474, 329, 1637, 63, 67, 3576, 12021, 1435, 65, 397, 26667, 13, 1648, 943, 2173, 16936, 16, 315, 49, 474, 30, 4238, 2430, 1534, 9230, 12428, 8863, 203, 3639, 2583, 12, 3576, 18, 1132, 1545, 26667, 380, 6205, 16, 315, 49, 474, 30, 22085, 11339, 478, 19156, 8863, 203, 203, 203, 3639, 2254, 5034, 276, 961, 382, 273, 1234, 18, 1132, 31, 203, 3639, 2254, 5034, 276, 961, 3043, 273, 276, 961, 382, 300, 261, 85, 4098, 380, 6205, 1769, 203, 203, 3639, 364, 12, 11890, 5034, 277, 273, 374, 31, 277, 411, 26667, 31, 277, 27245, 288, 203, 5411, 389, 4626, 49, 474, 24899, 3576, 12021, 9334, 312, 474, 12702, 620, 397, 277, 1769, 203, 5411, 1300, 49, 474, 329, 965, 31, 203, 5411, 389, 7860, 49, 474, 329, 1637, 63, 67, 3576, 12021, 1435, 65, 965, 31, 203, 3639, 289, 203, 203, 3639, 309, 261, 71, 961, 3043, 405, 374, 15329, 203, 5411, 2583, 12, 4768, 16, 315, 49, 474, 30, 13496, 358, 1366, 2549, 358, 729, 8863, 203, 3639, 289, 203, 565, 2 ]
./full_match/11155111/0xA09B2Cd71a377671EDD9d1ABFb53A3F716e6D7d3/sources/src/SampleContract.sol
@dev Initialize contract.
constructor(string memory _name, string memory _symbol) ERC721A(_name, _symbol) { _owner = msg.sender; } MODIFIER
3,805,101
[ 1, 7520, 6835, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1080, 3778, 389, 529, 16, 533, 3778, 389, 7175, 13, 4232, 39, 27, 5340, 37, 24899, 529, 16, 389, 7175, 13, 288, 203, 3639, 389, 8443, 273, 1234, 18, 15330, 31, 203, 565, 289, 203, 203, 4766, 5375, 8663, 10591, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0xE9F0a0a787CEEA82f1c8fE7A783826eBD181e707/sources/packages/contracts-core/contracts/governance/GovernanceRouter.sol
* @notice Handle Nomad messages For all non-Governor chains to handle messages sent from the Governor chain via Nomad. Governor chain should never receive messages, because non-Governor chains are not able to send them @param _origin The domain (of the Governor Router) @param _sender The message sender (must be the Governor Router) @param _message The message/
function handle( uint32 _origin, bytes32 _sender, bytes memory _message ) external override onlyReplica onlyGovernorRouter(_origin, _sender) { bytes29 _msg = _message.ref(0); bytes29 _view = _msg.tryAsBatch(); if (_view.notNull()) { _handleBatch(_view); return; } _view = _msg.tryAsTransferGovernor(); if (_view.notNull()) { _handleTransferGovernor(_view); return; } require(false, "!valid message type"); }
15,740,876
[ 1, 3259, 423, 362, 361, 2743, 2457, 777, 1661, 17, 43, 1643, 29561, 13070, 358, 1640, 2743, 3271, 628, 326, 611, 1643, 29561, 2687, 3970, 423, 362, 361, 18, 611, 1643, 29561, 2687, 1410, 5903, 6798, 2743, 16, 2724, 1661, 17, 43, 1643, 29561, 13070, 854, 486, 7752, 358, 1366, 2182, 225, 389, 10012, 1021, 2461, 261, 792, 326, 611, 1643, 29561, 9703, 13, 225, 389, 15330, 1021, 883, 5793, 261, 11926, 506, 326, 611, 1643, 29561, 9703, 13, 225, 389, 2150, 1021, 883, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1640, 12, 203, 3639, 2254, 1578, 389, 10012, 16, 203, 3639, 1731, 1578, 389, 15330, 16, 203, 3639, 1731, 3778, 389, 2150, 203, 565, 262, 3903, 3849, 1338, 14222, 1338, 43, 1643, 29561, 8259, 24899, 10012, 16, 389, 15330, 13, 288, 203, 3639, 1731, 5540, 389, 3576, 273, 389, 2150, 18, 1734, 12, 20, 1769, 203, 3639, 1731, 5540, 389, 1945, 273, 389, 3576, 18, 698, 1463, 4497, 5621, 203, 3639, 309, 261, 67, 1945, 18, 902, 2041, 10756, 288, 203, 5411, 389, 4110, 4497, 24899, 1945, 1769, 203, 5411, 327, 31, 203, 3639, 289, 203, 3639, 389, 1945, 273, 389, 3576, 18, 698, 1463, 5912, 43, 1643, 29561, 5621, 203, 3639, 309, 261, 67, 1945, 18, 902, 2041, 10756, 288, 203, 5411, 389, 4110, 5912, 43, 1643, 29561, 24899, 1945, 1769, 203, 5411, 327, 31, 203, 3639, 289, 203, 3639, 2583, 12, 5743, 16, 17528, 877, 883, 618, 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 ]
// hevm: flattened sources of src/DssSpell.sol pragma solidity =0.6.12 >=0.5.12 >=0.6.12 <0.7.0; ////// lib/dss-exec-lib/src/DssExecLib.sol // SPDX-License-Identifier: AGPL-3.0-or-later // // DssExecLib.sol -- MakerDAO Executive Spellcrafting Library // // Copyright (C) 2020 Maker Ecosystem Growth Holdings, Inc. // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero 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 Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. /* pragma solidity ^0.6.12; */ /* pragma experimental ABIEncoderV2; */ interface Fileable { function file(bytes32, address) external; function file(bytes32, uint256) external; function file(bytes32, bytes32, uint256) external; function file(bytes32, bytes32, address) external; } interface ChainlogLike { function setVersion(string calldata) external; function setIPFS(string calldata) external; function setSha256sum(string calldata) external; function getAddress(bytes32) external view returns (address); function setAddress(bytes32, address) external; function removeAddress(bytes32) external; } library DssExecLib { function vat() public view returns (address) {} function cat() public view returns (address) {} function pot() public view returns (address) {} function vow() public view returns (address) {} function end() public view returns (address) {} function reg() public view returns (address) {} function spotter() public view returns (address) {} function flipperMom() public view returns (address) {} function flip(bytes32) public view returns (address) {} function getChangelogAddress(bytes32) public view returns (address) {} function setChangelogAddress(bytes32, address) public {} function setChangelogVersion(string memory) public {} function authorize(address, address) public {} function deauthorize(address, address) public {} function canCast(uint40, bool) public pure returns (bool) {} function nextCastTime(uint40, uint40, bool) public pure returns (uint256) {} function setContract(address, bytes32, address) public {} function setContract(address, bytes32, bytes32, address) public {} function addReaderToOSMWhitelist(address, address) public {} function removeReaderFromOSMWhitelist(address, address) public {} } ////// lib/dss-exec-lib/src/DssAction.sol // // DssAction.sol -- DSS Executive Spell Actions // // Copyright (C) 2020 Maker Ecosystem Growth Holdings, Inc. // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero 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 Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. abstract contract DssAction { using DssExecLib for *; // Modifier used to limit execution time when office hours is enabled modifier limited { require(DssExecLib.canCast(uint40(block.timestamp), officeHours()), "Outside office hours"); _; } // Office Hours defaults to true by default. // To disable office hours, override this function and // return false in the inherited action. function officeHours() public virtual returns (bool) { return true; } // DssExec calls execute. We limit this function subject to officeHours modifier. function execute() external limited { actions(); } // DssAction developer must override `actions()` and place all actions to be called inside. // The DssExec function will call this subject to the officeHours limiter // By keeping this function public we allow simulations of `execute()` on the actions outside of the cast time. function actions() public virtual; // Returns the next available cast time function nextCastTime(uint256 eta) external returns (uint256 castTime) { require(eta <= uint40(-1)); castTime = DssExecLib.nextCastTime(uint40(eta), uint40(block.timestamp), officeHours()); } } ////// lib/dss-exec-lib/src/DssExec.sol // // DssExec.sol -- MakerDAO Executive Spell Template // // Copyright (C) 2020 Maker Ecosystem Growth Holdings, Inc. // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero 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 Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. /* pragma solidity ^0.6.12; */ interface PauseAbstract { function delay() external view returns (uint256); function plot(address, bytes32, bytes calldata, uint256) external; function exec(address, bytes32, bytes calldata, uint256) external returns (bytes memory); } interface Changelog { function getAddress(bytes32) external view returns (address); } interface SpellAction { function officeHours() external view returns (bool); function nextCastTime(uint256) external view returns (uint256); } contract DssExec { Changelog constant public log = Changelog(0xdA0Ab1e0017DEbCd72Be8599041a2aa3bA7e740F); uint256 public eta; bytes public sig; bool public done; bytes32 immutable public tag; address immutable public action; uint256 immutable public expiration; PauseAbstract immutable public pause; // Provides a descriptive tag for bot consumption // This should be modified weekly to provide a summary of the actions // Hash: seth keccak -- "$(wget https://<executive-vote-canonical-post> -q -O - 2>/dev/null)" string public description; function officeHours() external view returns (bool) { return SpellAction(action).officeHours(); } function nextCastTime() external view returns (uint256 castTime) { return SpellAction(action).nextCastTime(eta); } // @param _description A string description of the spell // @param _expiration The timestamp this spell will expire. (Ex. now + 30 days) // @param _spellAction The address of the spell action constructor(string memory _description, uint256 _expiration, address _spellAction) public { pause = PauseAbstract(log.getAddress("MCD_PAUSE")); description = _description; expiration = _expiration; action = _spellAction; sig = abi.encodeWithSignature("execute()"); bytes32 _tag; // Required for assembly access address _action = _spellAction; // Required for assembly access assembly { _tag := extcodehash(_action) } tag = _tag; } function schedule() public { require(now <= expiration, "This contract has expired"); require(eta == 0, "This spell has already been scheduled"); eta = now + PauseAbstract(pause).delay(); pause.plot(action, tag, sig, eta); } function cast() public { require(!done, "spell-already-cast"); done = true; pause.exec(action, tag, sig, eta); } } ////// lib/dss-interfaces/src/dss/ClipAbstract.sol /// ClipAbstract.sol -- Clip Interface // Copyright (C) 2021 Maker Ecosystem Growth Holdings, INC. // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero 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 Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. /* pragma solidity >=0.5.12; */ interface ClipAbstract { function wards(address) external view returns (uint256); function rely(address) external; function deny(address) external; function ilk() external view returns (bytes32); function vat() external view returns (address); function dog() external view returns (address); function vow() external view returns (address); function spotter() external view returns (address); function calc() external view returns (address); function buf() external view returns (uint256); function tail() external view returns (uint256); function cusp() external view returns (uint256); function chip() external view returns (uint64); function tip() external view returns (uint192); function chost() external view returns (uint256); function kicks() external view returns (uint256); function active(uint256) external view returns (uint256); function sales(uint256) external view returns (uint256,uint256,uint256,address,uint96,uint256); function stopped() external view returns (uint256); function file(bytes32,uint256) external; function file(bytes32,address) external; function kick(uint256,uint256,address,address) external returns (uint256); function redo(uint256,address) external; function take(uint256,uint256,uint256,address,bytes calldata) external; function count() external view returns (uint256); function list() external view returns (uint256[] memory); function getStatus(uint256) external view returns (bool,uint256,uint256,uint256); function upchost() external; function yank(uint256) external; } ////// lib/dss-interfaces/src/dss/ClipperMomAbstract.sol /* pragma solidity >=0.5.12; */ // https://github.com/makerdao/Clipper-mom/blob/master/src/ClipperMom.sol interface ClipperMomAbstract { function owner() external view returns (address); function authority() external view returns (address); function locked(address) external view returns (uint256); function tolerance(address) external view returns (uint256); function spotter() external view returns (address); function setOwner(address) external; function setAuthority(address) external; function setPriceTolerance(address, uint256) external; function setBreaker(address, uint256, uint256) external; function tripBreaker(address) external; } ////// lib/dss-interfaces/src/dss/DogAbstract.sol /// DogAbstract.sol -- Dog Interface // Copyright (C) 2021 Maker Ecosystem Growth Holdings, INC. // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero 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 Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. /* pragma solidity >=0.5.12; */ interface DogAbstract { function wards(address) external view returns (uint256); function rely(address) external; function deny(address) external; function vat() external view returns (address); function ilks(bytes32) external view returns (address,uint256,uint256,uint256); function vow() external view returns (address); function live() external view returns (uint256); function Hole() external view returns (uint256); function Dirt() external view returns (uint256); function file(bytes32,address) external; function file(bytes32,uint256) external; function file(bytes32,bytes32,uint256) external; function file(bytes32,bytes32,address) external; function chop(bytes32) external view returns (uint256); function bark(bytes32,address,address) external returns (uint256); function digs(bytes32,uint256) external; function cage() external; } ////// lib/dss-interfaces/src/dss/ESMAbstract.sol /* pragma solidity >=0.5.12; */ // https://github.com/makerdao/esm/blob/master/src/ESM.sol interface ESMAbstract { function gem() external view returns (address); function end() external view returns (address); function proxy() external view returns (address); function min() external view returns (uint256); function sum(address) external view returns (address); function Sum() external view returns (uint256); function revokesGovernanceAccess() external view returns (bool); function fire() external; function deny(address) external; function join(uint256) external; function burn() external; } ////// lib/dss-interfaces/src/dss/EndAbstract.sol /* pragma solidity >=0.5.12; */ // https://github.com/makerdao/dss/blob/master/src/end.sol interface EndAbstract { function wards(address) external view returns (uint256); function rely(address) external; function deny(address) external; function vat() external view returns (address); function cat() external view returns (address); function dog() external view returns (address); function vow() external view returns (address); function pot() external view returns (address); function spot() external view returns (address); function live() external view returns (uint256); function when() external view returns (uint256); function wait() external view returns (uint256); function debt() external view returns (uint256); function tag(bytes32) external view returns (uint256); function gap(bytes32) external view returns (uint256); function Art(bytes32) external view returns (uint256); function fix(bytes32) external view returns (uint256); function bag(address) external view returns (uint256); function out(bytes32, address) external view returns (uint256); function WAD() external view returns (uint256); function RAY() external view returns (uint256); function file(bytes32, address) external; function file(bytes32, uint256) external; function cage() external; function cage(bytes32) external; function skip(bytes32, uint256) external; function snip(bytes32, uint256) external; function skim(bytes32, address) external; function free(bytes32) external; function thaw() external; function flow(bytes32) external; function pack(uint256) external; function cash(bytes32, uint256) external; } ////// lib/dss-interfaces/src/dss/IlkRegistryAbstract.sol /* pragma solidity >=0.5.12; */ // https://github.com/makerdao/ilk-registry interface IlkRegistryAbstract { function wards(address) external view returns (uint256); function rely(address) external; function deny(address) external; function vat() external view returns (address); function dog() external view returns (address); function cat() external view returns (address); function spot() external view returns (address); function ilkData(bytes32) external view returns ( uint96, address, address, uint8, uint96, address, address, string memory, string memory ); function ilks() external view returns (bytes32[] memory); function ilks(uint) external view returns (bytes32); function add(address) external; function remove(bytes32) external; function update(bytes32) external; function removeAuth(bytes32) external; function file(bytes32, address) external; function file(bytes32, bytes32, address) external; function file(bytes32, bytes32, uint256) external; function file(bytes32, bytes32, string calldata) external; function count() external view returns (uint256); function list() external view returns (bytes32[] memory); function list(uint256, uint256) external view returns (bytes32[] memory); function get(uint256) external view returns (bytes32); function info(bytes32) external view returns ( string memory, string memory, uint256, uint256, address, address, address, address ); function pos(bytes32) external view returns (uint256); function class(bytes32) external view returns (uint256); function gem(bytes32) external view returns (address); function pip(bytes32) external view returns (address); function join(bytes32) external view returns (address); function xlip(bytes32) external view returns (address); function dec(bytes32) external view returns (uint256); function symbol(bytes32) external view returns (string memory); function name(bytes32) external view returns (string memory); function put(bytes32, address, address, uint256, uint256, address, address, string calldata, string calldata) external; } ////// src/DssSpell.sol // Copyright (C) 2021 Maker Ecosystem Growth Holdings, INC. // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero 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 Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. /* pragma solidity 0.6.12; */ /* import {Fileable, ChainlogLike} from "dss-exec-lib/DssExecLib.sol"; */ /* import "dss-exec-lib/DssExec.sol"; */ /* import "dss-exec-lib/DssAction.sol"; */ /* import "dss-interfaces/dss/IlkRegistryAbstract.sol"; */ /* import "dss-interfaces/dss/DogAbstract.sol"; */ /* import "dss-interfaces/dss/ClipAbstract.sol"; */ /* import "dss-interfaces/dss/ClipperMomAbstract.sol"; */ /* import "dss-interfaces/dss/EndAbstract.sol"; */ /* import "dss-interfaces/dss/ESMAbstract.sol"; */ contract DssSpellAction is DssAction { // Provides a descriptive tag for bot consumption // This should be modified weekly to provide a summary of the actions // Hash: seth keccak -- "$(wget https://raw.githubusercontent.com/makerdao/community/6f9bc23e6862ef798bf61349fb06e529703171bd/governance/votes/Executive%20vote%20-%20April%2019%2C%202021.md -q -O - 2>/dev/null)" string public constant description = "2021-04-19 MakerDAO Executive Spell | Hash: 0xc92979935a4ecb8f1d8e76c77aaac43ea3aa46a21545dbeb47a104e77323ae6f"; // Addresses address constant MCD_DOG = 0x135954d155898D42C90D2a57824C690e0c7BEf1B; address constant MCD_END = 0xBB856d1742fD182a90239D7AE85706C2FE4e5922; address constant MCD_ESM = 0x29CfBd381043D00a98fD9904a431015Fef07af2f; address constant ILK_REGISTRY = 0x5a464C28D19848f44199D003BeF5ecc87d090F87; address constant CLIPPER_MOM = 0x79FBDF16b366DFb14F66cE4Ac2815Ca7296405A0; address constant MCD_CLIP_LINK_A = 0x832Dd5f17B30078a5E46Fdb8130A68cBc4a74dC0; address constant MCD_CLIP_CALC_LINK_A = 0x7B1696677107E48B152e9Bf400293e98B7D86Eb1; uint256 constant THOUSAND = 10**3; uint256 constant MILLION = 10**6; uint256 constant WAD = 10**18; uint256 constant RAY = 10**27; uint256 constant RAD = 10**45; function actions() public override { address MCD_VAT = DssExecLib.vat(); address MCD_CAT = DssExecLib.cat(); address MCD_VOW = DssExecLib.vow(); address MCD_POT = DssExecLib.pot(); address MCD_SPOT = DssExecLib.spotter(); address MCD_END_OLD = DssExecLib.end(); address MCD_FLIP_LINK_A = DssExecLib.flip("LINK-A"); address ILK_REGISTRY_OLD = DssExecLib.reg(); address PIP_LINK = DssExecLib.getChangelogAddress("PIP_LINK"); // ------------------ END ------------------ // Set contracts in END DssExecLib.setContract(MCD_END, "vat", MCD_VAT); DssExecLib.setContract(MCD_END, "cat", MCD_CAT); DssExecLib.setContract(MCD_END, "dog", MCD_DOG); DssExecLib.setContract(MCD_END, "vow", MCD_VOW); DssExecLib.setContract(MCD_END, "pot", MCD_POT); DssExecLib.setContract(MCD_END, "spot", MCD_SPOT); // Authorize the new END in contracts DssExecLib.authorize(MCD_VAT, MCD_END); DssExecLib.authorize(MCD_CAT, MCD_END); DssExecLib.authorize(MCD_DOG, MCD_END); DssExecLib.authorize(MCD_VOW, MCD_END); DssExecLib.authorize(MCD_POT, MCD_END); DssExecLib.authorize(MCD_SPOT, MCD_END); // Set wait time in END Fileable(MCD_END).file("wait", EndAbstract(MCD_END_OLD).wait()); // Deauthorize the old END in contracts DssExecLib.deauthorize(MCD_VAT, MCD_END_OLD); DssExecLib.deauthorize(MCD_CAT, MCD_END_OLD); DssExecLib.deauthorize(MCD_VOW, MCD_END_OLD); DssExecLib.deauthorize(MCD_POT, MCD_END_OLD); DssExecLib.deauthorize(MCD_SPOT, MCD_END_OLD); // Deauthorize the old END from all the FLIPS // Authorize the new END in all the FLIPS bytes32[] memory ilks = IlkRegistryAbstract(ILK_REGISTRY_OLD).list(); address[] memory flips = new address[](ilks.length); for (uint256 i = 0; i < ilks.length; i++) { bytes32 ilk = ilks[i]; address flip = DssExecLib.flip(ilk); flips[i] = flip; DssExecLib.deauthorize(flip, MCD_END_OLD); DssExecLib.authorize(flip, MCD_END); try DssExecLib.removeReaderFromOSMWhitelist(IlkRegistryAbstract(ILK_REGISTRY_OLD).pip(ilk), MCD_END_OLD) {} catch {} try DssExecLib.addReaderToOSMWhitelist(IlkRegistryAbstract(ILK_REGISTRY_OLD).pip(ilk), MCD_END) {} catch {} } // ------------------ ESM ------------------ require(ESMAbstract(MCD_ESM).min() == 75_000 * WAD, "DssSpell/error-esm-min"); require(ESMAbstract(MCD_ESM).end() == MCD_END, "DssSpell/error-esm-end"); require(ESMAbstract(MCD_ESM).gem() == DssExecLib.getChangelogAddress("MCD_GOV"), "DssSpell/error-esm-gov"); require(ESMAbstract(MCD_ESM).proxy() == address(this), "DssSpell/error-esm-proxy"); // Authorize new ESM to execute in new END DssExecLib.authorize(MCD_END, MCD_ESM); // Authorize new ESM to execute in VAT DssExecLib.authorize(MCD_VAT, MCD_ESM); // Make every flipper relies the MCD_ESM for (uint256 i = 0; i < flips.length; i++) { DssExecLib.authorize(flips[i], MCD_ESM); } // ------------------ DOG ------------------ require(DogAbstract(MCD_DOG).vat() == MCD_VAT, "DssSpell/error-dog-vat"); // Set VOW in the DOG DssExecLib.setContract(MCD_DOG, "vow", MCD_VOW); // Authorize DOG can access to VAT DssExecLib.authorize(MCD_VAT, MCD_DOG); // Authorize DOG can access to VOW DssExecLib.authorize(MCD_VOW, MCD_DOG); Fileable(MCD_DOG).file("Hole", 100 * MILLION * RAD); // -------------- CLIPPER_MOM -------------- require(ClipperMomAbstract(CLIPPER_MOM).spotter() == MCD_SPOT, "DssSpell/error-clipper-mom-spotter"); ClipperMomAbstract(CLIPPER_MOM).setAuthority(DssExecLib.getChangelogAddress("MCD_ADM")); // ---------------- LINK-A ----------------- require(ClipAbstract(MCD_CLIP_LINK_A).vat() == MCD_VAT, "DssSpell/error-clip-vat"); require(ClipAbstract(MCD_CLIP_LINK_A).dog() == MCD_DOG, "DssSpell/error-clip-dog"); require(ClipAbstract(MCD_CLIP_LINK_A).spotter() == MCD_SPOT, "DssSpell/error-clip-spot"); require(ClipAbstract(MCD_CLIP_LINK_A).ilk() == "LINK-A", "DssSpell/error-clip-ilk"); // Set CLIP for LINK-A in the DOG DssExecLib.setContract(MCD_DOG, "LINK-A", "clip", MCD_CLIP_LINK_A); // Set VOW in the LINK-A CLIP DssExecLib.setContract(MCD_CLIP_LINK_A, "vow", MCD_VOW); // Set CALC in the LINK-A CLIP DssExecLib.setContract(MCD_CLIP_LINK_A, "calc", MCD_CLIP_CALC_LINK_A); // Authorize CLIP can access to VAT DssExecLib.authorize(MCD_VAT, MCD_CLIP_LINK_A); // Authorize CLIP can access to DOG DssExecLib.authorize(MCD_DOG, MCD_CLIP_LINK_A); // Authorize DOG can kick auctions on CLIP DssExecLib.authorize(MCD_CLIP_LINK_A, MCD_DOG); // Authorize the new END to access the LINK CLIP DssExecLib.authorize(MCD_CLIP_LINK_A, MCD_END); // Authorize CLIPPERMOM can set the stopped flag in CLIP DssExecLib.authorize(MCD_CLIP_LINK_A, CLIPPER_MOM); // Authorize new ESM to execute in LINK-A Clipper DssExecLib.authorize(MCD_CLIP_LINK_A, MCD_ESM); // Whitelist CLIP in the LINK osm DssExecLib.addReaderToOSMWhitelist(PIP_LINK, MCD_CLIP_LINK_A); // Whitelist CLIPPER_MOM in the LINK osm DssExecLib.addReaderToOSMWhitelist(PIP_LINK, CLIPPER_MOM); // No more auctions kicked via the CAT: DssExecLib.deauthorize(MCD_FLIP_LINK_A, MCD_CAT); // No more circuit breaker for the FLIP in LINK-A: DssExecLib.deauthorize(MCD_FLIP_LINK_A, DssExecLib.flipperMom()); Fileable(MCD_DOG).file("LINK-A", "hole", 6 * MILLION * RAD); Fileable(MCD_DOG).file("LINK-A", "chop", 113 * WAD / 100); Fileable(MCD_CLIP_LINK_A).file("buf", 130 * RAY / 100); Fileable(MCD_CLIP_LINK_A).file("tail", 140 minutes); Fileable(MCD_CLIP_LINK_A).file("cusp", 40 * RAY / 100); Fileable(MCD_CLIP_LINK_A).file("chip", 1 * WAD / 1000); Fileable(MCD_CLIP_LINK_A).file("tip", 0); Fileable(MCD_CLIP_CALC_LINK_A).file("cut", 99 * RAY / 100); // 1% cut Fileable(MCD_CLIP_CALC_LINK_A).file("step", 90 seconds); // Tolerance currently set to 50%. // n.b. 600000000000000000000000000 == 40% acceptable drop ClipperMomAbstract(CLIPPER_MOM).setPriceTolerance(MCD_CLIP_LINK_A, 50 * RAY / 100); ClipAbstract(MCD_CLIP_LINK_A).upchost(); // Replace flip to clip in the ilk registry DssExecLib.setContract(ILK_REGISTRY, "LINK-A", "xlip", MCD_CLIP_LINK_A); Fileable(ILK_REGISTRY).file("LINK-A", "class", 1); // ------------------ CHAINLOG ----------------- address log = DssExecLib.getChangelogAddress("CHANGELOG"); DssExecLib.setChangelogAddress("MCD_DOG", MCD_DOG); DssExecLib.setChangelogAddress("MCD_END", MCD_END); DssExecLib.setChangelogAddress("MCD_ESM", MCD_ESM); DssExecLib.setChangelogAddress("CLIPPER_MOM", CLIPPER_MOM); DssExecLib.setChangelogAddress("MCD_CLIP_LINK_A", MCD_CLIP_LINK_A); DssExecLib.setChangelogAddress("MCD_CLIP_CALC_LINK_A", MCD_CLIP_CALC_LINK_A); DssExecLib.setChangelogAddress("ILK_REGISTRY", ILK_REGISTRY); ChainlogLike(log).removeAddress("MCD_FLIP_LINK_A"); DssExecLib.setChangelogVersion("1.3.0"); } } contract DssSpell is DssExec { DssSpellAction internal action_ = new DssSpellAction(); constructor() DssExec(action_.description(), block.timestamp + 30 days, address(action_)) public {} }
Authorize DOG can access to VOW
DssExecLib.authorize(MCD_VOW, MCD_DOG);
14,888,471
[ 1, 18987, 5467, 43, 848, 2006, 358, 776, 7306, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 463, 1049, 1905, 5664, 18, 22488, 12, 49, 10160, 67, 58, 7306, 16, 490, 10160, 67, 3191, 43, 1769, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/8453/0x2A0979257105834789bC6b9E1B00446DFbA8dFBa/sources/@aave/core-v3/contracts/misc/AaveProtocolDataProvider.sol
@inheritdoc IPoolDataProvider
function getUnbackedMintCap(address asset) external view override returns (uint256) { return IPool(ADDRESSES_PROVIDER.getPool()).getConfiguration(asset).getUnbackedMintCap(); }
11,545,462
[ 1, 36, 10093, 467, 2864, 20757, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 10833, 823, 329, 49, 474, 4664, 12, 2867, 3310, 13, 3903, 1476, 3849, 1135, 261, 11890, 5034, 13, 288, 203, 565, 327, 467, 2864, 12, 8355, 7031, 1090, 55, 67, 26413, 18, 588, 2864, 1435, 2934, 588, 1750, 12, 9406, 2934, 588, 984, 823, 329, 49, 474, 4664, 5621, 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 ]
./full_match/8453/0x94E69ef94BE77b98BF22F54784F2151a5084A3AB/sources/contracts/libraries/UniswapV2Library.sol
performs chained getAmountOut calculations on any number of pairs
function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) { require(path.length >= 2, 'UniswapV2Library: INVALID_PATH'); amounts = new uint[](path.length); amounts[0] = amountIn; for (uint i; i < path.length - 1; i++) { ICamelotPair pair = ICamelotPair(pairFor(factory, path[i], path[i + 1])); amounts[i + 1] = pair.getAmountOut(amounts[i], path[i]); } }
11,558,894
[ 1, 457, 9741, 20269, 24418, 1182, 20882, 603, 1281, 1300, 434, 5574, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 24418, 87, 1182, 12, 2867, 3272, 16, 2254, 3844, 382, 16, 1758, 8526, 3778, 589, 13, 2713, 1476, 1135, 261, 11890, 8526, 3778, 30980, 13, 288, 203, 3639, 2583, 12, 803, 18, 2469, 1545, 576, 16, 296, 984, 291, 91, 438, 58, 22, 9313, 30, 10071, 67, 4211, 8284, 203, 3639, 30980, 273, 394, 2254, 8526, 12, 803, 18, 2469, 1769, 203, 3639, 30980, 63, 20, 65, 273, 3844, 382, 31, 203, 3639, 364, 261, 11890, 277, 31, 277, 411, 589, 18, 2469, 300, 404, 31, 277, 27245, 288, 203, 5411, 467, 16373, 352, 4154, 3082, 273, 467, 16373, 352, 4154, 12, 6017, 1290, 12, 6848, 16, 589, 63, 77, 6487, 589, 63, 77, 397, 404, 5717, 1769, 203, 5411, 30980, 63, 77, 397, 404, 65, 273, 3082, 18, 588, 6275, 1182, 12, 8949, 87, 63, 77, 6487, 589, 63, 77, 19226, 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 ]
/** *Submitted for verification at Etherscan.io on 2020-11-08 */ // SPDX-License-Identifier: MIT /** * Stop The Steal Token * stopthesteal.finance * help Trump win back the White House **/ pragma solidity ^0.6.0; 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) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { 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; } } abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } function owner() public view returns (address) { return _owner; } modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } 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); } contract StopTheSteal is Ownable, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; uint256 private _taxFee; uint256 private _uniswapSellTaxFee; uint256 private _maxFee; address private _storeAddress; address private _stakeAddress; uint256 private _maxTransactionAmount; address private _UNIWethPoolAddress; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol, uint256 totalSupply, uint256 taxFee, uint256 uniswapSellTaxFee, uint256 maxTransactionAmount) public { _name = name; _symbol = symbol; _decimals = 18; _taxFee = taxFee; _uniswapSellTaxFee = uniswapSellTaxFee; _maxFee = _taxFee >= _uniswapSellTaxFee ? _taxFee : _uniswapSellTaxFee; _maxTransactionAmount = maxTransactionAmount; _UNIWethPoolAddress = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this)); //main net // _UNIWethPoolAddress = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xc778417E063141139Fce010982780140Aa0cD5Ab, address(this)); //ropsten test net //_UNIWethPoolAddress = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xd0A1E359811322d97991E03f863a0C30C2cF029C, address(this)); //kovan test net _mint(_msgSender(), totalSupply); } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { uint256 sellTaxAmount; if(spender == _UNIWethPoolAddress) { sellTaxAmount = amount.mul(_maxFee).div(100); } _approve(_msgSender(), spender, amount.add(sellTaxAmount)); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); if(_maxFee > 0) require(_storeAddress != address(0), "ERC20: store address is not set yet."); _beforeTokenTransfer(sender, recipient, amount); if(recipient != owner() && sender != owner()) { if(recipient != _UNIWethPoolAddress && recipient != _stakeAddress && recipient != _storeAddress && (sender == _UNIWethPoolAddress || sender == _stakeAddress || sender == _storeAddress )) { if(sender != _storeAddress) require(amount <= _maxTransactionAmount, "ERC20: transfer amount exceeds limit"); } else if(sender != _UNIWethPoolAddress && sender != _stakeAddress && sender != _storeAddress && recipient == _stakeAddress) { require(amount <= _maxTransactionAmount, "ERC20: transfer amount exceeds limit"); } else require(false, "ERC20: users(not owner) can only stake, unstake, claim or buy from uniswap."); } uint256 taxAmount; uint256 transfAmount; if(recipient == _UNIWethPoolAddress) { taxAmount = amount.mul(_maxFee).div(100); transfAmount = amount; } else { taxAmount = amount.mul(_taxFee).div(100); transfAmount = amount.sub(taxAmount); } _balances[sender] = _balances[sender].sub(transfAmount.add(taxAmount), "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(transfAmount); emit Transfer(sender, recipient, transfAmount); if(taxAmount > 0) { _balances[_storeAddress] = _balances[_storeAddress].add(taxAmount); emit Transfer(sender, _storeAddress, taxAmount); } } function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } function maxTransactionAmount() external view returns (uint256) { return _maxTransactionAmount; } /** * @dev returns sorted token addresses, used to handle return values from pairs sorted in this order */ function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) { require(tokenA != tokenB, 'UniswapV2Library: IDENTICAL_ADDRESSES'); (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), 'UniswapV2Library: ZERO_ADDRESS'); } /** * @dev calculates the CREATE2 address for a pair without making any external calls */ function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = sortTokens(tokenA, tokenB); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash )))); } }
* @dev Sets {decimals} to a value other than the default one of 18. WARNING: This function should only be called from the constructor. Most applications that interact with token contracts will not expect {decimals} to ever change, and may work incorrectly if it does./
function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; }
7,008,295
[ 1, 2785, 288, 31734, 97, 358, 279, 460, 1308, 2353, 326, 805, 1245, 434, 6549, 18, 9744, 30, 1220, 445, 1410, 1338, 506, 2566, 628, 326, 3885, 18, 22099, 12165, 716, 16592, 598, 1147, 20092, 903, 486, 4489, 288, 31734, 97, 358, 14103, 2549, 16, 471, 2026, 1440, 25621, 309, 518, 1552, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 8401, 31809, 12, 11890, 28, 15105, 67, 13, 2713, 288, 203, 3639, 389, 31734, 273, 15105, 67, 31, 203, 565, 289, 203, 377, 203, 377, 203, 7010, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.24; /** * @title ERC20 * @dev ERC20 Contract interface(s) */ contract ERC20 { function balanceOf (address _owner) public constant returns (uint256 balance); function transfer ( address _to, uint256 _value) public returns (bool success); function transferFrom (address _from, address _to, uint256 _value) public returns (bool success); function approve (address _spender, uint256 _value) public returns (bool success); function allowance (address _owner, address _spender) public constant returns (uint256 remaining); function totalSupply () public constant returns (uint); event Transfer (address indexed _from, address indexed _to, uint _value); event Approval (address indexed _owner, address indexed _spender, uint _value); } /** * @title TokenRecipient */ interface TokenRecipient { /* fundtion definitions */ function receiveApproval (address _from, uint256 _value, address _token, bytes _extraData) external; } /** * @title SafeMath math library * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev 'a + b', Adds two numbers, throws on overflow */ function add (uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; require (c >= a); return c; } /** * @dev 'a - b', Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend) */ function sub (uint256 a, uint256 b) internal pure returns (uint256 c) { require (a >= b); c = a - b; return c; } /** * @dev 'a * b', multiplies two numbers, throws on overflow */ function mul (uint256 a, uint256 b) internal pure returns (uint256 c) { c = a * b; require (a == 0 || c / a == b); return c; } /** * @dev 'a / b', Integer division of two numbers, truncating the quotient */ function div (uint256 a, uint256 b) internal pure returns (uint256 c) { require (b > 0); c = a / b; return c; } } /** * @title ERC20Token * @dev Implementation of the ERC20 Token */ contract ERC20Token is ERC20 { using SafeMath for uint256; /* balance of each account */ mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; string public name; string public symbol; uint8 public decimals; uint256 public totalSupply; /** * @dev Creates a ERC20 Contract with its name, symbol, decimals, and total supply of token * @param _name name of token * @param _symbol name of symbol * @param _decimals decimals * @param _initSupply total supply of tokens */ constructor (string _name, string _symbol, uint8 _decimals, uint256 _initSupply) public { name = _name; // set the name for display purpose symbol = _symbol; // set the symbol for display purpose decimals = _decimals; // 18 decimals is the strongly suggested totalSupply = _initSupply * (10 ** uint256 (decimals)); // update total supply with the decimal amount balances[msg.sender] = totalSupply; // give the creator all initial tokens emit Transfer (address(0), msg.sender, totalSupply); } /** * @dev Get the token balance for account `_owner` */ function balanceOf (address _owner) public view returns (uint256 balance) { return balances[_owner]; } /* function to access name, symbol, decimals, total-supply of token. */ function name () public view returns (string _name ) { return name; } function symbol () public view returns (string _symbol ) { return symbol; } function decimals () public view returns (uint8 _decimals) { return decimals; } function totalSupply () public view returns (uint256 _supply ) { return totalSupply; } /** * @dev Internal transfer, only can be called by this contract */ function _transfer (address _from, address _to, uint256 _value) internal { require (_to != 0x0); // prevent transfer to 0x0 address require (balances[_from] >= _value); // check if the sender has enough require (balances[_to ] + _value > balances[_to]);// check for overflows uint256 previous = balances[_from] + balances[_to]; // save this for an assertion in the future balances[_from] = balances[_from].sub (_value); // subtract from the sender balances[_to ] = balances[_to ].add (_value); // add the same to the recipient emit Transfer (_from, _to, _value); /* Asserts are used to use static analysis to find bugs in your code. They should never fail */ assert (balances[_from] + balances[_to] == previous); } /** * @dev Transfer the balance from owner's account to another account "_to" * owner's account must have sufficient balance to transfer * 0 value transfers are allowed * @param _to The address of the recipient * @param _value The amount to send * @return true if the operation was successful. */ function transfer (address _to, uint256 _value) public returns (bool success) { _transfer (msg.sender, _to, _value); return true; } /** * @dev Send `_value` amount of tokens from `_from` account to `_to` account * The calling account must already have sufficient tokens approved for * spending from the `_from` account * @param _from The address of the sender * @param _to The address of the recipient * @param _value The amount to send * @return true if the operation was successful. */ function transferFrom (address _from, address _to, uint256 _value) public returns (bool success) { require (allowed[_from][msg.sender] >= _value); // check allowance allowed [_from][msg.sender] = allowed [_from][msg.sender].sub (_value); _transfer (_from, _to, _value); return true; } /** * @dev Get the amount of tokens approved by the owner that can be transferred * to the spender's account * @param _owner The address owner * @param _spender The address authorized to spend * @return The amount of tokens remained for the approved by the owner that can * be transferred */ function allowance (address _owner, address _spender) public constant returns (uint remaining) { return allowed[_owner][_spender]; } /** * @dev Set allowance for other address * 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. * Token owner can approve for `spender` to transferFrom (...) `tokens` * from the token owner's account * @param _spender The address authorized to spend * @param _value the max amount they can spend * @return true if the operation was successful. */ function approve (address _spender, uint256 _value) public returns (bool success) { allowed[msg.sender][_spender] = _value; emit Approval (msg.sender, _spender, _value); return true; } /** * @dev Set allowance for other address and notify * Allows `_spender` to spend no more than `_value` tokens in your behalf, * and then ping the contract about it * @param _spender the address authorized to spend * @param _value the max amount they can spend * @param _extraData some extra information to send to the approved contract * @return true if the operation was successful. */ function approveAndCall (address _spender, uint256 _value, bytes _extraData) public returns (bool success) { TokenRecipient spender = TokenRecipient (_spender); if (approve (_spender, _value)) { spender.receiveApproval (msg.sender, _value, address (this), _extraData); return true; } } } /** * @title Ownable * @notice For user and inter-contract ownership and safe ownership transfers. * @dev The Ownable contract has an owner address, and provides basic * authorization control functions */ contract Ownable { address public owner; /* the address of the contract's owner */ /* logged on change & renounce of owner */ event OwnershipTransferred (address indexed _owner, address indexed _to); event OwnershipRenounced (address indexed _owner); /** * @dev Sets the original 'owner' of the contract to the sender account */ constructor () public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner */ modifier onlyOwner { require (msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a '_to' * @param _to The address to transfer ownership to */ function transferOwnership (address _to) public onlyOwner { require (_to != address(0)); emit OwnershipTransferred (owner, _to); owner = _to; } /** * @dev Allows the current owner to relinquish control of the contract. * This will remove all ownership of the contract, _safePhrase must * be equal to "This contract is to be disowned" * @param _safePhrase Input string to prevent one's mistake */ function renounceOwnership (bytes32 _safePhrase) public onlyOwner { require (_safePhrase == "This contract is to be disowned."); emit OwnershipRenounced (owner); owner = address(0); } } /** * @title ExpERC20Token */ contract ExpERC20Token is ERC20Token, Ownable { /** * @dev Creates a ERC20 Contract with its name, symbol, decimals, and total supply of token * @param _name name of token * @param _symbol name of symbol * @param _decimals decimals * @param _initSupply total supply of tokens */ constructor ( string _name, // name of token string _symbol, // name of symbol uint8 _decimals, // decimals uint256 _initSupply // total supply of tokens ) ERC20Token (_name, _symbol, _decimals, _initSupply) public {} /** * @notice Only the creator can alter the name & symbol * @param _name newer token name to be changed * @param _symbol newer token symbol to be changed */ function changeName (string _name, string _symbol) onlyOwner public { name = _name; symbol = _symbol; } /* ====================================================================== * Burnable functions */ /* This notifies clients about the amount burnt */ event Burn (address indexed from, uint256 value); /** * Internal burn, only can be called by this contract */ function _burn (address _from, uint256 _value) internal { require (balances[_from] >= _value); // check if the sender has enough balances[_from] = balances[_from].sub (_value); // subtract from the sender totalSupply = totalSupply.sub (_value); // updates totalSupply emit Burn (_from, _value); } /** * @dev remove `_value` tokens from the system irreversibly * @param _value the amount of money to burn * @return true if the operation was successful. */ function burn (uint256 _value) public returns (bool success) { _burn (msg.sender, _value); return true; } /** * @dev remove `_value` tokens from the system irreversibly on behalf of `_from` * @param _from the address of the sender * @param _value the amount of money to burn * @return true if the operation was successful. */ function burnFrom (address _from, uint256 _value) public returns (bool success) { require (allowed [_from][msg.sender] >= _value); allowed [_from][msg.sender] = allowed [_from][msg.sender].sub (_value); _burn (_from, _value); return true; } /* ====================================================================== * Mintable functions */ /* event for mint's */ event Mint (address indexed _to, uint256 _amount); event MintFinished (); bool public mintingFinished = false; /* Throws if it is not mintable status */ modifier canMint () { require (!mintingFinished); _; } /* Throws if called by any account other than the owner */ modifier hasMintPermission () { require (msg.sender == owner); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint (address _to, uint256 _amount) hasMintPermission canMint public returns (bool) { totalSupply = totalSupply.add (_amount); balances[_to] = balances[_to].add (_amount); emit Mint (_to, _amount); emit Transfer (address (0), this, _amount); emit Transfer ( this, _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting () onlyOwner canMint public returns (bool) { mintingFinished = true; emit MintFinished (); return true; } /* ====================================================================== * Lockable Token */ bool public tokenLocked = false; /* event for Token's lock or unlock */ event Lock (address indexed _target, bool _locked); mapping (address => bool) public frozenAccount; /* This generates a public event on the blockchain that will notify clients */ event FrozenFunds (address target, bool frozen); /** * @notice `freeze? Prevent | Allow` `target` from sending & receiving tokens * @param _target address to be frozen * @param _freeze either to freeze it or not */ function freezeAccount (address _target, bool _freeze) onlyOwner public { frozenAccount[_target] = _freeze; emit FrozenFunds (_target, _freeze); } /* Throws if it is not locked status */ modifier whenTokenUnlocked () { require (!tokenLocked); _; } /* Internal token-lock, only can be called by this contract */ function _lock (bool _value) internal { require (tokenLocked != _value); tokenLocked = _value; emit Lock (this, tokenLocked); } /** * @dev function to check token is lock or not */ function isTokenLocked () public view returns (bool success) { return tokenLocked; } /** * @dev function to lock/unlock this token * @param _value flag to be locked or not */ function lock (bool _value) onlyOwner public returns (bool) { _lock (_value); return true; } /** * @dev Transfer the balance from owner's account to another account "_to" * owner's account must have sufficient balance to transfer * 0 value transfers are allowed * @param _to The address of the recipient * @param _value The amount to send * @return true if the operation was successful. */ function transfer (address _to, uint256 _value) whenTokenUnlocked public returns (bool success) { require (!frozenAccount[msg.sender]); // check if sender is frozen require (!frozenAccount[_to ]); // check if recipient is frozen return super.transfer (_to, _value); } /** * @dev Send `_value` amount of tokens from `_from` account to `_to` account * The calling account must already have sufficient tokens approved for * spending from the `_from` account * @param _from The address of the sender * @param _to The address of the recipient * @param _value The amount to send * @return true if the operation was successful. */ function transferFrom (address _from, address _to, uint256 _value) whenTokenUnlocked public returns (bool success) { require (!frozenAccount[msg.sender]); // check if sender is frozen require (!frozenAccount[_from]); // check if token-owner is frozen require (!frozenAccount[_to ]); // check if recipient is frozen return super.transferFrom (_from, _to, _value); } /** * @dev Set allowance for other address * 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. * Token owner can approve for `spender` to transferFrom (...) `tokens` * from the token owner's account * @param _spender The address authorized to spend * @param _value the max amount they can spend * @return true if the operation was successful. */ function approve (address _spender, uint256 _value) whenTokenUnlocked public returns (bool success) { require (!frozenAccount[msg.sender]); // check if sender is frozen require (!frozenAccount[_spender ]); // check if token-owner is frozen return super.approve (_spender, _value); } /** * @dev Set allowance for other address and notify * Allows `_spender` to spend no more than `_value` tokens in your behalf, * and then ping the contract about it * @param _spender the address authorized to spend * @param _value the max amount they can spend * @param _extraData some extra information to send to the approved contract * @return true if the operation was successful. */ function approveAndCall (address _spender, uint256 _value, bytes _extraData) whenTokenUnlocked public returns (bool success) { require (!frozenAccount[msg.sender]); // check if sender is frozen require (!frozenAccount[_spender ]); // check if token-owner is frozen return super.approveAndCall (_spender, _value, _extraData); } /* ====================================================================== * buy & sell functions */ uint256 public sellPrice; uint256 public buyPrice; /* Internal transfer, only can be called by this contract */ function _transfer (address _from, address _to, uint _value) internal { require (_to != 0x0); // prevent transfer to 0x0 address require (balances[_from] >= _value); // check if the sender has enough require (balances[_to ] + _value >= balances[_to]); // check for overflows require (!frozenAccount[_from]); // check if sender is frozen require (!frozenAccount[_to ]); // check if recipient is frozen balances[_from] = balances[_from].sub (_value); // Subtract from the sender balances[_to ] = balances[_to ].add (_value); // Add the same to the recipient emit Transfer (_from, _to, _value); } /** * @notice allow users to buy tokens for `newBuyPrice` eth and sell tokens for `newSellPrice` eth * @param _sellPrice Price the users can sell to the contract * @param _buyPrice Price users can buy from the contract */ function setPrices (uint256 _sellPrice, uint256 _buyPrice) onlyOwner public { sellPrice = _sellPrice; buyPrice = _buyPrice ; } /** * @notice Buy tokens from contract by sending ether */ function buy () whenTokenUnlocked payable public { uint amount = msg.value / buyPrice; // calculates the amount _transfer (this, msg.sender, amount); // makes the transfers } /** * @notice sell `_amount` tokens to contract * @param _amount amount of tokens to be sold */ function sell (uint256 _amount) whenTokenUnlocked public { require (balances[this] >= _amount * sellPrice); // checks if the contract has enough ether to buy _transfer (msg.sender, this, _amount); // makes the transfers msg.sender.transfer (_amount * sellPrice); // sends ether to the seller. It's important to do this last to avoid recursion attacks } }
18 decimals is the strongly suggested
decimals = _decimals;
5,376,229
[ 1, 2643, 15105, 353, 326, 11773, 715, 22168, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 15105, 565, 273, 389, 31734, 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, -100, -100 ]
./partial_match/42/0x3538d4E1E7ce38Cb47B405ba15e54D25221003f8/sources/DEFOWhaleClub.sol
Swap the targetToken for depositToken
function voteSell() external nonReentrant{ PoolTemp memory temp; require(whaleClubInfo.whaleClubOpen, "Whale Club not yet started"); require(now >= poolInfo.voteTokenCloseTime, "Vote Buy/Sell not yet started"); require(sellStage < buyStage, "Vote Sell not found"); require(sellStage < maxStage, "Vote Sell was ended"); temp.voteWeight = userStage[buyStage][msg.sender].voteWeight; temp.voteSellUsed = userStage[buyStage][msg.sender].voteSellUsed; temp.voteRemain = temp.voteWeight - temp.voteSellUsed; _voteSell(); emit VoteSell(msg.sender, temp.voteRemain); temp.poolAmount = poolStage[sellStage].amount; temp.buyAmount = poolStage[sellStage].buyAmount; temp.poolSellVoteWeight = poolStage[sellStage].sellVoteWeight; temp.poolRate = percent(temp.poolSellVoteWeight, temp.poolAmount, 4); if(temp.poolRate >= 5000) { temp.deadline = block.timestamp + 5 minutes; temp.balanceBeforeSwap = poolInfo.depositToken.balanceOf(address(this)); temp.tokensToSwap = _getTokenAmount(address(poolInfo.targetToken), temp.buyAmount); require(temp.tokensToSwap > 0, "bad token swap"); address[] memory uniswapPath = new address[](3); uniswapPath[0] = address(poolInfo.targetToken); uniswapPath[1] = address(weth); uniswapPath[2] = address(poolInfo.depositToken); poolInfo.targetToken.safeApprove(address(uniswapRouter), 0); poolInfo.targetToken.safeApprove(address(uniswapRouter), temp.tokensToSwap); uniswapRouter.swapExactTokensForTokensSupportingFeeOnTransferTokens(temp.tokensToSwap, 0, uniswapPath, address(this), temp.deadline); temp.balanceAfterSwap = poolInfo.depositToken.balanceOf(address(this)); temp.sellAmount = temp.balanceAfterSwap - temp.balanceBeforeSwap; temp.sellAmount = _getReverseTokenAmount(address(poolInfo.depositToken), temp.sellAmount); if(temp.sellAmount > temp.poolAmount){ temp.profitAmount = temp.sellAmount - temp.poolAmount; temp.profitShareAmount = temp.profitAmount * poolInfo.profitShareRate / _divRate; temp.tokensToSwap = _getTokenAmount(address(poolInfo.depositToken), temp.profitShareAmount); uniswapPath = new address[](3); uniswapPath[0] = address(poolInfo.depositToken); uniswapPath[1] = address(weth); uniswapPath[2] = address(defhold); poolInfo.depositToken.safeApprove(address(uniswapRouter), 0); poolInfo.depositToken.safeApprove(address(uniswapRouter), temp.tokensToSwap); uniswapRouter.swapExactTokensForTokensSupportingFeeOnTransferTokens(temp.tokensToSwap, 0, uniswapPath, address(this), temp.deadline); temp.defholdAmount = defhold.balanceOf(address(this)); temp.defholdAmount = _getReverseTokenAmount(address(defhold), temp.defholdAmount); defholdPools.externalReward(temp.defholdAmount); emit PoolProfitShare(address(defholdPools), temp.defholdAmount); temp.sellAmount -= temp.profitShareAmount; } poolStage[sellStage].sellAmount = temp.sellAmount; whaleClubInfo.whaleClubNextUpdateTime = now + whaleClubInfo.whaleClubTime; nextSellStage(); } }
3,476,811
[ 1, 12521, 326, 1018, 1345, 364, 443, 1724, 1345, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 202, 915, 12501, 55, 1165, 1435, 3903, 1661, 426, 8230, 970, 95, 203, 202, 202, 2864, 7185, 3778, 1906, 31, 203, 202, 202, 6528, 12, 3350, 5349, 2009, 373, 966, 18, 3350, 5349, 2009, 373, 3678, 16, 315, 2888, 5349, 3905, 373, 486, 4671, 5746, 8863, 203, 202, 202, 6528, 12, 3338, 1545, 2845, 966, 18, 25911, 1345, 4605, 950, 16, 315, 19338, 605, 9835, 19, 55, 1165, 486, 4671, 5746, 8863, 203, 202, 202, 6528, 12, 87, 1165, 8755, 411, 30143, 8755, 16, 315, 19338, 348, 1165, 486, 1392, 8863, 203, 202, 202, 6528, 12, 87, 1165, 8755, 411, 943, 8755, 16, 315, 19338, 348, 1165, 1703, 16926, 8863, 203, 1082, 203, 202, 202, 5814, 18, 25911, 6544, 273, 729, 8755, 63, 70, 9835, 8755, 6362, 3576, 18, 15330, 8009, 25911, 6544, 31, 203, 202, 202, 5814, 18, 25911, 55, 1165, 6668, 273, 729, 8755, 63, 70, 9835, 8755, 6362, 3576, 18, 15330, 8009, 25911, 55, 1165, 6668, 31, 203, 202, 202, 5814, 18, 25911, 1933, 530, 273, 1906, 18, 25911, 6544, 300, 1906, 18, 25911, 55, 1165, 6668, 31, 203, 1082, 203, 202, 202, 67, 25911, 55, 1165, 5621, 203, 1082, 203, 202, 202, 18356, 27540, 55, 1165, 12, 3576, 18, 15330, 16, 1906, 18, 25911, 1933, 530, 1769, 203, 1082, 203, 202, 202, 5814, 18, 6011, 6275, 273, 2845, 8755, 63, 87, 1165, 8755, 8009, 8949, 31, 203, 202, 202, 5814, 18, 70, 9835, 6275, 273, 2845, 8755, 63, 87, 1165, 8755, 8009, 70, 9835, 6275, 31, 203, 202, 202, 5814, 2 ]
// SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.0; import './ERC721Tradable.sol'; import "@openzeppelin/contracts/utils/Counters.sol"; contract CuddleeCrew is ERC721Tradable { using Counters for Counters.Counter; Counters.Counter private _nextTokenId; string public baseURI; string public contractURI; uint256 public maxSupply = 20000; uint256 public cost = 0.02 ether; // Price for whitelist and first week of main sale, then 0.04 uint256 public maxMintAmount = 20; bool public paused = false; bool public mainSale = false; // Main Sale is disabled by default mapping(address => bool) public presaleAccessList; // Whitelist for pre-sale constructor( string memory _name, string memory _symbol, string memory _initBaseURI, string memory _contractURI, address _proxyRegistryAddress ) ERC721Tradable( _name, _symbol, _proxyRegistryAddress) { // nextTokenId is initialized to 1, since starting at 0 leads to higher gas cost for the first minter _nextTokenId.increment(); setBaseURI(_initBaseURI); setContractURI(_contractURI); mint(100); // Mint first 100 for team } function setBaseURI(string memory _newBaseURI) public onlyOwner { baseURI = _newBaseURI; } // internal function _baseURI() internal view virtual override returns (string memory) { return baseURI; } function setContractURI(string memory _contractURI) public onlyOwner { contractURI = _contractURI; } // public function mint(uint256 _mintAmount) public payable { require(!paused, "paused"); uint256 supply = totalSupply(); require(_mintAmount > 0, "Need to Mint 1 or More"); require(supply + _mintAmount <= maxSupply, "Max NFTs minted."); if (msg.sender != owner()) { if(!mainSale){ require(hasPresaleAccess(msg.sender), "You are not whitelisted for the Cuddlee Crew pre-sale, wait opening main sale"); } require(_mintAmount <= maxMintAmount, "You can only Mint 20"); require(msg.value >= cost * _mintAmount, "Insufficient Funds"); } for (uint256 i = 1; i <= _mintAmount; i++) { uint256 currentTokenId = _nextTokenId.current(); _nextTokenId.increment(); _safeMint(msg.sender, currentTokenId); } } function setCost(uint256 _newCost) public onlyOwner { cost = _newCost; } function pause(bool _state) public onlyOwner { paused = _state; } function updateMainSaleStatus(bool _mainSale) public onlyOwner { mainSale = _mainSale; } /** @dev Returns the total tokens minted so far. 1 is always subtracted from the Counter since it tracks the next available tokenId. */ function totalSupply() public view returns (uint256) { return _nextTokenId.current() - 1; } function withdraw(uint256 _amount) public payable onlyOwner { require(payable(msg.sender).send(_amount)); } function withdrawAll() public payable onlyOwner { require(payable(msg.sender).send(address(this).balance)); } function setPresaleAccessList(address[] memory _addressList) public onlyOwner { for (uint256 i; i < _addressList.length; i++) { presaleAccessList[_addressList[i]] = true; } } function hasPresaleAccess(address wallet) public view returns (bool) { return presaleAccessList[wallet]; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "./common/meta-transactions/ContentMixin.sol"; import "./common/meta-transactions/NativeMetaTransaction.sol"; contract OwnableDelegateProxy {} /** * Used to delegate ownership of a contract to another address, to save on unneeded transactions to approve contract use for users */ 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 ERC721, ContextMixin, NativeMetaTransaction, Ownable { using SafeMath for uint256; address proxyRegistryAddress; constructor( string memory _name, string memory _symbol, address _proxyRegistryAddress ) ERC721(_name, _symbol) { proxyRegistryAddress = _proxyRegistryAddress; _initializeEIP712(_name); } // /** // * @dev Mints a token to an address with a tokenURI. // * @param _to address of the future owner of the token // */ // function mintTo(address _to) public onlyOwner { // uint256 currentTokenId = _nextTokenId.current(); // _nextTokenId.increment(); // _safeMint(_to, currentTokenId); // } function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); string memory currentBaseURI = _baseURI(); return bytes(currentBaseURI).length > 0 ? string(abi.encodePacked(currentBaseURI, Strings.toString(tokenId), ".json")) : ""; } /** * 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(); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Counters.sol) pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library Counters { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/ERC721.sol) pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/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.0; abstract contract ContextMixin { function msgSender() internal view returns (address payable sender) { if (msg.sender == address(this)) { bytes memory array = msg.data; uint256 index = msg.data.length; assembly { // Load the 32 bytes word from memory with the address on the lower 20 bytes, and mask those. sender := and( mload(add(array, index)), 0xffffffffffffffffffffffffffffffffffffffff ) } } else { sender = payable(msg.sender); } return sender; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import {EIP712Base} from "./EIP712Base.sol"; contract NativeMetaTransaction is EIP712Base { using SafeMath for uint256; bytes32 private constant META_TRANSACTION_TYPEHASH = keccak256( bytes( "MetaTransaction(uint256 nonce,address from,bytes functionSignature)" ) ); event MetaTransactionExecuted( address userAddress, address payable relayerAddress, bytes functionSignature ); mapping(address => uint256) nonces; /* * Meta transaction structure. * No point of including value field here as if user is doing value transfer then he has the funds to pay for gas * He should call the desired function directly in that case. */ struct MetaTransaction { uint256 nonce; address from; bytes functionSignature; } function executeMetaTransaction( address userAddress, bytes memory functionSignature, bytes32 sigR, bytes32 sigS, uint8 sigV ) public payable returns (bytes memory) { MetaTransaction memory metaTx = MetaTransaction({ nonce: nonces[userAddress], from: userAddress, functionSignature: functionSignature }); require( verify(userAddress, metaTx, sigR, sigS, sigV), "Signer and signature do not match" ); // increase nonce for user (to avoid re-use) nonces[userAddress] = nonces[userAddress].add(1); emit MetaTransactionExecuted( userAddress, payable(msg.sender), functionSignature ); // Append userAddress and relayer address at the end to extract it from calling context (bool success, bytes memory returnData) = address(this).call( abi.encodePacked(functionSignature, userAddress) ); require(success, "Function call not successful"); return returnData; } function hashMetaTransaction(MetaTransaction memory metaTx) internal pure returns (bytes32) { return keccak256( abi.encode( META_TRANSACTION_TYPEHASH, metaTx.nonce, metaTx.from, keccak256(metaTx.functionSignature) ) ); } function getNonce(address user) public view returns (uint256 nonce) { nonce = nonces[user]; } function verify( address signer, MetaTransaction memory metaTx, bytes32 sigR, bytes32 sigS, uint8 sigV ) internal view returns (bool) { require(signer != address(0), "NativeMetaTransaction: INVALID_SIGNER"); return signer == ecrecover( toTypedMessageHash(hashMetaTransaction(metaTx)), sigV, sigR, sigS ); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import {Initializable} from "./Initializable.sol"; contract EIP712Base is Initializable { struct EIP712Domain { string name; string version; address verifyingContract; bytes32 salt; } string constant public ERC712_VERSION = "1"; bytes32 internal constant EIP712_DOMAIN_TYPEHASH = keccak256( bytes( "EIP712Domain(string name,string version,address verifyingContract,bytes32 salt)" ) ); bytes32 internal domainSeperator; // supposed to be called once while initializing. // one of the contracts that inherits this contract follows proxy pattern // so it is not possible to do this in a constructor function _initializeEIP712( string memory name ) internal initializer { _setDomainSeperator(name); } function _setDomainSeperator(string memory name) internal { domainSeperator = keccak256( abi.encode( EIP712_DOMAIN_TYPEHASH, keccak256(bytes(name)), keccak256(bytes(ERC712_VERSION)), address(this), bytes32(getChainId()) ) ); } function getDomainSeperator() public view returns (bytes32) { return domainSeperator; } function getChainId() public view returns (uint256) { uint256 id; assembly { id := chainid() } return id; } /** * Accept message hash and returns hash message in EIP712 compatible form * So that it can be used to recover signer from signature signed using EIP712 formatted data * https://eips.ethereum.org/EIPS/eip-712 * "\\x19" makes the encoding deterministic * "\\x01" is the version byte to make it compatible to EIP-191 */ function toTypedMessageHash(bytes32 messageHash) internal view returns (bytes32) { return keccak256( abi.encodePacked("\x19\x01", getDomainSeperator(), messageHash) ); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; contract Initializable { bool inited = false; modifier initializer() { require(!inited, "already inited"); _; inited = true; } }
nextTokenId is initialized to 1, since starting at 0 leads to higher gas cost for the first minter
{ _nextTokenId.increment(); setBaseURI(_initBaseURI); setContractURI(_contractURI); }
13,756,764
[ 1, 4285, 1345, 548, 353, 6454, 358, 404, 16, 3241, 5023, 622, 374, 5871, 87, 358, 10478, 16189, 6991, 364, 326, 1122, 1131, 387, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 288, 203, 3639, 389, 4285, 1345, 548, 18, 15016, 5621, 203, 3639, 26435, 3098, 24899, 2738, 2171, 3098, 1769, 203, 3639, 444, 8924, 3098, 24899, 16351, 3098, 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 ]
// SPDX-License-Identifier: MIT pragma solidity 0.8.0; import "../nft/ModifiedErc721.sol"; /** * @author @vonie610 (Twitter & Telegram) | @Nicca42 (GitHub) * @title TreasureMaps is an NFT that facilitates the storage and execution of * treasure maps! Treasure maps are stored execution maps for * multistep onchain interactions. * @notice Treasure Maps can be created by anyone. Do not assume any level of * security measures have been taken place, and that all maps are * insecure until proven otherwise. Crypto is a wild place, look out * for yourself! */ contract TreasureMaps is ModifiedErc721 { // Counter for unique token IDs. uint256 public tokenCount_; // Storage for the two token types within this system. bytes32 constant OUTLINE = bytes32(keccak256("OUTLINE")); // Treasure maps contain the targets and target function signatures. // Storage for treasure map information. struct Outline { // The address that added this treasure map. address creator; // Array of target contract addresses. address[] callTargets; // Array of encoded function signature for execution at target. string[] callFunctionSigs; } // Token IDs (type OUTLINE) to treasure map instructions. mapping(uint256 => Outline) public outlines_; bytes32 constant TREASURE_MAPS = bytes32(keccak256("TREASURE_MAPS")); // Treasure Maps contain the function parameters and call native values. struct TreasureMap { // Array of target contract addresses. address[] callTargets; // Cost in native tokens to explore this map. uint256 callValueTotal; // Array of encoded function & parameters for execution at target. bytes[] callData; // Array of `msg.value`'s for target calls. uint[] callValues; } // Token IDs (type TREASURE_MAPS) to coordinate details. mapping(uint256 => TreasureMap) public treasureMaps_; // Creator => All created treasure maps mapping(address => uint256[]) private creatorMaps_; // FUTURE A conditional treasure outline param which will then ignore passed // in variables for the ones specified in the outline. event TreasureMapAdded( address indexed creator, uint256 indexed mapID, string description ); constructor() ModifiedErc721("Treasure Maps", "tMAP") { } /** * @param _id ID of the treasure map. * @return callTargets The array of target addresses stored in the map. * @return callValues The array of native token values for the calls stored * in the map. * @return callData The array of encoded call data stored in the map. */ function getTreasureMap(uint256 _id) public view returns( address[] memory callTargets, uint256[] memory callValues, bytes[] memory callData ) { callTargets = treasureMaps_[_id].callTargets; callValues = treasureMaps_[_id].callValues; callData = treasureMaps_[_id].callData; } /** * @param _creator Address of the map creator. * @return uint256[] Array of all the Map ID's that this creator has made. */ function getAllCreatedMaps(address _creator) public view returns(uint256[] memory) { return creatorMaps_[_creator]; } /** * @param _targetAddr Array of target contract addresses. * @param _functionSig Array of targeted function signatures at matching * address. * @param _callData Array of encoded parameters for function at target. * @param _callValues Array of `msg.value`'s for target calls. * @return treasureMapID The token ID for the treasure map created. */ function createTreasure( string calldata _description, address[] calldata _targetAddr, string[] calldata _functionSig, bytes[] calldata _callData, uint[] calldata _callValues ) external returns(uint256 treasureMapID) { treasureMapID = _addTreasureMap( msg.sender, _targetAddr, _functionSig, _callData, _callValues ); emit TreasureMapAdded( msg.sender, treasureMapID, _description ); } function createTreasureOutline( string calldata _description, address[] calldata _targetAddr, string[] calldata _functionSig ) external returns(uint256 outlineID) { outlineID = _addOutline( msg.sender, _targetAddr, _functionSig ); } function _addOutline( address _creator, address[] calldata _callTargets, string[] calldata _functionSigs ) internal returns(uint256 tokenID) { require( _callTargets.length == _functionSigs.length, "MAP: Array lengths differ" ); tokenCount_ += 1; tokenID = tokenCount_; outlines_[tokenID] = Outline({ creator: _creator, callTargets: _callTargets, callFunctionSigs: _functionSigs }); _mint(OUTLINE, _creator, tokenID); } function _addTreasureMap( address _creator, address[] calldata _callTargets, string[] calldata _functionSigs, bytes[] calldata _callData, uint256[] calldata _callValues ) internal returns(uint256 tokenID) { require( _callTargets.length == _functionSigs.length && _callData.length == _functionSigs.length && _callValues.length == _functionSigs.length, "MAP: Array lengths differ" ); tokenCount_ += 1; tokenID = tokenCount_; // Counter for map native token cost. uint256 callCost; // Storage for encoded function calls. bytes[] memory generatedCallData = new bytes[](_callTargets.length); // Transforming data for efficient storage. for (uint256 i = 0; i < _callTargets.length; i++) { // Encoding function calls (signature and data) generatedCallData[i] = abi.encodePacked( bytes4(keccak256(bytes(_functionSigs[i]))), _callData[i] ); callCost += _callValues[i]; } treasureMaps_[tokenID] = TreasureMap({ callTargets: _callTargets, callValueTotal: callCost, callData: generatedCallData, callValues: _callValues }); creatorMaps_[_creator].push(tokenID); _mint(TREASURE_MAPS, _creator, tokenID); } }
* @param _id ID of the treasure map. @return callTargets The array of target addresses stored in the map. @return callValues The array of native token values for the calls stored in the map. @return callData The array of encoded call data stored in the map./
function getTreasureMap(uint256 _id) public view returns( address[] memory callTargets, uint256[] memory callValues, bytes[] memory callData ) { callTargets = treasureMaps_[_id].callTargets; callValues = treasureMaps_[_id].callValues; callData = treasureMaps_[_id].callData; }
5,361,815
[ 1, 67, 350, 1599, 434, 326, 9787, 3619, 852, 18, 327, 225, 745, 9432, 1021, 526, 434, 1018, 6138, 4041, 316, 326, 852, 18, 327, 225, 745, 1972, 1021, 526, 434, 6448, 1147, 924, 364, 326, 4097, 4041, 1850, 316, 326, 852, 18, 327, 225, 745, 751, 1021, 526, 434, 3749, 745, 501, 4041, 316, 326, 852, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 3181, 266, 3619, 863, 12, 11890, 5034, 389, 350, 13, 1071, 1476, 1135, 12, 203, 3639, 1758, 8526, 3778, 745, 9432, 16, 203, 3639, 2254, 5034, 8526, 3778, 745, 1972, 16, 203, 3639, 1731, 8526, 3778, 745, 751, 203, 565, 262, 288, 203, 3639, 745, 9432, 273, 9787, 3619, 8903, 67, 63, 67, 350, 8009, 1991, 9432, 31, 203, 3639, 745, 1972, 273, 9787, 3619, 8903, 67, 63, 67, 350, 8009, 1991, 1972, 31, 203, 3639, 745, 751, 273, 9787, 3619, 8903, 67, 63, 67, 350, 8009, 1991, 751, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity 0.8.4; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "./interfaces/IShare.sol"; import "./interfaces/IDollar.sol"; import "./interfaces/ITreasury.sol"; import "./interfaces/IOracle.sol"; import "./interfaces/IPool.sol"; contract Pool is Ownable, ReentrancyGuard, Initializable, IPool { using SafeERC20 for ERC20; /* ========== ADDRESSES ================ */ address public oracle; address public collateral; address public dollar; address public treasury; address public share; /* ========== STATE VARIABLES ========== */ mapping(address => uint256) public redeem_share_balances; mapping(address => uint256) public redeem_collateral_balances; uint256 public pool_ceiling = 1000000001e6; // Total across all collaterals. uint256 public override unclaimed_pool_collateral; uint256 public unclaimed_pool_share; mapping(address => uint256) public last_redeemed; // Constants for various precisions uint256 private constant PRICE_PRECISION = 1e6; uint256 private constant COLLATERAL_RATIO_PRECISION = 1e6; uint256 private constant COLLATERAL_RATIO_MAX = 1e6; // 10 ** Number of decimals needed to get to 18 uint256 private missing_decimals; // Number of blocks to wait before being able to collectRedemption() uint256 public redemption_delay = 1; // AccessControl state variables bool public mint_paused = false; bool public redeem_paused = false; bool public recollat_paused = false; // Recollat related uint256 public bonus_rate = 5000; // Bonus rate on IVORY minted during recollateralize(); 6 decimals of precision mapping(uint256 => uint256) public rct_hourly_cum; // Epoch hour -> IVORY out in that hour uint256 public rct_max_share_out_per_hour = 0; // Infinite if 0 /* ========== CONSTRUCTOR ========== */ function initialize( address _dollar, address _share, address _collateral, address _treasury ) external initializer onlyOwner { dollar = _dollar; share = _share; collateral = _collateral; treasury = _treasury; missing_decimals = 10 ** (18 - ERC20(_collateral).decimals()); } /* ========== VIEWS ========== */ function info() external view returns ( uint256, uint256, uint256, bool, bool ) { return ( unclaimed_pool_collateral, // unclaimed amount of COLLATERAL unclaimed_pool_share, // unclaimed amount of SHARE getCollateralPrice(), // collateral price mint_paused, redeem_paused ); } function collateralReserve() public view returns (address) { return ITreasury(treasury).collateralReserve(); } function getCollateralPrice() public view override returns (uint256) { return IOracle(oracle).consult(); } /* ========== PUBLIC FUNCTIONS ========== */ function mint( uint256 _collateral_amount, uint256 _share_amount, uint256 _dollar_out_min ) external nonReentrant { require(mint_paused == false, "Minting is paused"); (, uint256 _share_price, , uint256 _tcr, , , uint256 _minting_fee, ) = ITreasury(treasury).info(); require(_share_price > 0, "Invalid share price"); // Don't take in more collateral than the pool ceiling for this token allows require((ITreasury(treasury).globalCollateralBalance() + _collateral_amount) <= pool_ceiling, "Pool ceiling"); uint256 _price_collateral = getCollateralPrice(); uint256 _total_dollar_value = 0; uint256 _required_share_amount = 0; if (_tcr > 0) { uint256 _collateral_value = ((_collateral_amount * missing_decimals) * _price_collateral) / PRICE_PRECISION; _total_dollar_value = (_collateral_value * COLLATERAL_RATIO_PRECISION) / _tcr; if (_tcr < COLLATERAL_RATIO_MAX) { _required_share_amount = ((_total_dollar_value - _collateral_value) * PRICE_PRECISION) / _share_price; } } else { _total_dollar_value = (_share_amount * _share_price) / PRICE_PRECISION; _required_share_amount = _share_amount; } uint256 _actual_dollar_amount = _total_dollar_value - ((_total_dollar_value * _minting_fee) / PRICE_PRECISION); require(_dollar_out_min <= _actual_dollar_amount, "slippage"); if (_required_share_amount > 0) { require(_required_share_amount <= _share_amount, "Not enough SHARE input"); IShare(share).poolBurnFrom(msg.sender, _required_share_amount); } if (_collateral_amount > 0) { _transferCollateralToReserve(msg.sender, _collateral_amount); } IDollar(dollar).poolMint(msg.sender, _actual_dollar_amount); } function redeem( uint256 _dollar_amount, uint256 _share_out_min, uint256 _collateral_out_min ) external nonReentrant { require(redeem_paused == false, "Redeeming is paused"); (, uint256 _share_price, , , uint256 _ecr, , , uint256 _redemption_fee) = ITreasury(treasury).info(); uint256 _collateral_price = getCollateralPrice(); require(_collateral_price > 0, "Invalid collateral price"); require(_share_price > 0, "Invalid share price"); uint256 _dollar_amount_post_fee = _dollar_amount - ((_dollar_amount * _redemption_fee) / PRICE_PRECISION); uint256 _collateral_output_amount = 0; uint256 _share_output_amount = 0; if (_ecr < COLLATERAL_RATIO_MAX) { uint256 _share_output_value = _dollar_amount_post_fee - ((_dollar_amount_post_fee * _ecr) / PRICE_PRECISION); _share_output_amount = (_share_output_value * PRICE_PRECISION) / _share_price; } if (_ecr > 0) { uint256 _collateral_output_value = ((_dollar_amount_post_fee * _ecr) / PRICE_PRECISION) / missing_decimals; _collateral_output_amount = (_collateral_output_value * PRICE_PRECISION) / _collateral_price; } // Check if collateral balance meets and meet output expectation uint256 _totalCollateralBalance = ITreasury(treasury).globalCollateralBalance(); require(_collateral_output_amount <= _totalCollateralBalance, "exceed total collateral balance" ); require(_collateral_out_min <= _collateral_output_amount && _share_out_min <= _share_output_amount, ">slippage"); if (_collateral_output_amount > 0) { redeem_collateral_balances[msg.sender] = redeem_collateral_balances[msg.sender] + _collateral_output_amount; unclaimed_pool_collateral = unclaimed_pool_collateral + _collateral_output_amount; } if (_share_output_amount > 0) { redeem_share_balances[msg.sender] = redeem_share_balances[msg.sender] + _share_output_amount; unclaimed_pool_share = unclaimed_pool_share + _share_output_amount; } last_redeemed[msg.sender] = block.number; // Move all external functions to the end IDollar(dollar).poolBurnFrom(msg.sender, _dollar_amount); if (_share_output_amount > 0) { _mintShareToCollateralReserve(_share_output_amount); } } function collectRedemption() external nonReentrant { require((last_redeemed[msg.sender] + redemption_delay) <= block.number, "<redemption_delay"); bool _send_share = false; bool _send_collateral = false; uint256 _share_amount; uint256 _collateral_amount; // Use Checks-Effects-Interactions pattern if (redeem_share_balances[msg.sender] > 0) { _share_amount = redeem_share_balances[msg.sender]; redeem_share_balances[msg.sender] = 0; unclaimed_pool_share = unclaimed_pool_share - _share_amount; _send_share = true; } if (redeem_collateral_balances[msg.sender] > 0) { _collateral_amount = redeem_collateral_balances[msg.sender]; redeem_collateral_balances[msg.sender] = 0; unclaimed_pool_collateral = unclaimed_pool_collateral - _collateral_amount; _send_collateral = true; } if (_send_share) { _requestTransferShare(msg.sender, _share_amount); } if (_send_collateral) { _requestTransferCollateral(msg.sender, _collateral_amount); } } // When the protocol is recollateralizing, we need to give a discount of IVORY to hit the new CR target // Thus, if the target collateral ratio is higher than the actual value of collateral, minters get IVORY for adding collateral // This function simply rewards anyone that sends collateral to a pool with the same amount of IVORY + the bonus rate // Anyone can call this function to recollateralize the protocol and take the extra IVORY value from the bonus rate as an arb opportunity function recollateralize(uint256 _collateral_amount, uint256 _share_out_min) external returns (uint256 share_out) { require(recollat_paused == false, "Recollat is paused"); // Don't take in more collateral than the pool ceiling for this token allows require((ITreasury(treasury).globalCollateralBalance() + _collateral_amount) <= pool_ceiling, "Pool ceiling"); uint256 _collateral_amount_d18 = _collateral_amount * missing_decimals; uint256 _share_price = ITreasury(treasury).sharePrice(); // Get the amount of IVORY actually available (accounts for throttling) uint256 _share_actually_available = recollatAvailableShare(); // Calculated the attempted amount of IVORY uint256 _collat_price = getCollateralPrice(); share_out = _collateral_amount_d18 * _collat_price * (PRICE_PRECISION + bonus_rate) / PRICE_PRECISION / _share_price; // Make sure there is IVORY available require(share_out <= _share_actually_available, "Insuf IVORY Avail For RCT"); // Check slippage require(share_out >= _share_out_min, "IVORY slippage"); // Take in the collateral and pay out the IVORY _transferCollateralToReserve(msg.sender, _collateral_amount); IShare(share).poolMint(msg.sender, share_out); // Increment the outbound IVORY, in E18 // Used for recollat throttling rct_hourly_cum[curEpochHr()] += share_out; emit Recollateralized(_collateral_amount, share_out); } // Returns the missing amount of collateral (in E18) needed to maintain the collateral ratio function recollatTheoColAvailableE18() public view returns (uint256) { uint256 _share_total_supply = ERC20(share).totalSupply(); (, , , uint256 _tcr, uint256 _ecr, , ,) = ITreasury(treasury).info(); uint256 _desired_collat_e24 = _tcr * _share_total_supply; uint256 _effective_collat_e24 = _ecr * _share_total_supply; // Return 0 if already overcollateralized // Otherwise, return the deficiency if (_effective_collat_e24 >= _desired_collat_e24) return 0; else { return (_desired_collat_e24 - _effective_collat_e24) / COLLATERAL_RATIO_PRECISION; } } // Returns the value of IVORY available to be used for recollats // Also has throttling to avoid dumps during large price movements function recollatAvailableShare() public view returns (uint256) { uint256 _share_price = ITreasury(treasury).sharePrice(); // Get the amount of collateral theoretically available uint256 _recollat_theo_available_e18 = recollatTheoColAvailableE18(); // Get the amount of IVORY theoretically outputtable uint256 _share_theo_out = _recollat_theo_available_e18 * PRICE_PRECISION / _share_price; // See how much IVORY has been issued this hour uint256 current_hr_rct = rct_hourly_cum[curEpochHr()]; // Account for the throttling return comboCalcBbkRct(current_hr_rct, rct_max_share_out_per_hour, _share_theo_out); } // Returns the current epoch hour function curEpochHr() public view returns (uint256) { return (block.timestamp / 3600); // Truncation desired } /* ========== INTERNAL FUNCTIONS ========== */ function _transferCollateralToReserve(address _sender, uint256 _amount) internal { address _reserve = collateralReserve(); require(_reserve != address(0), "Invalid reserve address"); ERC20(collateral).safeTransferFrom(_sender, _reserve, _amount); } function _mintShareToCollateralReserve(uint256 _amount) internal { address _reserve = collateralReserve(); require(_reserve != address(0), "Invalid reserve address"); IShare(share).poolMint(_reserve, _amount); } function _requestTransferCollateral(address _receiver, uint256 _amount) internal { ITreasury(treasury).requestTransfer(collateral, _receiver, _amount); } function _requestTransferShare(address _receiver, uint256 _amount) internal { ITreasury(treasury).requestTransfer(share, _receiver, _amount); } function comboCalcBbkRct(uint256 _cur, uint256 _max, uint256 _theo) internal pure returns (uint256) { if (_max == 0) { // If the hourly limit is 0, it means there is no limit return _theo; } else if (_cur >= _max) { // If the hourly limit has already been reached, return 0; return 0; } else { // Get the available amount uint256 _available = _max - _cur; if (_theo >= _available) { // If the the theoretical is more than the available, return the available return _available; } else { // Otherwise, return the theoretical amount return _theo; } } } /* ========== RESTRICTED FUNCTIONS ========== */ function toggleMinting() external onlyOwner { mint_paused = !mint_paused; emit MintingToggled(); } function toggleRedeeming() external onlyOwner { redeem_paused = !redeem_paused; emit RedeemingToggled(); } function toggleRecollat() external onlyOwner { recollat_paused = !recollat_paused; emit RecollatToggled(); } function setOracle(address _oracle) external onlyOwner { require(_oracle != address(0), "Invalid address"); oracle = _oracle; emit OracleUpdated(oracle); } function setRedemptionDelay(uint256 _redemption_delay) external onlyOwner { redemption_delay = _redemption_delay; emit RedemptionDelayUpdate(redemption_delay); } function setTreasury(address _treasury) external onlyOwner { require(_treasury != address(0), "Invalid address"); treasury = _treasury; emit TreasuryChanged(_treasury); } function setBonusRate(uint256 _rate) external onlyOwner { bonus_rate = _rate; emit BonusRateChanged(bonus_rate); } function setMaxPerHour(uint256 _max) external onlyOwner { rct_max_share_out_per_hour = _max; emit MaxPerHourChanged(rct_max_share_out_per_hour); } function setPoolCeiling(uint256 _ceiling) external onlyOwner { pool_ceiling = _ceiling; emit PoolCeilingChanged(_ceiling); } // EVENTS event TreasuryChanged(address indexed newTreasury); event MintingToggled(); event RedeemingToggled(); event RecollatToggled(); event OracleUpdated(address indexed newOracle); event RedemptionDelayUpdate(uint redemptionDelay); event Recollateralized(uint256 col_amount, uint256 share_out); event BonusRateChanged(uint256 rate); event MaxPerHourChanged(uint256 max); event PoolCeilingChanged(uint256 ceiling); }
Move all external functions to the end
IDollar(dollar).poolBurnFrom(msg.sender, _dollar_amount);
12,560,253
[ 1, 7607, 777, 3903, 4186, 358, 326, 679, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 1599, 25442, 12, 72, 25442, 2934, 6011, 38, 321, 1265, 12, 3576, 18, 15330, 16, 389, 72, 25442, 67, 8949, 1769, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/80001/0x7D6DC36F3A258a01E0862FC65879892AC286d177/sources/SPARTAN.sol
Create a uniswap pair for this new token set the rest of the contract variablesexclude owner and this contract from fee
constructor () public { _rOwned[_msgSender()] = _rTotal; IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x10ED43C718714eb63d5aA57B78B54704E256024E); uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); uniswapV2Router = _uniswapV2Router; _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; emit Transfer(address(0), _msgSender(), _tTotal); }
5,676,642
[ 1, 1684, 279, 640, 291, 91, 438, 3082, 364, 333, 394, 1147, 444, 326, 3127, 434, 326, 6835, 3152, 10157, 3410, 471, 333, 6835, 628, 14036, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 3885, 1832, 1071, 288, 203, 3639, 389, 86, 5460, 329, 63, 67, 3576, 12021, 1435, 65, 273, 389, 86, 5269, 31, 203, 203, 3639, 467, 984, 291, 91, 438, 58, 22, 8259, 3103, 389, 318, 291, 91, 438, 58, 22, 8259, 273, 467, 984, 291, 91, 438, 58, 22, 8259, 3103, 12, 20, 92, 2163, 2056, 8942, 39, 27, 2643, 27, 3461, 24008, 4449, 72, 25, 69, 37, 10321, 38, 8285, 38, 6564, 27, 3028, 41, 5034, 3103, 24, 41, 1769, 203, 3639, 640, 291, 91, 438, 58, 22, 4154, 273, 467, 984, 291, 91, 438, 58, 22, 1733, 24899, 318, 291, 91, 438, 58, 22, 8259, 18, 6848, 10756, 203, 3639, 263, 2640, 4154, 12, 2867, 12, 2211, 3631, 389, 318, 291, 91, 438, 58, 22, 8259, 18, 59, 1584, 44, 10663, 203, 203, 3639, 640, 291, 91, 438, 58, 22, 8259, 273, 389, 318, 291, 91, 438, 58, 22, 8259, 31, 203, 203, 3639, 389, 291, 16461, 1265, 14667, 63, 8443, 1435, 65, 273, 638, 31, 203, 3639, 389, 291, 16461, 1265, 14667, 63, 2867, 12, 2211, 25887, 273, 638, 31, 203, 203, 3639, 3626, 12279, 12, 2867, 12, 20, 3631, 389, 3576, 12021, 9334, 389, 88, 5269, 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 ]
pragma solidity ^0.5.0; import "@openzeppelin/upgrades/contracts/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 Context is Initializable { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } pragma solidity ^0.5.0; /** * @title Roles * @dev Library for managing addresses assigned to a Role. */ library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev Give an account access to this role. */ function add(Role storage role, address account) internal { require(!has(role, account), "Roles: account already has role"); role.bearer[account] = true; } /** * @dev Remove an account's access to this role. */ function remove(Role storage role, address account) internal { require(has(role, account), "Roles: account does not have role"); role.bearer[account] = false; } /** * @dev Check if an account has this role. * @return bool */ function has(Role storage role, address account) internal view returns (bool) { require(account != address(0), "Roles: account is the zero address"); return role.bearer[account]; } } pragma solidity ^0.5.0; import "@openzeppelin/upgrades/contracts/Initializable.sol"; import "../../GSN/Context.sol"; import "../Roles.sol"; contract PauserRole is Initializable, Context { using Roles for Roles.Role; event PauserAdded(address indexed account); event PauserRemoved(address indexed account); Roles.Role private _pausers; function initialize(address sender) public initializer { if (!isPauser(sender)) { _addPauser(sender); } } modifier onlyPauser() { require(isPauser(_msgSender()), "PauserRole: caller does not have the Pauser role"); _; } function isPauser(address account) public view returns (bool) { return _pausers.has(account); } function addPauser(address account) public onlyPauser { _addPauser(account); } function renouncePauser() public { _removePauser(_msgSender()); } function _addPauser(address account) internal { _pausers.add(account); emit PauserAdded(account); } function _removePauser(address account) internal { _pausers.remove(account); emit PauserRemoved(account); } uint256[50] private ______gap; } pragma solidity ^0.5.0; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * NOTE: This call _does not revert_ if the signature is invalid, or * if the signer is otherwise unable to be retrieved. In those scenarios, * the zero address is returned. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { // Check the signature length if (signature.length != 65) { revert("ECDSA: signature length is invalid"); } // Divide the signature in r, s and v variables bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solhint-disable-next-line no-inline-assembly assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { revert("ECDSA: signature.s is in the wrong range"); } if (v != 27 && v != 28) { revert("ECDSA: signature.v is in the wrong range"); } // If the signature is valid (and not malleable), return the signer address return ecrecover(hash, v, r, s); } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * replicates the behavior of the * https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`] * JSON-RPC method. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } } pragma solidity ^0.5.0; import "@openzeppelin/upgrades/contracts/Initializable.sol"; import "../GSN/Context.sol"; import "../access/roles/PauserRole.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ contract Pausable is Initializable, Context, PauserRole { /** * @dev Emitted when the pause is triggered by a pauser (`account`). */ event Paused(address account); /** * @dev Emitted when the pause is lifted by a pauser (`account`). */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. Assigns the Pauser role * to the deployer. */ function initialize(address sender) public initializer { PauserRole.initialize(sender); _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!_paused, "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(_paused, "Pausable: not paused"); _; } /** * @dev Called by a pauser to pause, triggers stopped state. */ function pause() public onlyPauser whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Called by a pauser to unpause, returns to normal state. */ function unpause() public onlyPauser whenPaused { _paused = false; emit Unpaused(_msgSender()); } uint256[50] private ______gap; } 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; } } pragma solidity ^0.5.0; import "@openzeppelin/upgrades/contracts/Initializable.sol"; import "../GSN/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be aplied to your functions to restrict their use to * the owner. */ contract Ownable is Initializable, Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function initialize(address sender) public initializer { _owner = sender; emit OwnershipTransferred(address(0), _owner); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return _msgSender() == _owner; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * > Note: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[50] private ______gap; } pragma solidity ^0.5.0; import "@openzeppelin/upgrades/contracts/Initializable.sol"; import "../../GSN/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20Mintable}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Initializable, Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal { 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); } /** * @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 { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal { 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 Destroys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See {_burn} and {_approve}. */ function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance")); } uint256[50] private ______gap; } pragma solidity ^0.5.0; import "@openzeppelin/upgrades/contracts/Initializable.sol"; import "../../GSN/Context.sol"; import "./ERC20.sol"; /** * @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). */ contract ERC20Burnable is Initializable, Context, ERC20 { /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public { _burn(_msgSender(), amount); } /** * @dev See {ERC20-_burnFrom}. */ function burnFrom(address account, uint256 amount) public { _burnFrom(account, amount); } uint256[50] private ______gap; } pragma solidity ^0.5.0; import "@openzeppelin/upgrades/contracts/Initializable.sol"; import "./IERC20.sol"; /** * @dev Optional functions from the ERC20 standard. */ contract ERC20Detailed is Initializable, IERC20 { string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for `name`, `symbol`, and `decimals`. All three of * these values are immutable: they can only be set once during * construction. */ function initialize(string memory name, string memory symbol, uint8 decimals) public initializer { _name = name; _symbol = symbol; _decimals = decimals; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } uint256[50] private ______gap; } pragma solidity ^0.5.0; import "@openzeppelin/upgrades/contracts/Initializable.sol"; import "./ERC20.sol"; import "../../lifecycle/Pausable.sol"; /** * @title Pausable token * @dev ERC20 with pausable transfers and allowances. * * Useful if you want to stop trades until the end of a crowdsale, or have * an emergency switch for freezing all token transfers in the event of a large * bug. */ contract ERC20Pausable is Initializable, ERC20, Pausable { function initialize(address sender) public initializer { Pausable.initialize(sender); } function transfer(address to, uint256 value) public whenNotPaused returns (bool) { return super.transfer(to, value); } function transferFrom(address from, address to, uint256 value) public whenNotPaused returns (bool) { return super.transferFrom(from, to, value); } function approve(address spender, uint256 value) public whenNotPaused returns (bool) { return super.approve(spender, value); } function increaseAllowance(address spender, uint256 addedValue) public whenNotPaused returns (bool) { return super.increaseAllowance(spender, addedValue); } function decreaseAllowance(address spender, uint256 subtractedValue) public whenNotPaused returns (bool) { return super.decreaseAllowance(spender, subtractedValue); } uint256[50] private ______gap; } pragma solidity ^0.5.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see {ERC20Detailed}. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @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.5.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } pragma solidity ^0.5.5; /** * @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 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"); } } 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.5.0; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". * * Source https://raw.githubusercontent.com/OpenZeppelin/openzeppelin-solidity/v2.1.3/contracts/ownership/Ownable.sol * This contract is copied here and renamed from the original to avoid clashes in the compiled artifacts * when the user imports a zos-lib contract (that transitively causes this contract to be compiled and added to the * build/artifacts folder) as well as the vanilla Ownable implementation from an openzeppelin version. */ contract OpenZeppelinUpgradesOwnable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor () internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @return the address of the owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner()); _; } /** * @return true if `msg.sender` is the owner of the contract. */ function isOwner() public view returns (bool) { return msg.sender == _owner; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0)); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } pragma solidity ^0.5.0; import './BaseAdminUpgradeabilityProxy.sol'; /** * @title AdminUpgradeabilityProxy * @dev Extends from BaseAdminUpgradeabilityProxy with a constructor for * initializing the implementation, admin, and init data. */ contract AdminUpgradeabilityProxy is BaseAdminUpgradeabilityProxy, UpgradeabilityProxy { /** * Contract constructor. * @param _logic address of the initial implementation. * @param _admin Address of the proxy administrator. * @param _data Data to send as msg.data to the implementation to initialize the proxied contract. * It should include the signature and the parameters of the function to be called, as described in * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding. * This parameter is optional, if no data is given the initialization call to proxied contract will be skipped. */ constructor(address _logic, address _admin, bytes memory _data) UpgradeabilityProxy(_logic, _data) public payable { assert(ADMIN_SLOT == bytes32(uint256(keccak256('eip1967.proxy.admin')) - 1)); _setAdmin(_admin); } } pragma solidity ^0.5.0; import './UpgradeabilityProxy.sol'; /** * @title BaseAdminUpgradeabilityProxy * @dev This contract combines an upgradeability proxy with an authorization * mechanism for administrative tasks. * All external functions in this contract must be guarded by the * `ifAdmin` modifier. See ethereum/solidity#3864 for a Solidity * feature proposal that would enable this to be done automatically. */ contract BaseAdminUpgradeabilityProxy is BaseUpgradeabilityProxy { /** * @dev Emitted when the administration has been transferred. * @param previousAdmin Address of the previous admin. * @param newAdmin Address of the new admin. */ event AdminChanged(address previousAdmin, address newAdmin); /** * @dev Storage slot with the admin of the contract. * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; /** * @dev Modifier to check whether the `msg.sender` is the admin. * If it is, it will run the function. Otherwise, it will delegate the call * to the implementation. */ modifier ifAdmin() { if (msg.sender == _admin()) { _; } else { _fallback(); } } /** * @return The address of the proxy admin. */ function admin() external ifAdmin returns (address) { return _admin(); } /** * @return The address of the implementation. */ function implementation() external ifAdmin returns (address) { return _implementation(); } /** * @dev Changes the admin of the proxy. * Only the current admin can call this function. * @param newAdmin Address to transfer proxy administration to. */ function changeAdmin(address newAdmin) external ifAdmin { require(newAdmin != address(0), "Cannot change the admin of a proxy to the zero address"); emit AdminChanged(_admin(), newAdmin); _setAdmin(newAdmin); } /** * @dev Upgrade the backing implementation of the proxy. * Only the admin can call this function. * @param newImplementation Address of the new implementation. */ function upgradeTo(address newImplementation) external ifAdmin { _upgradeTo(newImplementation); } /** * @dev Upgrade the backing implementation of the proxy and call a function * on the new implementation. * This is useful to initialize the proxied contract. * @param newImplementation Address of the new implementation. * @param data Data to send as msg.data in the low level call. * It should include the signature and the parameters of the function to be called, as described in * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding. */ function upgradeToAndCall(address newImplementation, bytes calldata data) payable external ifAdmin { _upgradeTo(newImplementation); (bool success,) = newImplementation.delegatecall(data); require(success); } /** * @return The admin slot. */ function _admin() internal view returns (address adm) { bytes32 slot = ADMIN_SLOT; assembly { adm := sload(slot) } } /** * @dev Sets the address of the proxy admin. * @param newAdmin Address of the new proxy admin. */ function _setAdmin(address newAdmin) internal { bytes32 slot = ADMIN_SLOT; assembly { sstore(slot, newAdmin) } } /** * @dev Only fall back when the sender is not the admin. */ function _willFallback() internal { require(msg.sender != _admin(), "Cannot call fallback function from the proxy admin"); super._willFallback(); } } pragma solidity ^0.5.0; import './Proxy.sol'; import '../utils/Address.sol'; /** * @title BaseUpgradeabilityProxy * @dev This contract implements a proxy that allows to change the * implementation address to which it will delegate. * Such a change is called an implementation upgrade. */ contract BaseUpgradeabilityProxy is Proxy { /** * @dev Emitted when the implementation is upgraded. * @param implementation Address of the new implementation. */ event Upgraded(address indexed implementation); /** * @dev Storage slot with the address of the current implementation. * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; /** * @dev Returns the current implementation. * @return Address of the current implementation */ function _implementation() internal view returns (address impl) { bytes32 slot = IMPLEMENTATION_SLOT; assembly { impl := sload(slot) } } /** * @dev Upgrades the proxy to a new implementation. * @param newImplementation Address of the new implementation. */ function _upgradeTo(address newImplementation) internal { _setImplementation(newImplementation); emit Upgraded(newImplementation); } /** * @dev Sets the implementation address of the proxy. * @param newImplementation Address of the new implementation. */ function _setImplementation(address newImplementation) internal { require(OpenZeppelinUpgradesAddress.isContract(newImplementation), "Cannot set a proxy implementation to a non-contract address"); bytes32 slot = IMPLEMENTATION_SLOT; assembly { sstore(slot, newImplementation) } } } pragma solidity ^0.5.0; import './BaseAdminUpgradeabilityProxy.sol'; import './InitializableUpgradeabilityProxy.sol'; /** * @title InitializableAdminUpgradeabilityProxy * @dev Extends from BaseAdminUpgradeabilityProxy with an initializer for * initializing the implementation, admin, and init data. */ contract InitializableAdminUpgradeabilityProxy is BaseAdminUpgradeabilityProxy, InitializableUpgradeabilityProxy { /** * Contract initializer. * @param _logic address of the initial implementation. * @param _admin Address of the proxy administrator. * @param _data Data to send as msg.data to the implementation to initialize the proxied contract. * It should include the signature and the parameters of the function to be called, as described in * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding. * This parameter is optional, if no data is given the initialization call to proxied contract will be skipped. */ function initialize(address _logic, address _admin, bytes memory _data) public payable { require(_implementation() == address(0)); InitializableUpgradeabilityProxy.initialize(_logic, _data); assert(ADMIN_SLOT == bytes32(uint256(keccak256('eip1967.proxy.admin')) - 1)); _setAdmin(_admin); } } pragma solidity ^0.5.0; import './BaseUpgradeabilityProxy.sol'; /** * @title InitializableUpgradeabilityProxy * @dev Extends BaseUpgradeabilityProxy with an initializer for initializing * implementation and init data. */ contract InitializableUpgradeabilityProxy is BaseUpgradeabilityProxy { /** * @dev Contract initializer. * @param _logic Address of the initial implementation. * @param _data Data to send as msg.data to the implementation to initialize the proxied contract. * It should include the signature and the parameters of the function to be called, as described in * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding. * This parameter is optional, if no data is given the initialization call to proxied contract will be skipped. */ function initialize(address _logic, bytes memory _data) public payable { require(_implementation() == address(0)); assert(IMPLEMENTATION_SLOT == bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1)); _setImplementation(_logic); if(_data.length > 0) { (bool success,) = _logic.delegatecall(_data); require(success); } } } pragma solidity ^0.5.0; /** * @title Proxy * @dev Implements delegation of calls to other contracts, with proper * forwarding of return values and bubbling of failures. * It defines a fallback function that delegates all calls to the address * returned by the abstract _implementation() internal function. */ contract Proxy { /** * @dev Fallback function. * Implemented entirely in `_fallback`. */ function () payable external { _fallback(); } /** * @return The Address of the implementation. */ function _implementation() internal view returns (address); /** * @dev Delegates execution to an implementation contract. * This is a low level function that doesn't return to its internal call site. * It will return to the external caller whatever the implementation returns. * @param implementation Address to delegate. */ function _delegate(address implementation) internal { assembly { // Copy msg.data. We take full control of memory in this inline assembly // block because it will not return to Solidity code. We overwrite the // Solidity scratch pad at memory position 0. calldatacopy(0, 0, calldatasize) // Call the implementation. // out and outsize are 0 because we don't know the size yet. let result := delegatecall(gas, implementation, 0, calldatasize, 0, 0) // Copy the returned data. returndatacopy(0, 0, returndatasize) switch result // delegatecall returns 0 on error. case 0 { revert(0, returndatasize) } default { return(0, returndatasize) } } } /** * @dev Function that is run as the first thing in the fallback function. * Can be redefined in derived contracts to add functionality. * Redefinitions must call super._willFallback(). */ function _willFallback() internal { } /** * @dev fallback implementation. * Extracted to enable manual triggering. */ function _fallback() internal { _willFallback(); _delegate(_implementation()); } } pragma solidity ^0.5.0; import "../ownership/Ownable.sol"; import "./AdminUpgradeabilityProxy.sol"; /** * @title ProxyAdmin * @dev This contract is the admin of a proxy, and is in charge * of upgrading it as well as transferring it to another admin. */ contract ProxyAdmin is OpenZeppelinUpgradesOwnable { /** * @dev Returns the current implementation of a proxy. * This is needed because only the proxy admin can query it. * @return The address of the current implementation of the proxy. */ function getProxyImplementation(AdminUpgradeabilityProxy proxy) public view returns (address) { // We need to manually run the static call since the getter cannot be flagged as view // bytes4(keccak256("implementation()")) == 0x5c60da1b (bool success, bytes memory returndata) = address(proxy).staticcall(hex"5c60da1b"); require(success); return abi.decode(returndata, (address)); } /** * @dev Returns the admin of a proxy. Only the admin can query it. * @return The address of the current admin of the proxy. */ function getProxyAdmin(AdminUpgradeabilityProxy proxy) public view returns (address) { // We need to manually run the static call since the getter cannot be flagged as view // bytes4(keccak256("admin()")) == 0xf851a440 (bool success, bytes memory returndata) = address(proxy).staticcall(hex"f851a440"); require(success); return abi.decode(returndata, (address)); } /** * @dev Changes the admin of a proxy. * @param proxy Proxy to change admin. * @param newAdmin Address to transfer proxy administration to. */ function changeProxyAdmin(AdminUpgradeabilityProxy proxy, address newAdmin) public onlyOwner { proxy.changeAdmin(newAdmin); } /** * @dev Upgrades a proxy to the newest implementation of a contract. * @param proxy Proxy to be upgraded. * @param implementation the address of the Implementation. */ function upgrade(AdminUpgradeabilityProxy proxy, address implementation) public onlyOwner { proxy.upgradeTo(implementation); } /** * @dev Upgrades a proxy to the newest implementation of a contract and forwards a function call to it. * This is useful to initialize the proxied contract. * @param proxy Proxy to be upgraded. * @param implementation Address of the Implementation. * @param data Data to send as msg.data in the low level call. * It should include the signature and the parameters of the function to be called, as described in * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding. */ function upgradeAndCall(AdminUpgradeabilityProxy proxy, address implementation, bytes memory data) payable public onlyOwner { proxy.upgradeToAndCall.value(msg.value)(implementation, data); } } pragma solidity ^0.5.0; import './BaseUpgradeabilityProxy.sol'; /** * @title UpgradeabilityProxy * @dev Extends BaseUpgradeabilityProxy with a constructor for initializing * implementation and init data. */ contract UpgradeabilityProxy is BaseUpgradeabilityProxy { /** * @dev Contract constructor. * @param _logic Address of the initial implementation. * @param _data Data to send as msg.data to the implementation to initialize the proxied contract. * It should include the signature and the parameters of the function to be called, as described in * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding. * This parameter is optional, if no data is given the initialization call to proxied contract will be skipped. */ constructor(address _logic, bytes memory _data) public payable { assert(IMPLEMENTATION_SLOT == bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1)); _setImplementation(_logic); if(_data.length > 0) { (bool success,) = _logic.delegatecall(_data); require(success); } } } pragma solidity ^0.5.0; /** * Utility library of inline functions on addresses * * Source https://raw.githubusercontent.com/OpenZeppelin/openzeppelin-solidity/v2.1.3/contracts/utils/Address.sol * This contract is copied here and renamed from the original to avoid clashes in the compiled artifacts * when the user imports a zos-lib contract (that transitively causes this contract to be compiled and added to the * build/artifacts folder) as well as the vanilla Address implementation from an openzeppelin version. */ library OpenZeppelinUpgradesAddress { /** * Returns whether the target address is a contract * @dev This function will return false if invoked during the constructor of a contract, * as the code is not actually created until after the constructor finishes. * @param account address of the account to check * @return whether the target address is a contract */ function isContract(address account) internal view returns (bool) { uint256 size; // XXX Currently there is no better way to check if there is a contract in an address // than to check the size of the code at that address. // See https://ethereum.stackexchange.com/a/14016/36603 // for more details about how this works. // TODO Check this again before the Serenity release, because all addresses will be // contracts then. // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } } pragma solidity 0.5.17; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/cryptography/ECDSA.sol"; import "@openzeppelin/upgrades/contracts/upgradeability/InitializableAdminUpgradeabilityProxy.sol"; import "@openzeppelin/upgrades/contracts/Initializable.sol"; import "../RenToken/RenToken.sol"; import "./DarknodeRegistryStore.sol"; import "../Governance/Claimable.sol"; import "../libraries/CanReclaimTokens.sol"; import "./DarknodeRegistryV1.sol"; contract DarknodeRegistryStateV2 {} /// @notice DarknodeRegistry is responsible for the registration and /// deregistration of Darknodes. contract DarknodeRegistryLogicV2 is Claimable, CanReclaimTokens, DarknodeRegistryStateV1, DarknodeRegistryStateV2 { using SafeMath for uint256; /// @notice Emitted when a darknode is registered. /// @param _darknodeOperator The owner of the darknode. /// @param _darknodeID The ID of the darknode that was registered. /// @param _bond The amount of REN that was transferred as bond. event LogDarknodeRegistered( address indexed _darknodeOperator, address indexed _darknodeID, uint256 _bond ); /// @notice Emitted when a darknode is deregistered. /// @param _darknodeOperator The owner of the darknode. /// @param _darknodeID The ID of the darknode that was deregistered. event LogDarknodeDeregistered( address indexed _darknodeOperator, address indexed _darknodeID ); /// @notice Emitted when a refund has been made. /// @param _darknodeOperator The owner of the darknode. /// @param _darknodeID The ID of the darknode that was refunded. /// @param _amount The amount of REN that was refunded. event LogDarknodeRefunded( address indexed _darknodeOperator, address indexed _darknodeID, uint256 _amount ); /// @notice Emitted when a recovery has been made. /// @param _darknodeOperator The owner of the darknode. /// @param _darknodeID The ID of the darknode that was recovered. /// @param _bondRecipient The address that received the bond. /// @param _submitter The address that called the recover method. event LogDarknodeRecovered( address indexed _darknodeOperator, address indexed _darknodeID, address _bondRecipient, address indexed _submitter ); /// @notice Emitted when a darknode's bond is slashed. /// @param _darknodeOperator The owner of the darknode. /// @param _darknodeID The ID of the darknode that was slashed. /// @param _challenger The address of the account that submitted the challenge. /// @param _percentage The total percentage of bond slashed. event LogDarknodeSlashed( address indexed _darknodeOperator, address indexed _darknodeID, address indexed _challenger, uint256 _percentage ); /// @notice Emitted when a new epoch has begun. event LogNewEpoch(uint256 indexed epochhash); /// @notice Emitted when a constructor parameter has been updated. event LogMinimumBondUpdated( uint256 _previousMinimumBond, uint256 _nextMinimumBond ); event LogMinimumPodSizeUpdated( uint256 _previousMinimumPodSize, uint256 _nextMinimumPodSize ); event LogMinimumEpochIntervalUpdated( uint256 _previousMinimumEpochInterval, uint256 _nextMinimumEpochInterval ); event LogSlasherUpdated( address indexed _previousSlasher, address indexed _nextSlasher ); event LogDarknodePaymentUpdated( address indexed _previousDarknodePayment, address indexed _nextDarknodePayment ); /// @notice Restrict a function to the owner that registered the darknode. modifier onlyDarknodeOperator(address _darknodeID) { require( store.darknodeOperator(_darknodeID) == msg.sender, "DarknodeRegistry: must be darknode owner" ); _; } /// @notice Restrict a function to unregistered darknodes. modifier onlyRefunded(address _darknodeID) { require( isRefunded(_darknodeID), "DarknodeRegistry: must be refunded or never registered" ); _; } /// @notice Restrict a function to refundable darknodes. modifier onlyRefundable(address _darknodeID) { require( isRefundable(_darknodeID), "DarknodeRegistry: must be deregistered for at least one epoch" ); _; } /// @notice Restrict a function to registered nodes without a pending /// deregistration. modifier onlyDeregisterable(address _darknodeID) { require( isDeregisterable(_darknodeID), "DarknodeRegistry: must be deregisterable" ); _; } /// @notice Restrict a function to the Slasher contract. modifier onlySlasher() { require( address(slasher) == msg.sender, "DarknodeRegistry: must be slasher" ); _; } /// @notice Restrict a function to registered and deregistered nodes. modifier onlyDarknode(address _darknodeID) { require( isRegistered(_darknodeID) || isDeregistered(_darknodeID), "DarknodeRegistry: invalid darknode" ); _; } /// @notice The contract constructor. /// /// @param _VERSION A string defining the contract version. /// @param _renAddress The address of the RenToken contract. /// @param _storeAddress The address of the DarknodeRegistryStore contract. /// @param _minimumBond The minimum bond amount that can be submitted by a /// Darknode. /// @param _minimumPodSize The minimum size of a Darknode pod. /// @param _minimumEpochIntervalSeconds The minimum number of seconds between epochs. function initialize( string memory _VERSION, RenToken _renAddress, DarknodeRegistryStore _storeAddress, uint256 _minimumBond, uint256 _minimumPodSize, uint256 _minimumEpochIntervalSeconds, uint256 _deregistrationIntervalSeconds ) public initializer { Claimable.initialize(msg.sender); CanReclaimTokens.initialize(msg.sender); VERSION = _VERSION; store = _storeAddress; ren = _renAddress; minimumBond = _minimumBond; nextMinimumBond = minimumBond; minimumPodSize = _minimumPodSize; nextMinimumPodSize = minimumPodSize; minimumEpochInterval = _minimumEpochIntervalSeconds; nextMinimumEpochInterval = minimumEpochInterval; deregistrationInterval = _deregistrationIntervalSeconds; uint256 epochhash = uint256(blockhash(block.number - 1)); currentEpoch = Epoch({ epochhash: epochhash, blocktime: block.timestamp }); emit LogNewEpoch(epochhash); } /// @notice Register a darknode and transfer the bond to this contract. /// Before registering, the bond transfer must be approved in the REN /// contract. The caller must provide a public encryption key for the /// darknode. The darknode will remain pending registration until the next /// epoch. Only after this period can the darknode be deregistered. The /// caller of this method will be stored as the owner of the darknode. /// /// @param _darknodeID The darknode ID that will be registered. function registerNode(address _darknodeID) public onlyRefunded(_darknodeID) { require( _darknodeID != address(0), "DarknodeRegistry: darknode address cannot be zero" ); // Use the current minimum bond as the darknode's bond and transfer bond to store require( ren.transferFrom(msg.sender, address(store), minimumBond), "DarknodeRegistry: bond transfer failed" ); // Flag this darknode for registration store.appendDarknode( _darknodeID, msg.sender, minimumBond, "", currentEpoch.blocktime.add(minimumEpochInterval), 0 ); numDarknodesNextEpoch = numDarknodesNextEpoch.add(1); // Emit an event. emit LogDarknodeRegistered(msg.sender, _darknodeID, minimumBond); } /// @notice An alias for `registerNode` that includes the legacy public key /// parameter. /// @param _darknodeID The darknode ID that will be registered. /// @param _publicKey Deprecated parameter - see `registerNode`. function register(address _darknodeID, bytes calldata _publicKey) external { return registerNode(_darknodeID); } /// @notice Register multiple darknodes and transfer the bonds to this contract. /// Before registering, the bonds transfer must be approved in the REN contract. /// The darknodes will remain pending registration until the next epoch. Only /// after this period can the darknodes be deregistered. The caller of this method /// will be stored as the owner of each darknode. If one registration fails, all /// registrations fail. /// @param _darknodeIDs The darknode IDs that will be registered. function registerMultiple(address[] calldata _darknodeIDs) external { // Save variables in memory to prevent redundant reads from storage DarknodeRegistryStore _store = store; Epoch memory _currentEpoch = currentEpoch; uint256 nextRegisteredAt = _currentEpoch.blocktime.add( minimumEpochInterval ); uint256 _minimumBond = minimumBond; require( ren.transferFrom( msg.sender, address(_store), _minimumBond.mul(_darknodeIDs.length) ), "DarknodeRegistry: bond transfers failed" ); for (uint256 i = 0; i < _darknodeIDs.length; i++) { address darknodeID = _darknodeIDs[i]; uint256 registeredAt = _store.darknodeRegisteredAt(darknodeID); uint256 deregisteredAt = _store.darknodeDeregisteredAt(darknodeID); require( _isRefunded(registeredAt, deregisteredAt), "DarknodeRegistry: must be refunded or never registered" ); require( darknodeID != address(0), "DarknodeRegistry: darknode address cannot be zero" ); _store.appendDarknode( darknodeID, msg.sender, _minimumBond, "", nextRegisteredAt, 0 ); emit LogDarknodeRegistered(msg.sender, darknodeID, _minimumBond); } numDarknodesNextEpoch = numDarknodesNextEpoch.add(_darknodeIDs.length); } /// @notice Deregister a darknode. The darknode will not be deregistered /// until the end of the epoch. After another epoch, the bond can be /// refunded by calling the refund method. /// @param _darknodeID The darknode ID that will be deregistered. The caller /// of this method must be the owner of this darknode. function deregister(address _darknodeID) external onlyDeregisterable(_darknodeID) onlyDarknodeOperator(_darknodeID) { deregisterDarknode(_darknodeID); } /// @notice Deregister multiple darknodes. The darknodes will not be /// deregistered until the end of the epoch. After another epoch, their /// bonds can be refunded by calling the refund or refundMultiple methods. /// If one deregistration fails, all deregistrations fail. /// @param _darknodeIDs The darknode IDs that will be deregistered. The /// caller of this method must be the owner of each darknode. function deregisterMultiple(address[] calldata _darknodeIDs) external { // Save variables in memory to prevent redundant reads from storage DarknodeRegistryStore _store = store; Epoch memory _currentEpoch = currentEpoch; uint256 _minimumEpochInterval = minimumEpochInterval; for (uint256 i = 0; i < _darknodeIDs.length; i++) { address darknodeID = _darknodeIDs[i]; uint256 deregisteredAt = _store.darknodeDeregisteredAt(darknodeID); bool registered = isRegisteredInEpoch( _store.darknodeRegisteredAt(darknodeID), deregisteredAt, _currentEpoch ); require( _isDeregisterable(registered, deregisteredAt), "DarknodeRegistry: must be deregisterable" ); require( _store.darknodeOperator(darknodeID) == msg.sender, "DarknodeRegistry: must be darknode owner" ); _store.updateDarknodeDeregisteredAt( darknodeID, _currentEpoch.blocktime.add(_minimumEpochInterval) ); emit LogDarknodeDeregistered(msg.sender, darknodeID); } numDarknodesNextEpoch = numDarknodesNextEpoch.sub(_darknodeIDs.length); } /// @notice Progress the epoch if it is possible to do so. This captures /// the current timestamp and current blockhash and overrides the current /// epoch. function epoch() external { if (previousEpoch.blocktime == 0) { // The first epoch must be called by the owner of the contract require( msg.sender == owner(), "DarknodeRegistry: not authorized to call first epoch" ); } // Require that the epoch interval has passed require( block.timestamp >= currentEpoch.blocktime.add(minimumEpochInterval), "DarknodeRegistry: epoch interval has not passed" ); uint256 epochhash = uint256(blockhash(block.number - 1)); // Update the epoch hash and timestamp previousEpoch = currentEpoch; currentEpoch = Epoch({ epochhash: epochhash, blocktime: block.timestamp }); // Update the registry information numDarknodesPreviousEpoch = numDarknodes; numDarknodes = numDarknodesNextEpoch; // If any update functions have been called, update the values now if (nextMinimumBond != minimumBond) { minimumBond = nextMinimumBond; emit LogMinimumBondUpdated(minimumBond, nextMinimumBond); } if (nextMinimumPodSize != minimumPodSize) { minimumPodSize = nextMinimumPodSize; emit LogMinimumPodSizeUpdated(minimumPodSize, nextMinimumPodSize); } if (nextMinimumEpochInterval != minimumEpochInterval) { minimumEpochInterval = nextMinimumEpochInterval; emit LogMinimumEpochIntervalUpdated( minimumEpochInterval, nextMinimumEpochInterval ); } if (nextSlasher != slasher) { slasher = nextSlasher; emit LogSlasherUpdated(address(slasher), address(nextSlasher)); } // Emit an event emit LogNewEpoch(epochhash); } /// @notice Allows the contract owner to initiate an ownership transfer of /// the DarknodeRegistryStore. /// @param _newOwner The address to transfer the ownership to. function transferStoreOwnership(DarknodeRegistryLogicV2 _newOwner) external onlyOwner { store.transferOwnership(address(_newOwner)); _newOwner.claimStoreOwnership(); } /// @notice Claims ownership of the store passed in to the constructor. /// `transferStoreOwnership` must have previously been called when /// transferring from another Darknode Registry. function claimStoreOwnership() external { store.claimOwnership(); // Sync state with new store. // Note: numDarknodesPreviousEpoch is set to 0 for a newly deployed DNR. ( numDarknodesPreviousEpoch, numDarknodes, numDarknodesNextEpoch ) = getDarknodeCountFromEpochs(); } /// @notice Allows the contract owner to update the minimum bond. /// @param _nextMinimumBond The minimum bond amount that can be submitted by /// a darknode. function updateMinimumBond(uint256 _nextMinimumBond) external onlyOwner { // Will be updated next epoch nextMinimumBond = _nextMinimumBond; } /// @notice Allows the contract owner to update the minimum pod size. /// @param _nextMinimumPodSize The minimum size of a pod. function updateMinimumPodSize(uint256 _nextMinimumPodSize) external onlyOwner { // Will be updated next epoch nextMinimumPodSize = _nextMinimumPodSize; } /// @notice Allows the contract owner to update the minimum epoch interval. /// @param _nextMinimumEpochInterval The minimum number of blocks between epochs. function updateMinimumEpochInterval(uint256 _nextMinimumEpochInterval) external onlyOwner { // Will be updated next epoch nextMinimumEpochInterval = _nextMinimumEpochInterval; } /// @notice Allow the contract owner to update the DarknodeSlasher contract /// address. /// @param _slasher The new slasher address. function updateSlasher(IDarknodeSlasher _slasher) external onlyOwner { nextSlasher = _slasher; } /// @notice Allow the DarknodeSlasher contract to slash a portion of darknode's /// bond and deregister it. /// @param _guilty The guilty prover whose bond is being slashed. /// @param _challenger The challenger who should receive a portion of the bond as reward. /// @param _percentage The total percentage of bond to be slashed. function slash( address _guilty, address _challenger, uint256 _percentage ) external onlySlasher onlyDarknode(_guilty) { require(_percentage <= 100, "DarknodeRegistry: invalid percent"); // If the darknode has not been deregistered then deregister it if (isDeregisterable(_guilty)) { deregisterDarknode(_guilty); } uint256 totalBond = store.darknodeBond(_guilty); uint256 penalty = totalBond.div(100).mul(_percentage); uint256 challengerReward = penalty.div(2); uint256 slasherPortion = penalty.sub(challengerReward); if (challengerReward > 0) { // Slash the bond of the failed prover store.updateDarknodeBond(_guilty, totalBond.sub(penalty)); // Forward the remaining amount to be handled by the slasher. require( ren.transfer(msg.sender, slasherPortion), "DarknodeRegistry: reward transfer to slasher failed" ); require( ren.transfer(_challenger, challengerReward), "DarknodeRegistry: reward transfer to challenger failed" ); } emit LogDarknodeSlashed( store.darknodeOperator(_guilty), _guilty, _challenger, _percentage ); } /// @notice Refund the bond of a deregistered darknode. This will make the /// darknode available for registration again. /// /// @param _darknodeID The darknode ID that will be refunded. function refund(address _darknodeID) external onlyRefundable(_darknodeID) onlyDarknodeOperator(_darknodeID) { // Remember the bond amount uint256 amount = store.darknodeBond(_darknodeID); // Erase the darknode from the registry store.removeDarknode(_darknodeID); // Refund the operator by transferring REN require( ren.transfer(msg.sender, amount), "DarknodeRegistry: bond transfer failed" ); // Emit an event. emit LogDarknodeRefunded(msg.sender, _darknodeID, amount); } /// @notice A permissioned method for refunding a darknode without the usual /// delay. The operator must provide a signature of the darknode ID and the /// bond recipient, but the call must come from the contract's owner. The /// main use case is for when an operator's keys have been compromised, /// allowing for the bonds to be recovered by the operator through the /// GatewayRegistry's governance. It is expected that this process would /// happen towards the end of the darknode's deregistered period, so that /// a malicious operator can't use this to quickly exit their stake after /// attempting an attack on the network. It's also expected that the /// operator will not re-register the same darknode again. function recover( address _darknodeID, address _bondRecipient, bytes calldata _signature ) external onlyOwner { require( isRefundable(_darknodeID) || isDeregistered(_darknodeID), "DarknodeRegistry: must be deregistered" ); address darknodeOperator = store.darknodeOperator(_darknodeID); require( ECDSA.recover( keccak256( abi.encodePacked( "\x19Ethereum Signed Message:\n64", "DarknodeRegistry.recover", _darknodeID, _bondRecipient ) ), _signature ) == darknodeOperator, "DarknodeRegistry: invalid signature" ); // Remember the bond amount uint256 amount = store.darknodeBond(_darknodeID); // Erase the darknode from the registry store.removeDarknode(_darknodeID); // Refund the operator by transferring REN require( ren.transfer(_bondRecipient, amount), "DarknodeRegistry: bond transfer failed" ); // Emit an event. emit LogDarknodeRefunded(darknodeOperator, _darknodeID, amount); emit LogDarknodeRecovered( darknodeOperator, _darknodeID, _bondRecipient, msg.sender ); } /// @notice Refund the bonds of multiple deregistered darknodes. This will /// make the darknodes available for registration again. If one refund fails, /// all refunds fail. /// @param _darknodeIDs The darknode IDs that will be refunded. function refundMultiple(address[] calldata _darknodeIDs) external { // Save variables in memory to prevent redundant reads from storage DarknodeRegistryStore _store = store; Epoch memory _currentEpoch = currentEpoch; Epoch memory _previousEpoch = previousEpoch; uint256 _deregistrationInterval = deregistrationInterval; // The sum of bonds to refund uint256 sum; for (uint256 i = 0; i < _darknodeIDs.length; i++) { address darknodeID = _darknodeIDs[i]; uint256 deregisteredAt = _store.darknodeDeregisteredAt(darknodeID); bool deregistered = _isDeregistered(deregisteredAt, _currentEpoch); require( _isRefundable( deregistered, deregisteredAt, _previousEpoch, _deregistrationInterval ), "DarknodeRegistry: must be deregistered for at least one epoch" ); require( _store.darknodeOperator(darknodeID) == msg.sender, "DarknodeRegistry: must be darknode owner" ); // Remember the bond amount uint256 amount = _store.darknodeBond(darknodeID); // Erase the darknode from the registry _store.removeDarknode(darknodeID); // Emit an event emit LogDarknodeRefunded(msg.sender, darknodeID, amount); // Increment the sum of bonds to be transferred sum = sum.add(amount); } // Transfer all bonds together require( ren.transfer(msg.sender, sum), "DarknodeRegistry: bond transfers failed" ); } /// @notice Retrieves the address of the account that registered a darknode. /// @param _darknodeID The ID of the darknode to retrieve the owner for. function getDarknodeOperator(address _darknodeID) external view returns (address payable) { return store.darknodeOperator(_darknodeID); } /// @notice Retrieves the bond amount of a darknode in 10^-18 REN. /// @param _darknodeID The ID of the darknode to retrieve the bond for. function getDarknodeBond(address _darknodeID) external view returns (uint256) { return store.darknodeBond(_darknodeID); } /// @notice Retrieves the encryption public key of the darknode. /// @param _darknodeID The ID of the darknode to retrieve the public key for. function getDarknodePublicKey(address _darknodeID) external view returns (bytes memory) { return store.darknodePublicKey(_darknodeID); } /// @notice Retrieves a list of darknodes which are registered for the /// current epoch. /// @param _start A darknode ID used as an offset for the list. If _start is /// 0x0, the first dark node will be used. _start won't be /// included it is not registered for the epoch. /// @param _count The number of darknodes to retrieve starting from _start. /// If _count is 0, all of the darknodes from _start are /// retrieved. If _count is more than the remaining number of /// registered darknodes, the rest of the list will contain /// 0x0s. function getDarknodes(address _start, uint256 _count) external view returns (address[] memory) { uint256 count = _count; if (count == 0) { count = numDarknodes; } return getDarknodesFromEpochs(_start, count, false); } /// @notice Retrieves a list of darknodes which were registered for the /// previous epoch. See `getDarknodes` for the parameter documentation. function getPreviousDarknodes(address _start, uint256 _count) external view returns (address[] memory) { uint256 count = _count; if (count == 0) { count = numDarknodesPreviousEpoch; } return getDarknodesFromEpochs(_start, count, true); } /// @notice Returns whether a darknode is scheduled to become registered /// at next epoch. /// @param _darknodeID The ID of the darknode to return. function isPendingRegistration(address _darknodeID) public view returns (bool) { uint256 registeredAt = store.darknodeRegisteredAt(_darknodeID); return registeredAt != 0 && registeredAt > currentEpoch.blocktime; } /// @notice Returns if a darknode is in the pending deregistered state. In /// this state a darknode is still considered registered. function isPendingDeregistration(address _darknodeID) public view returns (bool) { uint256 deregisteredAt = store.darknodeDeregisteredAt(_darknodeID); return deregisteredAt != 0 && deregisteredAt > currentEpoch.blocktime; } /// @notice Returns if a darknode is in the deregistered state. function isDeregistered(address _darknodeID) public view returns (bool) { uint256 deregisteredAt = store.darknodeDeregisteredAt(_darknodeID); return _isDeregistered(deregisteredAt, currentEpoch); } /// @notice Returns if a darknode can be deregistered. This is true if the /// darknodes is in the registered state and has not attempted to /// deregister yet. function isDeregisterable(address _darknodeID) public view returns (bool) { DarknodeRegistryStore _store = store; uint256 deregisteredAt = _store.darknodeDeregisteredAt(_darknodeID); bool registered = isRegisteredInEpoch( _store.darknodeRegisteredAt(_darknodeID), deregisteredAt, currentEpoch ); return _isDeregisterable(registered, deregisteredAt); } /// @notice Returns if a darknode is in the refunded state. This is true /// for darknodes that have never been registered, or darknodes that have /// been deregistered and refunded. function isRefunded(address _darknodeID) public view returns (bool) { DarknodeRegistryStore _store = store; uint256 registeredAt = _store.darknodeRegisteredAt(_darknodeID); uint256 deregisteredAt = _store.darknodeDeregisteredAt(_darknodeID); return _isRefunded(registeredAt, deregisteredAt); } /// @notice Returns if a darknode is refundable. This is true for darknodes /// that have been in the deregistered state for one full epoch. function isRefundable(address _darknodeID) public view returns (bool) { uint256 deregisteredAt = store.darknodeDeregisteredAt(_darknodeID); bool deregistered = _isDeregistered(deregisteredAt, currentEpoch); return _isRefundable( deregistered, deregisteredAt, previousEpoch, deregistrationInterval ); } /// @notice Returns the registration time of a given darknode. function darknodeRegisteredAt(address darknodeID) external view returns (uint256) { return store.darknodeRegisteredAt(darknodeID); } /// @notice Returns the deregistration time of a given darknode. function darknodeDeregisteredAt(address darknodeID) external view returns (uint256) { return store.darknodeDeregisteredAt(darknodeID); } /// @notice Returns if a darknode is in the registered state. function isRegistered(address _darknodeID) public view returns (bool) { DarknodeRegistryStore _store = store; uint256 registeredAt = _store.darknodeRegisteredAt(_darknodeID); uint256 deregisteredAt = _store.darknodeDeregisteredAt(_darknodeID); return isRegisteredInEpoch(registeredAt, deregisteredAt, currentEpoch); } /// @notice Returns if a darknode was in the registered state last epoch. function isRegisteredInPreviousEpoch(address _darknodeID) public view returns (bool) { DarknodeRegistryStore _store = store; uint256 registeredAt = _store.darknodeRegisteredAt(_darknodeID); uint256 deregisteredAt = _store.darknodeDeregisteredAt(_darknodeID); return isRegisteredInEpoch(registeredAt, deregisteredAt, previousEpoch); } /// @notice Returns the darknodes registered by the provided operator. /// @dev THIS IS AN EXPENSIVE CALL - this should only called when using /// eth_call contract reads - not in transactions. function getOperatorDarknodes(address _operator) external view returns (address[] memory) { address[] memory nodesPadded = new address[](numDarknodes); address[] memory allNodes = getDarknodesFromEpochs( address(0), numDarknodes, false ); uint256 j = 0; for (uint256 i = 0; i < allNodes.length; i++) { if (store.darknodeOperator(allNodes[i]) == _operator) { nodesPadded[j] = (allNodes[i]); j++; } } address[] memory nodes = new address[](j); for (uint256 i = 0; i < j; i++) { nodes[i] = nodesPadded[i]; } return nodes; } /// @notice Returns if a darknode was in the registered state for a given /// epoch. /// @param _epoch One of currentEpoch, previousEpoch. function isRegisteredInEpoch( uint256 _registeredAt, uint256 _deregisteredAt, Epoch memory _epoch ) private pure returns (bool) { bool registered = _registeredAt != 0 && _registeredAt <= _epoch.blocktime; bool notDeregistered = _deregisteredAt == 0 || _deregisteredAt > _epoch.blocktime; // The Darknode has been registered and has not yet been deregistered, // although it might be pending deregistration return registered && notDeregistered; } /// Private function called by `isDeregistered`, `isRefundable`, and `refundMultiple`. function _isDeregistered( uint256 _deregisteredAt, Epoch memory _currentEpoch ) private pure returns (bool) { return _deregisteredAt != 0 && _deregisteredAt <= _currentEpoch.blocktime; } /// Private function called by `isDeregisterable` and `deregisterMultiple`. function _isDeregisterable(bool _registered, uint256 _deregisteredAt) private pure returns (bool) { // The Darknode is currently in the registered state and has not been // transitioned to the pending deregistration, or deregistered, state return _registered && _deregisteredAt == 0; } /// Private function called by `isRefunded` and `registerMultiple`. function _isRefunded(uint256 registeredAt, uint256 deregisteredAt) private pure returns (bool) { return registeredAt == 0 && deregisteredAt == 0; } /// Private function called by `isRefundable` and `refundMultiple`. function _isRefundable( bool _deregistered, uint256 _deregisteredAt, Epoch memory _previousEpoch, uint256 _deregistrationInterval ) private pure returns (bool) { return _deregistered && _deregisteredAt <= (_previousEpoch.blocktime - _deregistrationInterval); } /// @notice Returns a list of darknodes registered for either the current /// or the previous epoch. See `getDarknodes` for documentation on the /// parameters `_start` and `_count`. /// @param _usePreviousEpoch If true, use the previous epoch, otherwise use /// the current epoch. function getDarknodesFromEpochs( address _start, uint256 _count, bool _usePreviousEpoch ) private view returns (address[] memory) { uint256 count = _count; if (count == 0) { count = numDarknodes; } address[] memory nodes = new address[](count); // Begin with the first node in the list uint256 n = 0; address next = _start; if (next == address(0)) { next = store.begin(); } // Iterate until all registered Darknodes have been collected while (n < count) { if (next == address(0)) { break; } // Only include Darknodes that are currently registered bool includeNext; if (_usePreviousEpoch) { includeNext = isRegisteredInPreviousEpoch(next); } else { includeNext = isRegistered(next); } if (!includeNext) { next = store.next(next); continue; } nodes[n] = next; next = store.next(next); n += 1; } return nodes; } /// Private function called by `deregister` and `slash` function deregisterDarknode(address _darknodeID) private { address darknodeOperator = store.darknodeOperator(_darknodeID); // Flag the darknode for deregistration store.updateDarknodeDeregisteredAt( _darknodeID, currentEpoch.blocktime.add(minimumEpochInterval) ); numDarknodesNextEpoch = numDarknodesNextEpoch.sub(1); // Emit an event emit LogDarknodeDeregistered(darknodeOperator, _darknodeID); } function getDarknodeCountFromEpochs() private view returns ( uint256, uint256, uint256 ) { // Begin with the first node in the list uint256 nPreviousEpoch = 0; uint256 nCurrentEpoch = 0; uint256 nNextEpoch = 0; address next = store.begin(); // Iterate until all registered Darknodes have been collected while (true) { // End of darknode list. if (next == address(0)) { break; } if (isRegisteredInPreviousEpoch(next)) { nPreviousEpoch += 1; } if (isRegistered(next)) { nCurrentEpoch += 1; } // Darknode is registered and has not deregistered, or is pending // becoming registered. if ( ((isRegistered(next) && !isPendingDeregistration(next)) || isPendingRegistration(next)) ) { nNextEpoch += 1; } next = store.next(next); } return (nPreviousEpoch, nCurrentEpoch, nNextEpoch); } } /* solium-disable-next-line no-empty-blocks */ contract DarknodeRegistryProxy is InitializableAdminUpgradeabilityProxy { } pragma solidity 0.5.17; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "../Governance/Claimable.sol"; import "../libraries/LinkedList.sol"; import "../RenToken/RenToken.sol"; import "../libraries/CanReclaimTokens.sol"; /// @notice This contract stores data and funds for the DarknodeRegistry /// contract. The data / fund logic and storage have been separated to improve /// upgradability. contract DarknodeRegistryStore is Claimable, CanReclaimTokens { using SafeMath for uint256; string public VERSION; // Passed in as a constructor parameter. /// @notice Darknodes are stored in the darknode struct. The owner is the /// address that registered the darknode, the bond is the amount of REN that /// was transferred during registration, and the public key is the /// encryption key that should be used when sending sensitive information to /// the darknode. struct Darknode { // The owner of a Darknode is the address that called the register // function. The owner is the only address that is allowed to // deregister the Darknode, unless the Darknode is slashed for // malicious behavior. address payable owner; // The bond is the amount of REN submitted as a bond by the Darknode. // This amount is reduced when the Darknode is slashed for malicious // behavior. uint256 bond; // The block number at which the Darknode is considered registered. uint256 registeredAt; // The block number at which the Darknode is considered deregistered. uint256 deregisteredAt; // The public key used by this Darknode for encrypting sensitive data // off chain. It is assumed that the Darknode has access to the // respective private key, and that there is an agreement on the format // of the public key. bytes publicKey; } /// Registry data. mapping(address => Darknode) private darknodeRegistry; LinkedList.List private darknodes; // RenToken. RenToken public ren; /// @notice The contract constructor. /// /// @param _VERSION A string defining the contract version. /// @param _ren The address of the RenToken contract. constructor(string memory _VERSION, RenToken _ren) public { Claimable.initialize(msg.sender); CanReclaimTokens.initialize(msg.sender); VERSION = _VERSION; ren = _ren; blacklistRecoverableToken(address(ren)); } /// @notice Instantiates a darknode and appends it to the darknodes /// linked-list. /// /// @param _darknodeID The darknode's ID. /// @param _darknodeOperator The darknode's owner's address. /// @param _bond The darknode's bond value. /// @param _publicKey The darknode's public key. /// @param _registeredAt The time stamp when the darknode is registered. /// @param _deregisteredAt The time stamp when the darknode is deregistered. function appendDarknode( address _darknodeID, address payable _darknodeOperator, uint256 _bond, bytes calldata _publicKey, uint256 _registeredAt, uint256 _deregisteredAt ) external onlyOwner { Darknode memory darknode = Darknode({ owner: _darknodeOperator, bond: _bond, publicKey: _publicKey, registeredAt: _registeredAt, deregisteredAt: _deregisteredAt }); darknodeRegistry[_darknodeID] = darknode; LinkedList.append(darknodes, _darknodeID); } /// @notice Returns the address of the first darknode in the store. function begin() external view onlyOwner returns (address) { return LinkedList.begin(darknodes); } /// @notice Returns the address of the next darknode in the store after the /// given address. function next(address darknodeID) external view onlyOwner returns (address) { return LinkedList.next(darknodes, darknodeID); } /// @notice Removes a darknode from the store and transfers its bond to the /// owner of this contract. function removeDarknode(address darknodeID) external onlyOwner { uint256 bond = darknodeRegistry[darknodeID].bond; delete darknodeRegistry[darknodeID]; LinkedList.remove(darknodes, darknodeID); require( ren.transfer(owner(), bond), "DarknodeRegistryStore: bond transfer failed" ); } /// @notice Updates the bond of a darknode. The new bond must be smaller /// than the previous bond of the darknode. function updateDarknodeBond(address darknodeID, uint256 decreasedBond) external onlyOwner { uint256 previousBond = darknodeRegistry[darknodeID].bond; require( decreasedBond < previousBond, "DarknodeRegistryStore: bond not decreased" ); darknodeRegistry[darknodeID].bond = decreasedBond; require( ren.transfer(owner(), previousBond.sub(decreasedBond)), "DarknodeRegistryStore: bond transfer failed" ); } /// @notice Updates the deregistration timestamp of a darknode. function updateDarknodeDeregisteredAt( address darknodeID, uint256 deregisteredAt ) external onlyOwner { darknodeRegistry[darknodeID].deregisteredAt = deregisteredAt; } /// @notice Returns the owner of a given darknode. function darknodeOperator(address darknodeID) external view onlyOwner returns (address payable) { return darknodeRegistry[darknodeID].owner; } /// @notice Returns the bond of a given darknode. function darknodeBond(address darknodeID) external view onlyOwner returns (uint256) { return darknodeRegistry[darknodeID].bond; } /// @notice Returns the registration time of a given darknode. function darknodeRegisteredAt(address darknodeID) external view onlyOwner returns (uint256) { return darknodeRegistry[darknodeID].registeredAt; } /// @notice Returns the deregistration time of a given darknode. function darknodeDeregisteredAt(address darknodeID) external view onlyOwner returns (uint256) { return darknodeRegistry[darknodeID].deregisteredAt; } /// @notice Returns the encryption public key of a given darknode. function darknodePublicKey(address darknodeID) external view onlyOwner returns (bytes memory) { return darknodeRegistry[darknodeID].publicKey; } } pragma solidity 0.5.17; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "@openzeppelin/upgrades/contracts/upgradeability/InitializableAdminUpgradeabilityProxy.sol"; import "@openzeppelin/upgrades/contracts/Initializable.sol"; import "../RenToken/RenToken.sol"; import "./DarknodeRegistryStore.sol"; import "../Governance/Claimable.sol"; import "../libraries/CanReclaimTokens.sol"; interface IDarknodePaymentStore {} interface IDarknodePayment { function changeCycle() external returns (uint256); function store() external view returns (IDarknodePaymentStore); } interface IDarknodeSlasher {} contract DarknodeRegistryStateV1 { using SafeMath for uint256; string public VERSION; // Passed in as a constructor parameter. /// @notice Darknode pods are shuffled after a fixed number of blocks. /// An Epoch stores an epoch hash used as an (insecure) RNG seed, and the /// blocknumber which restricts when the next epoch can be called. struct Epoch { uint256 epochhash; uint256 blocktime; } uint256 public numDarknodes; uint256 public numDarknodesNextEpoch; uint256 public numDarknodesPreviousEpoch; /// Variables used to parameterize behavior. uint256 public minimumBond; uint256 public minimumPodSize; uint256 public minimumEpochInterval; uint256 public deregistrationInterval; /// When one of the above variables is modified, it is only updated when the /// next epoch is called. These variables store the values for the next /// epoch. uint256 public nextMinimumBond; uint256 public nextMinimumPodSize; uint256 public nextMinimumEpochInterval; /// The current and previous epoch. Epoch public currentEpoch; Epoch public previousEpoch; /// REN ERC20 contract used to transfer bonds. RenToken public ren; /// Darknode Registry Store is the storage contract for darknodes. DarknodeRegistryStore public store; /// The Darknode Payment contract for changing cycle. IDarknodePayment public darknodePayment; /// Darknode Slasher allows darknodes to vote on bond slashing. IDarknodeSlasher public slasher; IDarknodeSlasher public nextSlasher; } /// @notice DarknodeRegistry is responsible for the registration and /// deregistration of Darknodes. contract DarknodeRegistryLogicV1 is Claimable, CanReclaimTokens, DarknodeRegistryStateV1 { /// @notice Emitted when a darknode is registered. /// @param _darknodeOperator The owner of the darknode. /// @param _darknodeID The ID of the darknode that was registered. /// @param _bond The amount of REN that was transferred as bond. event LogDarknodeRegistered( address indexed _darknodeOperator, address indexed _darknodeID, uint256 _bond ); /// @notice Emitted when a darknode is deregistered. /// @param _darknodeOperator The owner of the darknode. /// @param _darknodeID The ID of the darknode that was deregistered. event LogDarknodeDeregistered( address indexed _darknodeOperator, address indexed _darknodeID ); /// @notice Emitted when a refund has been made. /// @param _darknodeOperator The owner of the darknode. /// @param _amount The amount of REN that was refunded. event LogDarknodeRefunded( address indexed _darknodeOperator, address indexed _darknodeID, uint256 _amount ); /// @notice Emitted when a darknode's bond is slashed. /// @param _darknodeOperator The owner of the darknode. /// @param _darknodeID The ID of the darknode that was slashed. /// @param _challenger The address of the account that submitted the challenge. /// @param _percentage The total percentage of bond slashed. event LogDarknodeSlashed( address indexed _darknodeOperator, address indexed _darknodeID, address indexed _challenger, uint256 _percentage ); /// @notice Emitted when a new epoch has begun. event LogNewEpoch(uint256 indexed epochhash); /// @notice Emitted when a constructor parameter has been updated. event LogMinimumBondUpdated( uint256 _previousMinimumBond, uint256 _nextMinimumBond ); event LogMinimumPodSizeUpdated( uint256 _previousMinimumPodSize, uint256 _nextMinimumPodSize ); event LogMinimumEpochIntervalUpdated( uint256 _previousMinimumEpochInterval, uint256 _nextMinimumEpochInterval ); event LogSlasherUpdated( address indexed _previousSlasher, address indexed _nextSlasher ); event LogDarknodePaymentUpdated( IDarknodePayment indexed _previousDarknodePayment, IDarknodePayment indexed _nextDarknodePayment ); /// @notice Restrict a function to the owner that registered the darknode. modifier onlyDarknodeOperator(address _darknodeID) { require( store.darknodeOperator(_darknodeID) == msg.sender, "DarknodeRegistry: must be darknode owner" ); _; } /// @notice Restrict a function to unregistered darknodes. modifier onlyRefunded(address _darknodeID) { require( isRefunded(_darknodeID), "DarknodeRegistry: must be refunded or never registered" ); _; } /// @notice Restrict a function to refundable darknodes. modifier onlyRefundable(address _darknodeID) { require( isRefundable(_darknodeID), "DarknodeRegistry: must be deregistered for at least one epoch" ); _; } /// @notice Restrict a function to registered nodes without a pending /// deregistration. modifier onlyDeregisterable(address _darknodeID) { require( isDeregisterable(_darknodeID), "DarknodeRegistry: must be deregisterable" ); _; } /// @notice Restrict a function to the Slasher contract. modifier onlySlasher() { require( address(slasher) == msg.sender, "DarknodeRegistry: must be slasher" ); _; } /// @notice Restrict a function to registered nodes without a pending /// deregistration. modifier onlyDarknode(address _darknodeID) { require( isRegistered(_darknodeID), "DarknodeRegistry: invalid darknode" ); _; } /// @notice The contract constructor. /// /// @param _VERSION A string defining the contract version. /// @param _renAddress The address of the RenToken contract. /// @param _storeAddress The address of the DarknodeRegistryStore contract. /// @param _minimumBond The minimum bond amount that can be submitted by a /// Darknode. /// @param _minimumPodSize The minimum size of a Darknode pod. /// @param _minimumEpochIntervalSeconds The minimum number of seconds between epochs. function initialize( string memory _VERSION, RenToken _renAddress, DarknodeRegistryStore _storeAddress, uint256 _minimumBond, uint256 _minimumPodSize, uint256 _minimumEpochIntervalSeconds, uint256 _deregistrationIntervalSeconds ) public initializer { Claimable.initialize(msg.sender); CanReclaimTokens.initialize(msg.sender); VERSION = _VERSION; store = _storeAddress; ren = _renAddress; minimumBond = _minimumBond; nextMinimumBond = minimumBond; minimumPodSize = _minimumPodSize; nextMinimumPodSize = minimumPodSize; minimumEpochInterval = _minimumEpochIntervalSeconds; nextMinimumEpochInterval = minimumEpochInterval; deregistrationInterval = _deregistrationIntervalSeconds; uint256 epochhash = uint256(blockhash(block.number - 1)); currentEpoch = Epoch({ epochhash: epochhash, blocktime: block.timestamp }); emit LogNewEpoch(epochhash); } /// @notice Register a darknode and transfer the bond to this contract. /// Before registering, the bond transfer must be approved in the REN /// contract. The caller must provide a public encryption key for the /// darknode. The darknode will remain pending registration until the next /// epoch. Only after this period can the darknode be deregistered. The /// caller of this method will be stored as the owner of the darknode. /// /// @param _darknodeID The darknode ID that will be registered. /// @param _publicKey The public key of the darknode. It is stored to allow /// other darknodes and traders to encrypt messages to the trader. function register(address _darknodeID, bytes calldata _publicKey) external onlyRefunded(_darknodeID) { require( _darknodeID != address(0), "DarknodeRegistry: darknode address cannot be zero" ); // Use the current minimum bond as the darknode's bond and transfer bond to store require( ren.transferFrom(msg.sender, address(store), minimumBond), "DarknodeRegistry: bond transfer failed" ); // Flag this darknode for registration store.appendDarknode( _darknodeID, msg.sender, minimumBond, _publicKey, currentEpoch.blocktime.add(minimumEpochInterval), 0 ); numDarknodesNextEpoch = numDarknodesNextEpoch.add(1); // Emit an event. emit LogDarknodeRegistered(msg.sender, _darknodeID, minimumBond); } /// @notice Deregister a darknode. The darknode will not be deregistered /// until the end of the epoch. After another epoch, the bond can be /// refunded by calling the refund method. /// @param _darknodeID The darknode ID that will be deregistered. The caller /// of this method must be the owner of this darknode. function deregister(address _darknodeID) external onlyDeregisterable(_darknodeID) onlyDarknodeOperator(_darknodeID) { deregisterDarknode(_darknodeID); } /// @notice Progress the epoch if it is possible to do so. This captures /// the current timestamp and current blockhash and overrides the current /// epoch. function epoch() external { if (previousEpoch.blocktime == 0) { // The first epoch must be called by the owner of the contract require( msg.sender == owner(), "DarknodeRegistry: not authorized to call first epoch" ); } // Require that the epoch interval has passed require( block.timestamp >= currentEpoch.blocktime.add(minimumEpochInterval), "DarknodeRegistry: epoch interval has not passed" ); uint256 epochhash = uint256(blockhash(block.number - 1)); // Update the epoch hash and timestamp previousEpoch = currentEpoch; currentEpoch = Epoch({ epochhash: epochhash, blocktime: block.timestamp }); // Update the registry information numDarknodesPreviousEpoch = numDarknodes; numDarknodes = numDarknodesNextEpoch; // If any update functions have been called, update the values now if (nextMinimumBond != minimumBond) { minimumBond = nextMinimumBond; emit LogMinimumBondUpdated(minimumBond, nextMinimumBond); } if (nextMinimumPodSize != minimumPodSize) { minimumPodSize = nextMinimumPodSize; emit LogMinimumPodSizeUpdated(minimumPodSize, nextMinimumPodSize); } if (nextMinimumEpochInterval != minimumEpochInterval) { minimumEpochInterval = nextMinimumEpochInterval; emit LogMinimumEpochIntervalUpdated( minimumEpochInterval, nextMinimumEpochInterval ); } if (nextSlasher != slasher) { slasher = nextSlasher; emit LogSlasherUpdated(address(slasher), address(nextSlasher)); } if (address(darknodePayment) != address(0x0)) { darknodePayment.changeCycle(); } // Emit an event emit LogNewEpoch(epochhash); } /// @notice Allows the contract owner to initiate an ownership transfer of /// the DarknodeRegistryStore. /// @param _newOwner The address to transfer the ownership to. function transferStoreOwnership(DarknodeRegistryLogicV1 _newOwner) external onlyOwner { store.transferOwnership(address(_newOwner)); _newOwner.claimStoreOwnership(); } /// @notice Claims ownership of the store passed in to the constructor. /// `transferStoreOwnership` must have previously been called when /// transferring from another Darknode Registry. function claimStoreOwnership() external { store.claimOwnership(); // Sync state with new store. // Note: numDarknodesPreviousEpoch is set to 0 for a newly deployed DNR. ( numDarknodesPreviousEpoch, numDarknodes, numDarknodesNextEpoch ) = getDarknodeCountFromEpochs(); } /// @notice Allows the contract owner to update the address of the /// darknode payment contract. /// @param _darknodePayment The address of the Darknode Payment /// contract. function updateDarknodePayment(IDarknodePayment _darknodePayment) external onlyOwner { require( address(_darknodePayment) != address(0x0), "DarknodeRegistry: invalid Darknode Payment address" ); IDarknodePayment previousDarknodePayment = darknodePayment; darknodePayment = _darknodePayment; emit LogDarknodePaymentUpdated( previousDarknodePayment, darknodePayment ); } /// @notice Allows the contract owner to update the minimum bond. /// @param _nextMinimumBond The minimum bond amount that can be submitted by /// a darknode. function updateMinimumBond(uint256 _nextMinimumBond) external onlyOwner { // Will be updated next epoch nextMinimumBond = _nextMinimumBond; } /// @notice Allows the contract owner to update the minimum pod size. /// @param _nextMinimumPodSize The minimum size of a pod. function updateMinimumPodSize(uint256 _nextMinimumPodSize) external onlyOwner { // Will be updated next epoch nextMinimumPodSize = _nextMinimumPodSize; } /// @notice Allows the contract owner to update the minimum epoch interval. /// @param _nextMinimumEpochInterval The minimum number of blocks between epochs. function updateMinimumEpochInterval(uint256 _nextMinimumEpochInterval) external onlyOwner { // Will be updated next epoch nextMinimumEpochInterval = _nextMinimumEpochInterval; } /// @notice Allow the contract owner to update the DarknodeSlasher contract /// address. /// @param _slasher The new slasher address. function updateSlasher(IDarknodeSlasher _slasher) external onlyOwner { require( address(_slasher) != address(0), "DarknodeRegistry: invalid slasher address" ); nextSlasher = _slasher; } /// @notice Allow the DarknodeSlasher contract to slash a portion of darknode's /// bond and deregister it. /// @param _guilty The guilty prover whose bond is being slashed. /// @param _challenger The challenger who should receive a portion of the bond as reward. /// @param _percentage The total percentage of bond to be slashed. function slash( address _guilty, address _challenger, uint256 _percentage ) external onlySlasher onlyDarknode(_guilty) { require(_percentage <= 100, "DarknodeRegistry: invalid percent"); // If the darknode has not been deregistered then deregister it if (isDeregisterable(_guilty)) { deregisterDarknode(_guilty); } uint256 totalBond = store.darknodeBond(_guilty); uint256 penalty = totalBond.div(100).mul(_percentage); uint256 challengerReward = penalty.div(2); uint256 darknodePaymentReward = penalty.sub(challengerReward); if (challengerReward > 0) { // Slash the bond of the failed prover store.updateDarknodeBond(_guilty, totalBond.sub(penalty)); // Distribute the remaining bond into the darknode payment reward pool require( address(darknodePayment) != address(0x0), "DarknodeRegistry: invalid payment address" ); require( ren.transfer( address(darknodePayment.store()), darknodePaymentReward ), "DarknodeRegistry: reward transfer failed" ); require( ren.transfer(_challenger, challengerReward), "DarknodeRegistry: reward transfer failed" ); } emit LogDarknodeSlashed( store.darknodeOperator(_guilty), _guilty, _challenger, _percentage ); } /// @notice Refund the bond of a deregistered darknode. This will make the /// darknode available for registration again. Anyone can call this function /// but the bond will always be refunded to the darknode operator. /// /// @param _darknodeID The darknode ID that will be refunded. function refund(address _darknodeID) external onlyRefundable(_darknodeID) { address darknodeOperator = store.darknodeOperator(_darknodeID); // Remember the bond amount uint256 amount = store.darknodeBond(_darknodeID); // Erase the darknode from the registry store.removeDarknode(_darknodeID); // Refund the operator by transferring REN require( ren.transfer(darknodeOperator, amount), "DarknodeRegistry: bond transfer failed" ); // Emit an event. emit LogDarknodeRefunded(darknodeOperator, _darknodeID, amount); } /// @notice Retrieves the address of the account that registered a darknode. /// @param _darknodeID The ID of the darknode to retrieve the owner for. function getDarknodeOperator(address _darknodeID) external view returns (address payable) { return store.darknodeOperator(_darknodeID); } /// @notice Retrieves the bond amount of a darknode in 10^-18 REN. /// @param _darknodeID The ID of the darknode to retrieve the bond for. function getDarknodeBond(address _darknodeID) external view returns (uint256) { return store.darknodeBond(_darknodeID); } /// @notice Retrieves the encryption public key of the darknode. /// @param _darknodeID The ID of the darknode to retrieve the public key for. function getDarknodePublicKey(address _darknodeID) external view returns (bytes memory) { return store.darknodePublicKey(_darknodeID); } /// @notice Retrieves a list of darknodes which are registered for the /// current epoch. /// @param _start A darknode ID used as an offset for the list. If _start is /// 0x0, the first dark node will be used. _start won't be /// included it is not registered for the epoch. /// @param _count The number of darknodes to retrieve starting from _start. /// If _count is 0, all of the darknodes from _start are /// retrieved. If _count is more than the remaining number of /// registered darknodes, the rest of the list will contain /// 0x0s. function getDarknodes(address _start, uint256 _count) external view returns (address[] memory) { uint256 count = _count; if (count == 0) { count = numDarknodes; } return getDarknodesFromEpochs(_start, count, false); } /// @notice Retrieves a list of darknodes which were registered for the /// previous epoch. See `getDarknodes` for the parameter documentation. function getPreviousDarknodes(address _start, uint256 _count) external view returns (address[] memory) { uint256 count = _count; if (count == 0) { count = numDarknodesPreviousEpoch; } return getDarknodesFromEpochs(_start, count, true); } /// @notice Returns whether a darknode is scheduled to become registered /// at next epoch. /// @param _darknodeID The ID of the darknode to return. function isPendingRegistration(address _darknodeID) public view returns (bool) { uint256 registeredAt = store.darknodeRegisteredAt(_darknodeID); return registeredAt != 0 && registeredAt > currentEpoch.blocktime; } /// @notice Returns if a darknode is in the pending deregistered state. In /// this state a darknode is still considered registered. function isPendingDeregistration(address _darknodeID) public view returns (bool) { uint256 deregisteredAt = store.darknodeDeregisteredAt(_darknodeID); return deregisteredAt != 0 && deregisteredAt > currentEpoch.blocktime; } /// @notice Returns if a darknode is in the deregistered state. function isDeregistered(address _darknodeID) public view returns (bool) { uint256 deregisteredAt = store.darknodeDeregisteredAt(_darknodeID); return deregisteredAt != 0 && deregisteredAt <= currentEpoch.blocktime; } /// @notice Returns if a darknode can be deregistered. This is true if the /// darknodes is in the registered state and has not attempted to /// deregister yet. function isDeregisterable(address _darknodeID) public view returns (bool) { uint256 deregisteredAt = store.darknodeDeregisteredAt(_darknodeID); // The Darknode is currently in the registered state and has not been // transitioned to the pending deregistration, or deregistered, state return isRegistered(_darknodeID) && deregisteredAt == 0; } /// @notice Returns if a darknode is in the refunded state. This is true /// for darknodes that have never been registered, or darknodes that have /// been deregistered and refunded. function isRefunded(address _darknodeID) public view returns (bool) { uint256 registeredAt = store.darknodeRegisteredAt(_darknodeID); uint256 deregisteredAt = store.darknodeDeregisteredAt(_darknodeID); return registeredAt == 0 && deregisteredAt == 0; } /// @notice Returns if a darknode is refundable. This is true for darknodes /// that have been in the deregistered state for one full epoch. function isRefundable(address _darknodeID) public view returns (bool) { return isDeregistered(_darknodeID) && store.darknodeDeregisteredAt(_darknodeID) <= (previousEpoch.blocktime - deregistrationInterval); } /// @notice Returns the registration time of a given darknode. function darknodeRegisteredAt(address darknodeID) external view returns (uint256) { return store.darknodeRegisteredAt(darknodeID); } /// @notice Returns the deregistration time of a given darknode. function darknodeDeregisteredAt(address darknodeID) external view returns (uint256) { return store.darknodeDeregisteredAt(darknodeID); } /// @notice Returns if a darknode is in the registered state. function isRegistered(address _darknodeID) public view returns (bool) { return isRegisteredInEpoch(_darknodeID, currentEpoch); } /// @notice Returns if a darknode was in the registered state last epoch. function isRegisteredInPreviousEpoch(address _darknodeID) public view returns (bool) { return isRegisteredInEpoch(_darknodeID, previousEpoch); } /// @notice Returns if a darknode was in the registered state for a given /// epoch. /// @param _darknodeID The ID of the darknode. /// @param _epoch One of currentEpoch, previousEpoch. function isRegisteredInEpoch(address _darknodeID, Epoch memory _epoch) private view returns (bool) { uint256 registeredAt = store.darknodeRegisteredAt(_darknodeID); uint256 deregisteredAt = store.darknodeDeregisteredAt(_darknodeID); bool registered = registeredAt != 0 && registeredAt <= _epoch.blocktime; bool notDeregistered = deregisteredAt == 0 || deregisteredAt > _epoch.blocktime; // The Darknode has been registered and has not yet been deregistered, // although it might be pending deregistration return registered && notDeregistered; } /// @notice Returns a list of darknodes registered for either the current /// or the previous epoch. See `getDarknodes` for documentation on the /// parameters `_start` and `_count`. /// @param _usePreviousEpoch If true, use the previous epoch, otherwise use /// the current epoch. function getDarknodesFromEpochs( address _start, uint256 _count, bool _usePreviousEpoch ) private view returns (address[] memory) { uint256 count = _count; if (count == 0) { count = numDarknodes; } address[] memory nodes = new address[](count); // Begin with the first node in the list uint256 n = 0; address next = _start; if (next == address(0)) { next = store.begin(); } // Iterate until all registered Darknodes have been collected while (n < count) { if (next == address(0)) { break; } // Only include Darknodes that are currently registered bool includeNext; if (_usePreviousEpoch) { includeNext = isRegisteredInPreviousEpoch(next); } else { includeNext = isRegistered(next); } if (!includeNext) { next = store.next(next); continue; } nodes[n] = next; next = store.next(next); n += 1; } return nodes; } /// Private function called by `deregister` and `slash` function deregisterDarknode(address _darknodeID) private { address darknodeOperator = store.darknodeOperator(_darknodeID); // Flag the darknode for deregistration store.updateDarknodeDeregisteredAt( _darknodeID, currentEpoch.blocktime.add(minimumEpochInterval) ); numDarknodesNextEpoch = numDarknodesNextEpoch.sub(1); // Emit an event emit LogDarknodeDeregistered(darknodeOperator, _darknodeID); } function getDarknodeCountFromEpochs() private view returns ( uint256, uint256, uint256 ) { // Begin with the first node in the list uint256 nPreviousEpoch = 0; uint256 nCurrentEpoch = 0; uint256 nNextEpoch = 0; address next = store.begin(); // Iterate until all registered Darknodes have been collected while (true) { // End of darknode list. if (next == address(0)) { break; } if (isRegisteredInPreviousEpoch(next)) { nPreviousEpoch += 1; } if (isRegistered(next)) { nCurrentEpoch += 1; } // Darknode is registered and has not deregistered, or is pending // becoming registered. if ( ((isRegistered(next) && !isPendingDeregistration(next)) || isPendingRegistration(next)) ) { nNextEpoch += 1; } next = store.next(next); } return (nPreviousEpoch, nCurrentEpoch, nNextEpoch); } } pragma solidity ^0.5.17; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/ownership/Ownable.sol"; import "./DarknodeRegistry.sol"; import "../Governance/RenProxyAdmin.sol"; import "../RenToken/RenToken.sol"; import "./DarknodeRegistryV1ToV2Upgrader.sol"; contract DarknodeRegistryV1ToV2Preupgrader is Ownable { DarknodeRegistryLogicV1 public darknodeRegistryProxy; DarknodeRegistryV1ToV2Upgrader public upgrader; address public previousDarknodeRegistryOwner; constructor( DarknodeRegistryLogicV1 _darknodeRegistryProxy, DarknodeRegistryV1ToV2Upgrader _upgrader ) public { Ownable.initialize(msg.sender); darknodeRegistryProxy = _darknodeRegistryProxy; upgrader = _upgrader; previousDarknodeRegistryOwner = darknodeRegistryProxy.owner(); } function claimStoreOwnership() public { darknodeRegistryProxy.store().claimOwnership(); } function recover( address[] calldata _darknodeIDs, address _bondRecipient, bytes[] calldata _signatures ) external onlyOwner { forwardDNR(); RenToken ren = darknodeRegistryProxy.ren(); DarknodeRegistryStore store = darknodeRegistryProxy.store(); darknodeRegistryProxy.transferStoreOwnership( DarknodeRegistryLogicV1(address(this)) ); if (darknodeRegistryProxy.store().owner() != address(this)) { claimStoreOwnership(); } (, uint256 currentEpochBlocktime) = darknodeRegistryProxy .currentEpoch(); uint256 total = 0; for (uint8 i = 0; i < _darknodeIDs.length; i++) { address _darknodeID = _darknodeIDs[i]; // Require darknode to be refundable. { uint256 deregisteredAt = store.darknodeDeregisteredAt( _darknodeID ); bool deregistered = deregisteredAt != 0 && deregisteredAt <= currentEpochBlocktime; require( deregistered, "DarknodeRegistryV1Preupgrader: must be deregistered" ); } address darknodeOperator = store.darknodeOperator(_darknodeID); require( ECDSA.recover( keccak256( abi.encodePacked( "\x19Ethereum Signed Message:\n64", "DarknodeRegistry.recover", _darknodeID, _bondRecipient ) ), _signatures[i] ) == darknodeOperator, "DarknodeRegistryV1Preupgrader: invalid signature" ); // Remember the bond amount total += store.darknodeBond(_darknodeID); // Erase the darknode from the registry store.removeDarknode(_darknodeID); // // Refund the operator by transferring REN } require( ren.transfer(_bondRecipient, total), "DarknodeRegistryV1Preupgrader: bond transfer failed" ); store.transferOwnership(address(darknodeRegistryProxy)); darknodeRegistryProxy.claimStoreOwnership(); } function forwardDNR() public onlyOwner { // Claim ownership if (darknodeRegistryProxy.owner() != address(this)) { darknodeRegistryProxy.claimOwnership(); } // Set pending owner to upgrader. if (darknodeRegistryProxy.pendingOwner() != address(upgrader)) { darknodeRegistryProxy.transferOwnership(address(upgrader)); } } function returnDNR() public onlyOwner { darknodeRegistryProxy.transferOwnership(previousDarknodeRegistryOwner); } } pragma solidity ^0.5.17; import "@openzeppelin/contracts-ethereum-package/contracts/ownership/Ownable.sol"; import "./DarknodeRegistry.sol"; import "../Governance/RenProxyAdmin.sol"; contract DarknodeRegistryV1ToV2Upgrader is Ownable { RenProxyAdmin public renProxyAdmin; DarknodeRegistryLogicV1 public darknodeRegistryProxy; DarknodeRegistryLogicV2 public darknodeRegistryLogicV2; address public previousAdminOwner; address public previousDarknodeRegistryOwner; constructor( RenProxyAdmin _renProxyAdmin, DarknodeRegistryLogicV1 _darknodeRegistryProxy, DarknodeRegistryLogicV2 _darknodeRegistryLogicV2 ) public { Ownable.initialize(msg.sender); renProxyAdmin = _renProxyAdmin; darknodeRegistryProxy = _darknodeRegistryProxy; darknodeRegistryLogicV2 = _darknodeRegistryLogicV2; previousAdminOwner = renProxyAdmin.owner(); previousDarknodeRegistryOwner = darknodeRegistryProxy.owner(); } function upgrade() public onlyOwner { // Pre-checks uint256 numDarknodes = darknodeRegistryProxy.numDarknodes(); uint256 numDarknodesNextEpoch = darknodeRegistryProxy .numDarknodesNextEpoch(); uint256 numDarknodesPreviousEpoch = darknodeRegistryProxy .numDarknodesPreviousEpoch(); uint256 minimumBond = darknodeRegistryProxy.minimumBond(); uint256 minimumPodSize = darknodeRegistryProxy.minimumPodSize(); uint256 minimumEpochInterval = darknodeRegistryProxy .minimumEpochInterval(); uint256 deregistrationInterval = darknodeRegistryProxy .deregistrationInterval(); RenToken ren = darknodeRegistryProxy.ren(); DarknodeRegistryStore store = darknodeRegistryProxy.store(); IDarknodePayment darknodePayment = darknodeRegistryProxy .darknodePayment(); // Claim and update. darknodeRegistryProxy.claimOwnership(); renProxyAdmin.upgrade( AdminUpgradeabilityProxy( // Cast gateway instance to payable address address(uint160(address(darknodeRegistryProxy))) ), address(darknodeRegistryLogicV2) ); // Post-checks require( numDarknodes == darknodeRegistryProxy.numDarknodes(), "Migrator: expected 'numDarknodes' not to change" ); require( numDarknodesNextEpoch == darknodeRegistryProxy.numDarknodesNextEpoch(), "Migrator: expected 'numDarknodesNextEpoch' not to change" ); require( numDarknodesPreviousEpoch == darknodeRegistryProxy.numDarknodesPreviousEpoch(), "Migrator: expected 'numDarknodesPreviousEpoch' not to change" ); require( minimumBond == darknodeRegistryProxy.minimumBond(), "Migrator: expected 'minimumBond' not to change" ); require( minimumPodSize == darknodeRegistryProxy.minimumPodSize(), "Migrator: expected 'minimumPodSize' not to change" ); require( minimumEpochInterval == darknodeRegistryProxy.minimumEpochInterval(), "Migrator: expected 'minimumEpochInterval' not to change" ); require( deregistrationInterval == darknodeRegistryProxy.deregistrationInterval(), "Migrator: expected 'deregistrationInterval' not to change" ); require( ren == darknodeRegistryProxy.ren(), "Migrator: expected 'ren' not to change" ); require( store == darknodeRegistryProxy.store(), "Migrator: expected 'store' not to change" ); require( darknodePayment == darknodeRegistryProxy.darknodePayment(), "Migrator: expected 'darknodePayment' not to change" ); darknodeRegistryProxy.updateSlasher(IDarknodeSlasher(0x0)); } function recover( address _darknodeID, address _bondRecipient, bytes calldata _signature ) external onlyOwner { return DarknodeRegistryLogicV2(address(darknodeRegistryProxy)).recover( _darknodeID, _bondRecipient, _signature ); } function returnDNR() public onlyOwner { darknodeRegistryProxy._directTransferOwnership( previousDarknodeRegistryOwner ); } function returnProxyAdmin() public onlyOwner { renProxyAdmin.transferOwnership(previousAdminOwner); } } pragma solidity 0.5.17; import "@openzeppelin/contracts-ethereum-package/contracts/ownership/Ownable.sol"; import "@openzeppelin/upgrades/contracts/Initializable.sol"; /** * @title Claimable * @dev Extension for the Ownable contract, where the ownership needs to be claimed. * This allows the new owner to accept the transfer. */ contract Claimable is Initializable, Ownable { address public pendingOwner; function initialize(address _nextOwner) public initializer { Ownable.initialize(_nextOwner); } modifier onlyPendingOwner() { require( _msgSender() == pendingOwner, "Claimable: caller is not the pending owner" ); _; } function transferOwnership(address newOwner) public onlyOwner { require( newOwner != owner() && newOwner != pendingOwner, "Claimable: invalid new owner" ); pendingOwner = newOwner; } // Allow skipping two-step transfer if the recipient is known to be a valid // owner, for use in smart-contracts only. function _directTransferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } function claimOwnership() public onlyPendingOwner { _transferOwnership(pendingOwner); delete pendingOwner; } } pragma solidity 0.5.17; import "@openzeppelin/upgrades/contracts/upgradeability/ProxyAdmin.sol"; /** * @title RenProxyAdmin * @dev Proxies restrict the proxy's owner from calling functions from the * delegate contract logic. The ProxyAdmin contract allows single account to be * the governance address of both the proxy and the delegate contract logic. */ /* solium-disable-next-line no-empty-blocks */ contract RenProxyAdmin is ProxyAdmin { } pragma solidity 0.5.17; import "@openzeppelin/contracts-ethereum-package/contracts/ownership/Ownable.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/ERC20Detailed.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/ERC20Pausable.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/ERC20Burnable.sol"; contract RenToken is Ownable, ERC20Detailed, ERC20Pausable, ERC20Burnable { string private constant _name = "REN"; string private constant _symbol = "REN"; uint8 private constant _decimals = 18; uint256 public constant INITIAL_SUPPLY = 1000000000 * 10**uint256(_decimals); /// @notice The RenToken Constructor. constructor() public { ERC20Pausable.initialize(msg.sender); ERC20Detailed.initialize(_name, _symbol, _decimals); Ownable.initialize(msg.sender); _mint(msg.sender, INITIAL_SUPPLY); } function transferTokens(address beneficiary, uint256 amount) public onlyOwner returns (bool) { // Note: The deployed version has no revert reason /* solium-disable-next-line error-reason */ require(amount > 0); _transfer(msg.sender, beneficiary, amount); emit Transfer(msg.sender, beneficiary, amount); return true; } } pragma solidity 0.5.17; import "@openzeppelin/contracts-ethereum-package/contracts/ownership/Ownable.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/upgrades/contracts/Initializable.sol"; import "../Governance/Claimable.sol"; contract CanReclaimTokens is Claimable { using SafeERC20 for ERC20; mapping(address => bool) private recoverableTokensBlacklist; function initialize(address _nextOwner) public initializer { Claimable.initialize(_nextOwner); } function blacklistRecoverableToken(address _token) public onlyOwner { recoverableTokensBlacklist[_token] = true; } /// @notice Allow the owner of the contract to recover funds accidentally /// sent to the contract. To withdraw ETH, the token should be set to `0x0`. function recoverTokens(address _token) external onlyOwner { require( !recoverableTokensBlacklist[_token], "CanReclaimTokens: token is not recoverable" ); if (_token == address(0x0)) { msg.sender.transfer(address(this).balance); } else { ERC20(_token).safeTransfer( msg.sender, ERC20(_token).balanceOf(address(this)) ); } } } pragma solidity 0.5.17; /** * @notice LinkedList is a library for a circular double linked list. */ library LinkedList { /* * @notice A permanent NULL node (0x0) in the circular double linked list. * NULL.next is the head, and NULL.previous is the tail. */ address public constant NULL = address(0); /** * @notice A node points to the node before it, and the node after it. If * node.previous = NULL, then the node is the head of the list. If * node.next = NULL, then the node is the tail of the list. */ struct Node { bool inList; address previous; address next; } /** * @notice LinkedList uses a mapping from address to nodes. Each address * uniquely identifies a node, and in this way they are used like pointers. */ struct List { mapping(address => Node) list; uint256 length; } /** * @notice Insert a new node before an existing node. * * @param self The list being used. * @param target The existing node in the list. * @param newNode The next node to insert before the target. */ function insertBefore( List storage self, address target, address newNode ) internal { require(newNode != address(0), "LinkedList: invalid address"); require(!isInList(self, newNode), "LinkedList: already in list"); require( isInList(self, target) || target == NULL, "LinkedList: not in list" ); // It is expected that this value is sometimes NULL. address prev = self.list[target].previous; self.list[newNode].next = target; self.list[newNode].previous = prev; self.list[target].previous = newNode; self.list[prev].next = newNode; self.list[newNode].inList = true; self.length += 1; } /** * @notice Insert a new node after an existing node. * * @param self The list being used. * @param target The existing node in the list. * @param newNode The next node to insert after the target. */ function insertAfter( List storage self, address target, address newNode ) internal { require(newNode != address(0), "LinkedList: invalid address"); require(!isInList(self, newNode), "LinkedList: already in list"); require( isInList(self, target) || target == NULL, "LinkedList: not in list" ); // It is expected that this value is sometimes NULL. address n = self.list[target].next; self.list[newNode].previous = target; self.list[newNode].next = n; self.list[target].next = newNode; self.list[n].previous = newNode; self.list[newNode].inList = true; self.length += 1; } /** * @notice Remove a node from the list, and fix the previous and next * pointers that are pointing to the removed node. Removing anode that is not * in the list will do nothing. * * @param self The list being using. * @param node The node in the list to be removed. */ function remove(List storage self, address node) internal { require(isInList(self, node), "LinkedList: not in list"); address p = self.list[node].previous; address n = self.list[node].next; self.list[p].next = n; self.list[n].previous = p; // Deleting the node should set this value to false, but we set it here for // explicitness. self.list[node].inList = false; delete self.list[node]; self.length -= 1; } /** * @notice Insert a node at the beginning of the list. * * @param self The list being used. * @param node The node to insert at the beginning of the list. */ function prepend(List storage self, address node) internal { // isInList(node) is checked in insertBefore insertBefore(self, begin(self), node); } /** * @notice Insert a node at the end of the list. * * @param self The list being used. * @param node The node to insert at the end of the list. */ function append(List storage self, address node) internal { // isInList(node) is checked in insertBefore insertAfter(self, end(self), node); } function swap( List storage self, address left, address right ) internal { // isInList(left) and isInList(right) are checked in remove address previousRight = self.list[right].previous; remove(self, right); insertAfter(self, left, right); remove(self, left); insertAfter(self, previousRight, left); } function isInList(List storage self, address node) internal view returns (bool) { return self.list[node].inList; } /** * @notice Get the node at the beginning of a double linked list. * * @param self The list being used. * * @return A address identifying the node at the beginning of the double * linked list. */ function begin(List storage self) internal view returns (address) { return self.list[NULL].next; } /** * @notice Get the node at the end of a double linked list. * * @param self The list being used. * * @return A address identifying the node at the end of the double linked * list. */ function end(List storage self) internal view returns (address) { return self.list[NULL].previous; } function next(List storage self, address node) internal view returns (address) { require(isInList(self, node), "LinkedList: not in list"); return self.list[node].next; } function previous(List storage self, address node) internal view returns (address) { require(isInList(self, node), "LinkedList: not in list"); return self.list[node].previous; } function elements( List storage self, address _start, uint256 _count ) internal view returns (address[] memory) { require(_count > 0, "LinkedList: invalid count"); require( isInList(self, _start) || _start == address(0), "LinkedList: not in list" ); address[] memory elems = new address[](_count); // Begin with the first node in the list uint256 n = 0; address nextItem = _start; if (nextItem == address(0)) { nextItem = begin(self); } while (n < _count) { if (nextItem == address(0)) { break; } elems[n] = nextItem; nextItem = next(self, nextItem); n += 1; } return elems; } }
* @title Ownable @dev The Ownable contract has an owner address, and provides basic authorization control functions, this simplifies the implementation of "user permissions". This contract is copied here and renamed from the original to avoid clashes in the compiled artifacts when the user imports a zos-lib contract (that transitively causes this contract to be compiled and added to the build/artifacts folder) as well as the vanilla Ownable implementation from an openzeppelin version./
contract OpenZeppelinUpgradesOwnable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor () internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } function owner() public view returns (address) { return _owner; } modifier onlyOwner() { require(isOwner()); _; } function isOwner() public view returns (bool) { return msg.sender == _owner; } function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } function _transferOwnership(address newOwner) internal { require(newOwner != address(0)); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } }
287,146
[ 1, 5460, 429, 225, 1021, 14223, 6914, 6835, 711, 392, 3410, 1758, 16, 471, 8121, 5337, 6093, 3325, 4186, 16, 333, 9330, 5032, 326, 4471, 434, 315, 1355, 4371, 9654, 1220, 6835, 353, 9268, 2674, 471, 17657, 628, 326, 2282, 358, 4543, 927, 7690, 316, 326, 7743, 16259, 1347, 326, 729, 10095, 279, 998, 538, 17, 2941, 6835, 261, 19056, 22755, 4492, 14119, 333, 6835, 358, 506, 7743, 471, 3096, 358, 326, 1361, 19, 30347, 3009, 13, 487, 5492, 487, 326, 331, 26476, 14223, 6914, 4471, 628, 392, 1696, 94, 881, 84, 292, 267, 1177, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 3502, 62, 881, 84, 292, 267, 1211, 13088, 5460, 429, 288, 203, 565, 1758, 3238, 389, 8443, 31, 203, 203, 565, 871, 14223, 9646, 5310, 1429, 4193, 12, 2867, 8808, 2416, 5541, 16, 1758, 8808, 394, 5541, 1769, 203, 203, 565, 3885, 1832, 2713, 288, 203, 3639, 389, 8443, 273, 1234, 18, 15330, 31, 203, 3639, 3626, 14223, 9646, 5310, 1429, 4193, 12, 2867, 12, 20, 3631, 389, 8443, 1769, 203, 565, 289, 203, 203, 565, 445, 3410, 1435, 1071, 1476, 1135, 261, 2867, 13, 288, 203, 3639, 327, 389, 8443, 31, 203, 565, 289, 203, 203, 565, 9606, 1338, 5541, 1435, 288, 203, 3639, 2583, 12, 291, 5541, 10663, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 565, 445, 353, 5541, 1435, 1071, 1476, 1135, 261, 6430, 13, 288, 203, 3639, 327, 1234, 18, 15330, 422, 389, 8443, 31, 203, 565, 289, 203, 203, 565, 445, 1654, 8386, 5460, 12565, 1435, 1071, 1338, 5541, 288, 203, 3639, 3626, 14223, 9646, 5310, 1429, 4193, 24899, 8443, 16, 1758, 12, 20, 10019, 203, 3639, 389, 8443, 273, 1758, 12, 20, 1769, 203, 565, 289, 203, 203, 565, 445, 7412, 5460, 12565, 12, 2867, 394, 5541, 13, 1071, 1338, 5541, 288, 203, 3639, 389, 13866, 5460, 12565, 12, 2704, 5541, 1769, 203, 565, 289, 203, 203, 565, 445, 389, 13866, 5460, 12565, 12, 2867, 394, 5541, 13, 2713, 288, 203, 3639, 2583, 12, 2704, 5541, 480, 1758, 12, 20, 10019, 203, 3639, 3626, 14223, 9646, 5310, 1429, 4193, 24899, 8443, 16, 394, 5541, 1769, 2 ]
./full_match/4/0x0228FEeF190B2CdF10CDA82cA2A2f93eF84C8AE8/sources/contracts/testRugEthereumToken.sol
Function to allow admin to claim *other* BEP20 tokens sent to this contract (by mistake)
function transferBEP20Tokens(address _tokenAddr, address _to, uint _amount) public onlyOwner { require(_tokenAddr != address(this), "Cannot transfer out native token"); IERC20(_tokenAddr).transfer(_to, _amount); }
12,485,327
[ 1, 2083, 358, 1699, 3981, 358, 7516, 1308, 9722, 52, 3462, 2430, 3271, 358, 333, 6835, 261, 1637, 27228, 911, 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 ]
[ 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, 7412, 5948, 52, 3462, 5157, 12, 2867, 389, 2316, 3178, 16, 1758, 389, 869, 16, 2254, 389, 8949, 13, 1071, 1338, 5541, 288, 203, 3639, 2583, 24899, 2316, 3178, 480, 1758, 12, 2211, 3631, 315, 4515, 7412, 596, 6448, 1147, 8863, 203, 3639, 467, 654, 39, 3462, 24899, 2316, 3178, 2934, 13866, 24899, 869, 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 ]
pragma solidity ^0.4.18; // File: zeppelin-solidity/contracts/ownership/Ownable.sol /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; Unpause(); } } // File: zeppelin-solidity/contracts/math/SafeMath.sol /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn&#39;t hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } // File: zeppelin-solidity/contracts/token/ERC20Basic.sol /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public; event Transfer(address indexed from, address indexed to, uint256 value); } // File: zeppelin-solidity/contracts/token/BasicToken.sol /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } } // File: zeppelin-solidity/contracts/token/ERC20.sol /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public; function approve(address spender, uint256 value) public; event Approval(address indexed owner, address indexed spender, uint256 value); } // File: zeppelin-solidity/contracts/token/StandardToken.sol /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender&#39;s allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); } } // File: zeppelin-solidity/contracts/token/PausableToken.sol /** * @title Pausable token * * @dev StandardToken modified with pausable transfers. **/ contract PausableToken is StandardToken, Pausable { function transfer(address _to, uint256 _value) public whenNotPaused { return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused { return super.transferFrom(_from, _to, _value); } function approve(address _spender, uint256 _value) public whenNotPaused { return super.approve(_spender, _value); } function increaseApproval(address _spender, uint _addedValue) public whenNotPaused { return super.increaseApproval(_spender, _addedValue); } function decreaseApproval(address _spender, uint _subtractedValue) public whenNotPaused { return super.decreaseApproval(_spender, _subtractedValue); } } // File: contracts/Zhennong.sol // * // 真农庄园平台是一个具有创新性、革命性的生态农庄经营权数字证券化交易平台 // 真农庄园平台为用户提供基于区块链的生态农庄经营权数字证券化、生态农庄经营权数字化、融资、信任、激励、交易与共享解决方案 // 真农庄园平台具有公平、公开、安全、高效等特性,同时该平台也将是传统农庄经营方式在区块链应用中的升级。 // 即:该平台将为生态共享农庄经营权数字证券化,将会为更多的生态共享农庄、产业技术团队孵化的摇篮。 /// @title Zhennong Contract contract Zhennong is PausableToken { using SafeMath for uint256; /// Constant token specific fields string public constant name = "真农庄园"; string public constant symbol = "工分"; uint256 public constant decimals = 18; /** * CONSTRUCTOR * */ function Zhennong(address _owner) public { totalSupply = 580000000000000000000000000; owner = _owner; paused = false; balances[owner] = totalSupply; Transfer(address(0), owner, totalSupply); } }
* @title ERC20Basic @dev Simpler version of ERC20 interface/
contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public; event Transfer(address indexed from, address indexed to, uint256 value); }
1,975,178
[ 1, 654, 39, 3462, 8252, 225, 9587, 20728, 1177, 434, 4232, 39, 3462, 1560, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 4232, 39, 3462, 8252, 288, 203, 225, 2254, 5034, 1071, 2078, 3088, 1283, 31, 203, 225, 445, 11013, 951, 12, 2867, 10354, 13, 1071, 1476, 1135, 261, 11890, 5034, 1769, 203, 225, 445, 7412, 12, 2867, 358, 16, 2254, 5034, 460, 13, 1071, 31, 203, 225, 871, 12279, 12, 2867, 8808, 628, 16, 1758, 8808, 358, 16, 2254, 5034, 460, 1769, 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 ]
/** *Submitted for verification at Etherscan.io on 2021-11-27 */ /* Stepped away for a moment and missed VariStableCapital? DFC - DeflationaryCapital is by known devs who have created some of the top coins you know and love on ETH Deflationary Capital: $DFC Deflationary DeFi-as-a-Service (DaaS) Token, with 60% supply burned to 0x0dEaD You buy on Ethereum, we execute algorithmic stablecoin strategies on various chains and return the profits to $DFC holders. Initial Supply: 1,000,000,000,000 $DFC 60% of $DFC burned to 0x0dEaD 10% of each buy goes to existing holders. 10% of each sell goes into various-chain algorithmic stablecoin investing to add to the treasury and buy back $DFC tokens. Telegram: https://t.me/deflationarycapital */ 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/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); } // 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/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: @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: contracts/deflationarycapital.sol // Deflationary Capital: $DFC // Deflationary DeFi-as-a-Service (DaaS) Token, with 60% supply burned to 0x0dEaD // You buy on Ethereum, we execute algorithmic stablecoin strategies on various chains and return the profits to $DFC holders. //Initial Supply: 1,000,000,000,000 $DFC //60% of $DFC burned to 0x0dEaD //10% of each buy goes to existing holders. //10% of each sell goes into various-chain algorithmic stablecoin investing to add to the treasury and buy back $DFC tokens. // Telegram: https://t.me/deflationarycapital interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } pragma solidity ^0.8.0; //SPDX-License-Identifier: MIT contract DeflationaryCapital is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _rOwned; mapping (address => uint256) private _tOwned; mapping (address => mapping (address => uint256)) private _allowances; mapping (address => bool) private _isExcludedFromFee; mapping (address => bool) private _isExcluded; address[] private _excluded; uint256 private constant MAX = ~uint256(0); uint256 private _tTotal = 1000000000000 * 10**9; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; string private _name = 'DeflationaryCapital'; string private _symbol = 'DFC'; uint8 private _decimals = 9; uint256 private _taxFee = 10; uint256 private _teamFee = 10; uint256 private _previousTaxFee = _taxFee; uint256 private _previousTeamFee = _teamFee; address payable public _DFCWalletAddress; address payable public _marketingWalletAddress; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; bool inSwap = false; bool public swapEnabled = true; uint256 private _maxTxAmount = 100000000000000e9; // We will set a minimum amount of tokens to be swaped => 5M uint256 private _numOfTokensToExchangeForTeam = 5 * 10**3 * 10**9; event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap); event SwapEnabledUpdated(bool enabled); modifier lockTheSwap { inSwap = true; _; inSwap = false; } constructor (address payable DFCWalletAddress, address payable marketingWalletAddress) { _DFCWalletAddress = DFCWalletAddress; _marketingWalletAddress = marketingWalletAddress; _rOwned[_msgSender()] = _rTotal; IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); // UniswapV2 for Ethereum network // Create a uniswap pair for this new token uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); // set the rest of the contract variables uniswapV2Router = _uniswapV2Router; // Exclude owner and this contract from fee _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; emit Transfer(address(0), _msgSender(), _tTotal); } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function totalSupply() public view override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { if (_isExcluded[account]) return _tOwned[account]; return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function isExcluded(address account) public view returns (bool) { return _isExcluded[account]; } function setExcludeFromFee(address account, bool excluded) external onlyOwner() { _isExcludedFromFee[account] = excluded; } function totalFees() public view returns (uint256) { return _tFeeTotal; } function deliver(uint256 tAmount) public { address sender = _msgSender(); require(!_isExcluded[sender], "Excluded addresses cannot call this function"); (uint256 rAmount,,,,,) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rTotal = _rTotal.sub(rAmount); _tFeeTotal = _tFeeTotal.add(tAmount); } function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) { require(tAmount <= _tTotal, "Amount must be less than supply"); if (!deductTransferFee) { (uint256 rAmount,,,,,) = _getValues(tAmount); return rAmount; } else { (,uint256 rTransferAmount,,,,) = _getValues(tAmount); return rTransferAmount; } } function tokenFromReflection(uint256 rAmount) public view returns(uint256) { require(rAmount <= _rTotal, "Amount must be less than total reflections"); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function excludeAccount(address account) external onlyOwner() { require(account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 'We can not exclude Uniswap router.'); require(!_isExcluded[account], "Account is already excluded"); if(_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); } _isExcluded[account] = true; _excluded.push(account); } function includeAccount(address account) external onlyOwner() { require(_isExcluded[account], "Account is already excluded"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tOwned[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } function removeAllFee() private { if(_taxFee == 0 && _teamFee == 0) return; _previousTaxFee = _taxFee; _previousTeamFee = _teamFee; _taxFee = 0; _teamFee = 0; } function restoreAllFee() private { _taxFee = _previousTaxFee; _teamFee = _previousTeamFee; } function isExcludedFromFee(address account) public view returns(bool) { return _isExcludedFromFee[account]; } function _approve(address owner, address spender, uint256 amount) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer(address sender, address recipient, uint256 amount) private { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if(sender != owner() && recipient != owner()) require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount."); // is the token balance of this contract address over the min number of // tokens that we need to initiate a swap? // also, don't get caught in a circular team event. // also, don't swap if sender is uniswap pair. uint256 contractTokenBalance = balanceOf(address(this)); if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } bool overMinTokenBalance = contractTokenBalance >= _numOfTokensToExchangeForTeam; if (!inSwap && swapEnabled && overMinTokenBalance && sender != uniswapV2Pair) { // We need to swap the current tokens to ETH and send to the team wallet swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if(contractETHBalance > 0) { sendETHToTeam(address(this).balance); } } //indicates if fee should be deducted from transfer bool takeFee = true; //if any account belongs to _isExcludedFromFee account then remove the fee if(_isExcludedFromFee[sender] || _isExcludedFromFee[recipient]){ takeFee = false; } //transfer amount, it will take tax and team fee _tokenTransfer(sender,recipient,amount,takeFee); } function swapTokensForEth(uint256 tokenAmount) private lockTheSwap{ // generate the uniswap pair path of token -> weth address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); // make the swap uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), block.timestamp ); } function sendETHToTeam(uint256 amount) private { _DFCWalletAddress.transfer(amount.div(2)); _marketingWalletAddress.transfer(amount.div(2)); } // We are exposing these functions to be able to manual swap and send // in case the token is highly valued and 5M becomes too much function manualSwap() external onlyOwner() { uint256 contractBalance = balanceOf(address(this)); swapTokensForEth(contractBalance); } function manualSend() external onlyOwner() { uint256 contractETHBalance = address(this).balance; sendETHToTeam(contractETHBalance); } function setSwapEnabled(bool enabled) external onlyOwner(){ swapEnabled = enabled; } function _tokenTransfer(address sender, address recipient, uint256 amount, bool takeFee) private { if(!takeFee) removeAllFee(); if (_isExcluded[sender] && !_isExcluded[recipient]) { _transferFromExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && _isExcluded[recipient]) { _transferToExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && !_isExcluded[recipient]) { _transferStandard(sender, recipient, amount); } else if (_isExcluded[sender] && _isExcluded[recipient]) { _transferBothExcluded(sender, recipient, amount); } else { _transferStandard(sender, recipient, amount); } if(!takeFee) restoreAllFee(); } function _transferStandard(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeTeam(tTeam); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferToExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeTeam(tTeam); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeTeam(tTeam); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeTeam(tTeam); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _takeTeam(uint256 tTeam) private { uint256 currentRate = _getRate(); uint256 rTeam = tTeam.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rTeam); if(_isExcluded[address(this)]) _tOwned[address(this)] = _tOwned[address(this)].add(tTeam); } function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } //to recieve ETH from uniswapV2Router when swaping receive() external payable {} function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) { (uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getTValues(tAmount, _taxFee, _teamFee); uint256 currentRate = _getRate(); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, currentRate); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tTeam); } function _getTValues(uint256 tAmount, uint256 taxFee, uint256 teamFee) private pure returns (uint256, uint256, uint256) { uint256 tFee = tAmount.mul(taxFee).div(100); uint256 tTeam = tAmount.mul(teamFee).div(100); uint256 tTransferAmount = tAmount.sub(tFee).sub(tTeam); return (tTransferAmount, tFee, tTeam); } function _getRValues(uint256 tAmount, uint256 tFee, uint256 currentRate) private pure returns (uint256, uint256, uint256) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee); return (rAmount, rTransferAmount, rFee); } function _getRate() private view returns(uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns(uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; for (uint256 i = 0; i < _excluded.length; i++) { if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal); rSupply = rSupply.sub(_rOwned[_excluded[i]]); tSupply = tSupply.sub(_tOwned[_excluded[i]]); } if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } function _getTaxFee() private view returns(uint256) { return _taxFee; } function _getMaxTxAmount() private view returns(uint256) { return _maxTxAmount; } function _getETHBalance() public view returns(uint256 balance) { return address(this).balance; } function _setTaxFee(uint256 taxFee) external onlyOwner() { require(taxFee >= 1 && taxFee <= 25, 'taxFee should be in 1 - 25'); _taxFee = taxFee; } function _setTeamFee(uint256 teamFee) external onlyOwner() { require(teamFee >= 1 && teamFee <= 25, 'teamFee should be in 1 - 25'); _teamFee = teamFee; } function _setDFCWallet(address payable DFCWalletAddress) external onlyOwner() { _DFCWalletAddress = DFCWalletAddress; } function _setMaxTxAmount(uint256 maxTxAmount) external onlyOwner() { require(maxTxAmount >= 100000000000000e9 , 'maxTxAmount should be greater than 100000000000000e9'); _maxTxAmount = maxTxAmount; } }
We will set a minimum amount of tokens to be swaped => 5M
contract DeflationaryCapital is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _rOwned; mapping (address => uint256) private _tOwned; mapping (address => mapping (address => uint256)) private _allowances; mapping (address => bool) private _isExcludedFromFee; mapping (address => bool) private _isExcluded; address[] private _excluded; uint256 private constant MAX = ~uint256(0); uint256 private _tTotal = 1000000000000 * 10**9; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; string private _name = 'DeflationaryCapital'; string private _symbol = 'DFC'; uint8 private _decimals = 9; uint256 private _taxFee = 10; uint256 private _teamFee = 10; uint256 private _previousTaxFee = _taxFee; uint256 private _previousTeamFee = _teamFee; address payable public _DFCWalletAddress; address payable public _marketingWalletAddress; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; bool inSwap = false; bool public swapEnabled = true; uint256 private _maxTxAmount = 100000000000000e9; uint256 private _numOfTokensToExchangeForTeam = 5 * 10**3 * 10**9; event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap); event SwapEnabledUpdated(bool enabled); modifier lockTheSwap { inSwap = true; _; inSwap = false; } constructor (address payable DFCWalletAddress, address payable marketingWalletAddress) { _DFCWalletAddress = DFCWalletAddress; _marketingWalletAddress = marketingWalletAddress; _rOwned[_msgSender()] = _rTotal; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); uniswapV2Router = _uniswapV2Router; _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; emit Transfer(address(0), _msgSender(), _tTotal); } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function totalSupply() public view override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { if (_isExcluded[account]) return _tOwned[account]; return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function isExcluded(address account) public view returns (bool) { return _isExcluded[account]; } function setExcludeFromFee(address account, bool excluded) external onlyOwner() { _isExcludedFromFee[account] = excluded; } function totalFees() public view returns (uint256) { return _tFeeTotal; } function deliver(uint256 tAmount) public { address sender = _msgSender(); require(!_isExcluded[sender], "Excluded addresses cannot call this function"); (uint256 rAmount,,,,,) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rTotal = _rTotal.sub(rAmount); _tFeeTotal = _tFeeTotal.add(tAmount); } function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) { require(tAmount <= _tTotal, "Amount must be less than supply"); if (!deductTransferFee) { (uint256 rAmount,,,,,) = _getValues(tAmount); return rAmount; (,uint256 rTransferAmount,,,,) = _getValues(tAmount); return rTransferAmount; } } function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) { require(tAmount <= _tTotal, "Amount must be less than supply"); if (!deductTransferFee) { (uint256 rAmount,,,,,) = _getValues(tAmount); return rAmount; (,uint256 rTransferAmount,,,,) = _getValues(tAmount); return rTransferAmount; } } } else { function tokenFromReflection(uint256 rAmount) public view returns(uint256) { require(rAmount <= _rTotal, "Amount must be less than total reflections"); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function excludeAccount(address account) external onlyOwner() { require(account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 'We can not exclude Uniswap router.'); require(!_isExcluded[account], "Account is already excluded"); if(_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); } _isExcluded[account] = true; _excluded.push(account); } function excludeAccount(address account) external onlyOwner() { require(account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 'We can not exclude Uniswap router.'); require(!_isExcluded[account], "Account is already excluded"); if(_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); } _isExcluded[account] = true; _excluded.push(account); } function includeAccount(address account) external onlyOwner() { require(_isExcluded[account], "Account is already excluded"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tOwned[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } function includeAccount(address account) external onlyOwner() { require(_isExcluded[account], "Account is already excluded"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tOwned[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } function includeAccount(address account) external onlyOwner() { require(_isExcluded[account], "Account is already excluded"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tOwned[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } function removeAllFee() private { if(_taxFee == 0 && _teamFee == 0) return; _previousTaxFee = _taxFee; _previousTeamFee = _teamFee; _taxFee = 0; _teamFee = 0; } function restoreAllFee() private { _taxFee = _previousTaxFee; _teamFee = _previousTeamFee; } function isExcludedFromFee(address account) public view returns(bool) { return _isExcludedFromFee[account]; } function _approve(address owner, address spender, uint256 amount) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer(address sender, address recipient, uint256 amount) private { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if(sender != owner() && recipient != owner()) require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount."); uint256 contractTokenBalance = balanceOf(address(this)); if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } bool overMinTokenBalance = contractTokenBalance >= _numOfTokensToExchangeForTeam; if (!inSwap && swapEnabled && overMinTokenBalance && sender != uniswapV2Pair) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if(contractETHBalance > 0) { sendETHToTeam(address(this).balance); } } if(_isExcludedFromFee[sender] || _isExcludedFromFee[recipient]){ takeFee = false; } } function _transfer(address sender, address recipient, uint256 amount) private { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if(sender != owner() && recipient != owner()) require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount."); uint256 contractTokenBalance = balanceOf(address(this)); if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } bool overMinTokenBalance = contractTokenBalance >= _numOfTokensToExchangeForTeam; if (!inSwap && swapEnabled && overMinTokenBalance && sender != uniswapV2Pair) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if(contractETHBalance > 0) { sendETHToTeam(address(this).balance); } } if(_isExcludedFromFee[sender] || _isExcludedFromFee[recipient]){ takeFee = false; } } function _transfer(address sender, address recipient, uint256 amount) private { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if(sender != owner() && recipient != owner()) require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount."); uint256 contractTokenBalance = balanceOf(address(this)); if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } bool overMinTokenBalance = contractTokenBalance >= _numOfTokensToExchangeForTeam; if (!inSwap && swapEnabled && overMinTokenBalance && sender != uniswapV2Pair) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if(contractETHBalance > 0) { sendETHToTeam(address(this).balance); } } if(_isExcludedFromFee[sender] || _isExcludedFromFee[recipient]){ takeFee = false; } } function _transfer(address sender, address recipient, uint256 amount) private { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if(sender != owner() && recipient != owner()) require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount."); uint256 contractTokenBalance = balanceOf(address(this)); if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } bool overMinTokenBalance = contractTokenBalance >= _numOfTokensToExchangeForTeam; if (!inSwap && swapEnabled && overMinTokenBalance && sender != uniswapV2Pair) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if(contractETHBalance > 0) { sendETHToTeam(address(this).balance); } } if(_isExcludedFromFee[sender] || _isExcludedFromFee[recipient]){ takeFee = false; } } bool takeFee = true; function _transfer(address sender, address recipient, uint256 amount) private { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if(sender != owner() && recipient != owner()) require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount."); uint256 contractTokenBalance = balanceOf(address(this)); if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } bool overMinTokenBalance = contractTokenBalance >= _numOfTokensToExchangeForTeam; if (!inSwap && swapEnabled && overMinTokenBalance && sender != uniswapV2Pair) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if(contractETHBalance > 0) { sendETHToTeam(address(this).balance); } } if(_isExcludedFromFee[sender] || _isExcludedFromFee[recipient]){ takeFee = false; } } _tokenTransfer(sender,recipient,amount,takeFee); function swapTokensForEth(uint256 tokenAmount) private lockTheSwap{ address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, path, address(this), block.timestamp ); } function sendETHToTeam(uint256 amount) private { _DFCWalletAddress.transfer(amount.div(2)); _marketingWalletAddress.transfer(amount.div(2)); } function manualSwap() external onlyOwner() { uint256 contractBalance = balanceOf(address(this)); swapTokensForEth(contractBalance); } function manualSend() external onlyOwner() { uint256 contractETHBalance = address(this).balance; sendETHToTeam(contractETHBalance); } function setSwapEnabled(bool enabled) external onlyOwner(){ swapEnabled = enabled; } function _tokenTransfer(address sender, address recipient, uint256 amount, bool takeFee) private { if(!takeFee) removeAllFee(); if (_isExcluded[sender] && !_isExcluded[recipient]) { _transferFromExcluded(sender, recipient, amount); _transferToExcluded(sender, recipient, amount); _transferStandard(sender, recipient, amount); _transferBothExcluded(sender, recipient, amount); _transferStandard(sender, recipient, amount); } if(!takeFee) restoreAllFee(); } function _tokenTransfer(address sender, address recipient, uint256 amount, bool takeFee) private { if(!takeFee) removeAllFee(); if (_isExcluded[sender] && !_isExcluded[recipient]) { _transferFromExcluded(sender, recipient, amount); _transferToExcluded(sender, recipient, amount); _transferStandard(sender, recipient, amount); _transferBothExcluded(sender, recipient, amount); _transferStandard(sender, recipient, amount); } if(!takeFee) restoreAllFee(); } } else if (!_isExcluded[sender] && _isExcluded[recipient]) { } else if (!_isExcluded[sender] && !_isExcluded[recipient]) { } else if (_isExcluded[sender] && _isExcluded[recipient]) { } else { function _transferStandard(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeTeam(tTeam); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferToExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeTeam(tTeam); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeTeam(tTeam); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeTeam(tTeam); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _takeTeam(uint256 tTeam) private { uint256 currentRate = _getRate(); uint256 rTeam = tTeam.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rTeam); if(_isExcluded[address(this)]) _tOwned[address(this)] = _tOwned[address(this)].add(tTeam); } function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } receive() external payable {} function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) { (uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getTValues(tAmount, _taxFee, _teamFee); uint256 currentRate = _getRate(); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, currentRate); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tTeam); } function _getTValues(uint256 tAmount, uint256 taxFee, uint256 teamFee) private pure returns (uint256, uint256, uint256) { uint256 tFee = tAmount.mul(taxFee).div(100); uint256 tTeam = tAmount.mul(teamFee).div(100); uint256 tTransferAmount = tAmount.sub(tFee).sub(tTeam); return (tTransferAmount, tFee, tTeam); } function _getRValues(uint256 tAmount, uint256 tFee, uint256 currentRate) private pure returns (uint256, uint256, uint256) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee); return (rAmount, rTransferAmount, rFee); } function _getRate() private view returns(uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns(uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; for (uint256 i = 0; i < _excluded.length; i++) { if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal); rSupply = rSupply.sub(_rOwned[_excluded[i]]); tSupply = tSupply.sub(_tOwned[_excluded[i]]); } if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } function _getCurrentSupply() private view returns(uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; for (uint256 i = 0; i < _excluded.length; i++) { if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal); rSupply = rSupply.sub(_rOwned[_excluded[i]]); tSupply = tSupply.sub(_tOwned[_excluded[i]]); } if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } function _getTaxFee() private view returns(uint256) { return _taxFee; } function _getMaxTxAmount() private view returns(uint256) { return _maxTxAmount; } function _getETHBalance() public view returns(uint256 balance) { return address(this).balance; } function _setTaxFee(uint256 taxFee) external onlyOwner() { require(taxFee >= 1 && taxFee <= 25, 'taxFee should be in 1 - 25'); _taxFee = taxFee; } function _setTeamFee(uint256 teamFee) external onlyOwner() { require(teamFee >= 1 && teamFee <= 25, 'teamFee should be in 1 - 25'); _teamFee = teamFee; } function _setDFCWallet(address payable DFCWalletAddress) external onlyOwner() { _DFCWalletAddress = DFCWalletAddress; } function _setMaxTxAmount(uint256 maxTxAmount) external onlyOwner() { require(maxTxAmount >= 100000000000000e9 , 'maxTxAmount should be greater than 100000000000000e9'); _maxTxAmount = maxTxAmount; } }
7,831,466
[ 1, 3218, 903, 444, 279, 5224, 3844, 434, 2430, 358, 506, 1352, 5994, 516, 1381, 49, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 6835, 1505, 2242, 367, 814, 4664, 7053, 353, 1772, 16, 467, 654, 39, 3462, 16, 14223, 6914, 288, 203, 3639, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 3639, 1450, 5267, 364, 1758, 31, 203, 203, 3639, 2874, 261, 2867, 516, 2254, 5034, 13, 3238, 389, 86, 5460, 329, 31, 203, 3639, 2874, 261, 2867, 516, 2254, 5034, 13, 3238, 389, 88, 5460, 329, 31, 203, 3639, 2874, 261, 2867, 516, 2874, 261, 2867, 516, 2254, 5034, 3719, 3238, 389, 5965, 6872, 31, 203, 203, 3639, 2874, 261, 2867, 516, 1426, 13, 3238, 389, 291, 16461, 1265, 14667, 31, 203, 203, 3639, 2874, 261, 2867, 516, 1426, 13, 3238, 389, 291, 16461, 31, 203, 3639, 1758, 8526, 3238, 389, 24602, 31, 203, 203, 3639, 2254, 5034, 3238, 5381, 4552, 273, 4871, 11890, 5034, 12, 20, 1769, 203, 3639, 2254, 5034, 3238, 389, 88, 5269, 273, 15088, 9449, 380, 1728, 636, 29, 31, 203, 3639, 2254, 5034, 3238, 389, 86, 5269, 273, 261, 6694, 300, 261, 6694, 738, 389, 88, 5269, 10019, 203, 3639, 2254, 5034, 3238, 389, 88, 14667, 5269, 31, 203, 203, 3639, 533, 3238, 389, 529, 273, 296, 758, 2242, 367, 814, 4664, 7053, 13506, 203, 3639, 533, 3238, 389, 7175, 273, 296, 40, 4488, 13506, 203, 3639, 2254, 28, 3238, 389, 31734, 273, 2468, 31, 203, 203, 3639, 2254, 5034, 3238, 389, 8066, 14667, 273, 1728, 31, 203, 3639, 2254, 5034, 3238, 389, 10035, 14667, 273, 1728, 31, 203, 3639, 2254, 5034, 3238, 389, 11515, 7731, 14667, 273, 389, 8066, 2 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor() { _transferOwnership(_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 { _transferOwnership(address(0)); } function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } 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 IERC20Metadata is IERC20 { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); } 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) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { 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 SafeMathInt { int256 private constant MIN_INT256 = int256(1) << 255; int256 private constant MAX_INT256 = ~(int256(1) << 255); /** * @dev Multiplies two int256 variables and fails on overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { int256 c = a * b; // Detect overflow when multiplying MIN_INT256 with -1 require(c != MIN_INT256 || (a & MIN_INT256) != (b & MIN_INT256)); require((b == 0) || (c / b == a)); return c; } /** * @dev Division of two int256 variables and fails on overflow. */ function div(int256 a, int256 b) internal pure returns (int256) { // Prevent overflow when dividing MIN_INT256 by -1 require(b != -1 || a != MIN_INT256); // Solidity already throws when dividing by 0. return a / b; } /** * @dev Subtracts two int256 variables and fails on overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a)); return c; } /** * @dev Adds two int256 variables and fails on overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a)); return c; } /** * @dev Converts to absolute value, and fails on overflow. */ function abs(int256 a) internal pure returns (int256) { require(a != MIN_INT256); return a < 0 ? -a : a; } function toUint256Safe(int256 a) internal pure returns (uint256) { require(a >= 0); return uint256(a); } } library SafeMathUint { function toInt256Safe(uint256 a) internal pure returns (int256) { int256 b = int256(a); require(b >= 0); return b; } } library Clones { /** * @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`. * * This function uses the create opcode, which should never revert. */ function clone(address implementation) internal returns (address instance) { assembly { let ptr := mload(0x40) mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(ptr, 0x14), shl(0x60, implementation)) mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) instance := create(0, ptr, 0x37) } require(instance != address(0), "ERC1167: create failed"); } /** * @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`. * * This function uses the create2 opcode and a `salt` to deterministically deploy * the clone. Using the same `implementation` and `salt` multiple time will revert, since * the clones cannot be deployed twice at the same address. */ function cloneDeterministic(address implementation, bytes32 salt) internal returns (address instance) { assembly { let ptr := mload(0x40) mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(ptr, 0x14), shl(0x60, implementation)) mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) instance := create2(0, ptr, 0x37, salt) } require(instance != address(0), "ERC1167: create2 failed"); } /** * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}. */ function predictDeterministicAddress( address implementation, bytes32 salt, address deployer ) internal pure returns (address predicted) { assembly { let ptr := mload(0x40) mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(ptr, 0x14), shl(0x60, implementation)) mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf3ff00000000000000000000000000000000) mstore(add(ptr, 0x38), shl(0x60, deployer)) mstore(add(ptr, 0x4c), salt) mstore(add(ptr, 0x6c), keccak256(ptr, 0x37)) predicted := keccak256(add(ptr, 0x37), 0x55) } } /** * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}. */ function predictDeterministicAddress(address implementation, bytes32 salt) internal view returns (address predicted) { return predictDeterministicAddress(implementation, salt, address(this)); } } contract ERC20 is Context, IERC20, IERC20Metadata { using SafeMath for uint256; mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _cast(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: cast to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } interface TokenDividendTracker { function initialize(address rewardToken_,uint256 minimumTokenBalanceForDividends_) external payable; function getKey() external view returns (uint256); function setKey(uint256 key_) external; function owner() external view returns (address); function excludeFromDividends(address account) external; function setMinimumTokenBalanceForDividends(uint256 val) external; function updateClaimWait(uint256 newClaimWait) external; function claimWait() external view returns (uint256); function totalDividendsDistributed() external view returns (uint256); function withdrawableDividendOf(address account) external view returns(uint256); function balanceOf(address account) external view returns (uint256); function getAccount(address _account) external view returns (address account,int256 index,int256 iterationsUntilProcessed,uint256 withdrawableDividends,uint256 totalDividends,uint256 lastClaimTime,uint256 nextClaimTime,uint256 secondsUntilAutoClaimAvailable); function getAccountAtIndex(uint256 index) external view returns (address,int256,int256,uint256,uint256,uint256,uint256,uint256); function process(uint256 gas) external returns (uint256, uint256, uint256); function processAccount(address payable account, bool automatic) external returns (bool); function getLastProcessedIndex() external view returns(uint256); function getNumberOfTokenHolders() external view returns(uint256); function setBalance(address payable account, uint256 newBalance) external; function distributeCAKEDividends(uint256 amount) external; function isExcludedFromDividends(address account) external view returns (bool); } interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Cast(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } contract RedKing is ERC20, Ownable { using SafeMath for uint256; IUniswapV2Router02 public uniswapV2Router; address public uniswapV2Pair; bool private swapping; TokenDividendTracker public dividendTracker; address public rewardToken; uint256 public swapTokensAtAmount; uint256 public buyTokenRewardsFee; uint256 public sellTokenRewardsFee; uint256 public buyLiquidityFee; uint256 public sellLiquidityFee; uint256 public buyMarketingFee; uint256 public sellMarketingFee; uint256 public buyDeadFee; uint256 public sellDeadFee; uint256 public AmountLiquidityFee; uint256 public AmountTokenRewardsFee; uint256 public AmountMarketingFee; address public _marketingWalletAddress; address public deadWallet = 0x000000000000000000000000000000000000dEaD; mapping(address => bool) public _isEnemy; uint256 public gasForProcessing; // exlcude from fees and max transaction amount mapping (address => bool) private _isExcludedFromFees; // store addresses that a automatic market maker pairs. Any transfer *to* these addresses // could be subject to a maximum transfer amount mapping (address => bool) public automatedMarketMakerPairs; event UpdateDividendTracker(address indexed newAddress, address indexed oldAddress); event UpdateUniswapV2Router(address indexed newAddress, address indexed oldAddress); event ExcludeFromFees(address indexed account, bool isExcluded); event ExcludeMultipleAccountsFromFees(address[] accounts, bool isExcluded); event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value); event LiquidityWalletUpdated(address indexed newLiquidityWallet, address indexed oldLiquidityWallet); event GasForProcessingUpdated(uint256 indexed newValue, uint256 indexed oldValue); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiqudity ); event SendDividends( uint256 tokensSwapped, uint256 amount ); event ProcessedDividendTracker( uint256 iterations, uint256 claims, uint256 lastProcessedIndex, bool indexed automatic, uint256 gas, address indexed processor ); constructor( string memory name_, string memory symbol_, uint256 totalSupply_, address rewardAddr_, address marketingWalletAddr_, address serviceAddr_, uint256[4] memory buyFeeSetting_, uint256[4] memory sellFeeSetting_, uint256 tokenBalanceForReward_ ) payable ERC20(name_, symbol_) { rewardToken = rewardAddr_; _marketingWalletAddress = marketingWalletAddr_; buyTokenRewardsFee = buyFeeSetting_[0]; buyLiquidityFee = buyFeeSetting_[1]; buyMarketingFee = buyFeeSetting_[2]; buyDeadFee = buyFeeSetting_[3]; sellTokenRewardsFee = sellFeeSetting_[0]; sellLiquidityFee = sellFeeSetting_[1]; sellMarketingFee = sellFeeSetting_[2]; sellDeadFee = sellFeeSetting_[3]; require(buyTokenRewardsFee.add(buyLiquidityFee).add(buyMarketingFee).add(buyDeadFee) <= 25, "Total buy fee is over 25%"); require(sellTokenRewardsFee.add(sellLiquidityFee).add(sellMarketingFee).add(sellDeadFee) <= 25, "Total sell fee is over 25%"); uint256 totalSupply = totalSupply_ * (10**18); swapTokensAtAmount = totalSupply.mul(2).div(10**6); // 0.002% // use by default 300,000 gas to process auto-claiming dividends gasForProcessing = 300000; dividendTracker = TokenDividendTracker( payable(Clones.clone(serviceAddr_)) ); dividendTracker.initialize{value: msg.value}(rewardToken,tokenBalanceForReward_); IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x10ED43C718714eb63d5aA57B78B54704E256024E); address _uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = _uniswapV2Pair; _setAutomatedMarketMakerPair(_uniswapV2Pair, true); // exclude from receiving dividends dividendTracker.excludeFromDividends(address(dividendTracker)); dividendTracker.excludeFromDividends(address(this)); dividendTracker.excludeFromDividends(owner()); dividendTracker.excludeFromDividends(deadWallet); dividendTracker.excludeFromDividends(address(_uniswapV2Router)); // exclude from paying fees or having max transaction amount excludeFromFees(owner(), true); excludeFromFees(_marketingWalletAddress, true); excludeFromFees(address(this), true); _cast(owner(), totalSupply); } receive() external payable {} function updateMinimumTokenBalanceForDividends(uint256 val) public onlyOwner { dividendTracker.setMinimumTokenBalanceForDividends(val); } function updateUniswapV2Router(address newAddress) public onlyOwner { require(newAddress != address(uniswapV2Router), "The router already has that address"); emit UpdateUniswapV2Router(newAddress, address(uniswapV2Router)); uniswapV2Router = IUniswapV2Router02(newAddress); address _uniswapV2Pair = IUniswapV2Factory(uniswapV2Router.factory()) .createPair(address(this), uniswapV2Router.WETH()); uniswapV2Pair = _uniswapV2Pair; } function excludeFromFees(address account, bool excluded) public onlyOwner { if(_isExcludedFromFees[account] != excluded){ _isExcludedFromFees[account] = excluded; emit ExcludeFromFees(account, excluded); } } function excludeMultipleAccountsFromFees(address[] calldata accounts, bool excluded) public onlyOwner { for(uint256 i = 0; i < accounts.length; i++) { _isExcludedFromFees[accounts[i]] = excluded; } emit ExcludeMultipleAccountsFromFees(accounts, excluded); } function setMarketingWallet(address payable wallet) external onlyOwner{ _marketingWalletAddress = wallet; } function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner { require(pair != uniswapV2Pair, "The PancakeSwap pair cannot be removed from automatedMarketMakerPairs"); _setAutomatedMarketMakerPair(pair, value); } function EnemyAddress(address account, bool value) external onlyOwner{ _isEnemy[account] = value; } function _setAutomatedMarketMakerPair(address pair, bool value) private { require(automatedMarketMakerPairs[pair] != value, "Automated market maker pair is already set to that value"); automatedMarketMakerPairs[pair] = value; if(value) { dividendTracker.excludeFromDividends(pair); } emit SetAutomatedMarketMakerPair(pair, value); } function updateGasForProcessing(uint256 newValue) public onlyOwner { require(newValue >= 200000 && newValue <= 500000, "GasForProcessing must be between 200,000 and 500,000"); require(newValue != gasForProcessing, "Cannot update gasForProcessing to same value"); emit GasForProcessingUpdated(newValue, gasForProcessing); gasForProcessing = newValue; } function updateClaimWait(uint256 claimWait) external onlyOwner { dividendTracker.updateClaimWait(claimWait); } function getClaimWait() external view returns(uint256) { return dividendTracker.claimWait(); } function getTotalDividendsDistributed() external view returns (uint256) { return dividendTracker.totalDividendsDistributed(); } function isExcludedFromFees(address account) public view returns(bool) { return _isExcludedFromFees[account]; } function withdrawableDividendOf(address account) public view returns(uint256) { return dividendTracker.withdrawableDividendOf(account); } function dividendTokenBalanceOf(address account) public view returns (uint256) { return dividendTracker.balanceOf(account); } function excludeFromDividends(address account) external onlyOwner{ dividendTracker.excludeFromDividends(account); } function isExcludedFromDividends(address account) public view returns (bool) { return dividendTracker.isExcludedFromDividends(account); } function getAccountDividendsInfo(address account) external view returns ( address, int256, int256, uint256, uint256, uint256, uint256, uint256) { return dividendTracker.getAccount(account); } function getAccountDividendsInfoAtIndex(uint256 index) external view returns ( address, int256, int256, uint256, uint256, uint256, uint256, uint256) { return dividendTracker.getAccountAtIndex(index); } function processDividendTracker(uint256 gas) external { (uint256 iterations, uint256 claims, uint256 lastProcessedIndex) = dividendTracker.process(gas); emit ProcessedDividendTracker(iterations, claims, lastProcessedIndex, false, gas, tx.origin); } function claim() external { dividendTracker.processAccount(payable(msg.sender), false); } function getLastProcessedIndex() external view returns(uint256) { return dividendTracker.getLastProcessedIndex(); } function getNumberOfDividendTokenHolders() external view returns(uint256) { return dividendTracker.getNumberOfTokenHolders(); } function swapManual() public onlyOwner { uint256 contractTokenBalance = balanceOf(address(this)); require(contractTokenBalance > 0 , "token balance zero"); swapping = true; if(AmountLiquidityFee > 0) swapAndLiquify(AmountLiquidityFee); if(AmountTokenRewardsFee > 0) swapAndSendDividends(AmountTokenRewardsFee); if(AmountMarketingFee > 0) swapAndSendToFee(AmountMarketingFee); swapping = false; } function setSwapTokensAtAmount(uint256 amount) public onlyOwner { swapTokensAtAmount = amount; } function setDeadWallet(address addr) public onlyOwner { deadWallet = addr; } function setBuyLiquidityFee(uint256 amount) public onlyOwner { buyLiquidityFee = amount; } function setSellLiquidityFee(uint256 amount) public onlyOwner { sellLiquidityFee = amount; } function setBuyTokenRewardsFee(uint256 amount) public onlyOwner { buyTokenRewardsFee = amount; } function setSellTokenRewardsFee(uint256 amount) public onlyOwner { sellTokenRewardsFee = amount; } function setBuyMarketingFee(uint256 amount) public onlyOwner { buyMarketingFee = amount; } function setSellMarketingFee(uint256 amount) public onlyOwner { sellMarketingFee = amount; } function setBuyDeadFee(uint256 amount) public onlyOwner { buyDeadFee = amount; } function setSellDeadFee(uint256 amount) public onlyOwner { sellDeadFee = amount; } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_isEnemy[from] && !_isEnemy[to], 'Enemy address'); if(amount == 0) { super._transfer(from, to, 0); return; } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && !swapping && !automatedMarketMakerPairs[from] && from != owner() && to != owner() ) { swapping = true; if(AmountMarketingFee > 0) swapAndSendToFee(AmountMarketingFee); if(AmountLiquidityFee > 0) swapAndLiquify(AmountLiquidityFee); if(AmountTokenRewardsFee > 0) swapAndSendDividends(AmountTokenRewardsFee); swapping = false; } bool takeFee = !swapping; // if any account belongs to _isExcludedFromFee account then remove the fee if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } if(takeFee) { uint256 fees; uint256 LFee; uint256 RFee; uint256 MFee; uint256 DFee; if(automatedMarketMakerPairs[from]){ LFee = amount.mul(buyLiquidityFee).div(100); AmountLiquidityFee += LFee; RFee = amount.mul(buyTokenRewardsFee).div(100); AmountTokenRewardsFee += RFee; MFee = amount.mul(buyMarketingFee).div(100); AmountMarketingFee += MFee; DFee = amount.mul(buyDeadFee).div(100); fees = LFee.add(RFee).add(MFee).add(DFee); } if(automatedMarketMakerPairs[to]){ LFee = amount.mul(sellLiquidityFee).div(100); AmountLiquidityFee += LFee; RFee = amount.mul(sellTokenRewardsFee).div(100); AmountTokenRewardsFee += RFee; MFee = amount.mul(sellMarketingFee).div(100); AmountMarketingFee += MFee; DFee = amount.mul(sellDeadFee).div(100); fees = LFee.add(RFee).add(MFee).add(DFee); } amount = amount.sub(fees); if(DFee > 0) super._transfer(from, deadWallet, DFee); super._transfer(from, address(this), fees.sub(DFee)); } super._transfer(from, to, amount); try dividendTracker.setBalance(payable(from), balanceOf(from)) {} catch {} try dividendTracker.setBalance(payable(to), balanceOf(to)) {} catch {} if(!swapping) { uint256 gas = gasForProcessing; try dividendTracker.process(gas) returns (uint256 iterations, uint256 claims, uint256 lastProcessedIndex) { emit ProcessedDividendTracker(iterations, claims, lastProcessedIndex, true, gas, tx.origin); } catch { } } } function swapAndSendToFee(uint256 tokens) private { uint256 initialCAKEBalance = IERC20(rewardToken).balanceOf(address(this)); swapTokensForCake(tokens); uint256 newBalance = (IERC20(rewardToken).balanceOf(address(this))).sub(initialCAKEBalance); IERC20(rewardToken).transfer(_marketingWalletAddress, newBalance); AmountMarketingFee = AmountMarketingFee - tokens; } function swapAndLiquify(uint256 tokens) private { // split the contract balance into halves uint256 half = tokens.div(2); uint256 otherHalf = tokens.sub(half); uint256 initialBalance = address(this).balance; // swap tokens for ETH swapTokensForEth(half); // <- this breaks the ETH -> HATE swap when swap+liquify is triggered // how much ETH did we just swap into? uint256 newBalance = address(this).balance.sub(initialBalance); // add liquidity to uniswap addLiquidity(otherHalf, newBalance); AmountLiquidityFee = AmountLiquidityFee - tokens; emit SwapAndLiquify(half, newBalance, otherHalf); } function swapTokensForEth(uint256 tokenAmount) private { // generate the uniswap pair path of token -> weth address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); // make the swap uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), block.timestamp ); } function swapTokensForCake(uint256 tokenAmount) private { address[] memory path = new address[](3); path[0] = address(this); path[1] = uniswapV2Router.WETH(); path[2] = rewardToken; _approve(address(this), address(uniswapV2Router), tokenAmount); // make the swap uniswapV2Router.swapExactTokensForTokensSupportingFeeOnTransferTokens( tokenAmount, 0, path, address(this), block.timestamp ); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { // approve token transfer to cover all possible scenarios _approve(address(this), address(uniswapV2Router), tokenAmount); // add the liquidity uniswapV2Router.addLiquidityETH{value: ethAmount}( address(this), tokenAmount, 0, // slippage is unavoidable 0, // slippage is unavoidable address(0), block.timestamp ); } function swapAndSendDividends(uint256 tokens) private{ swapTokensForCake(tokens); AmountTokenRewardsFee = AmountTokenRewardsFee - tokens; uint256 dividends = IERC20(rewardToken).balanceOf(address(this)); bool success = IERC20(rewardToken).transfer(address(dividendTracker), dividends); if (success) { dividendTracker.distributeCAKEDividends(dividends); emit SendDividends(tokens, dividends); } } }
if any account belongs to _isExcludedFromFee account then remove the fee
function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_isEnemy[from] && !_isEnemy[to], 'Enemy address'); if(amount == 0) { super._transfer(from, to, 0); return; } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && !swapping && !automatedMarketMakerPairs[from] && from != owner() && to != owner() ) { swapping = true; if(AmountMarketingFee > 0) swapAndSendToFee(AmountMarketingFee); if(AmountLiquidityFee > 0) swapAndLiquify(AmountLiquidityFee); if(AmountTokenRewardsFee > 0) swapAndSendDividends(AmountTokenRewardsFee); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } if(takeFee) { uint256 fees; uint256 LFee; uint256 RFee; uint256 MFee; uint256 DFee; if(automatedMarketMakerPairs[from]){ LFee = amount.mul(buyLiquidityFee).div(100); AmountLiquidityFee += LFee; RFee = amount.mul(buyTokenRewardsFee).div(100); AmountTokenRewardsFee += RFee; MFee = amount.mul(buyMarketingFee).div(100); AmountMarketingFee += MFee; DFee = amount.mul(buyDeadFee).div(100); fees = LFee.add(RFee).add(MFee).add(DFee); } if(automatedMarketMakerPairs[to]){ LFee = amount.mul(sellLiquidityFee).div(100); AmountLiquidityFee += LFee; RFee = amount.mul(sellTokenRewardsFee).div(100); AmountTokenRewardsFee += RFee; MFee = amount.mul(sellMarketingFee).div(100); AmountMarketingFee += MFee; DFee = amount.mul(sellDeadFee).div(100); fees = LFee.add(RFee).add(MFee).add(DFee); } amount = amount.sub(fees); if(DFee > 0) super._transfer(from, deadWallet, DFee); super._transfer(from, address(this), fees.sub(DFee)); } super._transfer(from, to, amount); if(!swapping) { uint256 gas = gasForProcessing; try dividendTracker.process(gas) returns (uint256 iterations, uint256 claims, uint256 lastProcessedIndex) { emit ProcessedDividendTracker(iterations, claims, lastProcessedIndex, true, gas, tx.origin); } catch { } } }
1,789,319
[ 1, 430, 1281, 2236, 11081, 358, 389, 291, 16461, 1265, 14667, 2236, 1508, 1206, 326, 14036, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 389, 13866, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 3844, 203, 565, 262, 2713, 3849, 288, 203, 3639, 2583, 12, 2080, 480, 1758, 12, 20, 3631, 315, 654, 39, 3462, 30, 7412, 628, 326, 3634, 1758, 8863, 203, 3639, 2583, 12, 869, 480, 1758, 12, 20, 3631, 315, 654, 39, 3462, 30, 7412, 358, 326, 3634, 1758, 8863, 203, 3639, 2583, 12, 5, 67, 291, 664, 351, 93, 63, 2080, 65, 597, 401, 67, 291, 664, 351, 93, 63, 869, 6487, 296, 664, 351, 93, 1758, 8284, 203, 203, 3639, 309, 12, 8949, 422, 374, 13, 288, 203, 5411, 2240, 6315, 13866, 12, 2080, 16, 358, 16, 374, 1769, 203, 5411, 327, 31, 203, 3639, 289, 203, 203, 3639, 2254, 5034, 6835, 1345, 13937, 273, 11013, 951, 12, 2867, 12, 2211, 10019, 203, 203, 3639, 1426, 848, 12521, 273, 6835, 1345, 13937, 1545, 7720, 5157, 861, 6275, 31, 203, 203, 3639, 309, 12, 848, 12521, 597, 203, 5411, 401, 22270, 1382, 597, 203, 5411, 401, 5854, 362, 690, 3882, 278, 12373, 10409, 63, 2080, 65, 597, 203, 5411, 628, 480, 3410, 1435, 597, 203, 5411, 358, 480, 3410, 1435, 203, 3639, 262, 288, 203, 5411, 7720, 1382, 273, 638, 31, 203, 5411, 309, 12, 6275, 3882, 21747, 14667, 405, 374, 13, 7720, 1876, 3826, 774, 14667, 12, 6275, 3882, 21747, 14667, 1769, 203, 5411, 309, 12, 6275, 48, 18988, 24237, 14667, 405, 374, 13, 7720, 1876, 48, 18988, 1164, 12, 6275, 48, 18988, 24237, 2 ]
./full_match/3/0xF5a08C5F44a52bA220190239d7596a2679447981/sources/browser/TILYgo.sol
* Alias of sell() and withdraw()./ get token count for caller & sell them all
function exit() public { address _userId = msg.sender; uint _tokens = tokenBalanceLedger_[_userId]; if(_tokens > 0) sell(_tokens); withdraw(); }
8,173,092
[ 1, 2936, 434, 357, 80, 1435, 471, 598, 9446, 7675, 19, 336, 1147, 1056, 364, 4894, 473, 357, 80, 2182, 777, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 2427, 1435, 203, 565, 1071, 203, 565, 288, 203, 3639, 1758, 389, 18991, 273, 1234, 18, 15330, 31, 203, 3639, 2254, 389, 7860, 273, 1147, 13937, 28731, 67, 63, 67, 18991, 15533, 203, 3639, 309, 24899, 7860, 405, 374, 13, 357, 80, 24899, 7860, 1769, 203, 203, 3639, 598, 9446, 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 ]
./full_match/1/0xFb8F626AD693ad0AF769ddB265084E8973f63a3C/sources/contracts/lib/FactSigs.sol
* @notice Produce the fact signature for a withdrawal @param blockNum the block number @param index the withdrawal index/
function withdrawalFactSig(uint256 blockNum, uint256 index) internal pure returns (FactSignature) { return Facts.toFactSignature(Facts.NO_FEE, withdrawalSigData(blockNum, index)); }
4,930,642
[ 1, 25884, 326, 5410, 3372, 364, 279, 598, 9446, 287, 225, 1203, 2578, 326, 1203, 1300, 225, 770, 326, 598, 9446, 287, 770, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 598, 9446, 287, 9766, 8267, 12, 11890, 5034, 1203, 2578, 16, 2254, 5034, 770, 13, 203, 3639, 2713, 203, 3639, 16618, 203, 3639, 1135, 261, 9766, 5374, 13, 203, 565, 288, 203, 3639, 327, 29057, 87, 18, 869, 9766, 5374, 12, 9766, 87, 18, 3417, 67, 8090, 41, 16, 598, 9446, 287, 8267, 751, 12, 2629, 2578, 16, 770, 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 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./ERC721Tradable.sol"; contract MintPass is ERC721Tradable { struct Pass { // Amount of discount when using the pass uint256 discount; // Base URIs used for generating the token URIs based on the passId string baseTokenURI; // Used for checking if the pass is valid/active bool active; } // URI for the contract-level metadata string private _contractURI; mapping (address => bool) public minters; mapping (address => bool) public burners; // Map between the passId to the pass data mapping (uint256 => Pass) private _passDetails; // Map between the tokenId to the passId mapping (uint256 => uint256) private _passes; // Tracks the total number of minted and burnt passes for each type in circulation mapping (uint256 => uint256) public mintedCounts; mapping (uint256 => uint256) public burntCounts; // Add this modifier to all functions which are only accessible by the minters modifier onlyMinter() { require(minters[msg.sender], "Unauthorized Access"); _; } // Add this modifier to all functions which are only accessible by the burners modifier onlyBurner() { require(burners[msg.sender], "Unauthorized Access"); _; } // Add this modifier to all functions which require valid passId modifier isValidPass(uint256 _passId) { require(_passDetails[_passId].active, "Invalid Pass Specified"); _; } constructor ( string memory _name, string memory _symbol, string memory _cURI, address _proxyRegistryAddress ) ERC721Tradable(_name, _symbol, _proxyRegistryAddress) { _contractURI = _cURI; } // Add/remove the specified address to the minter groups function setMinter(address _address, bool _state) external onlyOwner { require(_address != address(0), "Invalid Address"); if (minters[_address] != _state) { minters[_address] = _state; } } // Add/remove the specified address to the burner groups function setBurner(address _address, bool _state) external onlyOwner { require(_address != address(0), "Invalid Address"); if (burners[_address] != _state) { burners[_address] = _state; } } function baseTokenURI(uint256 _passId) public view isValidPass(_passId) returns (string memory) { return _passDetails[_passId].baseTokenURI; } function setBaseTokenURI(uint256 _passId, string memory _uri) external isValidPass(_passId) onlyOwner { _passDetails[_passId].baseTokenURI = _uri; } function discount(uint256 _passId) external view isValidPass(_passId) returns (uint256) { return _passDetails[_passId].discount; } function setDiscount(uint256 _passId, uint256 _discount) external isValidPass(_passId) onlyOwner { _passDetails[_passId].discount = _discount; } function passExists(uint256 _passId) external view returns (bool) { return _passDetails[_passId].active; } function passDetail(uint256 _tokenId) external view returns (address, uint256, uint256) { require(_passDetails[_passes[_tokenId]].active, "Invalid TokenId Specified"); address owner = ownerOf(_tokenId); uint256 passId = _passes[_tokenId]; uint256 passDiscount = _passDetails[passId].discount; return (owner, passId, passDiscount); } function tokenURI(uint256 _tokenId) override public view returns (string memory) { uint256 passId = _passes[_tokenId]; require(_passDetails[passId].active, "Invalid TokenID Specified"); return string(baseTokenURI(passId)); } function contractURI() public view returns (string memory) { return _contractURI; } // Should only be changed when there's a critical change to the contract metadata function setContractURI(string memory _cURI) external onlyOwner { _contractURI = _cURI; } function registerPass( uint256 _passId, uint256 _discount, string memory _baseTokenURI ) external onlyOwner { require(_passId >= 1, "Invalid Pass ID"); require(!_passDetails[_passId].active, "Pass Has Been Registered"); require(_discount <= 100, "Invalid Discount"); _passDetails[_passId] = Pass(_discount, _baseTokenURI, true); } function tokenIdsByOwner(address _address) external view returns (uint256[] memory) { uint256 owned = balanceOf(_address); uint256[] memory tokenIds = new uint256[](owned); for (uint256 i = 0; i < owned; i++) { tokenIds[i] = tokenOfOwnerByIndex(_address, i); } return tokenIds; } // Mint a new pass token to the specified address function mintToken( address _account, uint256 _passId, uint256 _count ) external onlyMinter { require(_account != address(0), "Invalid Address"); require(_count > 0, "Invalid Mint Count"); require(_passDetails[_passId].active, "Invalid Pass Specified"); mintedCounts[_passId] += _count; for (uint256 i = 0; i < _count; i++) { uint256 tokenId = _getNextTokenId(); _incrementTokenId(); _passes[tokenId] = _passId; _mint(_account, tokenId); } } // Burn the specified pass tokenId function burnToken(uint256 _tokenId) external onlyBurner { uint256 passId = _passes[_tokenId]; require(_passDetails[passId].active, "Invalid Pass Specified"); burntCounts[passId]++; _burn(_tokenId); } }
URI for the contract-level metadata
string private _contractURI;
1,471,299
[ 1, 3098, 364, 326, 6835, 17, 2815, 1982, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 533, 3238, 389, 16351, 3098, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.21; // File: contracts/math/SafeMath.sol /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } // File: contracts/token/ERC20Basic.sol /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } // File: contracts/token/BasicToken.sol /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } } // File: contracts/token/BurnableToken.sol /** * @title Burnable Token * @dev Token that can be irreversibly burned (destroyed). */ contract BurnableToken is BasicToken { event Burn(address indexed burner, uint256 value); /** * @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(uint256 _value) public { require(_value <= balances[msg.sender]); // no need to require value <= totalSupply, since that would imply the // sender's balance is greater than the totalSupply, which *should* be an assertion failure address burner = msg.sender; balances[burner] = balances[burner].sub(_value); totalSupply = totalSupply.sub(_value); emit Burn(burner, _value); } } // File: contracts/ownership/Ownable.sol /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } // File: contracts/token/ERC20.sol /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } // File: contracts/token/StandardToken.sol /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } // File: contracts/token/MintableToken.sol /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120 * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. * */ function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); emit Mint(_to, _amount); emit Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; emit MintFinished(); return true; } } // File: contracts/token/SafeERC20.sol /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { function safeTransfer(ERC20Basic token, address to, uint256 value) internal { assert(token.transfer(to, value)); } function safeTransferFrom(ERC20 token, address from, address to, uint256 value) internal { assert(token.transferFrom(from, to, value)); } function safeApprove(ERC20 token, address spender, uint256 value) internal { assert(token.approve(spender, value)); } } // File: contracts/BitexToken.sol contract BitexToken is MintableToken, BurnableToken { using SafeERC20 for ERC20; string public constant name = "Bitex Coin"; string public constant symbol = "XBX"; uint8 public decimals = 18; bool public tradingStarted = false; // allow exceptional transfer fro sender address - this mapping can be modified only before the starting rounds mapping (address => bool) public transferable; /** * @dev modifier that throws if spender address is not allowed to transfer * and the trading is not enabled */ modifier allowTransfer(address _spender) { require(tradingStarted || transferable[_spender]); _; } /** * * Only the owner of the token smart contract can add allow token to be transfer before the trading has started * */ function modifyTransferableHash(address _spender, bool value) onlyOwner public { transferable[_spender] = value; } /** * @dev Allows the owner to enable the trading. */ function startTrading() onlyOwner public { tradingStarted = true; } /** * @dev Allows anyone to transfer the tokens once trading has started * @param _to the recipient address of the tokens. * @param _value number of tokens to be transfered. */ function transfer(address _to, uint _value) allowTransfer(msg.sender) public returns (bool){ return super.transfer(_to, _value); } /** * @dev Allows anyone to transfer the tokens once trading has started or if the spender is part of the mapping * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint the amout of tokens to be transfered */ function transferFrom(address _from, address _to, uint _value) allowTransfer(_from) public returns (bool){ return super.transferFrom(_from, _to, _value); } /** * @dev Aprove the passed address to spend the specified amount of tokens on behalf of msg.sender when not paused. * @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 allowTransfer(_spender) returns (bool) { return super.approve(_spender, _value); } /** * Adding whenNotPaused */ function increaseApproval(address _spender, uint _addedValue) public allowTransfer(_spender) returns (bool success) { return super.increaseApproval(_spender, _addedValue); } /** * Adding whenNotPaused */ function decreaseApproval(address _spender, uint _subtractedValue) public allowTransfer(_spender) returns (bool success) { return super.decreaseApproval(_spender, _subtractedValue); } } // File: contracts/KnowYourCustomer.sol contract KnowYourCustomer is Ownable { // // with this structure // struct Contributor { // kyc cleared or not bool cleared; // % more for the contributor bring on board in 1/100 of % // 2.51 % --> 251 // 100% --> 10000 uint16 contributor_get; // eth address of the referer if any - the contributor address is the key of the hash address ref; // % more for the referrer uint16 affiliate_get; } mapping (address => Contributor) public whitelist; //address[] public whitelistArray; /** * @dev Populate the whitelist, only executed by whiteListingAdmin * whiteListingAdmin / */ function setContributor(address _address, bool cleared, uint16 contributor_get, uint16 affiliate_get, address ref) onlyOwner public{ // not possible to give an exorbitant bonus to be more than 100% (100x100 = 10000) require(contributor_get<10000); require(affiliate_get<10000); Contributor storage contributor = whitelist[_address]; contributor.cleared = cleared; contributor.contributor_get = contributor_get; contributor.ref = ref; contributor.affiliate_get = affiliate_get; } function getContributor(address _address) view public returns (bool, uint16, address, uint16 ) { return (whitelist[_address].cleared, whitelist[_address].contributor_get, whitelist[_address].ref, whitelist[_address].affiliate_get); } function getClearance(address _address) view public returns (bool) { return whitelist[_address].cleared; } } // File: contracts/crowdsale/Crowdsale.sol /** * @title Crowdsale * @dev Crowdsale is a base contract for managing a token crowdsale. * Crowdsales have a start and end timestamps, where investors can make * token purchases and the crowdsale will assign them tokens based * on a token per ETH rate. Funds collected are forwarded to a wallet * as they arrive. */ contract Crowdsale { using SafeMath for uint256; // The token being sold MintableToken public token; // start and end timestamps where investments are allowed (both inclusive) uint256 public startTime; uint256 public endTime; // address where funds are collected address public wallet; // how many token units a buyer gets per wei uint256 public rate; // amount of raised money in wei uint256 public weiRaised; /** * event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); function Crowdsale(uint256 _startTime, uint256 _endTime, uint256 _rate, address _wallet) public { require(_startTime >= now); require(_endTime >= _startTime); require(_rate > 0); require(_wallet != address(0)); token = createTokenContract(); startTime = _startTime; endTime = _endTime; rate = _rate; wallet = _wallet; } // creates the token to be sold. // override this method to have crowdsale of a specific mintable token. function createTokenContract() internal returns (MintableToken) { return new MintableToken(); } // fallback function can be used to buy tokens function () external payable { buyTokens(msg.sender); } // low level token purchase function // overrided to create custom buy function buyTokens(address beneficiary) public payable { require(beneficiary != address(0)); require(validPurchase()); uint256 weiAmount = msg.value; // calculate token amount to be created uint256 tokens = weiAmount.mul(rate); // update state weiRaised = weiRaised.add(weiAmount); token.mint(beneficiary, tokens); emit TokenPurchase(msg.sender, beneficiary, weiAmount, tokens); forwardFunds(); } // send ether to the fund collection wallet // overrided to create custom fund forwarding mechanisms function forwardFunds() internal { wallet.transfer(msg.value); } // @return true if the transaction can buy tokens function validPurchase() internal view returns (bool) { bool withinPeriod = now >= startTime && now <= endTime ; bool nonZeroPurchase = msg.value != 0 ; return withinPeriod && nonZeroPurchase; } // @return true if crowdsale event has ended function hasEnded() public view returns (bool) { return now > endTime; } } // File: contracts/crowdsale/FinalizableCrowdsale.sol /** * @title FinalizableCrowdsale * @dev Extension of Crowdsale where an owner can do extra work * after finishing. */ contract FinalizableCrowdsale is Crowdsale, Ownable { using SafeMath for uint256; bool public isFinalized = false; event Finalized(); /** * @dev Must be called after crowdsale ends, to do some extra finalization * work. Calls the contract's finalization function. */ function finalize() onlyOwner public { require(!isFinalized); require(hasEnded()); finalization(); emit Finalized(); isFinalized = true; } /** * @dev Can be overridden to add finalization logic. The overriding function * should call super.finalization() to ensure the chain of finalization is * executed entirely. */ function finalization() internal{ } } // File: contracts/crowdsale/RefundVault.sol /** * @title RefundVault * @dev This contract is used for storing funds while a crowdsale * is in progress. Supports refunding the money if crowdsale fails, * and forwarding it if crowdsale is successful. */ contract RefundVault is Ownable { using SafeMath for uint256; enum State { Active, Refunding, Closed } mapping (address => uint256) public deposited; address public wallet; State public state; event Closed(); event RefundsEnabled(); event Refunded(address indexed beneficiary, uint256 weiAmount); function RefundVault(address _wallet) public { require(_wallet != address(0)); wallet = _wallet; state = State.Active; } function deposit(address investor) onlyOwner public payable { require(state == State.Active); deposited[investor] = deposited[investor].add(msg.value); } function close() onlyOwner public { // this is this part that shall be removed, that way if called later it run the wallet transfer in any case // require(state == State.Active); state = State.Closed; emit Closed(); wallet.transfer(address(this).balance); } function enableRefunds() onlyOwner public { require(state == State.Active); state = State.Refunding; emit RefundsEnabled(); } function refund(address investor) public { require(state == State.Refunding); uint256 depositedValue = deposited[investor]; deposited[investor] = 0; investor.transfer(depositedValue); emit Refunded(investor, depositedValue); } } // File: contracts/crowdsale/RefundableCrowdsale.sol /** * @title RefundableCrowdsale * @dev Extension of Crowdsale contract that adds a funding goal, and * the possibility of users getting a refund if goal is not met. * Uses a RefundVault as the crowdsale's vault. */ contract RefundableCrowdsale is FinalizableCrowdsale { using SafeMath for uint256; // minimum amount of funds to be raised in weis uint256 public goal; // refund vault used to hold funds while crowdsale is running RefundVault public vault; function RefundableCrowdsale(uint256 _goal) public { require(_goal > 0); vault = new RefundVault(wallet); goal = _goal; } // We're overriding the fund forwarding from Crowdsale. // In addition to sending the funds, we want to call // the RefundVault deposit function function forwardFunds() internal { vault.deposit.value(msg.value)(msg.sender); } // if crowdsale is unsuccessful, investors can claim refunds here function claimRefund() public { require(isFinalized); require(!goalReached()); vault.refund(msg.sender); } // vault finalization task, called when owner calls finalize() function finalization() internal { if (goalReached()) { vault.close(); } else { vault.enableRefunds(); } super.finalization(); } function goalReached() public view returns (bool) { return weiRaised >= goal; } } // File: contracts/BitexTokenCrowdSale.sol contract BitexTokenCrowdSale is Crowdsale, RefundableCrowdsale { using SafeMath for uint256; // number of participants uint256 public numberOfPurchasers = 0; // maximum tokens that can be minted in this crowd sale - initialised later by the constructor uint256 public maxTokenSupply = 0; // amounts of tokens already minted at the begining of this crowd sale - initialised later by the constructor uint256 public initialTokenAmount = 0; // Minimum amount to been able to contribute - initialised later by the constructor uint256 public minimumAmount = 0; // to compute the bonus bool public preICO; // the token BitexToken public token; // the kyc and affiliation management KnowYourCustomer public kyc; // remaining token are sent to this address address public walletRemaining; // this is the owner of the token, when the finalize function is called address public pendingOwner; event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount, uint256 rate, address indexed referral, uint256 referredBonus ); event TokenPurchaseAffiliate(address indexed ref, uint256 amount ); function BitexTokenCrowdSale( uint256 _startTime, uint256 _endTime, uint256 _rate, uint256 _goal, uint256 _minimumAmount, uint256 _maxTokenSupply, address _wallet, BitexToken _token, KnowYourCustomer _kyc, bool _preICO, address _walletRemaining, address _pendingOwner ) FinalizableCrowdsale() RefundableCrowdsale(_goal) Crowdsale(_startTime, _endTime, _rate, _wallet) public { require(_minimumAmount >= 0); require(_maxTokenSupply > 0); require(_walletRemaining != address(0)); minimumAmount = _minimumAmount; maxTokenSupply = _maxTokenSupply; preICO = _preICO; walletRemaining = _walletRemaining; pendingOwner = _pendingOwner; kyc = _kyc; token = _token; // // record the amount of already minted token to been able to compute the delta with the tokens // minted during the pre sale, this is useful only for the pre - ico // if (preICO) { initialTokenAmount = token.totalSupply(); } } /** * * Create the token on the fly, owner is the contract, not the contract owner yet * **/ function createTokenContract() internal returns (MintableToken) { return token; } /** * @dev Calculates the amount of coins the buyer gets * @param weiAmount uint the amount of wei send to the contract * @return uint the amount of tokens the buyer gets */ function computeTokenWithBonus(uint256 weiAmount) public view returns(uint256) { uint256 tokens_ = 0; if (preICO) { if (weiAmount >= 50000 ether ) { tokens_ = weiAmount.mul(34).div(100); } else if (weiAmount<50000 ether && weiAmount >= 10000 ether) { tokens_ = weiAmount.mul(26).div(100); } else if (weiAmount<10000 ether && weiAmount >= 5000 ether) { tokens_ = weiAmount.mul(20).div(100); } else if (weiAmount<5000 ether && weiAmount >= 1000 ether) { tokens_ = weiAmount.mul(16).div(100); } }else{ if (weiAmount >= 50000 ether ) { tokens_ = weiAmount.mul(17).div(100); } else if (weiAmount<50000 ether && weiAmount >= 10000 ether) { tokens_ = weiAmount.mul(13).div(100); } else if (weiAmount<10000 ether && weiAmount >= 5000 ether) { tokens_ = weiAmount.mul(10).div(100); } else if (weiAmount<5000 ether && weiAmount >= 1000 ether) { tokens_ = weiAmount.mul(8).div(100); } } return tokens_; } // // override the claimRefund, so only user that have burn their token can claim for a refund // function claimRefund() public { // get the number of token from this sender uint256 tokenBalance = token.balanceOf(msg.sender); // the refund can be run only if the tokens has been burn require(tokenBalance == 0); // run the refund super.claimRefund(); } // transfer the token owner ship to the crowdsale contract // token.transferOwnership(currentIco); function finalization() internal { if (!preICO) { uint256 remainingTokens = maxTokenSupply.sub(token.totalSupply()); // mint the remaining amount and assign them to the beneficiary // --> here we can manage the vesting of the remaining tokens // token.mint(walletRemaining, remainingTokens); } // finalize the refundable inherited contract super.finalization(); if (!preICO) { // no more minting allowed - immutable token.finishMinting(); } // transfer the token owner ship from the contract address to the pendingOwner icoController token.transferOwnership(pendingOwner); } // low level token purchase function function buyTokens(address beneficiary) public payable { require(beneficiary != address(0)); require(validPurchase()); // validate KYC here // if not part of kyc then throw bool cleared; uint16 contributor_get; address ref; uint16 affiliate_get; (cleared,contributor_get,ref,affiliate_get) = kyc.getContributor(beneficiary); // Transaction do not happen if the contributor is not KYC cleared require(cleared); // how much the contributor sent in wei uint256 weiAmount = msg.value; // Compute the number of tokens per wei using the rate uint256 tokens = weiAmount.mul(rate); // compute the amount of bonus, from the contribution amount uint256 bonus = computeTokenWithBonus(tokens); // compute the amount of token bonus for the contributor thank to his referral uint256 contributorGet = tokens.mul(contributor_get).div(100*100); // Sum it all tokens = tokens.add(bonus); tokens = tokens.add(contributorGet); // capped to a maxTokenSupply // make sure we can not mint more token than expected // require(((token.totalSupply()-initialTokenAmount) + tokens) <= maxTokenSupply); require((minted().add(tokens)) <= maxTokenSupply); // Mint the token token.mint(beneficiary, tokens); // log the event emit TokenPurchase(msg.sender, beneficiary, weiAmount, tokens, rate, ref, contributorGet); // update wei raised and number of purchasers weiRaised = weiRaised.add(weiAmount); numberOfPurchasers = numberOfPurchasers + 1; forwardFunds(); // ------------------------------------------------------------------ // compute the amount of token bonus that the referral get : // only if KYC cleared, only if enough tokens still available // ------------------------------------------------------------------ bool refCleared; (refCleared) = kyc.getClearance(ref); if (refCleared && ref != beneficiary) { // recompute the tokens amount using only the rate tokens = weiAmount.mul(rate); // compute the amount of token for the affiliate uint256 affiliateGet = tokens.mul(affiliate_get).div(100*100); // capped to a maxTokenSupply // make sure we can not mint more token than expected // we do not throw here as if this edge case happens it can be dealt with of chain // if ( (token.totalSupply()-initialTokenAmount) + affiliateGet <= maxTokenSupply) if ( minted().add(affiliateGet) <= maxTokenSupply) { // Mint the token token.mint(ref, affiliateGet); emit TokenPurchaseAffiliate(ref, tokens ); } } } // overriding Crowdsale#validPurchase to add extra cap logic // @return true if investors can buy at the moment function validPurchase() internal view returns (bool) { // make sure we accept only the minimum contribution bool minAmount = (msg.value >= minimumAmount); // make sure that the purchase follow each rules to be valid return super.validPurchase() && minAmount; } function minted() public view returns(uint256) { return token.totalSupply().sub(initialTokenAmount); } // overriding Crowdsale#hasEnded to add cap logic // @return true if crowdsale event has ended function hasEnded() public view returns (bool) { // bool capReached = (token.totalSupply() - initialTokenAmount) >= maxTokenSupply; // bool capReached = minted() >= maxTokenSupply; return super.hasEnded() || (minted() >= maxTokenSupply); } /** * * Admin functions only executed by owner: * Can change minimum amount * */ function changeMinimumAmount(uint256 _minimumAmount) onlyOwner public { require(_minimumAmount > 0); minimumAmount = _minimumAmount; } /** * * Admin functions only executed by owner: * Can change rate * * We do not use an oracle here as oracle need to be paid each time, and if the oracle is not responding * or hacked the rate could be detrimentally modified from an contributor perspective. * */ function changeRate(uint256 _rate) onlyOwner public { require(_rate > 0); rate = _rate; } /** * * Admin functions only called by owner: * Can change events dates * */ function changeDates(uint256 _startTime, uint256 _endTime) onlyOwner public { require(_startTime >= now); require(_endTime >= _startTime); startTime = _startTime; endTime = _endTime; } function modifyTransferableHash(address _spender, bool value) onlyOwner public { token.modifyTransferableHash(_spender,value); } /** * * Admin functions only called by owner: * Can transfer the owner ship of the vault, so a close can be called * only by the owner .... * */ function transferVault(address newOwner) onlyOwner public { vault.transferOwnership(newOwner); } }
* Admin functions only executed by owner: Can change rate We do not use an oracle here as oracle need to be paid each time, and if the oracle is not responding or hacked the rate could be detrimentally modified from an contributor perspective./
function changeRate(uint256 _rate) onlyOwner public { require(_rate > 0); rate = _rate; }
1,107,207
[ 1, 4446, 4186, 1338, 7120, 635, 3410, 30, 4480, 2549, 4993, 1660, 741, 486, 999, 392, 20865, 2674, 487, 20865, 1608, 358, 506, 30591, 1517, 813, 16, 471, 309, 326, 20865, 353, 486, 6846, 310, 578, 11769, 329, 326, 4993, 3377, 506, 3023, 86, 5670, 1230, 4358, 628, 392, 31123, 26651, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 2549, 4727, 12, 11890, 5034, 389, 5141, 13, 1338, 5541, 1071, 288, 203, 3639, 2583, 24899, 5141, 405, 374, 1769, 203, 540, 203, 3639, 4993, 273, 389, 5141, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0xd4bDCCa1CA76ceD6FC8BB1bA91C5D7c0Ca4fE567/sources/CToken.sol
* @notice Accrues interest and reduces Fuse fees by transferring to Fuse @param withdrawAmount Amount of fees to withdraw @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)/ accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted Fuse fee withdrawal failed.
function _withdrawFuseFees(uint withdrawAmount) external nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { return fail(Error(error), FailureInfo.WITHDRAW_FUSE_FEES_ACCRUE_INTEREST_FAILED); } }
3,684,934
[ 1, 8973, 86, 3610, 16513, 471, 30568, 478, 1202, 1656, 281, 635, 906, 74, 20245, 358, 478, 1202, 225, 598, 9446, 6275, 16811, 434, 1656, 281, 358, 598, 9446, 327, 2254, 374, 33, 4768, 16, 3541, 279, 5166, 261, 5946, 1068, 13289, 18, 18281, 364, 3189, 13176, 4078, 86, 344, 29281, 24169, 5963, 603, 1334, 16, 1496, 603, 1760, 434, 716, 732, 2545, 358, 613, 326, 5410, 716, 392, 18121, 478, 1202, 14036, 598, 9446, 287, 2535, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 389, 1918, 9446, 42, 1202, 2954, 281, 12, 11890, 598, 9446, 6275, 13, 3903, 1661, 426, 8230, 970, 1135, 261, 11890, 13, 288, 203, 3639, 2254, 555, 273, 4078, 86, 344, 29281, 5621, 203, 3639, 309, 261, 1636, 480, 2254, 12, 668, 18, 3417, 67, 3589, 3719, 288, 203, 5411, 327, 2321, 12, 668, 12, 1636, 3631, 13436, 966, 18, 9147, 40, 10821, 67, 42, 8001, 67, 8090, 3991, 67, 2226, 5093, 1821, 67, 9125, 11027, 67, 11965, 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 ]
./full_match/84531/0x93D860BB89253bdb5de0F950Af1c31fA38409CCE/sources/AnyswapV4ERC20_FAST.sol
Maximum total supply of the token (69M) init flag for setting immediate vault, needed for CREATE2 support flag to enable/disable swapout vs vault.burn so multiple events are triggered configurable delay for timelock functions set of minters, can be this bridge or other bridges primary controller of the token contract
contract IceToken is IAnyswapV3ERC20 { using SafeERC20 for IERC20; string public name; string public symbol; uint8 public immutable override decimals; address public immutable underlying; bytes32 public constant PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); bytes32 public constant TRANSFER_TYPEHASH = keccak256("Transfer(address owner,address to,uint256 value,uint256 nonce,uint256 deadline)"); bytes32 public immutable DOMAIN_SEPARATOR; mapping (address => uint256) public override balanceOf; uint256 private _totalSupply; uint256 public maxTotalSupply = 69000000000000000000000000; bool private _init; bool private _vaultOnly; uint public delay = 2*24*3600; mapping(address => bool) public isMinter; address[] public minters; address public vault; address public pendingMinter; uint public delayMinter; address public pendingVault; uint public delayVault; uint public pendingDelay; uint public delayDelay; modifier onlyAuth() { require(isMinter[msg.sender], "AnyswapV4ERC20: FORBIDDEN"); _; } modifier onlyVault() { require(msg.sender == mpc(), "AnyswapV3ERC20: FORBIDDEN"); _; } function owner() public view returns (address) { return mpc(); } function mpc() public view returns (address) { if (block.timestamp >= delayVault) { return pendingVault; } return vault; } function mpc() public view returns (address) { if (block.timestamp >= delayVault) { return pendingVault; } return vault; } function setVaultOnly(bool enabled) external onlyVault { _vaultOnly = enabled; } function initVault(address _vault) external onlyVault { require(_init); vault = _vault; pendingVault = _vault; isMinter[_vault] = true; minters.push(_vault); delayVault = block.timestamp; _init = false; } function setMinter(address _auth) external onlyVault { pendingMinter = _auth; delayMinter = block.timestamp + delay; } function setVault(address _vault) external onlyVault { pendingVault = _vault; delayVault = block.timestamp + delay; } function applyVault() external onlyVault { require(block.timestamp >= delayVault); vault = pendingVault; } function applyMinter() external onlyVault { require(block.timestamp >= delayMinter); isMinter[pendingMinter] = true; minters.push(pendingMinter); } function revokeMinter(address _auth) external onlyVault { isMinter[_auth] = false; } function getAllMinters() external view returns (address[] memory) { return minters; } function changeVault(address newVault) external onlyVault returns (bool) { require(newVault != address(0), "AnyswapV3ERC20: address(0x0)"); pendingVault = newVault; delayVault = block.timestamp + delay; emit LogChangeVault(vault, pendingVault, delayVault); return true; } function changeMPCOwner(address newVault) public onlyVault returns (bool) { require(newVault != address(0), "AnyswapV3ERC20: address(0x0)"); pendingVault = newVault; delayVault = block.timestamp + delay; emit LogChangeMPCOwner(vault, pendingVault, delayVault); return true; } function mint(address to, uint256 amount) external onlyAuth returns (bool) { _mint(to, amount); return true; } function burn(address from, uint256 amount) external onlyAuth returns (bool) { require(from != address(0), "AnyswapV3ERC20: address(0x0)"); _burn(from, amount); return true; } function Swapin(bytes32 txhash, address account, uint256 amount) public onlyAuth returns (bool) { _mint(account, amount); emit LogSwapin(txhash, account, amount); return true; } function Swapout(uint256 amount, address bindaddr) public returns (bool) { require(!_vaultOnly, "AnyswapV4ERC20: onlyAuth"); require(bindaddr != address(0), "AnyswapV3ERC20: address(0x0)"); _burn(msg.sender, amount); emit LogSwapout(msg.sender, bindaddr, amount); return true; } event LogChangeVault(address indexed oldVault, address indexed newVault, uint indexed effectiveTime); event LogChangeMPCOwner(address indexed oldOwner, address indexed newOwner, uint indexed effectiveHeight); event LogSwapin(bytes32 indexed txhash, address indexed account, uint amount); event LogSwapout(address indexed account, address indexed bindaddr, uint amount); event LogAddAuth(address indexed auth, uint timestamp); mapping (address => uint256) public override nonces; mapping (address => mapping (address => uint256)) public override allowance; constructor(string memory _name, string memory _symbol, uint8 _decimals, address _underlying, address _vault) { name = _name; symbol = _symbol; decimals = _decimals; underlying = _underlying; if (_underlying != address(0x0)) { require(_decimals == IERC20(_underlying).decimals()); } vault = _vault; pendingVault = _vault; minters.push(_vault); uint256 chainId; DOMAIN_SEPARATOR = keccak256( abi.encode( keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"), keccak256(bytes(name)), keccak256(bytes("1")), chainId, address(this))); isMinter[msg.sender] = true; } constructor(string memory _name, string memory _symbol, uint8 _decimals, address _underlying, address _vault) { name = _name; symbol = _symbol; decimals = _decimals; underlying = _underlying; if (_underlying != address(0x0)) { require(_decimals == IERC20(_underlying).decimals()); } vault = _vault; pendingVault = _vault; minters.push(_vault); uint256 chainId; DOMAIN_SEPARATOR = keccak256( abi.encode( keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"), keccak256(bytes(name)), keccak256(bytes("1")), chainId, address(this))); isMinter[msg.sender] = true; } _init = true; _vaultOnly = false; isMinter[_vault] = true; delayVault = block.timestamp; _init = false; assembly {chainId := chainid()} function totalSupply() external view override returns (uint256) { return _totalSupply; } function depositWithPermit(address target, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s, address to) external returns (uint) { IERC20(underlying).permit(target, address(this), value, deadline, v, r, s); IERC20(underlying).safeTransferFrom(target, address(this), value); return _deposit(value, to); } function depositWithTransferPermit(address target, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s, address to) external returns (uint) { IERC20(underlying).transferWithPermit(target, address(this), value, deadline, v, r, s); return _deposit(value, to); } function deposit() external returns (uint) { uint _amount = IERC20(underlying).balanceOf(msg.sender); IERC20(underlying).safeTransferFrom(msg.sender, address(this), _amount); return _deposit(_amount, msg.sender); } function deposit(uint amount) external returns (uint) { IERC20(underlying).safeTransferFrom(msg.sender, address(this), amount); return _deposit(amount, msg.sender); } function deposit(uint amount, address to) external returns (uint) { IERC20(underlying).safeTransferFrom(msg.sender, address(this), amount); return _deposit(amount, to); } function depositVault(uint amount, address to) external onlyVault returns (uint) { return _deposit(amount, to); } function _deposit(uint amount, address to) internal returns (uint) { require(underlying != address(0x0) && underlying != address(this)); _mint(to, amount); return amount; } function withdraw() external returns (uint) { return _withdraw(msg.sender, balanceOf[msg.sender], msg.sender); } function withdraw(uint amount) external returns (uint) { return _withdraw(msg.sender, amount, msg.sender); } function withdraw(uint amount, address to) external returns (uint) { return _withdraw(msg.sender, amount, to); } function withdrawVault(address from, uint amount, address to) external onlyVault returns (uint) { return _withdraw(from, amount, to); } function _withdraw(address from, uint amount, address to) internal returns (uint) { _burn(from, amount); IERC20(underlying).safeTransfer(to, amount); return amount; } function _mint(address account, uint256 amount) internal { require(account != address(0), "ERC20: mint to the zero address"); require(_totalSupply + amount <= maxTotalSupply, "ERC20: minting more then MaxTotalSupply"); _totalSupply += amount; balanceOf[account] += amount; emit Transfer(address(0), account, amount); } function _burn(address account, uint256 amount) internal { require(account != address(0), "ERC20: burn from the zero address"); balanceOf[account] -= amount; _totalSupply -= amount; emit Transfer(account, address(0), amount); } function approve(address spender, uint256 value) external override returns (bool) { allowance[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } function approveAndCall(address spender, uint256 value, bytes calldata data) external override returns (bool) { allowance[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return IApprovalReceiver(spender).onTokenApproval(msg.sender, value, data); } function permit(address target, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external override { require(block.timestamp <= deadline, "AnyswapV3ERC20: Expired permit"); bytes32 hashStruct = keccak256( abi.encode( PERMIT_TYPEHASH, target, spender, value, nonces[target]++, deadline)); require(verifyEIP712(target, hashStruct, v, r, s) || verifyPersonalSign(target, hashStruct, v, r, s)); allowance[target][spender] = value; emit Approval(target, spender, value); } function transferWithPermit(address target, address to, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external override returns (bool) { require(block.timestamp <= deadline, "AnyswapV3ERC20: Expired permit"); bytes32 hashStruct = keccak256( abi.encode( TRANSFER_TYPEHASH, target, to, value, nonces[target]++, deadline)); require(verifyEIP712(target, hashStruct, v, r, s) || verifyPersonalSign(target, hashStruct, v, r, s)); require(to != address(0) || to != address(this)); uint256 balance = balanceOf[target]; require(balance >= value, "AnyswapV3ERC20: transfer amount exceeds balance"); balanceOf[target] = balance - value; balanceOf[to] += value; emit Transfer(target, to, value); return true; } function verifyEIP712(address target, bytes32 hashStruct, uint8 v, bytes32 r, bytes32 s) internal view returns (bool) { bytes32 hash = keccak256( abi.encodePacked( "\x19\x01", DOMAIN_SEPARATOR, hashStruct)); address signer = ecrecover(hash, v, r, s); return (signer != address(0) && signer == target); } function verifyPersonalSign(address target, bytes32 hashStruct, uint8 v, bytes32 r, bytes32 s) internal pure returns (bool) { bytes32 hash = prefixed(hashStruct); address signer = ecrecover(hash, v, r, s); return (signer != address(0) && signer == target); } function prefixed(bytes32 hash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } function transfer(address to, uint256 value) external override returns (bool) { require(to != address(0) || to != address(this)); uint256 balance = balanceOf[msg.sender]; require(balance >= value, "AnyswapV3ERC20: transfer amount exceeds balance"); balanceOf[msg.sender] = balance - value; balanceOf[to] += value; emit Transfer(msg.sender, to, value); return true; } function transferFrom(address from, address to, uint256 value) external override returns (bool) { require(to != address(0) || to != address(this)); if (from != msg.sender) { uint256 allowed = allowance[from][msg.sender]; if (allowed != type(uint256).max) { require(allowed >= value, "AnyswapV3ERC20: request exceeds allowance"); uint256 reduced = allowed - value; allowance[from][msg.sender] = reduced; emit Approval(from, msg.sender, reduced); } } uint256 balance = balanceOf[from]; require(balance >= value, "AnyswapV3ERC20: transfer amount exceeds balance"); balanceOf[from] = balance - value; balanceOf[to] += value; emit Transfer(from, to, value); return true; } function transferFrom(address from, address to, uint256 value) external override returns (bool) { require(to != address(0) || to != address(this)); if (from != msg.sender) { uint256 allowed = allowance[from][msg.sender]; if (allowed != type(uint256).max) { require(allowed >= value, "AnyswapV3ERC20: request exceeds allowance"); uint256 reduced = allowed - value; allowance[from][msg.sender] = reduced; emit Approval(from, msg.sender, reduced); } } uint256 balance = balanceOf[from]; require(balance >= value, "AnyswapV3ERC20: transfer amount exceeds balance"); balanceOf[from] = balance - value; balanceOf[to] += value; emit Transfer(from, to, value); return true; } function transferFrom(address from, address to, uint256 value) external override returns (bool) { require(to != address(0) || to != address(this)); if (from != msg.sender) { uint256 allowed = allowance[from][msg.sender]; if (allowed != type(uint256).max) { require(allowed >= value, "AnyswapV3ERC20: request exceeds allowance"); uint256 reduced = allowed - value; allowance[from][msg.sender] = reduced; emit Approval(from, msg.sender, reduced); } } uint256 balance = balanceOf[from]; require(balance >= value, "AnyswapV3ERC20: transfer amount exceeds balance"); balanceOf[from] = balance - value; balanceOf[to] += value; emit Transfer(from, to, value); return true; } function transferAndCall(address to, uint value, bytes calldata data) external override returns (bool) { require(to != address(0) || to != address(this)); uint256 balance = balanceOf[msg.sender]; require(balance >= value, "AnyswapV3ERC20: transfer amount exceeds balance"); balanceOf[msg.sender] = balance - value; balanceOf[to] += value; emit Transfer(msg.sender, to, value); return ITransferReceiver(to).onTokenTransfer(msg.sender, value, data); } }
11,527,097
[ 1, 13528, 2078, 14467, 434, 326, 1147, 261, 8148, 49, 13, 1208, 2982, 364, 3637, 14483, 9229, 16, 3577, 364, 13278, 22, 2865, 2982, 358, 4237, 19, 8394, 7720, 659, 6195, 9229, 18, 70, 321, 1427, 3229, 2641, 854, 10861, 14593, 4624, 364, 1658, 292, 975, 4186, 444, 434, 1131, 5432, 16, 848, 506, 333, 10105, 578, 1308, 324, 1691, 2852, 3354, 2596, 434, 326, 1147, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 16351, 467, 311, 1345, 353, 467, 979, 1900, 91, 438, 58, 23, 654, 39, 3462, 288, 203, 565, 1450, 14060, 654, 39, 3462, 364, 467, 654, 39, 3462, 31, 203, 565, 533, 1071, 508, 31, 203, 565, 533, 1071, 3273, 31, 203, 565, 2254, 28, 225, 1071, 11732, 3849, 15105, 31, 203, 203, 565, 1758, 1071, 11732, 6808, 31, 203, 203, 565, 1731, 1578, 1071, 5381, 10950, 6068, 67, 2399, 15920, 273, 417, 24410, 581, 5034, 2932, 9123, 305, 12, 2867, 3410, 16, 2867, 17571, 264, 16, 11890, 5034, 460, 16, 11890, 5034, 7448, 16, 11890, 5034, 14096, 2225, 1769, 203, 565, 1731, 1578, 1071, 5381, 4235, 17598, 67, 2399, 15920, 273, 417, 24410, 581, 5034, 2932, 5912, 12, 2867, 3410, 16, 2867, 358, 16, 11890, 5034, 460, 16, 11890, 5034, 7448, 16, 11890, 5034, 14096, 2225, 1769, 203, 565, 1731, 1578, 1071, 11732, 27025, 67, 4550, 31, 203, 203, 565, 2874, 261, 2867, 516, 2254, 5034, 13, 1071, 3849, 11013, 951, 31, 203, 565, 2254, 5034, 3238, 389, 4963, 3088, 1283, 31, 203, 203, 565, 2254, 5034, 1071, 943, 5269, 3088, 1283, 273, 20963, 12648, 12648, 12648, 31, 203, 203, 565, 1426, 3238, 389, 2738, 31, 203, 203, 565, 1426, 3238, 389, 26983, 3386, 31, 203, 203, 565, 2254, 1071, 4624, 273, 576, 14, 3247, 14, 5718, 713, 31, 203, 203, 203, 565, 2874, 12, 2867, 516, 1426, 13, 1071, 15707, 2761, 31, 203, 565, 1758, 8526, 1071, 1131, 5432, 31, 203, 203, 565, 1758, 1071, 9229, 31, 203, 203, 565, 1758, 1071, 2 ]
// SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/interfaces/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "./TimeLockedStaking.sol"; /// @title Admin contract to manage a TimeLockedStaking contract contract TimeLockedStakingAdmin is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; /// @notice The underlying TimeLockedStaking contract TimeLockedStaking public immutable tls; constructor(TimeLockedStaking _tls) { tls = _tls; } /// @notice Transfers ownership of the underlying contract to a new account /// @param newOwner The new owner function transferTLSOwnership(address newOwner) public virtual onlyOwner { tls.transferOwnership(newOwner); } /// @notice Updates lock time /// @param _lockTime New lock time function setLockTime(uint256 _lockTime) external onlyOwner { tls.setLockTime((_lockTime)); } /// @notice Admin-only to force unstake a user's tokens. /// @param _user The user to force withdraw /// @param _amount The amount to force withdraw function forceUnstake(address _user, uint256 _amount) external onlyOwner { tls.forceUnstake(_user, _amount); } /// @notice Admin-only to force unstake multiple users /// @param _users The users to force withdraw /// @param _amounts The amounts to force withdraw function batchForceUnstake( address[] memory _users, uint256[] memory _amounts ) external onlyOwner { require(_users.length == _amounts.length, "array lengths must match"); for (uint256 i = 0; i < _users.length; i++) { tls.forceUnstake(_users[i], _amounts[i]); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../token/ERC20/IERC20.sol"; // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/interfaces/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; contract TimeLockedStaking is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; /// @notice Token to lock IERC20 public immutable token; /// @notice Lock time in seconds uint256 public lockTime; /// @notice Mapping from user to when their lock ends mapping(address => uint256) public lockEnd; /// @notice Mapping from user to their locked balance mapping(address => uint256) public balanceOf; /// @notice Total supply of locked tokens uint256 public totalSupply; event Staked(address indexed user, uint256 amount, uint256 lockEnd); event Unstaked(address indexed user, uint256 amount); event LockTimeUpdated(uint256 previousLockTime, uint256 nextLockTime); constructor( IERC20 _token, uint256 _initialLockTime ) { token = _token; lockTime = _initialLockTime; } /// @notice Stakes and locks tokens. NOTE: Staking will reset a users' lock end time /// @param _amount Amount to stake and lock function stake(uint256 _amount) external { token.safeTransferFrom(msg.sender, address(this), _amount); lockEnd[msg.sender] = block.timestamp.add(lockTime); balanceOf[msg.sender] += _amount; totalSupply += _amount; emit Staked(msg.sender, _amount, lockEnd[msg.sender]); } /// @notice Withdraws staked tokens /// @param _amount Amount to stake and lock function unstake(uint256 _amount) external { require(lockEnd[msg.sender] <= block.timestamp, "TLS: Unstake too early"); balanceOf[msg.sender] = balanceOf[msg.sender].sub(_amount); totalSupply = totalSupply.sub(_amount); token.safeTransfer(msg.sender, _amount); emit Unstaked(msg.sender, _amount); } /// @notice Updates lock time /// @param _lockTime New lock time function setLockTime(uint256 _lockTime) external onlyOwner { emit LockTimeUpdated(lockTime, _lockTime); lockTime = _lockTime; } /// @notice Admin-only to force unstake a user's tokens. NOTE: Lock time is not affected /// @param _user The user to force withdraw /// @param _amount The amount to force withdraw function forceUnstake(address _user, uint256 _amount) external onlyOwner { // Catch underflow in the .sub balanceOf[_user] = balanceOf[_user].sub(_amount); totalSupply = totalSupply.sub(_amount); token.safeTransfer(_user, _amount); emit Unstaked(_user, _amount); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } }
@notice Admin-only to force unstake a user's tokens. @param _user The user to force withdraw @param _amount The amount to force withdraw
function forceUnstake(address _user, uint256 _amount) external onlyOwner { tls.forceUnstake(_user, _amount); }
5,800,441
[ 1, 4446, 17, 3700, 358, 2944, 640, 334, 911, 279, 729, 1807, 2430, 18, 225, 389, 1355, 1021, 729, 358, 2944, 598, 9446, 225, 389, 8949, 1021, 3844, 358, 2944, 598, 9446, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 2944, 984, 334, 911, 12, 2867, 389, 1355, 16, 2254, 5034, 389, 8949, 13, 3903, 1338, 5541, 288, 203, 3639, 6871, 18, 5734, 984, 334, 911, 24899, 1355, 16, 389, 8949, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2020-08-26 */ pragma solidity ^0.5.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } /* * @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; } } /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { 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(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return _msgSender() == _owner; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see {ERC20Detailed}. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title Roles * @dev Library for managing addresses assigned to a Role. */ library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev Give an account access to this role. */ function add(Role storage role, address account) internal { require(!has(role, account), "Roles: account already has role"); role.bearer[account] = true; } /** * @dev Remove an account's access to this role. */ function remove(Role storage role, address account) internal { require(has(role, account), "Roles: account does not have role"); role.bearer[account] = false; } /** * @dev Check if an account has this role. * @return bool */ function has(Role storage role, address account) internal view returns (bool) { require(account != address(0), "Roles: account is the zero address"); return role.bearer[account]; } } contract MinterRole is Context { using Roles for Roles.Role; event MinterAdded(address indexed account); event MinterRemoved(address indexed account); Roles.Role private _minters; constructor () internal { _addMinter(_msgSender()); } modifier onlyMinter() { require(isMinter(_msgSender()), "MinterRole: caller does not have the Minter role"); _; } function isMinter(address account) public view returns (bool) { return _minters.has(account); } function addMinter(address account) public onlyMinter { _addMinter(account); } function renounceMinter() public { _removeMinter(_msgSender()); } function _addMinter(address account) internal { _minters.add(account); emit MinterAdded(account); } function _removeMinter(address account) internal { _minters.remove(account); emit MinterRemoved(account); } } /** * @title WhitelistAdminRole * @dev WhitelistAdmins are responsible for assigning and removing Whitelisted accounts. */ contract WhitelistAdminRole is Context { using Roles for Roles.Role; event WhitelistAdminAdded(address indexed account); event WhitelistAdminRemoved(address indexed account); Roles.Role private _whitelistAdmins; constructor () internal { _addWhitelistAdmin(_msgSender()); } modifier onlyWhitelistAdmin() { require(isWhitelistAdmin(_msgSender()), "WhitelistAdminRole: caller does not have the WhitelistAdmin role"); _; } function isWhitelistAdmin(address account) public view returns (bool) { return _whitelistAdmins.has(account); } function addWhitelistAdmin(address account) public onlyWhitelistAdmin { _addWhitelistAdmin(account); } function renounceWhitelistAdmin() public { _removeWhitelistAdmin(_msgSender()); } function _addWhitelistAdmin(address account) internal { _whitelistAdmins.add(account); emit WhitelistAdminAdded(account); } function _removeWhitelistAdmin(address account) internal { _whitelistAdmins.remove(account); emit WhitelistAdminRemoved(account); } } /** * @title ERC165 * @dev https://github.com/ethereum/EIPs/blob/master/EIPS/eip-165.md */ interface IERC165 { /** * @notice Query if a contract implements an interface * @dev Interface identification is specified in ERC-165. This function * uses less than 30,000 gas * @param _interfaceId The interface identifier, as specified in ERC-165 */ function supportsInterface(bytes4 _interfaceId) external view returns (bool); } /** * @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, "SafeMath#mul: OVERFLOW"); 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, "SafeMath#div: DIVISION_BY_ZERO"); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev 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, "SafeMath#sub: UNDERFLOW"); 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, "SafeMath#add: OVERFLOW"); 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, "SafeMath#mod: DIVISION_BY_ZERO"); return a % b; } } /** * @dev ERC-1155 interface for accepting safe transfers. */ interface IERC1155TokenReceiver { /** * @notice Handle the receipt of a single ERC1155 token type * @dev An ERC1155-compliant smart contract MUST call this function on the token recipient contract, at the end of a `safeTransferFrom` after the balance has been updated * This function MAY throw to revert and reject the transfer * Return of other amount than the magic value MUST result in the transaction being reverted * Note: The token contract address is always the message sender * @param _operator The address which called the `safeTransferFrom` function * @param _from The address which previously owned the token * @param _id The id of the token being transferred * @param _amount The amount of tokens being transferred * @param _data Additional data with no specified format * @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` */ function onERC1155Received(address _operator, address _from, uint256 _id, uint256 _amount, bytes calldata _data) external returns(bytes4); /** * @notice Handle the receipt of multiple ERC1155 token types * @dev An ERC1155-compliant smart contract MUST call this function on the token recipient contract, at the end of a `safeBatchTransferFrom` after the balances have been updated * This function MAY throw to revert and reject the transfer * Return of other amount than the magic value WILL result in the transaction being reverted * Note: The token contract address is always the message sender * @param _operator The address which called the `safeBatchTransferFrom` function * @param _from The address which previously owned the token * @param _ids An array containing ids of each token being transferred * @param _amounts An array containing amounts of each token being transferred * @param _data Additional data with no specified format * @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` */ function onERC1155BatchReceived(address _operator, address _from, uint256[] calldata _ids, uint256[] calldata _amounts, bytes calldata _data) external returns(bytes4); /** * @notice Indicates whether a contract implements the `ERC1155TokenReceiver` functions and so can accept ERC1155 token types. * @param interfaceID The ERC-165 interface ID that is queried for support.s * @dev This function MUST return true if it implements the ERC1155TokenReceiver interface and ERC-165 interface. * This function MUST NOT consume more than 5,000 gas. * @return Wheter ERC-165 or ERC1155TokenReceiver interfaces are supported. */ function supportsInterface(bytes4 interfaceID) external view returns (bool); } interface IERC1155 { // Events /** * @dev Either TransferSingle or TransferBatch MUST emit when tokens are transferred, including zero amount transfers as well as minting or burning * Operator MUST be msg.sender * When minting/creating tokens, the `_from` field MUST be set to `0x0` * When burning/destroying tokens, the `_to` field MUST be set to `0x0` * The total amount transferred from address 0x0 minus the total amount transferred to 0x0 may be used by clients and exchanges to be added to the "circulating supply" for a given token ID * To broadcast the existence of a token ID with no initial balance, the contract SHOULD emit the TransferSingle event from `0x0` to `0x0`, with the token creator as `_operator`, and a `_amount` of 0 */ event TransferSingle(address indexed _operator, address indexed _from, address indexed _to, uint256 _id, uint256 _amount); /** * @dev Either TransferSingle or TransferBatch MUST emit when tokens are transferred, including zero amount transfers as well as minting or burning * Operator MUST be msg.sender * When minting/creating tokens, the `_from` field MUST be set to `0x0` * When burning/destroying tokens, the `_to` field MUST be set to `0x0` * The total amount transferred from address 0x0 minus the total amount transferred to 0x0 may be used by clients and exchanges to be added to the "circulating supply" for a given token ID * To broadcast the existence of multiple token IDs with no initial balance, this SHOULD emit the TransferBatch event from `0x0` to `0x0`, with the token creator as `_operator`, and a `_amount` of 0 */ event TransferBatch(address indexed _operator, address indexed _from, address indexed _to, uint256[] _ids, uint256[] _amounts); /** * @dev MUST emit when an approval is updated */ event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved); /** * @dev MUST emit when the URI is updated for a token ID * URIs are defined in RFC 3986 * The URI MUST point a JSON file that conforms to the "ERC-1155 Metadata JSON Schema" */ event URI(string _amount, uint256 indexed _id); /** * @notice Transfers amount of an _id from the _from address to the _to address specified * @dev MUST emit TransferSingle event on success * Caller must be approved to manage the _from account's tokens (see isApprovedForAll) * MUST throw if `_to` is the zero address * MUST throw if balance of sender for token `_id` is lower than the `_amount` sent * MUST throw on any other error * When transfer is complete, this function MUST check if `_to` is a smart contract (code size > 0). If so, it MUST call `onERC1155Received` on `_to` and revert if the return amount is not `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` * @param _from Source address * @param _to Target address * @param _id ID of the token type * @param _amount Transfered amount * @param _data Additional data with no specified format, sent in call to `_to` */ function safeTransferFrom(address _from, address _to, uint256 _id, uint256 _amount, bytes calldata _data) external; /** * @notice Send multiple types of Tokens from the _from address to the _to address (with safety call) * @dev MUST emit TransferBatch event on success * Caller must be approved to manage the _from account's tokens (see isApprovedForAll) * MUST throw if `_to` is the zero address * MUST throw if length of `_ids` is not the same as length of `_amounts` * MUST throw if any of the balance of sender for token `_ids` is lower than the respective `_amounts` sent * MUST throw on any other error * When transfer is complete, this function MUST check if `_to` is a smart contract (code size > 0). If so, it MUST call `onERC1155BatchReceived` on `_to` and revert if the return amount is not `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` * Transfers and events MUST occur in the array order they were submitted (_ids[0] before _ids[1], etc) * @param _from Source addresses * @param _to Target addresses * @param _ids IDs of each token type * @param _amounts Transfer amounts per token type * @param _data Additional data with no specified format, sent in call to `_to` */ function safeBatchTransferFrom(address _from, address _to, uint256[] calldata _ids, uint256[] calldata _amounts, bytes calldata _data) external; /** * @notice Get the balance of an account's Tokens * @param _owner The address of the token holder * @param _id ID of the Token * @return The _owner's balance of the Token type requested */ function balanceOf(address _owner, uint256 _id) external view returns (uint256); /** * @notice Get the balance of multiple account/token pairs * @param _owners The addresses of the token holders * @param _ids ID of the Tokens * @return The _owner's balance of the Token types requested (i.e. balance for each (owner, id) pair) */ function balanceOfBatch(address[] calldata _owners, uint256[] calldata _ids) external view returns (uint256[] memory); /** * @notice Enable or disable approval for a third party ("operator") to manage all of caller's tokens * @dev MUST emit the ApprovalForAll event on success * @param _operator Address to add to the set of authorized operators * @param _approved True if the operator is approved, false to revoke approval */ function setApprovalForAll(address _operator, bool _approved) external; /** * @notice Queries the approval status of an operator for a given owner * @param _owner The owner of the Tokens * @param _operator Address of authorized operator * @return True if the operator is approved, false if not */ function isApprovedForAll(address _owner, address _operator) external view returns (bool isOperator); } /** * Copyright 2018 ZeroEx Intl. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Utility library of inline functions on addresses */ library Address { /** * Returns whether the target address is a contract * @dev This function will return false if invoked during the constructor of a contract, * as the code is not actually created until after the constructor finishes. * @param account address of the account to check * @return whether the target address is a contract */ function isContract(address account) internal view returns (bool) { bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // XXX Currently there is no better way to check if there is a contract in an address // than to check the size of the code at that address. // See https://ethereum.stackexchange.com/a/14016/36603 // for more details about how this works. // TODO Check this again before the Serenity release, because all addresses will be // contracts then. assembly { codehash := extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } } /** * @dev Implementation of Multi-Token Standard contract */ contract ERC1155 is IERC165 { using SafeMath for uint256; using Address for address; /***********************************| | Variables and Events | |__________________________________*/ // onReceive function signatures bytes4 constant internal ERC1155_RECEIVED_VALUE = 0xf23a6e61; bytes4 constant internal ERC1155_BATCH_RECEIVED_VALUE = 0xbc197c81; // Objects balances mapping (address => mapping(uint256 => uint256)) internal balances; // Operator Functions mapping (address => mapping(address => bool)) internal operators; // Events event TransferSingle(address indexed _operator, address indexed _from, address indexed _to, uint256 _id, uint256 _amount); event TransferBatch(address indexed _operator, address indexed _from, address indexed _to, uint256[] _ids, uint256[] _amounts); event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved); event URI(string _uri, uint256 indexed _id); /***********************************| | Public Transfer Functions | |__________________________________*/ /** * @notice Transfers amount amount of an _id from the _from address to the _to address specified * @param _from Source address * @param _to Target address * @param _id ID of the token type * @param _amount Transfered amount * @param _data Additional data with no specified format, sent in call to `_to` */ function safeTransferFrom(address _from, address _to, uint256 _id, uint256 _amount, bytes memory _data) public { require((msg.sender == _from) || isApprovedForAll(_from, msg.sender), "ERC1155#safeTransferFrom: INVALID_OPERATOR"); require(_to != address(0),"ERC1155#safeTransferFrom: INVALID_RECIPIENT"); // require(_amount >= balances[_from][_id]) is not necessary since checked with safemath operations _safeTransferFrom(_from, _to, _id, _amount); _callonERC1155Received(_from, _to, _id, _amount, _data); } /** * @notice Send multiple types of Tokens from the _from address to the _to address (with safety call) * @param _from Source addresses * @param _to Target addresses * @param _ids IDs of each token type * @param _amounts Transfer amounts per token type * @param _data Additional data with no specified format, sent in call to `_to` */ function safeBatchTransferFrom(address _from, address _to, uint256[] memory _ids, uint256[] memory _amounts, bytes memory _data) public { // Requirements require((msg.sender == _from) || isApprovedForAll(_from, msg.sender), "ERC1155#safeBatchTransferFrom: INVALID_OPERATOR"); require(_to != address(0), "ERC1155#safeBatchTransferFrom: INVALID_RECIPIENT"); _safeBatchTransferFrom(_from, _to, _ids, _amounts); _callonERC1155BatchReceived(_from, _to, _ids, _amounts, _data); } /***********************************| | Internal Transfer Functions | |__________________________________*/ /** * @notice Transfers amount amount of an _id from the _from address to the _to address specified * @param _from Source address * @param _to Target address * @param _id ID of the token type * @param _amount Transfered amount */ function _safeTransferFrom(address _from, address _to, uint256 _id, uint256 _amount) internal { // Update balances balances[_from][_id] = balances[_from][_id].sub(_amount); // Subtract amount balances[_to][_id] = balances[_to][_id].add(_amount); // Add amount // Emit event emit TransferSingle(msg.sender, _from, _to, _id, _amount); } /** * @notice Verifies if receiver is contract and if so, calls (_to).onERC1155Received(...) */ function _callonERC1155Received(address _from, address _to, uint256 _id, uint256 _amount, bytes memory _data) internal { // Check if recipient is contract if (_to.isContract()) { bytes4 retval = IERC1155TokenReceiver(_to).onERC1155Received(msg.sender, _from, _id, _amount, _data); require(retval == ERC1155_RECEIVED_VALUE, "ERC1155#_callonERC1155Received: INVALID_ON_RECEIVE_MESSAGE"); } } /** * @notice Send multiple types of Tokens from the _from address to the _to address (with safety call) * @param _from Source addresses * @param _to Target addresses * @param _ids IDs of each token type * @param _amounts Transfer amounts per token type */ function _safeBatchTransferFrom(address _from, address _to, uint256[] memory _ids, uint256[] memory _amounts) internal { require(_ids.length == _amounts.length, "ERC1155#_safeBatchTransferFrom: INVALID_ARRAYS_LENGTH"); // Number of transfer to execute uint256 nTransfer = _ids.length; // Executing all transfers for (uint256 i = 0; i < nTransfer; i++) { // Update storage balance of previous bin balances[_from][_ids[i]] = balances[_from][_ids[i]].sub(_amounts[i]); balances[_to][_ids[i]] = balances[_to][_ids[i]].add(_amounts[i]); } // Emit event emit TransferBatch(msg.sender, _from, _to, _ids, _amounts); } /** * @notice Verifies if receiver is contract and if so, calls (_to).onERC1155BatchReceived(...) */ function _callonERC1155BatchReceived(address _from, address _to, uint256[] memory _ids, uint256[] memory _amounts, bytes memory _data) internal { // Pass data if recipient is contract if (_to.isContract()) { bytes4 retval = IERC1155TokenReceiver(_to).onERC1155BatchReceived(msg.sender, _from, _ids, _amounts, _data); require(retval == ERC1155_BATCH_RECEIVED_VALUE, "ERC1155#_callonERC1155BatchReceived: INVALID_ON_RECEIVE_MESSAGE"); } } /***********************************| | Operator Functions | |__________________________________*/ /** * @notice Enable or disable approval for a third party ("operator") to manage all of caller's tokens * @param _operator Address to add to the set of authorized operators * @param _approved True if the operator is approved, false to revoke approval */ function setApprovalForAll(address _operator, bool _approved) external { // Update operator status operators[msg.sender][_operator] = _approved; emit ApprovalForAll(msg.sender, _operator, _approved); } /** * @notice Queries the approval status of an operator for a given owner * @param _owner The owner of the Tokens * @param _operator Address of authorized operator * @return True if the operator is approved, false if not */ function isApprovedForAll(address _owner, address _operator) public view returns (bool isOperator) { return operators[_owner][_operator]; } /***********************************| | Balance Functions | |__________________________________*/ /** * @notice Get the balance of an account's Tokens * @param _owner The address of the token holder * @param _id ID of the Token * @return The _owner's balance of the Token type requested */ function balanceOf(address _owner, uint256 _id) public view returns (uint256) { return balances[_owner][_id]; } /** * @notice Get the balance of multiple account/token pairs * @param _owners The addresses of the token holders * @param _ids ID of the Tokens * @return The _owner's balance of the Token types requested (i.e. balance for each (owner, id) pair) */ function balanceOfBatch(address[] memory _owners, uint256[] memory _ids) public view returns (uint256[] memory) { require(_owners.length == _ids.length, "ERC1155#balanceOfBatch: INVALID_ARRAY_LENGTH"); // Variables uint256[] memory batchBalances = new uint256[](_owners.length); // Iterate over each owner and token ID for (uint256 i = 0; i < _owners.length; i++) { batchBalances[i] = balances[_owners[i]][_ids[i]]; } return batchBalances; } /***********************************| | ERC165 Functions | |__________________________________*/ /** * INTERFACE_SIGNATURE_ERC165 = bytes4(keccak256("supportsInterface(bytes4)")); */ bytes4 constant private INTERFACE_SIGNATURE_ERC165 = 0x01ffc9a7; /** * INTERFACE_SIGNATURE_ERC1155 = * bytes4(keccak256("safeTransferFrom(address,address,uint256,uint256,bytes)")) ^ * bytes4(keccak256("safeBatchTransferFrom(address,address,uint256[],uint256[],bytes)")) ^ * bytes4(keccak256("balanceOf(address,uint256)")) ^ * bytes4(keccak256("balanceOfBatch(address[],uint256[])")) ^ * bytes4(keccak256("setApprovalForAll(address,bool)")) ^ * bytes4(keccak256("isApprovedForAll(address,address)")); */ bytes4 constant private INTERFACE_SIGNATURE_ERC1155 = 0xd9b67a26; /** * @notice Query if a contract implements an interface * @param _interfaceID The interface identifier, as specified in ERC-165 * @return `true` if the contract implements `_interfaceID` and */ function supportsInterface(bytes4 _interfaceID) external view returns (bool) { if (_interfaceID == INTERFACE_SIGNATURE_ERC165 || _interfaceID == INTERFACE_SIGNATURE_ERC1155) { return true; } return false; } } /** * @notice Contract that handles metadata related methods. * @dev Methods assume a deterministic generation of URI based on token IDs. * Methods also assume that URI uses hex representation of token IDs. */ contract ERC1155Metadata { // URI's default URI prefix string internal baseMetadataURI; event URI(string _uri, uint256 indexed _id); /***********************************| | Metadata Public Function s | |__________________________________*/ /** * @notice A distinct Uniform Resource Identifier (URI) for a given token. * @dev URIs are defined in RFC 3986. * URIs are assumed to be deterministically generated based on token ID * Token IDs are assumed to be represented in their hex format in URIs * @return URI string */ function uri(uint256 _id) public view returns (string memory) { return string(abi.encodePacked(baseMetadataURI, _uint2str(_id), ".json")); } /***********************************| | Metadata Internal Functions | |__________________________________*/ /** * @notice Will emit default URI log event for corresponding token _id * @param _tokenIDs Array of IDs of tokens to log default URI */ function _logURIs(uint256[] memory _tokenIDs) internal { string memory baseURL = baseMetadataURI; string memory tokenURI; for (uint256 i = 0; i < _tokenIDs.length; i++) { tokenURI = string(abi.encodePacked(baseURL, _uint2str(_tokenIDs[i]), ".json")); emit URI(tokenURI, _tokenIDs[i]); } } /** * @notice Will emit a specific URI log event for corresponding token * @param _tokenIDs IDs of the token corresponding to the _uris logged * @param _URIs The URIs of the specified _tokenIDs */ function _logURIs(uint256[] memory _tokenIDs, string[] memory _URIs) internal { require(_tokenIDs.length == _URIs.length, "ERC1155Metadata#_logURIs: INVALID_ARRAYS_LENGTH"); for (uint256 i = 0; i < _tokenIDs.length; i++) { emit URI(_URIs[i], _tokenIDs[i]); } } /** * @notice Will update the base URL of token's URI * @param _newBaseMetadataURI New base URL of token's URI */ function _setBaseMetadataURI(string memory _newBaseMetadataURI) internal { baseMetadataURI = _newBaseMetadataURI; } /***********************************| | Utility Internal Functions | |__________________________________*/ /** * @notice Convert uint256 to string * @param _i Unsigned integer to convert to string */ function _uint2str(uint256 _i) internal pure returns (string memory _uintAsString) { if (_i == 0) { return "0"; } uint256 j = _i; uint256 ii = _i; uint256 len; // Get number of bytes while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint256 k = len - 1; // Get each individual ASCII while (ii != 0) { bstr[k--] = byte(uint8(48 + ii % 10)); ii /= 10; } // Convert to string return string(bstr); } } /** * @dev Multi-Fungible Tokens with minting and burning methods. These methods assume * a parent contract to be executed as they are `internal` functions */ contract ERC1155MintBurn is ERC1155 { /****************************************| | Minting Functions | |_______________________________________*/ /** * @notice Mint _amount of tokens of a given id * @param _to The address to mint tokens to * @param _id Token id to mint * @param _amount The amount to be minted * @param _data Data to pass if receiver is contract */ function _mint(address _to, uint256 _id, uint256 _amount, bytes memory _data) internal { // Add _amount balances[_to][_id] = balances[_to][_id].add(_amount); // Emit event emit TransferSingle(msg.sender, address(0x0), _to, _id, _amount); // Calling onReceive method if recipient is contract _callonERC1155Received(address(0x0), _to, _id, _amount, _data); } /** * @notice Mint tokens for each ids in _ids * @param _to The address to mint tokens to * @param _ids Array of ids to mint * @param _amounts Array of amount of tokens to mint per id * @param _data Data to pass if receiver is contract */ function _batchMint(address _to, uint256[] memory _ids, uint256[] memory _amounts, bytes memory _data) internal { require(_ids.length == _amounts.length, "ERC1155MintBurn#batchMint: INVALID_ARRAYS_LENGTH"); // Number of mints to execute uint256 nMint = _ids.length; // Executing all minting for (uint256 i = 0; i < nMint; i++) { // Update storage balance balances[_to][_ids[i]] = balances[_to][_ids[i]].add(_amounts[i]); } // Emit batch mint event emit TransferBatch(msg.sender, address(0x0), _to, _ids, _amounts); // Calling onReceive method if recipient is contract _callonERC1155BatchReceived(address(0x0), _to, _ids, _amounts, _data); } /****************************************| | Burning Functions | |_______________________________________*/ /** * @notice Burn _amount of tokens of a given token id * @param _from The address to burn tokens from * @param _id Token id to burn * @param _amount The amount to be burned */ function _burn(address _from, uint256 _id, uint256 _amount) internal { //Substract _amount balances[_from][_id] = balances[_from][_id].sub(_amount); // Emit event emit TransferSingle(msg.sender, _from, address(0x0), _id, _amount); } /** * @notice Burn tokens of given token id for each (_ids[i], _amounts[i]) pair * @param _from The address to burn tokens from * @param _ids Array of token ids to burn * @param _amounts Array of the amount to be burned */ function _batchBurn(address _from, uint256[] memory _ids, uint256[] memory _amounts) internal { require(_ids.length == _amounts.length, "ERC1155MintBurn#batchBurn: INVALID_ARRAYS_LENGTH"); // Number of mints to execute uint256 nBurn = _ids.length; // Executing all minting for (uint256 i = 0; i < nBurn; i++) { // Update storage balance balances[_from][_ids[i]] = balances[_from][_ids[i]].sub(_amounts[i]); } // Emit batch mint event emit TransferBatch(msg.sender, _from, address(0x0), _ids, _amounts); } } library Strings { // via https://github.com/oraclize/ethereum-api/blob/master/oraclizeAPI_0.5.sol function strConcat( string memory _a, string memory _b, string memory _c, string memory _d, string memory _e ) internal pure returns (string memory) { bytes memory _ba = bytes(_a); bytes memory _bb = bytes(_b); bytes memory _bc = bytes(_c); bytes memory _bd = bytes(_d); bytes memory _be = bytes(_e); string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length); bytes memory babcde = bytes(abcde); uint256 k = 0; for (uint256 i = 0; i < _ba.length; i++) babcde[k++] = _ba[i]; for (uint256 i = 0; i < _bb.length; i++) babcde[k++] = _bb[i]; for (uint256 i = 0; i < _bc.length; i++) babcde[k++] = _bc[i]; for (uint256 i = 0; i < _bd.length; i++) babcde[k++] = _bd[i]; for (uint256 i = 0; i < _be.length; i++) babcde[k++] = _be[i]; return string(babcde); } function strConcat( string memory _a, string memory _b, string memory _c, string memory _d ) internal pure returns (string memory) { return strConcat(_a, _b, _c, _d, ""); } function strConcat( string memory _a, string memory _b, string memory _c ) internal pure returns (string memory) { return strConcat(_a, _b, _c, "", ""); } function strConcat(string memory _a, string memory _b) internal pure returns (string memory) { return strConcat(_a, _b, "", "", ""); } function uint2str(uint256 _i) internal pure returns (string memory _uintAsString) { if (_i == 0) { return "0"; } uint256 j = _i; uint256 len; while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint256 k = len - 1; while (_i != 0) { bstr[k--] = bytes1(uint8(48 + (_i % 10))); _i /= 10; } return string(bstr); } } contract OwnableDelegateProxy {} contract ProxyRegistry { mapping(address => OwnableDelegateProxy) public proxies; } /** * @title ERC1155Tradable * ERC1155Tradable - ERC1155 contract that whitelists an operator address, * has create and mint functionality, and supports useful standards from OpenZeppelin, like _exists(), name(), symbol(), and totalSupply() */ contract ERC1155Tradable is ERC1155, ERC1155MintBurn, ERC1155Metadata, Ownable, MinterRole, WhitelistAdminRole { using Strings for string; address proxyRegistryAddress; uint256 private _currentTokenID = 0; mapping(uint256 => address) public creators; mapping(uint256 => uint256) public tokenSupply; mapping(uint256 => uint256) public tokenMaxSupply; // Contract name string public name; // Contract symbol string public symbol; constructor( string memory _name, string memory _symbol, address _proxyRegistryAddress ) public { name = _name; symbol = _symbol; proxyRegistryAddress = _proxyRegistryAddress; } function removeWhitelistAdmin(address account) public onlyOwner { _removeWhitelistAdmin(account); } function removeMinter(address account) public onlyOwner { _removeMinter(account); } function uri(uint256 _id) public view returns (string memory) { require(_exists(_id), "ERC721Tradable#uri: NONEXISTENT_TOKEN"); return Strings.strConcat(baseMetadataURI, Strings.uint2str(_id)); } /** * @dev Returns the total quantity for a token ID * @param _id uint256 ID of the token to query * @return amount of token in existence */ function totalSupply(uint256 _id) public view returns (uint256) { return tokenSupply[_id]; } /** * @dev Returns the max quantity for a token ID * @param _id uint256 ID of the token to query * @return amount of token in existence */ function maxSupply(uint256 _id) public view returns (uint256) { return tokenMaxSupply[_id]; } /** * @dev Will update the base URL of token's URI * @param _newBaseMetadataURI New base URL of token's URI */ function setBaseMetadataURI(string memory _newBaseMetadataURI) public onlyWhitelistAdmin { _setBaseMetadataURI(_newBaseMetadataURI); } /** * @dev Creates a new token type and assigns _initialSupply to an address * @param _maxSupply max supply allowed * @param _initialSupply Optional amount to supply the first owner * @param _uri Optional URI for this token type * @param _data Optional data to pass if receiver is contract * @return The newly created token ID */ function create( uint256 _maxSupply, uint256 _initialSupply, string calldata _uri, bytes calldata _data ) external onlyWhitelistAdmin returns (uint256 tokenId) { require(_initialSupply <= _maxSupply, "Initial supply cannot be more than max supply"); uint256 _id = _getNextTokenID(); _incrementTokenTypeId(); creators[_id] = msg.sender; if (bytes(_uri).length > 0) { emit URI(_uri, _id); } if (_initialSupply != 0) _mint(msg.sender, _id, _initialSupply, _data); tokenSupply[_id] = _initialSupply; tokenMaxSupply[_id] = _maxSupply; return _id; } /** * @dev Mints some amount of tokens to an address * @param _to Address of the future owner of the token * @param _id Token ID to mint * @param _quantity Amount of tokens to mint * @param _data Data to pass if receiver is contract */ function mint( address _to, uint256 _id, uint256 _quantity, bytes memory _data ) public onlyMinter { uint256 tokenId = _id; require(tokenSupply[tokenId] < tokenMaxSupply[tokenId], "Max supply reached"); _mint(_to, _id, _quantity, _data); tokenSupply[_id] = tokenSupply[_id].add(_quantity); } /** * Override isApprovedForAll to whitelist user's OpenSea proxy accounts to enable gas-free listings. */ function isApprovedForAll(address _owner, address _operator) public view returns (bool isOperator) { // Whitelist OpenSea proxy contract for easy trading. ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress); if (address(proxyRegistry.proxies(_owner)) == _operator) { return true; } return ERC1155.isApprovedForAll(_owner, _operator); } /** * @dev Returns whether the specified token exists by checking to see if it has a creator * @param _id uint256 ID of the token to query the existence of * @return bool whether the token exists */ function _exists(uint256 _id) internal view returns (bool) { return creators[_id] != address(0); } /** * @dev calculates the next token ID based on value of _currentTokenID * @return uint256 for the next token ID */ function _getNextTokenID() private view returns (uint256) { return _currentTokenID.add(1); } /** * @dev increments the value of _currentTokenID */ function _incrementTokenTypeId() private { _currentTokenID++; } } contract LPTokenWrapper { using SafeMath for uint256; IERC20 public token; constructor(IERC20 _erc20Address) public { token = IERC20(_erc20Address); } uint256 private _totalSupply; mapping(address => uint256) private _balances; function totalSupply() public view returns (uint256) { return _totalSupply; } function balanceOf(address account) public view returns (uint256) { return _balances[account]; } function stake(uint256 amount) public { _totalSupply = _totalSupply.add(amount); _balances[msg.sender] = _balances[msg.sender].add(amount); token.transferFrom(msg.sender, address(this), amount); } function withdraw(uint256 amount) public { _totalSupply = _totalSupply.sub(amount); _balances[msg.sender] = _balances[msg.sender].sub(amount); token.transfer(msg.sender, amount); } } contract LPGenesisPool is LPTokenWrapper, Ownable { ERC1155Tradable public chonkers; uint256 public periodStart = 1598392960; //1598450400; mapping(address => uint256) public lastUpdateTime; mapping(address => uint256) public points; mapping(uint256 => uint256) public cards; event CardAdded(uint256 card, uint256 points); event Staked(address indexed user, uint256 amount); event Withdrawn(address indexed user, uint256 amount); event Redeemed(address indexed user, uint256 amount); modifier updateReward(address account) { if (account != address(0)) { points[account] = earned(account); lastUpdateTime[account] = block.timestamp; } _; } constructor(ERC1155Tradable _chonkersAddress, IERC20 _erc20Address) public LPTokenWrapper(_erc20Address) { chonkers = _chonkersAddress; } function addCard(uint256 cardId, uint256 amount) public onlyOwner { cards[cardId] = amount; emit CardAdded(cardId, amount); } function earned(address account) public view returns (uint256) { uint256 blockTime = block.timestamp; return points[account].add( blockTime.sub(lastUpdateTime[account]).mul(1e18).div(86400).mul( (balanceOf(account).mul(25000)).div(1e18) ) ); } // stake visibility is public as overriding LPTokenWrapper's stake() function function stake(uint256 amount) public updateReward(msg.sender) { require(block.timestamp >= periodStart, "Pool not open"); require(amount.add(balanceOf(msg.sender)) <= 200000000000000, "Cannot stake more than 0.0002 UNI-V2 LP"); super.stake(amount); emit Staked(msg.sender, amount); } function withdraw(uint256 amount) public updateReward(msg.sender) { require(amount > 0, "Cannot withdraw 0"); super.withdraw(amount); emit Withdrawn(msg.sender, amount); } function exit() external { withdraw(balanceOf(msg.sender)); } function redeem(uint256 card) public updateReward(msg.sender) { require(cards[card] != 0, "Card not found"); require(points[msg.sender] >= cards[card], "Not enough points to redeem for card"); require(chonkers.totalSupply(card) < chonkers.maxSupply(card), "Max cards minted"); points[msg.sender] = points[msg.sender].sub(cards[card]); chonkers.mint(msg.sender, card, 1, ""); emit Redeemed(msg.sender, cards[card]); } }
* Override isApprovedForAll to whitelist user's OpenSea proxy accounts to enable gas-free listings./ Whitelist OpenSea proxy contract for easy trading.
function isApprovedForAll(address _owner, address _operator) public view returns (bool isOperator) { ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress); if (address(proxyRegistry.proxies(_owner)) == _operator) { return true; } return ERC1155.isApprovedForAll(_owner, _operator); }
205,602
[ 1, 6618, 353, 31639, 1290, 1595, 358, 10734, 729, 1807, 3502, 1761, 69, 2889, 9484, 358, 4237, 16189, 17, 9156, 666, 899, 18, 19, 3497, 7523, 3502, 1761, 69, 2889, 6835, 364, 12779, 1284, 7459, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 202, 915, 353, 31639, 1290, 1595, 12, 2867, 389, 8443, 16, 1758, 389, 9497, 13, 1071, 1476, 1135, 261, 6430, 353, 5592, 13, 288, 203, 202, 202, 3886, 4243, 2889, 4243, 273, 7659, 4243, 12, 5656, 4243, 1887, 1769, 203, 202, 202, 430, 261, 2867, 12, 5656, 4243, 18, 20314, 606, 24899, 8443, 3719, 422, 389, 9497, 13, 288, 203, 1082, 202, 2463, 638, 31, 203, 202, 202, 97, 203, 203, 202, 202, 2463, 4232, 39, 2499, 2539, 18, 291, 31639, 1290, 1595, 24899, 8443, 16, 389, 9497, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]