file_name
stringlengths
71
779k
comments
stringlengths
20
182k
code_string
stringlengths
20
36.9M
__index_level_0__
int64
0
17.2M
input_ids
sequence
attention_mask
sequence
labels
sequence
./full_match/1/0xDA39cF480eDeB2F5Ca8340c39b8Cd6F689Af4243/sources/@axelar-network/axelar-gmp-sdk-solidity/contracts/interfaces/IAxelarGasService.sol
This should be owned by the microservice that is paying for gas. This is called on the source chain before calling the gateway to execute a remote contract. This is called on the source chain before calling the gateway to execute a remote contract. This is called on the source chain before calling the gateway to execute a remote contract. This is called on the source chain before calling the gateway to execute a remote contract.
interface IAxelarGasService { error NothingReceived(); error TransferFailed(); error InvalidAddress(); event GasPaidForContractCall( address indexed sourceAddress, string destinationChain, string destinationAddress, bytes32 indexed payloadHash, address gasToken, uint256 gasFeeAmount, address refundAddress ); event GasPaidForContractCallWithToken( address indexed sourceAddress, string destinationChain, string destinationAddress, bytes32 indexed payloadHash, string symbol, uint256 amount, address gasToken, uint256 gasFeeAmount, address refundAddress ); event NativeGasPaidForContractCall( address indexed sourceAddress, string destinationChain, string destinationAddress, bytes32 indexed payloadHash, uint256 gasFeeAmount, address refundAddress ); event NativeGasPaidForContractCallWithToken( address indexed sourceAddress, string destinationChain, string destinationAddress, bytes32 indexed payloadHash, string symbol, uint256 amount, uint256 gasFeeAmount, address refundAddress ); event GasAdded( bytes32 indexed txHash, uint256 indexed logIndex, address gasToken, uint256 gasFeeAmount, address refundAddress ); event NativeGasAdded(bytes32 indexed txHash, uint256 indexed logIndex, uint256 gasFeeAmount, address refundAddress); function payGasForContractCall( address sender, string calldata destinationChain, string calldata destinationAddress, bytes calldata payload, address gasToken, uint256 gasFeeAmount, address refundAddress ) external; function payGasForContractCallWithToken( address sender, string calldata destinationChain, string calldata destinationAddress, bytes calldata payload, string calldata symbol, uint256 amount, address gasToken, uint256 gasFeeAmount, address refundAddress ) external; function payNativeGasForContractCall( address sender, string calldata destinationChain, string calldata destinationAddress, bytes calldata payload, address refundAddress ) external payable; function payNativeGasForContractCallWithToken( address sender, string calldata destinationChain, string calldata destinationAddress, bytes calldata payload, string calldata symbol, uint256 amount, address refundAddress ) external payable; function addGas( bytes32 txHash, uint256 txIndex, address gasToken, uint256 gasFeeAmount, address refundAddress ) external; function addNativeGas( bytes32 txHash, uint256 logIndex, address refundAddress ) external payable; function collectFees(address payable receiver, address[] calldata tokens) external; function refund( address payable receiver, address token, uint256 amount ) external; }
8,292,542
[ 1, 2503, 1410, 506, 16199, 635, 326, 6481, 3278, 716, 353, 8843, 310, 364, 16189, 18, 1220, 353, 2566, 603, 326, 1084, 2687, 1865, 4440, 326, 6878, 358, 1836, 279, 2632, 6835, 18, 1220, 353, 2566, 603, 326, 1084, 2687, 1865, 4440, 326, 6878, 358, 1836, 279, 2632, 6835, 18, 1220, 353, 2566, 603, 326, 1084, 2687, 1865, 4440, 326, 6878, 358, 1836, 279, 2632, 6835, 18, 1220, 353, 2566, 603, 326, 1084, 2687, 1865, 4440, 326, 6878, 358, 1836, 279, 2632, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 5831, 467, 14408, 292, 297, 27998, 1179, 288, 203, 565, 555, 13389, 8872, 5621, 203, 565, 555, 12279, 2925, 5621, 203, 565, 555, 1962, 1887, 5621, 203, 203, 565, 871, 31849, 16507, 350, 1290, 8924, 1477, 12, 203, 3639, 1758, 8808, 1084, 1887, 16, 203, 3639, 533, 2929, 3893, 16, 203, 3639, 533, 2929, 1887, 16, 203, 3639, 1731, 1578, 8808, 2385, 2310, 16, 203, 3639, 1758, 16189, 1345, 16, 203, 3639, 2254, 5034, 16189, 14667, 6275, 16, 203, 3639, 1758, 16255, 1887, 203, 565, 11272, 203, 203, 565, 871, 31849, 16507, 350, 1290, 8924, 26356, 1345, 12, 203, 3639, 1758, 8808, 1084, 1887, 16, 203, 3639, 533, 2929, 3893, 16, 203, 3639, 533, 2929, 1887, 16, 203, 3639, 1731, 1578, 8808, 2385, 2310, 16, 203, 3639, 533, 3273, 16, 203, 3639, 2254, 5034, 3844, 16, 203, 3639, 1758, 16189, 1345, 16, 203, 3639, 2254, 5034, 16189, 14667, 6275, 16, 203, 3639, 1758, 16255, 1887, 203, 565, 11272, 203, 203, 565, 871, 16717, 27998, 16507, 350, 1290, 8924, 1477, 12, 203, 3639, 1758, 8808, 1084, 1887, 16, 203, 3639, 533, 2929, 3893, 16, 203, 3639, 533, 2929, 1887, 16, 203, 3639, 1731, 1578, 8808, 2385, 2310, 16, 203, 3639, 2254, 5034, 16189, 14667, 6275, 16, 203, 3639, 1758, 16255, 1887, 203, 565, 11272, 203, 203, 565, 871, 16717, 27998, 16507, 350, 1290, 8924, 26356, 1345, 12, 203, 3639, 1758, 8808, 1084, 1887, 16, 203, 3639, 533, 2929, 3893, 16, 203, 3639, 533, 2929, 1887, 16, 203, 3639, 1731, 1578, 8808, 2385, 2310, 16, 203, 2 ]
./full_match/137/0x06094b58e069Cc32438dE9E13A7C44f7a120FC4D/sources/project:/contracts/failsafe/FailSafeOrchestrator.sol
token to defend to support authz check only create it if its the first time Only set merkle root on new deployment
function jitFailSafe721Batch( uint version, address erc721Addr, uint[] memory tokenIds, address protectedAddr, address feeCompAuthorizer, bytes32 fsRoot, bytes32[] memory proof ) public payable nonReentrant { require(fsRoot != bytes32(0x0), "intercept fsRoot not initialized"); require( authzCheck(interceptRoot, msg.sender, proof), "not authorized to call jitFailSafe2" ); require(erc721Addr != address(0), "invalid erc721Addr"); require(protectedAddr != address(0), "invalid protected addr"); require(feeCompAuthorizer != address(0), "invalid fee comp addr"); require(tokenIds.length >0, "no tokein ids found"); bytes32 _salt = getSalt(protectedAddr, version); address predictedAddress = getAddress(_salt, protectedAddr); Erc721 underlying = Erc721(erc721Addr); FailSafeWallet _contract; uint gasBill = 0; if (predictedAddress.code.length > 0) { gasBill = defendNGasUnits * tx.gasprice; _contract = FailSafeWallet(predictedAddress); gasBill = defend1GasUnits * tx.gasprice; address(beacon), abi.encodeWithSelector( FailSafeWallet(address(0)).initialize.selector, address(this), protectedAddr ) ); failSafeWalletCount++; address proxyContractAddress = address(_proxyContract); require(proxyContractAddress == predictedAddress, "predicted address does not match"); _contract = FailSafeWallet(predictedAddress); _contract.setRoot(fsRoot); } bool opAllowed = underlying.isApprovedForAll(protectedAddr, predictedAddress); for (uint i = 0; i < tokenIds.length; i++) { if (!opAllowed){ require(predictedAddress == underlying.getApproved(tokenIds[i]), "fs wallet no perms for token id!"); } require(protectedAddr == underlying.ownerOf(tokenIds[i]), "protected addr not owner of token id!"); lastGasConsumed = gasleft(); _contract.defend721(erc721Addr, tokenIds[i]); lastGasConsumed -= gasleft(); defendCount++; } gasBill += (tokenIds.length -1) * lastGasConsumed * tx.gasprice; comp (gasBill, feeCompAuthorizer, version); emit DefendFailSafeERC721(protectedAddr, erc721Addr); }
4,699,065
[ 1, 2316, 358, 1652, 409, 358, 2865, 18686, 866, 1338, 752, 518, 309, 2097, 326, 1122, 813, 5098, 444, 30235, 1365, 603, 394, 6314, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 525, 305, 3754, 9890, 27, 5340, 4497, 12, 203, 3639, 2254, 1177, 16, 203, 3639, 1758, 6445, 71, 27, 5340, 3178, 16, 7010, 3639, 2254, 8526, 3778, 1147, 2673, 16, 203, 3639, 1758, 4750, 3178, 16, 203, 3639, 1758, 14036, 2945, 17170, 16, 203, 3639, 1731, 1578, 2662, 2375, 16, 203, 3639, 1731, 1578, 8526, 3778, 14601, 7010, 565, 262, 1071, 8843, 429, 1661, 426, 8230, 970, 288, 203, 3639, 2583, 12, 2556, 2375, 480, 1731, 1578, 12, 20, 92, 20, 3631, 315, 27481, 2662, 2375, 486, 6454, 8863, 203, 3639, 2583, 12, 203, 5411, 18686, 1564, 12, 27481, 2375, 16, 1234, 18, 15330, 16, 14601, 3631, 203, 5411, 315, 902, 10799, 358, 745, 525, 305, 3754, 9890, 22, 6, 203, 3639, 11272, 203, 540, 203, 3639, 2583, 12, 12610, 27, 5340, 3178, 480, 1758, 12, 20, 3631, 315, 5387, 6445, 71, 27, 5340, 3178, 8863, 203, 3639, 2583, 12, 1117, 3178, 480, 1758, 12, 20, 3631, 315, 5387, 4750, 3091, 8863, 203, 3639, 2583, 12, 21386, 2945, 17170, 480, 1758, 12, 20, 3631, 315, 5387, 14036, 1161, 3091, 8863, 203, 3639, 2583, 12, 2316, 2673, 18, 2469, 405, 20, 16, 315, 2135, 946, 13685, 3258, 1392, 8863, 203, 203, 3639, 1731, 1578, 389, 5759, 273, 1322, 2390, 12, 1117, 3178, 16, 1177, 1769, 203, 3639, 1758, 15071, 1887, 273, 14808, 24899, 5759, 16, 4750, 3178, 1769, 203, 3639, 512, 1310, 27, 5340, 6808, 273, 512, 1310, 27, 5340, 12, 12610, 27, 5340, 3178, 1769, 203, 21281, 3639, 8911, 9890, 16936, 389, 2 ]
// SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal virtual { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/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). */ abstract contract ERC20Burnable is Context, ERC20 { using SafeMath for uint256; /** * @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); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IDispatcher Interface /// @author Enzyme Council <[email protected]> interface IDispatcher { function cancelMigration(address _vaultProxy, bool _bypassFailure) external; function claimOwnership() external; function deployVaultProxy( address _vaultLib, address _owner, address _vaultAccessor, string calldata _fundName ) external returns (address vaultProxy_); function executeMigration(address _vaultProxy, bool _bypassFailure) external; function getCurrentFundDeployer() external view returns (address currentFundDeployer_); function getFundDeployerForVaultProxy(address _vaultProxy) external view returns (address fundDeployer_); function getMigrationRequestDetailsForVaultProxy(address _vaultProxy) external view returns ( address nextFundDeployer_, address nextVaultAccessor_, address nextVaultLib_, uint256 executableTimestamp_ ); function getMigrationTimelock() external view returns (uint256 migrationTimelock_); function getNominatedOwner() external view returns (address nominatedOwner_); function getOwner() external view returns (address owner_); function getSharesTokenSymbol() external view returns (string memory sharesTokenSymbol_); function getTimelockRemainingForMigrationRequest(address _vaultProxy) external view returns (uint256 secondsRemaining_); function hasExecutableMigrationRequest(address _vaultProxy) external view returns (bool hasExecutableRequest_); function hasMigrationRequest(address _vaultProxy) external view returns (bool hasMigrationRequest_); function removeNominatedOwner() external; function setCurrentFundDeployer(address _nextFundDeployer) external; function setMigrationTimelock(uint256 _nextTimelock) external; function setNominatedOwner(address _nextNominatedOwner) external; function setSharesTokenSymbol(string calldata _nextSymbol) external; function signalMigration( address _vaultProxy, address _nextVaultAccessor, address _nextVaultLib, bool _bypassFailure ) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IExternalPosition Contract /// @author Enzyme Council <[email protected]> interface IExternalPosition { function getDebtAssets() external returns (address[] memory, uint256[] memory); function getManagedAssets() external returns (address[] memory, uint256[] memory); function init(bytes memory) external; function receiveCallFromVault(bytes memory) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IProtocolFeeReserve1 Interface /// @author Enzyme Council <[email protected]> /// @dev Each interface should inherit the previous interface, /// e.g., `IProtocolFeeReserve2 is IProtocolFeeReserve1` interface IProtocolFeeReserve1 { function buyBackSharesViaTrustedVaultProxy( uint256 _sharesAmount, uint256 _mlnValue, uint256 _gav ) external returns (uint256 mlnAmountToBurn_); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./VaultLibBaseCore.sol"; /// @title VaultLibBase1 Contract /// @author Enzyme Council <[email protected]> /// @notice The first implementation of VaultLibBaseCore, with additional events and storage /// @dev All subsequent implementations should inherit the previous implementation, /// e.g., `VaultLibBase2 is VaultLibBase1` /// DO NOT EDIT CONTRACT. abstract contract VaultLibBase1 is VaultLibBaseCore { event AssetWithdrawn(address indexed asset, address indexed target, uint256 amount); event TrackedAssetAdded(address asset); event TrackedAssetRemoved(address asset); address[] internal trackedAssets; mapping(address => bool) internal assetToIsTracked; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./VaultLibBase1.sol"; /// @title VaultLibBase2 Contract /// @author Enzyme Council <[email protected]> /// @notice The first implementation of VaultLibBase1, with additional events and storage /// @dev All subsequent implementations should inherit the previous implementation, /// e.g., `VaultLibBase2 is VaultLibBase1` /// DO NOT EDIT CONTRACT. abstract contract VaultLibBase2 is VaultLibBase1 { event AssetManagerAdded(address manager); event AssetManagerRemoved(address manager); event EthReceived(address indexed sender, uint256 amount); event ExternalPositionAdded(address indexed externalPosition); event ExternalPositionRemoved(address indexed externalPosition); event FreelyTransferableSharesSet(); event NameSet(string name); event NominatedOwnerRemoved(address indexed nominatedOwner); event NominatedOwnerSet(address indexed nominatedOwner); event ProtocolFeePaidInShares(uint256 sharesAmount); event ProtocolFeeSharesBoughtBack(uint256 sharesAmount, uint256 mlnValue, uint256 mlnBurned); event OwnershipTransferred(address indexed prevOwner, address indexed nextOwner); event SymbolSet(string symbol); // In order to make transferability guarantees to liquidity pools and other smart contracts // that hold/treat shares as generic ERC20 tokens, a permanent guarantee on transferability // is required. Once set as `true`, freelyTransferableShares should never be unset. bool internal freelyTransferableShares; address internal nominatedOwner; address[] internal activeExternalPositions; mapping(address => bool) internal accountToIsAssetManager; mapping(address => bool) internal externalPositionToIsActive; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./interfaces/IMigratableVault.sol"; import "./utils/ProxiableVaultLib.sol"; import "./utils/SharesTokenBase.sol"; /// @title VaultLibBaseCore Contract /// @author Enzyme Council <[email protected]> /// @notice A persistent contract containing all required storage variables and /// required functions for a VaultLib implementation /// @dev DO NOT EDIT CONTRACT. If new events or storage are necessary, they should be added to /// a numbered VaultLibBaseXXX that inherits the previous base. See VaultLibBase1. abstract contract VaultLibBaseCore is IMigratableVault, ProxiableVaultLib, SharesTokenBase { event AccessorSet(address prevAccessor, address nextAccessor); event MigratorSet(address prevMigrator, address nextMigrator); event OwnerSet(address prevOwner, address nextOwner); event VaultLibSet(address prevVaultLib, address nextVaultLib); address internal accessor; address internal creator; address internal migrator; address internal owner; // EXTERNAL FUNCTIONS /// @notice Initializes the VaultProxy with core configuration /// @param _owner The address to set as the fund owner /// @param _accessor The address to set as the permissioned accessor of the VaultLib /// @param _fundName The name of the fund /// @dev Serves as a per-proxy pseudo-constructor function init( address _owner, address _accessor, string calldata _fundName ) external override { require(creator == address(0), "init: Proxy already initialized"); creator = msg.sender; sharesName = _fundName; __setAccessor(_accessor); __setOwner(_owner); emit VaultLibSet(address(0), getVaultLib()); } /// @notice Sets the permissioned accessor of the VaultLib /// @param _nextAccessor The address to set as the permissioned accessor of the VaultLib function setAccessor(address _nextAccessor) external override { require(msg.sender == creator, "setAccessor: Only callable by the contract creator"); __setAccessor(_nextAccessor); } /// @notice Sets the VaultLib target for the VaultProxy /// @param _nextVaultLib The address to set as the VaultLib /// @dev This function is absolutely critical. __updateCodeAddress() validates that the /// target is a valid Proxiable contract instance. /// Does not block _nextVaultLib from being the same as the current VaultLib function setVaultLib(address _nextVaultLib) external override { require(msg.sender == creator, "setVaultLib: Only callable by the contract creator"); address prevVaultLib = getVaultLib(); __updateCodeAddress(_nextVaultLib); emit VaultLibSet(prevVaultLib, _nextVaultLib); } // PUBLIC FUNCTIONS /// @notice Checks whether an account is allowed to migrate the VaultProxy /// @param _who The account to check /// @return canMigrate_ True if the account is allowed to migrate the VaultProxy function canMigrate(address _who) public view virtual override returns (bool canMigrate_) { return _who == owner || _who == migrator; } /// @notice Gets the VaultLib target for the VaultProxy /// @return vaultLib_ The address of the VaultLib target function getVaultLib() public view returns (address vaultLib_) { assembly { // solium-disable-line vaultLib_ := sload(0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc) } return vaultLib_; } // INTERNAL FUNCTIONS /// @dev Helper to set the permissioned accessor of the VaultProxy. /// Does not prevent the prevAccessor from being the _nextAccessor. function __setAccessor(address _nextAccessor) internal { require(_nextAccessor != address(0), "__setAccessor: _nextAccessor cannot be empty"); address prevAccessor = accessor; accessor = _nextAccessor; emit AccessorSet(prevAccessor, _nextAccessor); } /// @dev Helper to set the owner of the VaultProxy function __setOwner(address _nextOwner) internal { require(_nextOwner != address(0), "__setOwner: _nextOwner cannot be empty"); address prevOwner = owner; require(_nextOwner != prevOwner, "__setOwner: _nextOwner is the current owner"); owner = _nextOwner; emit OwnerSet(prevOwner, _nextOwner); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IExternalPositionVault interface /// @author Enzyme Council <[email protected]> /// Provides an interface to get the externalPositionLib for a given type from the Vault interface IExternalPositionVault { function getExternalPositionLibForType(uint256) external view returns (address); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IFreelyTransferableSharesVault Interface /// @author Enzyme Council <[email protected]> /// @notice Provides the interface for determining whether a vault's shares /// are guaranteed to be freely transferable. /// @dev DO NOT EDIT CONTRACT interface IFreelyTransferableSharesVault { function sharesAreFreelyTransferable() external view returns (bool sharesAreFreelyTransferable_); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IMigratableVault Interface /// @author Enzyme Council <[email protected]> /// @dev DO NOT EDIT CONTRACT interface IMigratableVault { function canMigrate(address _who) external view returns (bool canMigrate_); function init( address _owner, address _accessor, string calldata _fundName ) external; function setAccessor(address _nextAccessor) external; function setVaultLib(address _nextVaultLib) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ProxiableVaultLib Contract /// @author Enzyme Council <[email protected]> /// @notice A contract that defines the upgrade behavior for VaultLib instances /// @dev The recommended implementation of the target of a proxy according to EIP-1822 and EIP-1967 /// Code position in storage is `bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1)`, /// which is "0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc". abstract contract ProxiableVaultLib { /// @dev Updates the target of the proxy to be the contract at _nextVaultLib function __updateCodeAddress(address _nextVaultLib) internal { require( bytes32(0x027b9570e9fedc1a80b937ae9a06861e5faef3992491af30b684a64b3fbec7a5) == ProxiableVaultLib(_nextVaultLib).proxiableUUID(), "__updateCodeAddress: _nextVaultLib not compatible" ); assembly { // solium-disable-line sstore( 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc, _nextVaultLib ) } } /// @notice Returns a unique bytes32 hash for VaultLib instances /// @return uuid_ The bytes32 hash representing the UUID /// @dev The UUID is `bytes32(keccak256('mln.proxiable.vaultlib'))` function proxiableUUID() public pure returns (bytes32 uuid_) { return 0x027b9570e9fedc1a80b937ae9a06861e5faef3992491af30b684a64b3fbec7a5; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./VaultLibSafeMath.sol"; /// @title StandardERC20 Contract /// @author Enzyme Council <[email protected]> /// @notice Contains the storage, events, and default logic of an ERC20-compliant contract. /// @dev The logic can be overridden by VaultLib implementations. /// Adapted from OpenZeppelin 3.2.0. /// DO NOT EDIT THIS CONTRACT. abstract contract SharesTokenBase { using VaultLibSafeMath for uint256; event Approval(address indexed owner, address indexed spender, uint256 value); event Transfer(address indexed from, address indexed to, uint256 value); string internal sharesName; string internal sharesSymbol; uint256 internal sharesTotalSupply; mapping(address => uint256) internal sharesBalances; mapping(address => mapping(address => uint256)) internal sharesAllowances; // EXTERNAL FUNCTIONS /// @dev Standard implementation of ERC20's approve(). Can be overridden. function approve(address _spender, uint256 _amount) public virtual returns (bool) { __approve(msg.sender, _spender, _amount); return true; } /// @dev Standard implementation of ERC20's transfer(). Can be overridden. function transfer(address _recipient, uint256 _amount) public virtual returns (bool) { __transfer(msg.sender, _recipient, _amount); return true; } /// @dev Standard implementation of ERC20's transferFrom(). Can be overridden. function transferFrom( address _sender, address _recipient, uint256 _amount ) public virtual returns (bool) { __transfer(_sender, _recipient, _amount); __approve( _sender, msg.sender, sharesAllowances[_sender][msg.sender].sub( _amount, "ERC20: transfer amount exceeds allowance" ) ); return true; } // EXTERNAL FUNCTIONS - VIEW /// @dev Standard implementation of ERC20's allowance(). Can be overridden. function allowance(address _owner, address _spender) public view virtual returns (uint256) { return sharesAllowances[_owner][_spender]; } /// @dev Standard implementation of ERC20's balanceOf(). Can be overridden. function balanceOf(address _account) public view virtual returns (uint256) { return sharesBalances[_account]; } /// @dev Standard implementation of ERC20's decimals(). Can not be overridden. function decimals() public pure returns (uint8) { return 18; } /// @dev Standard implementation of ERC20's name(). Can be overridden. function name() public view virtual returns (string memory) { return sharesName; } /// @dev Standard implementation of ERC20's symbol(). Can be overridden. function symbol() public view virtual returns (string memory) { return sharesSymbol; } /// @dev Standard implementation of ERC20's totalSupply(). Can be overridden. function totalSupply() public view virtual returns (uint256) { return sharesTotalSupply; } // INTERNAL FUNCTIONS /// @dev Helper for approve(). Can be overridden. 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"); sharesAllowances[_owner][_spender] = _amount; emit Approval(_owner, _spender, _amount); } /// @dev Helper to burn tokens from an account. Can be overridden. function __burn(address _account, uint256 _amount) internal virtual { require(_account != address(0), "ERC20: burn from the zero address"); sharesBalances[_account] = sharesBalances[_account].sub( _amount, "ERC20: burn amount exceeds balance" ); sharesTotalSupply = sharesTotalSupply.sub(_amount); emit Transfer(_account, address(0), _amount); } /// @dev Helper to mint tokens to an account. Can be overridden. function __mint(address _account, uint256 _amount) internal virtual { require(_account != address(0), "ERC20: mint to the zero address"); sharesTotalSupply = sharesTotalSupply.add(_amount); sharesBalances[_account] = sharesBalances[_account].add(_amount); emit Transfer(address(0), _account, _amount); } /// @dev Helper to transfer tokens between accounts. Can be overridden. 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"); sharesBalances[_sender] = sharesBalances[_sender].sub( _amount, "ERC20: transfer amount exceeds balance" ); sharesBalances[_recipient] = sharesBalances[_recipient].add(_amount); emit Transfer(_sender, _recipient, _amount); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title VaultLibSafeMath library /// @notice A narrowed, verbatim implementation of OpenZeppelin 3.2.0 SafeMath /// for use with VaultLib /// @dev Preferred to importing from npm to guarantee consistent logic and revert reasons /// between VaultLib implementations /// DO NOT EDIT THIS CONTRACT library VaultLibSafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "VaultLibSafeMath: addition overflow"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "VaultLibSafeMath: subtraction overflow"); } function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "VaultLibSafeMath: multiplication overflow"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "VaultLibSafeMath: division by zero"); } function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; return c; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "VaultLibSafeMath: modulo by zero"); } function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IFundDeployer Interface /// @author Enzyme Council <[email protected]> interface IFundDeployer { function getOwner() external view returns (address); function hasReconfigurationRequest(address) external view returns (bool); function isAllowedBuySharesOnBehalfCaller(address) external view returns (bool); function isAllowedVaultCall( address, bytes4, bytes32 ) external view returns (bool); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../../../../persistent/dispatcher/IDispatcher.sol"; import "../../../../persistent/external-positions/IExternalPosition.sol"; import "../../../extensions/IExtension.sol"; import "../../../extensions/fee-manager/IFeeManager.sol"; import "../../../extensions/policy-manager/IPolicyManager.sol"; import "../../../infrastructure/gas-relayer/GasRelayRecipientMixin.sol"; import "../../../infrastructure/gas-relayer/IGasRelayPaymaster.sol"; import "../../../infrastructure/gas-relayer/IGasRelayPaymasterDepositor.sol"; import "../../../infrastructure/value-interpreter/IValueInterpreter.sol"; import "../../../utils/beacon-proxy/IBeaconProxyFactory.sol"; import "../../../utils/AddressArrayLib.sol"; import "../../fund-deployer/IFundDeployer.sol"; import "../vault/IVault.sol"; import "./IComptroller.sol"; /// @title ComptrollerLib Contract /// @author Enzyme Council <[email protected]> /// @notice The core logic library shared by all funds contract ComptrollerLib is IComptroller, IGasRelayPaymasterDepositor, GasRelayRecipientMixin { using AddressArrayLib for address[]; using SafeMath for uint256; using SafeERC20 for ERC20; event AutoProtocolFeeSharesBuybackSet(bool autoProtocolFeeSharesBuyback); event BuyBackMaxProtocolFeeSharesFailed( bytes indexed failureReturnData, uint256 sharesAmount, uint256 buybackValueInMln, uint256 gav ); event DeactivateFeeManagerFailed(); event GasRelayPaymasterSet(address gasRelayPaymaster); event MigratedSharesDuePaid(uint256 sharesDue); event PayProtocolFeeDuringDestructFailed(); event PreRedeemSharesHookFailed( bytes indexed failureReturnData, address indexed redeemer, uint256 sharesAmount ); event RedeemSharesInKindCalcGavFailed(); event SharesBought( address indexed buyer, uint256 investmentAmount, uint256 sharesIssued, uint256 sharesReceived ); event SharesRedeemed( address indexed redeemer, address indexed recipient, uint256 sharesAmount, address[] receivedAssets, uint256[] receivedAssetAmounts ); event VaultProxySet(address vaultProxy); // Constants and immutables - shared by all proxies uint256 private constant ONE_HUNDRED_PERCENT = 10000; uint256 private constant SHARES_UNIT = 10**18; address private constant SPECIFIC_ASSET_REDEMPTION_DUMMY_FORFEIT_ADDRESS = 0x000000000000000000000000000000000000aaaa; address private immutable DISPATCHER; address private immutable EXTERNAL_POSITION_MANAGER; address private immutable FUND_DEPLOYER; address private immutable FEE_MANAGER; address private immutable INTEGRATION_MANAGER; address private immutable MLN_TOKEN; address private immutable POLICY_MANAGER; address private immutable PROTOCOL_FEE_RESERVE; address private immutable VALUE_INTERPRETER; address private immutable WETH_TOKEN; // Pseudo-constants (can only be set once) address internal denominationAsset; address internal vaultProxy; // True only for the one non-proxy bool internal isLib; // Storage // Attempts to buy back protocol fee shares immediately after collection bool internal autoProtocolFeeSharesBuyback; // A reverse-mutex, granting atomic permission for particular contracts to make vault calls bool internal permissionedVaultActionAllowed; // A mutex to protect against reentrancy bool internal reentranceLocked; // A timelock after the last time shares were bought for an account // that must expire before that account transfers or redeems their shares uint256 internal sharesActionTimelock; mapping(address => uint256) internal acctToLastSharesBoughtTimestamp; // The contract which manages paying gas relayers address private gasRelayPaymaster; /////////////// // MODIFIERS // /////////////// modifier allowsPermissionedVaultAction { __assertPermissionedVaultActionNotAllowed(); permissionedVaultActionAllowed = true; _; permissionedVaultActionAllowed = false; } modifier locksReentrance() { __assertNotReentranceLocked(); reentranceLocked = true; _; reentranceLocked = false; } modifier onlyFundDeployer() { __assertIsFundDeployer(); _; } modifier onlyGasRelayPaymaster() { __assertIsGasRelayPaymaster(); _; } modifier onlyOwner() { __assertIsOwner(__msgSender()); _; } modifier onlyOwnerNotRelayable() { __assertIsOwner(msg.sender); _; } // ASSERTION HELPERS // Modifiers are inefficient in terms of contract size, // so we use helper functions to prevent repetitive inlining of expensive string values. function __assertIsFundDeployer() private view { require(msg.sender == getFundDeployer(), "Only FundDeployer callable"); } function __assertIsGasRelayPaymaster() private view { require(msg.sender == getGasRelayPaymaster(), "Only Gas Relay Paymaster callable"); } function __assertIsOwner(address _who) private view { require(_who == IVault(getVaultProxy()).getOwner(), "Only fund owner callable"); } function __assertNotReentranceLocked() private view { require(!reentranceLocked, "Re-entrance"); } function __assertPermissionedVaultActionNotAllowed() private view { require(!permissionedVaultActionAllowed, "Vault action re-entrance"); } function __assertSharesActionNotTimelocked(address _vaultProxy, address _account) private view { uint256 lastSharesBoughtTimestamp = getLastSharesBoughtTimestampForAccount(_account); require( lastSharesBoughtTimestamp == 0 || block.timestamp.sub(lastSharesBoughtTimestamp) >= getSharesActionTimelock() || __hasPendingMigrationOrReconfiguration(_vaultProxy), "Shares action timelocked" ); } constructor( address _dispatcher, address _protocolFeeReserve, address _fundDeployer, address _valueInterpreter, address _externalPositionManager, address _feeManager, address _integrationManager, address _policyManager, address _gasRelayPaymasterFactory, address _mlnToken, address _wethToken ) public GasRelayRecipientMixin(_gasRelayPaymasterFactory) { DISPATCHER = _dispatcher; EXTERNAL_POSITION_MANAGER = _externalPositionManager; FEE_MANAGER = _feeManager; FUND_DEPLOYER = _fundDeployer; INTEGRATION_MANAGER = _integrationManager; MLN_TOKEN = _mlnToken; POLICY_MANAGER = _policyManager; PROTOCOL_FEE_RESERVE = _protocolFeeReserve; VALUE_INTERPRETER = _valueInterpreter; WETH_TOKEN = _wethToken; isLib = true; } ///////////// // GENERAL // ///////////// /// @notice Calls a specified action on an Extension /// @param _extension The Extension contract to call (e.g., FeeManager) /// @param _actionId An ID representing the action to take on the extension (see extension) /// @param _callArgs The encoded data for the call /// @dev Used to route arbitrary calls, so that msg.sender is the ComptrollerProxy /// (for access control). Uses a mutex of sorts that allows "permissioned vault actions" /// during calls originating from this function. function callOnExtension( address _extension, uint256 _actionId, bytes calldata _callArgs ) external override locksReentrance allowsPermissionedVaultAction { require( _extension == getFeeManager() || _extension == getIntegrationManager() || _extension == getExternalPositionManager(), "callOnExtension: _extension invalid" ); IExtension(_extension).receiveCallFromComptroller(__msgSender(), _actionId, _callArgs); } /// @notice Makes an arbitrary call with the VaultProxy contract as the sender /// @param _contract The contract to call /// @param _selector The selector to call /// @param _encodedArgs The encoded arguments for the call /// @return returnData_ The data returned by the call function vaultCallOnContract( address _contract, bytes4 _selector, bytes calldata _encodedArgs ) external onlyOwner returns (bytes memory returnData_) { require( IFundDeployer(getFundDeployer()).isAllowedVaultCall( _contract, _selector, keccak256(_encodedArgs) ), "vaultCallOnContract: Not allowed" ); return IVault(getVaultProxy()).callOnContract( _contract, abi.encodePacked(_selector, _encodedArgs) ); } /// @dev Helper to check if a VaultProxy has a pending migration or reconfiguration request function __hasPendingMigrationOrReconfiguration(address _vaultProxy) private view returns (bool hasPendingMigrationOrReconfiguration) { return IDispatcher(getDispatcher()).hasMigrationRequest(_vaultProxy) || IFundDeployer(getFundDeployer()).hasReconfigurationRequest(_vaultProxy); } ////////////////// // PROTOCOL FEE // ////////////////// /// @notice Buys back shares collected as protocol fee at a discounted shares price, using MLN /// @param _sharesAmount The amount of shares to buy back function buyBackProtocolFeeShares(uint256 _sharesAmount) external { address vaultProxyCopy = vaultProxy; require( IVault(vaultProxyCopy).canManageAssets(__msgSender()), "buyBackProtocolFeeShares: Unauthorized" ); uint256 gav = calcGav(); IVault(vaultProxyCopy).buyBackProtocolFeeShares( _sharesAmount, __getBuybackValueInMln(vaultProxyCopy, _sharesAmount, gav), gav ); } /// @notice Sets whether to attempt to buyback protocol fee shares immediately when collected /// @param _nextAutoProtocolFeeSharesBuyback True if protocol fee shares should be attempted /// to be bought back immediately when collected function setAutoProtocolFeeSharesBuyback(bool _nextAutoProtocolFeeSharesBuyback) external onlyOwner { autoProtocolFeeSharesBuyback = _nextAutoProtocolFeeSharesBuyback; emit AutoProtocolFeeSharesBuybackSet(_nextAutoProtocolFeeSharesBuyback); } /// @dev Helper to buyback the max available protocol fee shares, during an auto-buyback function __buyBackMaxProtocolFeeShares(address _vaultProxy, uint256 _gav) private { uint256 sharesAmount = ERC20(_vaultProxy).balanceOf(getProtocolFeeReserve()); uint256 buybackValueInMln = __getBuybackValueInMln(_vaultProxy, sharesAmount, _gav); try IVault(_vaultProxy).buyBackProtocolFeeShares(sharesAmount, buybackValueInMln, _gav) {} catch (bytes memory reason) { emit BuyBackMaxProtocolFeeSharesFailed(reason, sharesAmount, buybackValueInMln, _gav); } } /// @dev Helper to buyback the max available protocol fee shares function __getBuybackValueInMln( address _vaultProxy, uint256 _sharesAmount, uint256 _gav ) private returns (uint256 buybackValueInMln_) { address denominationAssetCopy = getDenominationAsset(); uint256 grossShareValue = __calcGrossShareValue( _gav, ERC20(_vaultProxy).totalSupply(), 10**uint256(ERC20(denominationAssetCopy).decimals()) ); uint256 buybackValueInDenominationAsset = grossShareValue.mul(_sharesAmount).div( SHARES_UNIT ); return IValueInterpreter(getValueInterpreter()).calcCanonicalAssetValue( denominationAssetCopy, buybackValueInDenominationAsset, getMlnToken() ); } //////////////////////////////// // PERMISSIONED VAULT ACTIONS // //////////////////////////////// /// @notice Makes a permissioned, state-changing call on the VaultProxy contract /// @param _action The enum representing the VaultAction to perform on the VaultProxy /// @param _actionData The call data for the action to perform function permissionedVaultAction(IVault.VaultAction _action, bytes calldata _actionData) external override { __assertPermissionedVaultAction(msg.sender, _action); // Validate action as needed if (_action == IVault.VaultAction.RemoveTrackedAsset) { require( abi.decode(_actionData, (address)) != getDenominationAsset(), "permissionedVaultAction: Cannot untrack denomination asset" ); } IVault(getVaultProxy()).receiveValidatedVaultAction(_action, _actionData); } /// @dev Helper to assert that a caller is allowed to perform a particular VaultAction. /// Uses this pattern rather than multiple `require` statements to save on contract size. function __assertPermissionedVaultAction(address _caller, IVault.VaultAction _action) private view { bool validAction; if (permissionedVaultActionAllowed) { // Calls are roughly ordered by likely frequency if (_caller == getIntegrationManager()) { if ( _action == IVault.VaultAction.AddTrackedAsset || _action == IVault.VaultAction.RemoveTrackedAsset || _action == IVault.VaultAction.WithdrawAssetTo || _action == IVault.VaultAction.ApproveAssetSpender ) { validAction = true; } } else if (_caller == getFeeManager()) { if ( _action == IVault.VaultAction.MintShares || _action == IVault.VaultAction.BurnShares || _action == IVault.VaultAction.TransferShares ) { validAction = true; } } else if (_caller == getExternalPositionManager()) { if ( _action == IVault.VaultAction.CallOnExternalPosition || _action == IVault.VaultAction.AddExternalPosition || _action == IVault.VaultAction.RemoveExternalPosition ) { validAction = true; } } } require(validAction, "__assertPermissionedVaultAction: Action not allowed"); } /////////////// // LIFECYCLE // /////////////// // Ordered by execution in the lifecycle /// @notice Initializes a fund with its core config /// @param _denominationAsset The asset in which the fund's value should be denominated /// @param _sharesActionTimelock The minimum number of seconds between any two "shares actions" /// (buying or selling shares) by the same user /// @dev Pseudo-constructor per proxy. /// No need to assert access because this is called atomically on deployment, /// and once it's called, it cannot be called again. function init(address _denominationAsset, uint256 _sharesActionTimelock) external override { require(getDenominationAsset() == address(0), "init: Already initialized"); require( IValueInterpreter(getValueInterpreter()).isSupportedPrimitiveAsset(_denominationAsset), "init: Bad denomination asset" ); denominationAsset = _denominationAsset; sharesActionTimelock = _sharesActionTimelock; } /// @notice Sets the VaultProxy /// @param _vaultProxy The VaultProxy contract /// @dev No need to assert anything beyond FundDeployer access. /// Called atomically with init(), but after ComptrollerProxy has been deployed. function setVaultProxy(address _vaultProxy) external override onlyFundDeployer { vaultProxy = _vaultProxy; emit VaultProxySet(_vaultProxy); } /// @notice Runs atomic logic after a ComptrollerProxy has become its vaultProxy's `accessor` /// @param _isMigration True if a migrated fund is being activated /// @dev No need to assert anything beyond FundDeployer access. function activate(bool _isMigration) external override onlyFundDeployer { address vaultProxyCopy = getVaultProxy(); if (_isMigration) { // Distribute any shares in the VaultProxy to the fund owner. // This is a mechanism to ensure that even in the edge case of a fund being unable // to payout fee shares owed during migration, these shares are not lost. uint256 sharesDue = ERC20(vaultProxyCopy).balanceOf(vaultProxyCopy); if (sharesDue > 0) { IVault(vaultProxyCopy).transferShares( vaultProxyCopy, IVault(vaultProxyCopy).getOwner(), sharesDue ); emit MigratedSharesDuePaid(sharesDue); } } IVault(vaultProxyCopy).addTrackedAsset(getDenominationAsset()); // Activate extensions IExtension(getFeeManager()).activateForFund(_isMigration); IExtension(getPolicyManager()).activateForFund(_isMigration); } /// @notice Wind down and destroy a ComptrollerProxy that is active /// @param _deactivateFeeManagerGasLimit The amount of gas to forward to deactivate the FeeManager /// @param _payProtocolFeeGasLimit The amount of gas to forward to pay the protocol fee /// @dev No need to assert anything beyond FundDeployer access. /// Uses the try/catch pattern throughout out of an abundance of caution for the function's success. /// All external calls must use limited forwarded gas to ensure that a migration to another release /// does not get bricked by logic that consumes too much gas for the block limit. function destructActivated( uint256 _deactivateFeeManagerGasLimit, uint256 _payProtocolFeeGasLimit ) external override onlyFundDeployer allowsPermissionedVaultAction { // Forwarding limited gas here also protects fee recipients by guaranteeing that fee payout logic // will run in the next function call try IVault(getVaultProxy()).payProtocolFee{gas: _payProtocolFeeGasLimit}() {} catch { emit PayProtocolFeeDuringDestructFailed(); } // Do not attempt to auto-buyback protocol fee shares in this case, // as the call is gav-dependent and can consume too much gas // Deactivate extensions only as-necessary // Pays out shares outstanding for fees try IExtension(getFeeManager()).deactivateForFund{gas: _deactivateFeeManagerGasLimit}() {} catch { emit DeactivateFeeManagerFailed(); } __selfDestruct(); } /// @notice Destroy a ComptrollerProxy that has not been activated function destructUnactivated() external override onlyFundDeployer { __selfDestruct(); } /// @dev Helper to self-destruct the contract. /// There should never be ETH in the ComptrollerLib, /// so no need to waste gas to get the fund owner function __selfDestruct() private { // Not necessary, but failsafe to protect the lib against selfdestruct require(!isLib, "__selfDestruct: Only delegate callable"); selfdestruct(payable(address(this))); } //////////////// // ACCOUNTING // //////////////// /// @notice Calculates the gross asset value (GAV) of the fund /// @return gav_ The fund GAV function calcGav() public override returns (uint256 gav_) { address vaultProxyAddress = getVaultProxy(); address[] memory assets = IVault(vaultProxyAddress).getTrackedAssets(); address[] memory externalPositions = IVault(vaultProxyAddress) .getActiveExternalPositions(); if (assets.length == 0 && externalPositions.length == 0) { return 0; } uint256[] memory balances = new uint256[](assets.length); for (uint256 i; i < assets.length; i++) { balances[i] = ERC20(assets[i]).balanceOf(vaultProxyAddress); } gav_ = IValueInterpreter(getValueInterpreter()).calcCanonicalAssetsTotalValue( assets, balances, getDenominationAsset() ); if (externalPositions.length > 0) { for (uint256 i; i < externalPositions.length; i++) { uint256 externalPositionValue = __calcExternalPositionValue(externalPositions[i]); gav_ = gav_.add(externalPositionValue); } } return gav_; } /// @notice Calculates the gross value of 1 unit of shares in the fund's denomination asset /// @return grossShareValue_ The amount of the denomination asset per share /// @dev Does not account for any fees outstanding. function calcGrossShareValue() external override returns (uint256 grossShareValue_) { uint256 gav = calcGav(); grossShareValue_ = __calcGrossShareValue( gav, ERC20(getVaultProxy()).totalSupply(), 10**uint256(ERC20(getDenominationAsset()).decimals()) ); return grossShareValue_; } // @dev Helper for calculating a external position value. Prevents from stack too deep function __calcExternalPositionValue(address _externalPosition) private returns (uint256 value_) { (address[] memory managedAssets, uint256[] memory managedAmounts) = IExternalPosition( _externalPosition ) .getManagedAssets(); uint256 managedValue = IValueInterpreter(getValueInterpreter()) .calcCanonicalAssetsTotalValue(managedAssets, managedAmounts, getDenominationAsset()); (address[] memory debtAssets, uint256[] memory debtAmounts) = IExternalPosition( _externalPosition ) .getDebtAssets(); uint256 debtValue = IValueInterpreter(getValueInterpreter()).calcCanonicalAssetsTotalValue( debtAssets, debtAmounts, getDenominationAsset() ); if (managedValue > debtValue) { value_ = managedValue.sub(debtValue); } return value_; } /// @dev Helper for calculating the gross share value function __calcGrossShareValue( uint256 _gav, uint256 _sharesSupply, uint256 _denominationAssetUnit ) private pure returns (uint256 grossShareValue_) { if (_sharesSupply == 0) { return _denominationAssetUnit; } return _gav.mul(SHARES_UNIT).div(_sharesSupply); } /////////////////// // PARTICIPATION // /////////////////// // BUY SHARES /// @notice Buys shares on behalf of another user /// @param _buyer The account on behalf of whom to buy shares /// @param _investmentAmount The amount of the fund's denomination asset with which to buy shares /// @param _minSharesQuantity The minimum quantity of shares to buy /// @return sharesReceived_ The actual amount of shares received /// @dev This function is freely callable if there is no sharesActionTimelock set, but it is /// limited to a list of trusted callers otherwise, in order to prevent a griefing attack /// where the caller buys shares for a _buyer, thereby resetting their lastSharesBought value. function buySharesOnBehalf( address _buyer, uint256 _investmentAmount, uint256 _minSharesQuantity ) external returns (uint256 sharesReceived_) { bool hasSharesActionTimelock = getSharesActionTimelock() > 0; address canonicalSender = __msgSender(); require( !hasSharesActionTimelock || IFundDeployer(getFundDeployer()).isAllowedBuySharesOnBehalfCaller(canonicalSender), "buySharesOnBehalf: Unauthorized" ); return __buyShares( _buyer, _investmentAmount, _minSharesQuantity, hasSharesActionTimelock, canonicalSender ); } /// @notice Buys shares /// @param _investmentAmount The amount of the fund's denomination asset /// with which to buy shares /// @param _minSharesQuantity The minimum quantity of shares to buy /// @return sharesReceived_ The actual amount of shares received function buyShares(uint256 _investmentAmount, uint256 _minSharesQuantity) external returns (uint256 sharesReceived_) { bool hasSharesActionTimelock = getSharesActionTimelock() > 0; address canonicalSender = __msgSender(); return __buyShares( canonicalSender, _investmentAmount, _minSharesQuantity, hasSharesActionTimelock, canonicalSender ); } /// @dev Helper for buy shares logic function __buyShares( address _buyer, uint256 _investmentAmount, uint256 _minSharesQuantity, bool _hasSharesActionTimelock, address _canonicalSender ) private locksReentrance allowsPermissionedVaultAction returns (uint256 sharesReceived_) { // Enforcing a _minSharesQuantity also validates `_investmentAmount > 0` // and guarantees the function cannot succeed while minting 0 shares require(_minSharesQuantity > 0, "__buyShares: _minSharesQuantity must be >0"); address vaultProxyCopy = getVaultProxy(); require( !_hasSharesActionTimelock || !__hasPendingMigrationOrReconfiguration(vaultProxyCopy), "__buyShares: Pending migration or reconfiguration" ); uint256 gav = calcGav(); // Gives Extensions a chance to run logic prior to the minting of bought shares. // Fees implementing this hook should be aware that // it might be the case that _investmentAmount != actualInvestmentAmount, // if the denomination asset charges a transfer fee, for example. __preBuySharesHook(_buyer, _investmentAmount, gav); // Pay the protocol fee after running other fees, but before minting new shares IVault(vaultProxyCopy).payProtocolFee(); if (doesAutoProtocolFeeSharesBuyback()) { __buyBackMaxProtocolFeeShares(vaultProxyCopy, gav); } // Transfer the investment asset to the fund. // Does not follow the checks-effects-interactions pattern, but it is necessary to // do this delta balance calculation before calculating shares to mint. uint256 receivedInvestmentAmount = __transferFromWithReceivedAmount( getDenominationAsset(), _canonicalSender, vaultProxyCopy, _investmentAmount ); // Calculate the amount of shares to issue with the investment amount uint256 sharePrice = __calcGrossShareValue( gav, ERC20(vaultProxyCopy).totalSupply(), 10**uint256(ERC20(getDenominationAsset()).decimals()) ); uint256 sharesIssued = receivedInvestmentAmount.mul(SHARES_UNIT).div(sharePrice); // Mint shares to the buyer uint256 prevBuyerShares = ERC20(vaultProxyCopy).balanceOf(_buyer); IVault(vaultProxyCopy).mintShares(_buyer, sharesIssued); // Gives Extensions a chance to run logic after shares are issued __postBuySharesHook(_buyer, receivedInvestmentAmount, sharesIssued, gav); // The number of actual shares received may differ from shares issued due to // how the PostBuyShares hooks are invoked by Extensions (i.e., fees) sharesReceived_ = ERC20(vaultProxyCopy).balanceOf(_buyer).sub(prevBuyerShares); require( sharesReceived_ >= _minSharesQuantity, "__buyShares: Shares received < _minSharesQuantity" ); if (_hasSharesActionTimelock) { acctToLastSharesBoughtTimestamp[_buyer] = block.timestamp; } emit SharesBought(_buyer, receivedInvestmentAmount, sharesIssued, sharesReceived_); return sharesReceived_; } /// @dev Helper for Extension actions immediately prior to issuing shares function __preBuySharesHook( address _buyer, uint256 _investmentAmount, uint256 _gav ) private { IFeeManager(getFeeManager()).invokeHook( IFeeManager.FeeHook.PreBuyShares, abi.encode(_buyer, _investmentAmount), _gav ); } /// @dev Helper for Extension actions immediately after issuing shares. /// This could be cleaned up so both Extensions take the same encoded args and handle GAV /// in the same way, but there is not the obvious need for gas savings of recycling /// the GAV value for the current policies as there is for the fees. function __postBuySharesHook( address _buyer, uint256 _investmentAmount, uint256 _sharesIssued, uint256 _preBuySharesGav ) private { uint256 gav = _preBuySharesGav.add(_investmentAmount); IFeeManager(getFeeManager()).invokeHook( IFeeManager.FeeHook.PostBuyShares, abi.encode(_buyer, _investmentAmount, _sharesIssued), gav ); IPolicyManager(getPolicyManager()).validatePolicies( address(this), IPolicyManager.PolicyHook.PostBuyShares, abi.encode(_buyer, _investmentAmount, _sharesIssued, gav) ); } /// @dev Helper to execute ERC20.transferFrom() while calculating the actual amount received function __transferFromWithReceivedAmount( address _asset, address _sender, address _recipient, uint256 _transferAmount ) private returns (uint256 receivedAmount_) { uint256 preTransferRecipientBalance = ERC20(_asset).balanceOf(_recipient); ERC20(_asset).safeTransferFrom(_sender, _recipient, _transferAmount); return ERC20(_asset).balanceOf(_recipient).sub(preTransferRecipientBalance); } // REDEEM SHARES /// @notice Redeems a specified amount of the sender's shares for specified asset proportions /// @param _recipient The account that will receive the specified assets /// @param _sharesQuantity The quantity of shares to redeem /// @param _payoutAssets The assets to payout /// @param _payoutAssetPercentages The percentage of the owed amount to pay out in each asset /// @return payoutAmounts_ The amount of each asset paid out to the _recipient /// @dev Redeem all shares of the sender by setting _sharesQuantity to the max uint value. /// _payoutAssetPercentages must total exactly 100%. In order to specify less and forgo the /// remaining gav owed on the redeemed shares, pass in address(0) with the percentage to forego. /// Unlike redeemSharesInKind(), this function allows policies to run and prevent redemption. function redeemSharesForSpecificAssets( address _recipient, uint256 _sharesQuantity, address[] calldata _payoutAssets, uint256[] calldata _payoutAssetPercentages ) external locksReentrance returns (uint256[] memory payoutAmounts_) { address canonicalSender = __msgSender(); require( _payoutAssets.length == _payoutAssetPercentages.length, "redeemSharesForSpecificAssets: Unequal arrays" ); require( _payoutAssets.isUniqueSet(), "redeemSharesForSpecificAssets: Duplicate payout asset" ); uint256 gav = calcGav(); IVault vaultProxyContract = IVault(getVaultProxy()); (uint256 sharesToRedeem, uint256 sharesSupply) = __redeemSharesSetup( vaultProxyContract, canonicalSender, _sharesQuantity, true, gav ); payoutAmounts_ = __payoutSpecifiedAssetPercentages( vaultProxyContract, _recipient, _payoutAssets, _payoutAssetPercentages, gav.mul(sharesToRedeem).div(sharesSupply) ); // Run post-redemption in order to have access to the payoutAmounts __postRedeemSharesForSpecificAssetsHook( canonicalSender, _recipient, sharesToRedeem, _payoutAssets, payoutAmounts_, gav ); emit SharesRedeemed( canonicalSender, _recipient, sharesToRedeem, _payoutAssets, payoutAmounts_ ); return payoutAmounts_; } /// @notice Redeems a specified amount of the sender's shares /// for a proportionate slice of the vault's assets /// @param _recipient The account that will receive the proportionate slice of assets /// @param _sharesQuantity The quantity of shares to redeem /// @param _additionalAssets Additional (non-tracked) assets to claim /// @param _assetsToSkip Tracked assets to forfeit /// @return payoutAssets_ The assets paid out to the _recipient /// @return payoutAmounts_ The amount of each asset paid out to the _recipient /// @dev Redeem all shares of the sender by setting _sharesQuantity to the max uint value. /// Any claim to passed _assetsToSkip will be forfeited entirely. This should generally /// only be exercised if a bad asset is causing redemption to fail. /// This function should never fail without a way to bypass the failure, which is assured /// through two mechanisms: /// 1. The FeeManager is called with the try/catch pattern to assure that calls to it /// can never block redemption. /// 2. If a token fails upon transfer(), that token can be skipped (and its balance forfeited) /// by explicitly specifying _assetsToSkip. /// Because of these assurances, shares should always be redeemable, with the exception /// of the timelock period on shares actions that must be respected. function redeemSharesInKind( address _recipient, uint256 _sharesQuantity, address[] calldata _additionalAssets, address[] calldata _assetsToSkip ) external locksReentrance returns (address[] memory payoutAssets_, uint256[] memory payoutAmounts_) { address canonicalSender = __msgSender(); require( _additionalAssets.isUniqueSet(), "redeemSharesInKind: _additionalAssets contains duplicates" ); require( _assetsToSkip.isUniqueSet(), "redeemSharesInKind: _assetsToSkip contains duplicates" ); // Parse the payout assets given optional params to add or skip assets. // Note that there is no validation that the _additionalAssets are known assets to // the protocol. This means that the redeemer could specify a malicious asset, // but since all state-changing, user-callable functions on this contract share the // non-reentrant modifier, there is nowhere to perform a reentrancy attack. payoutAssets_ = __parseRedemptionPayoutAssets( IVault(vaultProxy).getTrackedAssets(), _additionalAssets, _assetsToSkip ); // If protocol fee shares will be auto-bought back, attempt to calculate GAV to pass into fees, // as we will require GAV later during the buyback. uint256 gavOrZero; if (doesAutoProtocolFeeSharesBuyback()) { // Since GAV calculation can fail with a revering price or a no-longer-supported asset, // we must try/catch GAV calculation to ensure that in-kind redemption can still succeed try this.calcGav() returns (uint256 gav) { gavOrZero = gav; } catch { emit RedeemSharesInKindCalcGavFailed(); } } (uint256 sharesToRedeem, uint256 sharesSupply) = __redeemSharesSetup( IVault(vaultProxy), canonicalSender, _sharesQuantity, false, gavOrZero ); // Calculate and transfer payout asset amounts due to _recipient payoutAmounts_ = new uint256[](payoutAssets_.length); for (uint256 i; i < payoutAssets_.length; i++) { payoutAmounts_[i] = ERC20(payoutAssets_[i]) .balanceOf(vaultProxy) .mul(sharesToRedeem) .div(sharesSupply); // Transfer payout asset to _recipient if (payoutAmounts_[i] > 0) { IVault(vaultProxy).withdrawAssetTo( payoutAssets_[i], _recipient, payoutAmounts_[i] ); } } emit SharesRedeemed( canonicalSender, _recipient, sharesToRedeem, payoutAssets_, payoutAmounts_ ); return (payoutAssets_, payoutAmounts_); } /// @dev Helper to parse an array of payout assets during redemption, taking into account /// additional assets and assets to skip. _assetsToSkip ignores _additionalAssets. /// All input arrays are assumed to be unique. function __parseRedemptionPayoutAssets( address[] memory _trackedAssets, address[] memory _additionalAssets, address[] memory _assetsToSkip ) private pure returns (address[] memory payoutAssets_) { address[] memory trackedAssetsToPayout = _trackedAssets.removeItems(_assetsToSkip); if (_additionalAssets.length == 0) { return trackedAssetsToPayout; } // Add additional assets. Duplicates of trackedAssets are ignored. bool[] memory indexesToAdd = new bool[](_additionalAssets.length); uint256 additionalItemsCount; for (uint256 i; i < _additionalAssets.length; i++) { if (!trackedAssetsToPayout.contains(_additionalAssets[i])) { indexesToAdd[i] = true; additionalItemsCount++; } } if (additionalItemsCount == 0) { return trackedAssetsToPayout; } payoutAssets_ = new address[](trackedAssetsToPayout.length.add(additionalItemsCount)); for (uint256 i; i < trackedAssetsToPayout.length; i++) { payoutAssets_[i] = trackedAssetsToPayout[i]; } uint256 payoutAssetsIndex = trackedAssetsToPayout.length; for (uint256 i; i < _additionalAssets.length; i++) { if (indexesToAdd[i]) { payoutAssets_[payoutAssetsIndex] = _additionalAssets[i]; payoutAssetsIndex++; } } return payoutAssets_; } /// @dev Helper to payout specified asset percentages during redeemSharesForSpecificAssets() function __payoutSpecifiedAssetPercentages( IVault vaultProxyContract, address _recipient, address[] calldata _payoutAssets, uint256[] calldata _payoutAssetPercentages, uint256 _owedGav ) private returns (uint256[] memory payoutAmounts_) { address denominationAssetCopy = getDenominationAsset(); uint256 percentagesTotal; payoutAmounts_ = new uint256[](_payoutAssets.length); for (uint256 i; i < _payoutAssets.length; i++) { percentagesTotal = percentagesTotal.add(_payoutAssetPercentages[i]); // Used to explicitly specify less than 100% in total _payoutAssetPercentages if (_payoutAssets[i] == SPECIFIC_ASSET_REDEMPTION_DUMMY_FORFEIT_ADDRESS) { continue; } payoutAmounts_[i] = IValueInterpreter(getValueInterpreter()).calcCanonicalAssetValue( denominationAssetCopy, _owedGav.mul(_payoutAssetPercentages[i]).div(ONE_HUNDRED_PERCENT), _payoutAssets[i] ); // Guards against corner case of primitive-to-derivative asset conversion that floors to 0, // or redeeming a very low shares amount and/or percentage where asset value owed is 0 require( payoutAmounts_[i] > 0, "__payoutSpecifiedAssetPercentages: Zero amount for asset" ); vaultProxyContract.withdrawAssetTo(_payoutAssets[i], _recipient, payoutAmounts_[i]); } require( percentagesTotal == ONE_HUNDRED_PERCENT, "__payoutSpecifiedAssetPercentages: Percents must total 100%" ); return payoutAmounts_; } /// @dev Helper for system actions immediately prior to redeeming shares. /// Policy validation is not currently allowed on redemption, to ensure continuous redeemability. function __preRedeemSharesHook( address _redeemer, uint256 _sharesToRedeem, bool _forSpecifiedAssets, uint256 _gavIfCalculated ) private allowsPermissionedVaultAction { try IFeeManager(getFeeManager()).invokeHook( IFeeManager.FeeHook.PreRedeemShares, abi.encode(_redeemer, _sharesToRedeem, _forSpecifiedAssets), _gavIfCalculated ) {} catch (bytes memory reason) { emit PreRedeemSharesHookFailed(reason, _redeemer, _sharesToRedeem); } } /// @dev Helper to run policy validation after other logic for redeeming shares for specific assets. /// Avoids stack-too-deep error. function __postRedeemSharesForSpecificAssetsHook( address _redeemer, address _recipient, uint256 _sharesToRedeemPostFees, address[] memory _assets, uint256[] memory _assetAmounts, uint256 _gavPreRedeem ) private { IPolicyManager(getPolicyManager()).validatePolicies( address(this), IPolicyManager.PolicyHook.RedeemSharesForSpecificAssets, abi.encode( _redeemer, _recipient, _sharesToRedeemPostFees, _assets, _assetAmounts, _gavPreRedeem ) ); } /// @dev Helper to execute common pre-shares redemption logic function __redeemSharesSetup( IVault vaultProxyContract, address _redeemer, uint256 _sharesQuantityInput, bool _forSpecifiedAssets, uint256 _gavIfCalculated ) private returns (uint256 sharesToRedeem_, uint256 sharesSupply_) { __assertSharesActionNotTimelocked(address(vaultProxyContract), _redeemer); ERC20 sharesContract = ERC20(address(vaultProxyContract)); uint256 preFeesRedeemerSharesBalance = sharesContract.balanceOf(_redeemer); if (_sharesQuantityInput == type(uint256).max) { sharesToRedeem_ = preFeesRedeemerSharesBalance; } else { sharesToRedeem_ = _sharesQuantityInput; } require(sharesToRedeem_ > 0, "__redeemSharesSetup: No shares to redeem"); __preRedeemSharesHook(_redeemer, sharesToRedeem_, _forSpecifiedAssets, _gavIfCalculated); // Update the redemption amount if fees were charged (or accrued) to the redeemer uint256 postFeesRedeemerSharesBalance = sharesContract.balanceOf(_redeemer); if (_sharesQuantityInput == type(uint256).max) { sharesToRedeem_ = postFeesRedeemerSharesBalance; } else if (postFeesRedeemerSharesBalance < preFeesRedeemerSharesBalance) { sharesToRedeem_ = sharesToRedeem_.sub( preFeesRedeemerSharesBalance.sub(postFeesRedeemerSharesBalance) ); } // Pay the protocol fee after running other fees, but before burning shares vaultProxyContract.payProtocolFee(); if (_gavIfCalculated > 0 && doesAutoProtocolFeeSharesBuyback()) { __buyBackMaxProtocolFeeShares(address(vaultProxyContract), _gavIfCalculated); } // Destroy the shares after getting the shares supply sharesSupply_ = sharesContract.totalSupply(); vaultProxyContract.burnShares(_redeemer, sharesToRedeem_); return (sharesToRedeem_, sharesSupply_); } // TRANSFER SHARES /// @notice Runs logic prior to transferring shares that are not freely transferable /// @param _sender The sender of the shares /// @param _recipient The recipient of the shares /// @param _amount The amount of shares function preTransferSharesHook( address _sender, address _recipient, uint256 _amount ) external override { address vaultProxyCopy = getVaultProxy(); require(msg.sender == vaultProxyCopy, "preTransferSharesHook: Only VaultProxy callable"); __assertSharesActionNotTimelocked(vaultProxyCopy, _sender); IPolicyManager(getPolicyManager()).validatePolicies( address(this), IPolicyManager.PolicyHook.PreTransferShares, abi.encode(_sender, _recipient, _amount) ); } /// @notice Runs logic prior to transferring shares that are freely transferable /// @param _sender The sender of the shares /// @dev No need to validate caller, as policies are not run function preTransferSharesHookFreelyTransferable(address _sender) external view override { __assertSharesActionNotTimelocked(getVaultProxy(), _sender); } ///////////////// // GAS RELAYER // ///////////////// /// @notice Deploys a paymaster contract and deposits WETH, enabling gas relaying function deployGasRelayPaymaster() external onlyOwnerNotRelayable { require( getGasRelayPaymaster() == address(0), "deployGasRelayPaymaster: Paymaster already deployed" ); bytes memory constructData = abi.encodeWithSignature("init(address)", getVaultProxy()); address paymaster = IBeaconProxyFactory(getGasRelayPaymasterFactory()).deployProxy( constructData ); __setGasRelayPaymaster(paymaster); __depositToGasRelayPaymaster(paymaster); } /// @notice Tops up the gas relay paymaster deposit function depositToGasRelayPaymaster() external onlyOwner { __depositToGasRelayPaymaster(getGasRelayPaymaster()); } /// @notice Pull WETH from vault to gas relay paymaster /// @param _amount Amount of the WETH to pull from the vault function pullWethForGasRelayer(uint256 _amount) external override onlyGasRelayPaymaster { IVault(getVaultProxy()).withdrawAssetTo(getWethToken(), getGasRelayPaymaster(), _amount); } /// @notice Sets the gasRelayPaymaster variable value /// @param _nextGasRelayPaymaster The next gasRelayPaymaster value function setGasRelayPaymaster(address _nextGasRelayPaymaster) external override onlyFundDeployer { __setGasRelayPaymaster(_nextGasRelayPaymaster); } /// @notice Removes the gas relay paymaster, withdrawing the remaining WETH balance /// and disabling gas relaying function shutdownGasRelayPaymaster() external onlyOwnerNotRelayable { IGasRelayPaymaster(gasRelayPaymaster).withdrawBalance(); IVault(vaultProxy).addTrackedAsset(getWethToken()); delete gasRelayPaymaster; emit GasRelayPaymasterSet(address(0)); } /// @dev Helper to deposit to the gas relay paymaster function __depositToGasRelayPaymaster(address _paymaster) private { IGasRelayPaymaster(_paymaster).deposit(); } /// @dev Helper to set the next `gasRelayPaymaster` variable function __setGasRelayPaymaster(address _nextGasRelayPaymaster) private { gasRelayPaymaster = _nextGasRelayPaymaster; emit GasRelayPaymasterSet(_nextGasRelayPaymaster); } /////////////////// // STATE GETTERS // /////////////////// // LIB IMMUTABLES /// @notice Gets the `DISPATCHER` variable /// @return dispatcher_ The `DISPATCHER` variable value function getDispatcher() public view returns (address dispatcher_) { return DISPATCHER; } /// @notice Gets the `EXTERNAL_POSITION_MANAGER` variable /// @return externalPositionManager_ The `EXTERNAL_POSITION_MANAGER` variable value function getExternalPositionManager() public view override returns (address externalPositionManager_) { return EXTERNAL_POSITION_MANAGER; } /// @notice Gets the `FEE_MANAGER` variable /// @return feeManager_ The `FEE_MANAGER` variable value function getFeeManager() public view override returns (address feeManager_) { return FEE_MANAGER; } /// @notice Gets the `FUND_DEPLOYER` variable /// @return fundDeployer_ The `FUND_DEPLOYER` variable value function getFundDeployer() public view override returns (address fundDeployer_) { return FUND_DEPLOYER; } /// @notice Gets the `INTEGRATION_MANAGER` variable /// @return integrationManager_ The `INTEGRATION_MANAGER` variable value function getIntegrationManager() public view override returns (address integrationManager_) { return INTEGRATION_MANAGER; } /// @notice Gets the `MLN_TOKEN` variable /// @return mlnToken_ The `MLN_TOKEN` variable value function getMlnToken() public view returns (address mlnToken_) { return MLN_TOKEN; } /// @notice Gets the `POLICY_MANAGER` variable /// @return policyManager_ The `POLICY_MANAGER` variable value function getPolicyManager() public view override returns (address policyManager_) { return POLICY_MANAGER; } /// @notice Gets the `PROTOCOL_FEE_RESERVE` variable /// @return protocolFeeReserve_ The `PROTOCOL_FEE_RESERVE` variable value function getProtocolFeeReserve() public view returns (address protocolFeeReserve_) { return PROTOCOL_FEE_RESERVE; } /// @notice Gets the `VALUE_INTERPRETER` variable /// @return valueInterpreter_ The `VALUE_INTERPRETER` variable value function getValueInterpreter() public view returns (address valueInterpreter_) { return VALUE_INTERPRETER; } /// @notice Gets the `WETH_TOKEN` variable /// @return wethToken_ The `WETH_TOKEN` variable value function getWethToken() public view returns (address wethToken_) { return WETH_TOKEN; } // PROXY STORAGE /// @notice Checks if collected protocol fee shares are automatically bought back /// while buying or redeeming shares /// @return doesAutoBuyback_ True if shares are automatically bought back function doesAutoProtocolFeeSharesBuyback() public view returns (bool doesAutoBuyback_) { return autoProtocolFeeSharesBuyback; } /// @notice Gets the `denominationAsset` variable /// @return denominationAsset_ The `denominationAsset` variable value function getDenominationAsset() public view override returns (address denominationAsset_) { return denominationAsset; } /// @notice Gets the `gasRelayPaymaster` variable /// @return gasRelayPaymaster_ The `gasRelayPaymaster` variable value function getGasRelayPaymaster() public view override returns (address gasRelayPaymaster_) { return gasRelayPaymaster; } /// @notice Gets the timestamp of the last time shares were bought for a given account /// @param _who The account for which to get the timestamp /// @return lastSharesBoughtTimestamp_ The timestamp of the last shares bought function getLastSharesBoughtTimestampForAccount(address _who) public view returns (uint256 lastSharesBoughtTimestamp_) { return acctToLastSharesBoughtTimestamp[_who]; } /// @notice Gets the `sharesActionTimelock` variable /// @return sharesActionTimelock_ The `sharesActionTimelock` variable value function getSharesActionTimelock() public view returns (uint256 sharesActionTimelock_) { return sharesActionTimelock; } /// @notice Gets the `vaultProxy` variable /// @return vaultProxy_ The `vaultProxy` variable value function getVaultProxy() public view override returns (address vaultProxy_) { return vaultProxy; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../vault/IVault.sol"; /// @title IComptroller Interface /// @author Enzyme Council <[email protected]> interface IComptroller { function activate(bool) external; function calcGav() external returns (uint256); function calcGrossShareValue() external returns (uint256); function callOnExtension( address, uint256, bytes calldata ) external; function destructActivated(uint256, uint256) external; function destructUnactivated() external; function getDenominationAsset() external view returns (address); function getExternalPositionManager() external view returns (address); function getFeeManager() external view returns (address); function getFundDeployer() external view returns (address); function getGasRelayPaymaster() external view returns (address); function getIntegrationManager() external view returns (address); function getPolicyManager() external view returns (address); function getVaultProxy() external view returns (address); function init(address, uint256) external; function permissionedVaultAction(IVault.VaultAction, bytes calldata) external; function preTransferSharesHook( address, address, uint256 ) external; function preTransferSharesHookFreelyTransferable(address) external view; function setGasRelayPaymaster(address) external; function setVaultProxy(address) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../../persistent/vault/interfaces/IExternalPositionVault.sol"; import "../../../../persistent/vault/interfaces/IFreelyTransferableSharesVault.sol"; import "../../../../persistent/vault/interfaces/IMigratableVault.sol"; /// @title IVault Interface /// @author Enzyme Council <[email protected]> interface IVault is IMigratableVault, IFreelyTransferableSharesVault, IExternalPositionVault { enum VaultAction { None, // Shares management BurnShares, MintShares, TransferShares, // Asset management AddTrackedAsset, ApproveAssetSpender, RemoveTrackedAsset, WithdrawAssetTo, // External position management AddExternalPosition, CallOnExternalPosition, RemoveExternalPosition } function addTrackedAsset(address) external; function burnShares(address, uint256) external; function buyBackProtocolFeeShares( uint256, uint256, uint256 ) external; function callOnContract(address, bytes calldata) external returns (bytes memory); function canManageAssets(address) external view returns (bool); function canRelayCalls(address) external view returns (bool); function getAccessor() external view returns (address); function getOwner() external view returns (address); function getActiveExternalPositions() external view returns (address[] memory); function getTrackedAssets() external view returns (address[] memory); function isActiveExternalPosition(address) external view returns (bool); function isTrackedAsset(address) external view returns (bool); function mintShares(address, uint256) external; function payProtocolFee() external; function receiveValidatedVaultAction(VaultAction, bytes calldata) external; function setAccessorForFundReconfiguration(address) external; function setSymbol(string calldata) external; function transferShares( address, address, uint256 ) external; function withdrawAssetTo( address, address, uint256 ) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20Burnable.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../../../../persistent/dispatcher/IDispatcher.sol"; import "../../../../persistent/external-positions/IExternalPosition.sol"; import "../../../../persistent/protocol-fee-reserve/interfaces/IProtocolFeeReserve1.sol"; import "../../../../persistent/vault/VaultLibBase2.sol"; import "../../../infrastructure/gas-relayer/GasRelayRecipientMixin.sol"; import "../../../infrastructure/protocol-fees/IProtocolFeeTracker.sol"; import "../../../extensions/external-position-manager/IExternalPositionManager.sol"; import "../../../interfaces/IWETH.sol"; import "../../../utils/AddressArrayLib.sol"; import "../comptroller/IComptroller.sol"; import "./IVault.sol"; /// @title VaultLib Contract /// @author Enzyme Council <[email protected]> /// @notice The per-release proxiable library contract for VaultProxy /// @dev The difference in terminology between "asset" and "trackedAsset" is intentional. /// A fund might actually have asset balances of un-tracked assets, /// but only tracked assets are used in gav calculations. /// Note that this contract inherits VaultLibSafeMath (a verbatim Open Zeppelin SafeMath copy) /// from SharesTokenBase via VaultLibBase2 contract VaultLib is VaultLibBase2, IVault, GasRelayRecipientMixin { using AddressArrayLib for address[]; using SafeERC20 for ERC20; address private immutable EXTERNAL_POSITION_MANAGER; // The account to which to send $MLN earmarked for burn. // A value of `address(0)` signifies burning from the current contract. address private immutable MLN_BURNER; address private immutable MLN_TOKEN; // "Positions" are "tracked assets" + active "external positions" // Before updating POSITIONS_LIMIT in the future, it is important to consider: // 1. The highest positions limit ever allowed in the protocol // 2. That the next value will need to be respected by all future releases uint256 private immutable POSITIONS_LIMIT; address private immutable PROTOCOL_FEE_RESERVE; address private immutable PROTOCOL_FEE_TRACKER; address private immutable WETH_TOKEN; modifier notShares(address _asset) { require(_asset != address(this), "Cannot act on shares"); _; } modifier onlyAccessor() { require(msg.sender == accessor, "Only the designated accessor can make this call"); _; } modifier onlyOwner() { require(__msgSender() == owner, "Only the owner can call this function"); _; } constructor( address _externalPositionManager, address _gasRelayPaymasterFactory, address _protocolFeeReserve, address _protocolFeeTracker, address _mlnToken, address _mlnBurner, address _wethToken, uint256 _positionsLimit ) public GasRelayRecipientMixin(_gasRelayPaymasterFactory) { EXTERNAL_POSITION_MANAGER = _externalPositionManager; MLN_BURNER = _mlnBurner; MLN_TOKEN = _mlnToken; POSITIONS_LIMIT = _positionsLimit; PROTOCOL_FEE_RESERVE = _protocolFeeReserve; PROTOCOL_FEE_TRACKER = _protocolFeeTracker; WETH_TOKEN = _wethToken; } /// @dev If a VaultProxy receives ETH, immediately wrap into WETH. /// Will not be able to receive ETH via .transfer() or .send() due to limited gas forwarding. receive() external payable { uint256 ethAmount = payable(address(this)).balance; IWETH(payable(getWethToken())).deposit{value: ethAmount}(); emit EthReceived(msg.sender, ethAmount); } ///////////// // GENERAL // ///////////// /// @notice Gets the external position library contract for a given type /// @param _typeId The type for which to get the external position library /// @return externalPositionLib_ The external position library function getExternalPositionLibForType(uint256 _typeId) external view override returns (address externalPositionLib_) { return IExternalPositionManager(getExternalPositionManager()).getExternalPositionLibForType( _typeId ); } /// @notice Sets shares as (permanently) freely transferable /// @dev Once set, this can never be allowed to be unset, as it provides a critical /// transferability guarantee to liquidity pools and other smart contract holders /// that rely on transfers to function properly. Enabling this option will skip all /// policies run upon transferring shares, but will still respect the shares action timelock. function setFreelyTransferableShares() external onlyOwner { require(!sharesAreFreelyTransferable(), "setFreelyTransferableShares: Already set"); freelyTransferableShares = true; emit FreelyTransferableSharesSet(); } /// @notice Sets the shares name /// @param _nextName The next name value /// @dev Owners should consider the implications of changing an ERC20 name post-deployment, /// e.g., some apps/dapps may cache token names for display purposes, so changing the name /// in contract state may not be reflected in third party applications as desired. function setName(string calldata _nextName) external onlyOwner { sharesName = _nextName; emit NameSet(_nextName); } /// @notice Sets the shares token symbol /// @param _nextSymbol The next symbol value /// @dev Owners should consider the implications of changing an ERC20 symbol post-deployment, /// e.g., some apps/dapps may cache token symbols for display purposes, so changing the symbol /// in contract state may not be reflected in third party applications as desired. /// Only callable by the FundDeployer during vault creation or by the vault owner. function setSymbol(string calldata _nextSymbol) external override { require(__msgSender() == owner || msg.sender == getFundDeployer(), "Unauthorized"); sharesSymbol = _nextSymbol; emit SymbolSet(_nextSymbol); } //////////////////////// // PERMISSIONED ROLES // //////////////////////// /// @notice Registers accounts that can manage vault holdings within the protocol /// @param _managers The accounts to add as asset managers function addAssetManagers(address[] calldata _managers) external onlyOwner { for (uint256 i; i < _managers.length; i++) { require(!isAssetManager(_managers[i]), "addAssetManagers: Manager already registered"); accountToIsAssetManager[_managers[i]] = true; emit AssetManagerAdded(_managers[i]); } } /// @notice Claim ownership of the contract function claimOwnership() external { address nextOwner = nominatedOwner; require( msg.sender == nextOwner, "claimOwnership: Only the nominatedOwner can call this function" ); delete nominatedOwner; address prevOwner = owner; owner = nextOwner; emit OwnershipTransferred(prevOwner, nextOwner); } /// @notice Deregisters accounts that can manage vault holdings within the protocol /// @param _managers The accounts to remove as asset managers function removeAssetManagers(address[] calldata _managers) external onlyOwner { for (uint256 i; i < _managers.length; i++) { require(isAssetManager(_managers[i]), "removeAssetManagers: Manager not registered"); accountToIsAssetManager[_managers[i]] = false; emit AssetManagerRemoved(_managers[i]); } } /// @notice Revoke the nomination of a new contract owner function removeNominatedOwner() external onlyOwner { address removedNominatedOwner = nominatedOwner; require( removedNominatedOwner != address(0), "removeNominatedOwner: There is no nominated owner" ); delete nominatedOwner; emit NominatedOwnerRemoved(removedNominatedOwner); } /// @notice Sets the account that is allowed to migrate a fund to new releases /// @param _nextMigrator The account to set as the allowed migrator /// @dev Set to address(0) to remove the migrator. function setMigrator(address _nextMigrator) external onlyOwner { address prevMigrator = migrator; require(_nextMigrator != prevMigrator, "setMigrator: Value already set"); migrator = _nextMigrator; emit MigratorSet(prevMigrator, _nextMigrator); } /// @notice Nominate a new contract owner /// @param _nextNominatedOwner The account to nominate /// @dev Does not prohibit overwriting the current nominatedOwner function setNominatedOwner(address _nextNominatedOwner) external onlyOwner { require( _nextNominatedOwner != address(0), "setNominatedOwner: _nextNominatedOwner cannot be empty" ); require( _nextNominatedOwner != owner, "setNominatedOwner: _nextNominatedOwner is already the owner" ); require( _nextNominatedOwner != nominatedOwner, "setNominatedOwner: _nextNominatedOwner is already nominated" ); nominatedOwner = _nextNominatedOwner; emit NominatedOwnerSet(_nextNominatedOwner); } //////////////////////// // FUND DEPLOYER ONLY // //////////////////////// /// @notice Updates the accessor during a config change within this release /// @param _nextAccessor The next accessor function setAccessorForFundReconfiguration(address _nextAccessor) external override { require(msg.sender == getFundDeployer(), "Only the FundDeployer can make this call"); __setAccessor(_nextAccessor); } /////////////////////////////////////// // ACCESSOR (COMPTROLLER PROXY) ONLY // /////////////////////////////////////// /// @notice Adds a tracked asset /// @param _asset The asset to add as a tracked asset function addTrackedAsset(address _asset) external override onlyAccessor { __addTrackedAsset(_asset); } /// @notice Burns fund shares from a particular account /// @param _target The account for which to burn shares /// @param _amount The amount of shares to burn function burnShares(address _target, uint256 _amount) external override onlyAccessor { __burn(_target, _amount); } /// @notice Buys back shares collected as protocol fee at a discounted shares price, using MLN /// @param _sharesAmount The amount of shares to buy back /// @param _mlnValue The MLN-denominated market value of _sharesAmount /// @param _gav The total fund GAV /// @dev Since the vault controls both the MLN to burn and the admin function to burn any user's /// fund shares, there is no need to transfer assets back-and-forth with the ProtocolFeeReserve. /// We only need to know the correct discounted amount of MLN to burn. function buyBackProtocolFeeShares( uint256 _sharesAmount, uint256 _mlnValue, uint256 _gav ) external override onlyAccessor { uint256 mlnAmountToBurn = IProtocolFeeReserve1(getProtocolFeeReserve()) .buyBackSharesViaTrustedVaultProxy(_sharesAmount, _mlnValue, _gav); if (mlnAmountToBurn == 0) { return; } // Burn shares and MLN amounts // If shares or MLN balance is insufficient, will revert __burn(getProtocolFeeReserve(), _sharesAmount); if (getMlnBurner() == address(0)) { ERC20Burnable(getMlnToken()).burn(mlnAmountToBurn); } else { ERC20(getMlnToken()).safeTransfer(getMlnBurner(), mlnAmountToBurn); } emit ProtocolFeeSharesBoughtBack(_sharesAmount, _mlnValue, mlnAmountToBurn); } /// @notice Makes an arbitrary call with this contract as the sender /// @param _contract The contract to call /// @param _callData The call data for the call /// @return returnData_ The data returned by the call function callOnContract(address _contract, bytes calldata _callData) external override onlyAccessor returns (bytes memory returnData_) { bool success; (success, returnData_) = _contract.call(_callData); require(success, string(returnData_)); return returnData_; } /// @notice Mints fund shares to a particular account /// @param _target The account for which to burn shares /// @param _amount The amount of shares to mint function mintShares(address _target, uint256 _amount) external override onlyAccessor { __mint(_target, _amount); } /// @notice Pays the due protocol fee by minting shares to the ProtocolFeeReserve function payProtocolFee() external override onlyAccessor { uint256 sharesDue = IProtocolFeeTracker(getProtocolFeeTracker()).payFee(); if (sharesDue == 0) { return; } __mint(getProtocolFeeReserve(), sharesDue); emit ProtocolFeePaidInShares(sharesDue); } /// @notice Transfers fund shares from one account to another /// @param _from The account from which to transfer shares /// @param _to The account to which to transfer shares /// @param _amount The amount of shares to transfer /// @dev For protocol use only, all other transfers should operate /// via standard ERC20 functions function transferShares( address _from, address _to, uint256 _amount ) external override onlyAccessor { __transfer(_from, _to, _amount); } /// @notice Withdraws an asset from the VaultProxy to a given account /// @param _asset The asset to withdraw /// @param _target The account to which to withdraw the asset /// @param _amount The amount of asset to withdraw function withdrawAssetTo( address _asset, address _target, uint256 _amount ) external override onlyAccessor { __withdrawAssetTo(_asset, _target, _amount); } /////////////////////////// // VAULT ACTION DISPATCH // /////////////////////////// /// @notice Dispatches a call initiated from an Extension, validated by the ComptrollerProxy /// @param _action The VaultAction to perform /// @param _actionData The call data for the action to perform function receiveValidatedVaultAction(VaultAction _action, bytes calldata _actionData) external override onlyAccessor { if (_action == VaultAction.AddExternalPosition) { __executeVaultActionAddExternalPosition(_actionData); } else if (_action == VaultAction.AddTrackedAsset) { __executeVaultActionAddTrackedAsset(_actionData); } else if (_action == VaultAction.ApproveAssetSpender) { __executeVaultActionApproveAssetSpender(_actionData); } else if (_action == VaultAction.BurnShares) { __executeVaultActionBurnShares(_actionData); } else if (_action == VaultAction.CallOnExternalPosition) { __executeVaultActionCallOnExternalPosition(_actionData); } else if (_action == VaultAction.MintShares) { __executeVaultActionMintShares(_actionData); } else if (_action == VaultAction.RemoveExternalPosition) { __executeVaultActionRemoveExternalPosition(_actionData); } else if (_action == VaultAction.RemoveTrackedAsset) { __executeVaultActionRemoveTrackedAsset(_actionData); } else if (_action == VaultAction.TransferShares) { __executeVaultActionTransferShares(_actionData); } else if (_action == VaultAction.WithdrawAssetTo) { __executeVaultActionWithdrawAssetTo(_actionData); } } /// @dev Helper to decode actionData and execute VaultAction.AddExternalPosition function __executeVaultActionAddExternalPosition(bytes memory _actionData) private { __addExternalPosition(abi.decode(_actionData, (address))); } /// @dev Helper to decode actionData and execute VaultAction.AddTrackedAsset function __executeVaultActionAddTrackedAsset(bytes memory _actionData) private { __addTrackedAsset(abi.decode(_actionData, (address))); } /// @dev Helper to decode actionData and execute VaultAction.ApproveAssetSpender function __executeVaultActionApproveAssetSpender(bytes memory _actionData) private { (address asset, address target, uint256 amount) = abi.decode( _actionData, (address, address, uint256) ); __approveAssetSpender(asset, target, amount); } /// @dev Helper to decode actionData and execute VaultAction.BurnShares function __executeVaultActionBurnShares(bytes memory _actionData) private { (address target, uint256 amount) = abi.decode(_actionData, (address, uint256)); __burn(target, amount); } /// @dev Helper to decode actionData and execute VaultAction.CallOnExternalPosition function __executeVaultActionCallOnExternalPosition(bytes memory _actionData) private { ( address externalPosition, bytes memory callOnExternalPositionActionData, address[] memory assetsToTransfer, uint256[] memory amountsToTransfer, address[] memory assetsToReceive ) = abi.decode(_actionData, (address, bytes, address[], uint256[], address[])); __callOnExternalPosition( externalPosition, callOnExternalPositionActionData, assetsToTransfer, amountsToTransfer, assetsToReceive ); } /// @dev Helper to decode actionData and execute VaultAction.MintShares function __executeVaultActionMintShares(bytes memory _actionData) private { (address target, uint256 amount) = abi.decode(_actionData, (address, uint256)); __mint(target, amount); } /// @dev Helper to decode actionData and execute VaultAction.RemoveExternalPosition function __executeVaultActionRemoveExternalPosition(bytes memory _actionData) private { __removeExternalPosition(abi.decode(_actionData, (address))); } /// @dev Helper to decode actionData and execute VaultAction.RemoveTrackedAsset function __executeVaultActionRemoveTrackedAsset(bytes memory _actionData) private { __removeTrackedAsset(abi.decode(_actionData, (address))); } /// @dev Helper to decode actionData and execute VaultAction.TransferShares function __executeVaultActionTransferShares(bytes memory _actionData) private { (address from, address to, uint256 amount) = abi.decode( _actionData, (address, address, uint256) ); __transfer(from, to, amount); } /// @dev Helper to decode actionData and execute VaultAction.WithdrawAssetTo function __executeVaultActionWithdrawAssetTo(bytes memory _actionData) private { (address asset, address target, uint256 amount) = abi.decode( _actionData, (address, address, uint256) ); __withdrawAssetTo(asset, target, amount); } /////////////////// // VAULT ACTIONS // /////////////////// /// @dev Helper to track a new active external position function __addExternalPosition(address _externalPosition) private { if (!isActiveExternalPosition(_externalPosition)) { __validatePositionsLimit(); externalPositionToIsActive[_externalPosition] = true; activeExternalPositions.push(_externalPosition); emit ExternalPositionAdded(_externalPosition); } } /// @dev Helper to add a tracked asset function __addTrackedAsset(address _asset) private notShares(_asset) { if (!isTrackedAsset(_asset)) { __validatePositionsLimit(); assetToIsTracked[_asset] = true; trackedAssets.push(_asset); emit TrackedAssetAdded(_asset); } } /// @dev Helper to grant an allowance to a spender to use a vault asset function __approveAssetSpender( address _asset, address _target, uint256 _amount ) private notShares(_asset) { ERC20 assetContract = ERC20(_asset); if (assetContract.allowance(address(this), _target) > 0) { assetContract.safeApprove(_target, 0); } assetContract.safeApprove(_target, _amount); } /// @dev Helper to make a call on a external position contract /// @param _externalPosition The external position to call /// @param _actionData The action data for the call /// @param _assetsToTransfer The assets to transfer to the external position /// @param _amountsToTransfer The amount of assets to be transferred to the external position /// @param _assetsToReceive The assets that will be received from the call function __callOnExternalPosition( address _externalPosition, bytes memory _actionData, address[] memory _assetsToTransfer, uint256[] memory _amountsToTransfer, address[] memory _assetsToReceive ) private { require( isActiveExternalPosition(_externalPosition), "__callOnExternalPosition: Not an active external position" ); for (uint256 i; i < _assetsToTransfer.length; i++) { __withdrawAssetTo(_assetsToTransfer[i], _externalPosition, _amountsToTransfer[i]); } IExternalPosition(_externalPosition).receiveCallFromVault(_actionData); for (uint256 i; i < _assetsToReceive.length; i++) { __addTrackedAsset(_assetsToReceive[i]); } } /// @dev Helper to the get the Vault's balance of a given asset function __getAssetBalance(address _asset) private view returns (uint256 balance_) { return ERC20(_asset).balanceOf(address(this)); } /// @dev Helper to remove a external position from the vault function __removeExternalPosition(address _externalPosition) private { if (isActiveExternalPosition(_externalPosition)) { externalPositionToIsActive[_externalPosition] = false; activeExternalPositions.removeStorageItem(_externalPosition); emit ExternalPositionRemoved(_externalPosition); } } /// @dev Helper to remove a tracked asset function __removeTrackedAsset(address _asset) private { if (isTrackedAsset(_asset)) { assetToIsTracked[_asset] = false; trackedAssets.removeStorageItem(_asset); emit TrackedAssetRemoved(_asset); } } /// @dev Helper to validate that the positions limit has not been reached function __validatePositionsLimit() private view { require( trackedAssets.length + activeExternalPositions.length < getPositionsLimit(), "__validatePositionsLimit: Limit exceeded" ); } /// @dev Helper to withdraw an asset from the vault to a specified recipient function __withdrawAssetTo( address _asset, address _target, uint256 _amount ) private notShares(_asset) { ERC20(_asset).safeTransfer(_target, _amount); emit AssetWithdrawn(_asset, _target, _amount); } //////////////////////////// // SHARES ERC20 OVERRIDES // //////////////////////////// /// @notice Gets the `symbol` value of the shares token /// @return symbol_ The `symbol` value /// @dev Defers the shares symbol value to the Dispatcher contract if not set locally function symbol() public view override returns (string memory symbol_) { symbol_ = sharesSymbol; if (bytes(symbol_).length == 0) { symbol_ = IDispatcher(creator).getSharesTokenSymbol(); } return symbol_; } /// @dev Standard implementation of ERC20's transfer(). /// Overridden to allow arbitrary logic in ComptrollerProxy prior to transfer. function transfer(address _recipient, uint256 _amount) public override returns (bool success_) { __invokePreTransferSharesHook(msg.sender, _recipient, _amount); return super.transfer(_recipient, _amount); } /// @dev Standard implementation of ERC20's transferFrom(). /// Overridden to allow arbitrary logic in ComptrollerProxy prior to transfer. function transferFrom( address _sender, address _recipient, uint256 _amount ) public override returns (bool success_) { __invokePreTransferSharesHook(_sender, _recipient, _amount); return super.transferFrom(_sender, _recipient, _amount); } /// @dev Helper to call the relevant preTransferShares hook function __invokePreTransferSharesHook( address _sender, address _recipient, uint256 _amount ) private { if (sharesAreFreelyTransferable()) { IComptroller(accessor).preTransferSharesHookFreelyTransferable(_sender); } else { IComptroller(accessor).preTransferSharesHook(_sender, _recipient, _amount); } } /////////////////// // STATE GETTERS // /////////////////// /// @notice Checks whether an account can manage assets /// @param _who The account to check /// @return canManageAssets_ True if the account can manage assets function canManageAssets(address _who) external view override returns (bool canManageAssets_) { return _who == getOwner() || isAssetManager(_who); } /// @notice Checks whether an account can use gas relaying /// @param _who The account to check /// @return canRelayCalls_ True if the account can use gas relaying on this fund function canRelayCalls(address _who) external view override returns (bool canRelayCalls_) { return _who == getOwner() || isAssetManager(_who) || _who == getMigrator(); } /// @notice Gets the `accessor` variable /// @return accessor_ The `accessor` variable value function getAccessor() public view override returns (address accessor_) { return accessor; } /// @notice Gets the `creator` variable /// @return creator_ The `creator` variable value function getCreator() external view returns (address creator_) { return creator; } /// @notice Gets the `migrator` variable /// @return migrator_ The `migrator` variable value function getMigrator() public view returns (address migrator_) { return migrator; } /// @notice Gets the account that is nominated to be the next owner of this contract /// @return nominatedOwner_ The account that is nominated to be the owner function getNominatedOwner() external view returns (address nominatedOwner_) { return nominatedOwner; } /// @notice Gets the `activeExternalPositions` variable /// @return activeExternalPositions_ The `activeExternalPositions` variable value function getActiveExternalPositions() external view override returns (address[] memory activeExternalPositions_) { return activeExternalPositions; } /// @notice Gets the `trackedAssets` variable /// @return trackedAssets_ The `trackedAssets` variable value function getTrackedAssets() external view override returns (address[] memory trackedAssets_) { return trackedAssets; } // PUBLIC FUNCTIONS /// @notice Gets the `EXTERNAL_POSITION_MANAGER` variable /// @return externalPositionManager_ The `EXTERNAL_POSITION_MANAGER` variable value function getExternalPositionManager() public view returns (address externalPositionManager_) { return EXTERNAL_POSITION_MANAGER; } /// @notice Gets the vaults fund deployer /// @return fundDeployer_ The fund deployer contract associated with this vault function getFundDeployer() public view returns (address fundDeployer_) { return IDispatcher(creator).getFundDeployerForVaultProxy(address(this)); } /// @notice Gets the `MLN_BURNER` variable /// @return mlnBurner_ The `MLN_BURNER` variable value function getMlnBurner() public view returns (address mlnBurner_) { return MLN_BURNER; } /// @notice Gets the `MLN_TOKEN` variable /// @return mlnToken_ The `MLN_TOKEN` variable value function getMlnToken() public view returns (address mlnToken_) { return MLN_TOKEN; } /// @notice Gets the `owner` variable /// @return owner_ The `owner` variable value function getOwner() public view override returns (address owner_) { return owner; } /// @notice Gets the `POSITIONS_LIMIT` variable /// @return positionsLimit_ The `POSITIONS_LIMIT` variable value function getPositionsLimit() public view returns (uint256 positionsLimit_) { return POSITIONS_LIMIT; } /// @notice Gets the `PROTOCOL_FEE_RESERVE` variable /// @return protocolFeeReserve_ The `PROTOCOL_FEE_RESERVE` variable value function getProtocolFeeReserve() public view returns (address protocolFeeReserve_) { return PROTOCOL_FEE_RESERVE; } /// @notice Gets the `PROTOCOL_FEE_TRACKER` variable /// @return protocolFeeTracker_ The `PROTOCOL_FEE_TRACKER` variable value function getProtocolFeeTracker() public view returns (address protocolFeeTracker_) { return PROTOCOL_FEE_TRACKER; } /// @notice Check whether an external position is active on the vault /// @param _externalPosition The externalPosition to check /// @return isActiveExternalPosition_ True if the address is an active external position on the vault function isActiveExternalPosition(address _externalPosition) public view override returns (bool isActiveExternalPosition_) { return externalPositionToIsActive[_externalPosition]; } /// @notice Checks whether an account is an allowed asset manager /// @param _who The account to check /// @return isAssetManager_ True if the account is an allowed asset manager function isAssetManager(address _who) public view returns (bool isAssetManager_) { return accountToIsAssetManager[_who]; } /// @notice Checks whether an address is a tracked asset of the vault /// @param _asset The address to check /// @return isTrackedAsset_ True if the address is a tracked asset function isTrackedAsset(address _asset) public view override returns (bool isTrackedAsset_) { return assetToIsTracked[_asset]; } /// @notice Checks whether shares are (permanently) freely transferable /// @return sharesAreFreelyTransferable_ True if shares are (permanently) freely transferable function sharesAreFreelyTransferable() public view override returns (bool sharesAreFreelyTransferable_) { return freelyTransferableShares; } /// @notice Gets the `WETH_TOKEN` variable /// @return wethToken_ The `WETH_TOKEN` variable value function getWethToken() public view returns (address wethToken_) { return WETH_TOKEN; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IExtension Interface /// @author Enzyme Council <[email protected]> /// @notice Interface for all extensions interface IExtension { function activateForFund(bool _isMigration) external; function deactivateForFund() external; function receiveCallFromComptroller( address _caller, uint256 _actionId, bytes calldata _callArgs ) external; function setConfigForFund( address _comptrollerProxy, address _vaultProxy, bytes calldata _configData ) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IExternalPositionManager interface /// @author Enzyme Council <[email protected]> /// @notice Interface for the ExternalPositionManager interface IExternalPositionManager { struct ExternalPositionTypeInfo { address parser; address lib; } enum ExternalPositionManagerActions { CreateExternalPosition, CallOnExternalPosition, RemoveExternalPosition, ReactivateExternalPosition } function getExternalPositionLibForType(uint256) external view returns (address); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; /// @title FeeManager Interface /// @author Enzyme Council <[email protected]> /// @notice Interface for the FeeManager interface IFeeManager { // No fees for the current release are implemented post-redeemShares enum FeeHook {Continuous, PreBuyShares, PostBuyShares, PreRedeemShares} enum SettlementType {None, Direct, Mint, Burn, MintSharesOutstanding, BurnSharesOutstanding} function invokeHook( FeeHook, bytes calldata, uint256 ) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./IPolicyManager.sol"; /// @title Policy Interface /// @author Enzyme Council <[email protected]> interface IPolicy { function activateForFund(address _comptrollerProxy) external; function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings) external; function canDisable() external pure returns (bool canDisable_); function identifier() external pure returns (string memory identifier_); function implementedHooks() external pure returns (IPolicyManager.PolicyHook[] memory implementedHooks_); function updateFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings) external; function validateRule( address _comptrollerProxy, IPolicyManager.PolicyHook _hook, bytes calldata _encodedArgs ) external returns (bool isValid_); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; /// @title PolicyManager Interface /// @author Enzyme Council <[email protected]> /// @notice Interface for the PolicyManager interface IPolicyManager { // When updating PolicyHook, also update these functions in PolicyManager: // 1. __getAllPolicyHooks() // 2. __policyHookRestrictsCurrentInvestorActions() enum PolicyHook { PostBuyShares, PostCallOnIntegration, PreTransferShares, RedeemSharesForSpecificAssets, AddTrackedAssets, RemoveTrackedAssets, CreateExternalPosition, PostCallOnExternalPosition, RemoveExternalPosition, ReactivateExternalPosition } function validatePolicies( address, PolicyHook, bytes calldata ) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../../core/fund/comptroller/ComptrollerLib.sol"; import "../utils/DustEvaluatorMixin.sol"; import "../utils/PolicyBase.sol"; import "../utils/PricelessAssetBypassMixin.sol"; /// @title OnlyRemoveDustExternalPositionPolicy Contract /// @author Enzyme Council <[email protected]> /// @notice A policy that only allows removing external positions whose value can be considered negligible /// @dev Assets that do not have a valid price can be signaled via PricelessAssetBypassMixin to be valued at `0` contract OnlyRemoveDustExternalPositionPolicy is PolicyBase, DustEvaluatorMixin, PricelessAssetBypassMixin { constructor( address _policyManager, address _fundDeployer, address _valueInterpreter, address _wethToken, uint256 _pricelessAssetBypassTimelock, uint256 _pricelessAssetBypassTimeLimit ) public PolicyBase(_policyManager) DustEvaluatorMixin(_fundDeployer) PricelessAssetBypassMixin( _valueInterpreter, _wethToken, _pricelessAssetBypassTimelock, _pricelessAssetBypassTimeLimit ) {} // EXTERNAL FUNCTIONS /// @notice Add the initial policy settings for a fund function addFundSettings(address, bytes calldata) external override { // Not implemented } /// @notice Provides a constant string identifier for a policy /// @return identifier_ The identifier string function identifier() external pure override returns (string memory identifier_) { return "ONLY_REMOVE_DUST_EXTERNAL_POSITION"; } /// @notice Gets the implemented PolicyHooks for a policy /// @return implementedHooks_ The implemented PolicyHooks function implementedHooks() external pure override returns (IPolicyManager.PolicyHook[] memory implementedHooks_) { implementedHooks_ = new IPolicyManager.PolicyHook[](1); implementedHooks_[0] = IPolicyManager.PolicyHook.RemoveExternalPosition; return implementedHooks_; } /// @notice Apply the rule with the specified parameters of a PolicyHook /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedArgs Encoded args with which to validate the rule /// @return isValid_ True if the rule passes /// @dev onlyPolicyManager validation not necessary as no state is updated, /// but is cheap and nice-to-have since an event is fired function validateRule( address _comptrollerProxy, IPolicyManager.PolicyHook, bytes calldata _encodedArgs ) external override onlyPolicyManager returns (bool isValid_) { (, address externalPosition) = __decodeRemoveExternalPositionValidationData(_encodedArgs); return __isDust(__calcExternalPositionValue(_comptrollerProxy, externalPosition)); } // PRIVATE FUNCTIONS // @dev Helper for calculating an external position's value function __calcExternalPositionValue(address _comptrollerProxy, address _externalPosition) private returns (uint256 value_) { ( address[] memory managedAssets, uint256[] memory managedAssetBalances ) = IExternalPosition(_externalPosition).getManagedAssets(); uint256 managedAssetsValue = __calcTotalValueExlcudingBypassablePricelessAssets( _comptrollerProxy, managedAssets, managedAssetBalances, getPricelessAssetBypassWethToken() ); (address[] memory debtAssets, uint256[] memory debtAssetBalances) = IExternalPosition( _externalPosition ) .getDebtAssets(); uint256 debtAssetsValue = __calcTotalValueExlcudingBypassablePricelessAssets( _comptrollerProxy, debtAssets, debtAssetBalances, getPricelessAssetBypassWethToken() ); if (managedAssetsValue > debtAssetsValue) { return managedAssetsValue.sub(debtAssetsValue); } return 0; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../../utils/FundDeployerOwnerMixin.sol"; /// @title DustEvaluatorMixin Contract /// @author Enzyme Council <[email protected]> /// @notice A mixin used to evaluate where an amount of a given asset can be considered "dust," /// i.e., of negligible value abstract contract DustEvaluatorMixin is FundDeployerOwnerMixin { event DustToleranceInWethSet(uint256 nextDustToleranceInWeth); uint256 private dustToleranceInWeth; constructor(address _fundDeployer) public FundDeployerOwnerMixin(_fundDeployer) {} /// @notice Sets the dustToleranceInWeth variable value /// @param _nextDustToleranceInWeth The next dustToleranceInWeth value function setDustToleranceInWeth(uint256 _nextDustToleranceInWeth) external onlyFundDeployerOwner { dustToleranceInWeth = _nextDustToleranceInWeth; emit DustToleranceInWethSet(_nextDustToleranceInWeth); } /// @dev Helper to evaluate whether an amount of WETH is dust function __isDust(uint256 _wethAmount) internal view returns (bool isDust_) { return _wethAmount <= getDustToleranceInWeth(); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `dustToleranceInWeth` variable /// @return dustToleranceInWeth_ The `dustToleranceInWeth` variable value function getDustToleranceInWeth() public view returns (uint256 dustToleranceInWeth_) { return dustToleranceInWeth; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../IPolicy.sol"; /// @title PolicyBase Contract /// @author Enzyme Council <[email protected]> /// @notice Abstract base contract for all policies abstract contract PolicyBase is IPolicy { address internal immutable POLICY_MANAGER; modifier onlyPolicyManager { require(msg.sender == POLICY_MANAGER, "Only the PolicyManager can make this call"); _; } constructor(address _policyManager) public { POLICY_MANAGER = _policyManager; } /// @notice Validates and initializes a policy as necessary prior to fund activation /// @dev Unimplemented by default, can be overridden by the policy function activateForFund(address) external virtual override { return; } /// @notice Whether or not the policy can be disabled /// @return canDisable_ True if the policy can be disabled /// @dev False by default, can be overridden by the policy function canDisable() external pure virtual override returns (bool canDisable_) { return false; } /// @notice Updates the policy settings for a fund /// @dev Disallowed by default, can be overridden by the policy function updateFundSettings(address, bytes calldata) external virtual override { revert("updateFundSettings: Updates not allowed for this policy"); } ////////////////////////////// // VALIDATION DATA DECODING // ////////////////////////////// /// @dev Helper to parse validation arguments from encoded data for AddTrackedAssets policy hook function __decodeAddTrackedAssetsValidationData(bytes memory _validationData) internal pure returns (address caller_, address[] memory assets_) { return abi.decode(_validationData, (address, address[])); } /// @dev Helper to parse validation arguments from encoded data for CreateExternalPosition policy hook function __decodeCreateExternalPositionValidationData(bytes memory _validationData) internal pure returns ( address caller_, uint256 typeId_, bytes memory initializationData_ ) { return abi.decode(_validationData, (address, uint256, bytes)); } /// @dev Helper to parse validation arguments from encoded data for PreTransferShares policy hook function __decodePreTransferSharesValidationData(bytes memory _validationData) internal pure returns ( address sender_, address recipient_, uint256 amount_ ) { return abi.decode(_validationData, (address, address, uint256)); } /// @dev Helper to parse validation arguments from encoded data for PostBuyShares policy hook function __decodePostBuySharesValidationData(bytes memory _validationData) internal pure returns ( address buyer_, uint256 investmentAmount_, uint256 sharesIssued_, uint256 gav_ ) { return abi.decode(_validationData, (address, uint256, uint256, uint256)); } /// @dev Helper to parse validation arguments from encoded data for PostCallOnExternalPosition policy hook function __decodePostCallOnExternalPositionValidationData(bytes memory _validationData) internal pure returns ( address caller_, address externalPosition_, address[] memory assetsToTransfer_, uint256[] memory amountsToTransfer_, address[] memory assetsToReceive_, bytes memory encodedActionData_ ) { return abi.decode( _validationData, (address, address, address[], uint256[], address[], bytes) ); } /// @dev Helper to parse validation arguments from encoded data for PostCallOnIntegration policy hook function __decodePostCallOnIntegrationValidationData(bytes memory _validationData) internal pure returns ( address caller_, address adapter_, bytes4 selector_, address[] memory incomingAssets_, uint256[] memory incomingAssetAmounts_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_ ) { return abi.decode( _validationData, (address, address, bytes4, address[], uint256[], address[], uint256[]) ); } /// @dev Helper to parse validation arguments from encoded data for ReactivateExternalPosition policy hook function __decodeReactivateExternalPositionValidationData(bytes memory _validationData) internal pure returns (address caller_, address externalPosition_) { return abi.decode(_validationData, (address, address)); } /// @dev Helper to parse validation arguments from encoded data for RedeemSharesForSpecificAssets policy hook function __decodeRedeemSharesForSpecificAssetsValidationData(bytes memory _validationData) internal pure returns ( address redeemer_, address recipient_, uint256 sharesToRedeemPostFees_, address[] memory assets_, uint256[] memory assetAmounts_, uint256 gavPreRedeem_ ) { return abi.decode( _validationData, (address, address, uint256, address[], uint256[], uint256) ); } /// @dev Helper to parse validation arguments from encoded data for RemoveExternalPosition policy hook function __decodeRemoveExternalPositionValidationData(bytes memory _validationData) internal pure returns (address caller_, address externalPosition_) { return abi.decode(_validationData, (address, address)); } /// @dev Helper to parse validation arguments from encoded data for RemoveTrackedAssets policy hook function __decodeRemoveTrackedAssetsValidationData(bytes memory _validationData) internal pure returns (address caller_, address[] memory assets_) { return abi.decode(_validationData, (address, address[])); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `POLICY_MANAGER` variable value /// @return policyManager_ The `POLICY_MANAGER` variable value function getPolicyManager() external view returns (address policyManager_) { return POLICY_MANAGER; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../../../core/fund/comptroller/ComptrollerLib.sol"; import "../../../../core/fund/vault/VaultLib.sol"; import "../../../../infrastructure/value-interpreter/ValueInterpreter.sol"; /// @title PricelessAssetBypassMixin Contract /// @author Enzyme Council <[email protected]> /// @notice A mixin that facilitates timelocked actions for an asset that does not have a valid price abstract contract PricelessAssetBypassMixin { using SafeMath for uint256; event PricelessAssetBypassed(address indexed comptrollerProxy, address indexed asset); event PricelessAssetTimelockStarted(address indexed comptrollerProxy, address indexed asset); uint256 private immutable PRICELESS_ASSET_BYPASS_TIMELOCK; uint256 private immutable PRICELESS_ASSET_BYPASS_TIME_LIMIT; address private immutable PRICELESS_ASSET_BYPASS_VALUE_INTERPRETER; address private immutable PRICELESS_ASSET_BYPASS_WETH_TOKEN; mapping(address => mapping(address => uint256)) private comptrollerProxyToAssetToBypassWindowStart; constructor( address _valueInterpreter, address _wethToken, uint256 _timelock, uint256 _timeLimit ) public { PRICELESS_ASSET_BYPASS_TIMELOCK = _timelock; PRICELESS_ASSET_BYPASS_TIME_LIMIT = _timeLimit; PRICELESS_ASSET_BYPASS_VALUE_INTERPRETER = _valueInterpreter; PRICELESS_ASSET_BYPASS_WETH_TOKEN = _wethToken; } // EXTERNAL FUNCTIONS /// @notice Starts the timelock period for an asset without a valid price /// @param _asset The asset for which to start the timelock period /// @dev This function must be called via ComptrollerProxy.vaultCallOnContract(). /// This allows the function to be gas relay-able. /// It also means that the originator must be the owner. function startAssetBypassTimelock(address _asset) external { // No need to validate whether the VaultProxy is an Enzyme contract address comptrollerProxy = VaultLib(msg.sender).getAccessor(); require( msg.sender == ComptrollerLib(comptrollerProxy).getVaultProxy(), "startAssetBypassTimelock: Sender is not the VaultProxy of the associated ComptrollerProxy" ); try ValueInterpreter(getPricelessAssetBypassValueInterpreter()).calcCanonicalAssetValue( _asset, 1, // Any value >0 will attempt to retrieve a rate getPricelessAssetBypassWethToken() // Any valid asset would do ) { revert("startAssetBypassTimelock: Asset has a price"); } catch { comptrollerProxyToAssetToBypassWindowStart[comptrollerProxy][_asset] = block .timestamp .add(getPricelessAssetBypassTimelock()); emit PricelessAssetTimelockStarted(comptrollerProxy, _asset); } } // PUBLIC FUNCTIONS /// @notice Checks whether an asset is bypassable (if still without a valid price) for a given fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _asset The asset for which to check if it is bypassable /// @return isBypassable_ True if the asset is bypassable function assetIsBypassableForFund(address _comptrollerProxy, address _asset) public view returns (bool isBypassable_) { uint256 windowStart = getAssetBypassWindowStartForFund(_comptrollerProxy, _asset); return windowStart <= block.timestamp && windowStart.add(getPricelessAssetBypassTimeLimit()) >= block.timestamp; } // INTERNAL FUNCTIONS /// @dev Helper to execute __calcValueExcludingBypassablePricelessAsset() for an array of base asset amounts function __calcTotalValueExlcudingBypassablePricelessAssets( address _comptrollerProxy, address[] memory _baseAssets, uint256[] memory _baseAssetAmounts, address _quoteAsset ) internal returns (uint256 value_) { for (uint256 i; i < _baseAssets.length; i++) { value_ = value_.add( __calcValueExcludingBypassablePricelessAsset( _comptrollerProxy, _baseAssets[i], _baseAssetAmounts[i], _quoteAsset ) ); } } /// @dev Helper to calculate the value of a base asset amount in terms of a quote asset, /// returning a value of `0` for an asset without a valid price that is within its bypass window function __calcValueExcludingBypassablePricelessAsset( address _comptrollerProxy, address _baseAsset, uint256 _baseAssetAmount, address _quoteAsset ) internal returns (uint256 value_) { try ValueInterpreter(getPricelessAssetBypassValueInterpreter()).calcCanonicalAssetValue( _baseAsset, _baseAssetAmount, _quoteAsset ) returns (uint256 result) { return result; } catch { require( assetIsBypassableForFund(_comptrollerProxy, _baseAsset), "__calcValueExcludingBypassablePricelessAsset: Invalid asset not bypassable" ); emit PricelessAssetBypassed(_comptrollerProxy, _baseAsset); } return 0; } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the timestamp from which an asset without a valid price can be considered to be valued at `0` /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _asset The asset /// @return windowStart_ The timestamp function getAssetBypassWindowStartForFund(address _comptrollerProxy, address _asset) public view returns (uint256 windowStart_) { return comptrollerProxyToAssetToBypassWindowStart[_comptrollerProxy][_asset]; } /// @notice Gets the `PRICELESS_ASSET_BYPASS_TIME_LIMIT` variable /// @return timeLimit_ The `PRICELESS_ASSET_BYPASS_TIME_LIMIT` variable value function getPricelessAssetBypassTimeLimit() public view returns (uint256 timeLimit_) { return PRICELESS_ASSET_BYPASS_TIME_LIMIT; } /// @notice Gets the `PRICELESS_ASSET_BYPASS_TIMELOCK` variable /// @return timelock_ The `PRICELESS_ASSET_BYPASS_TIMELOCK` variable value function getPricelessAssetBypassTimelock() public view returns (uint256 timelock_) { return PRICELESS_ASSET_BYPASS_TIMELOCK; } /// @notice Gets the `PRICELESS_ASSET_BYPASS_VALUE_INTERPRETER` variable /// @return valueInterpreter_ The `PRICELESS_ASSET_BYPASS_VALUE_INTERPRETER` variable value function getPricelessAssetBypassValueInterpreter() public view returns (address valueInterpreter_) { return PRICELESS_ASSET_BYPASS_VALUE_INTERPRETER; } /// @notice Gets the `PRICELESS_ASSET_BYPASS_WETH_TOKEN` variable /// @return wethToken_ The `PRICELESS_ASSET_BYPASS_WETH_TOKEN` variable value function getPricelessAssetBypassWethToken() public view returns (address wethToken_) { return PRICELESS_ASSET_BYPASS_WETH_TOKEN; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ import "../../utils/beacon-proxy/IBeaconProxyFactory.sol"; import "./IGasRelayPaymaster.sol"; pragma solidity 0.6.12; /// @title GasRelayRecipientMixin Contract /// @author Enzyme Council <[email protected]> /// @notice A mixin that enables receiving GSN-relayed calls /// @dev IMPORTANT: Do not use storage var in this contract, /// unless it is no longer inherited by the VaultLib abstract contract GasRelayRecipientMixin { address internal immutable GAS_RELAY_PAYMASTER_FACTORY; constructor(address _gasRelayPaymasterFactory) internal { GAS_RELAY_PAYMASTER_FACTORY = _gasRelayPaymasterFactory; } /// @dev Helper to parse the canonical sender of a tx based on whether it has been relayed function __msgSender() internal view returns (address payable canonicalSender_) { if (msg.data.length >= 24 && msg.sender == getGasRelayTrustedForwarder()) { assembly { canonicalSender_ := shr(96, calldataload(sub(calldatasize(), 20))) } return canonicalSender_; } return msg.sender; } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `GAS_RELAY_PAYMASTER_FACTORY` variable /// @return gasRelayPaymasterFactory_ The `GAS_RELAY_PAYMASTER_FACTORY` variable value function getGasRelayPaymasterFactory() public view returns (address gasRelayPaymasterFactory_) { return GAS_RELAY_PAYMASTER_FACTORY; } /// @notice Gets the trusted forwarder for GSN relaying /// @return trustedForwarder_ The trusted forwarder function getGasRelayTrustedForwarder() public view returns (address trustedForwarder_) { return IGasRelayPaymaster( IBeaconProxyFactory(getGasRelayPaymasterFactory()).getCanonicalLib() ) .trustedForwarder(); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "../../interfaces/IGsnPaymaster.sol"; /// @title IGasRelayPaymaster Interface /// @author Enzyme Council <[email protected]> interface IGasRelayPaymaster is IGsnPaymaster { function deposit() external; function withdrawBalance() external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IGasRelayPaymasterDepositor Interface /// @author Enzyme Council <[email protected]> interface IGasRelayPaymasterDepositor { function pullWethForGasRelayer(uint256) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./IDerivativePriceFeed.sol"; /// @title AggregatedDerivativePriceFeedMixin Contract /// @author Enzyme Council <[email protected]> /// @notice Aggregates multiple derivative price feeds (e.g., Compound, Chai) and dispatches /// rate requests to the appropriate feed abstract contract AggregatedDerivativePriceFeedMixin { event DerivativeAdded(address indexed derivative, address priceFeed); event DerivativeRemoved(address indexed derivative); mapping(address => address) private derivativeToPriceFeed; /// @notice Gets the rates for 1 unit of the derivative to its underlying assets /// @param _derivative The derivative for which to get the rates /// @return underlyings_ The underlying assets for the _derivative /// @return underlyingAmounts_ The rates for the _derivative to the underlyings_ function __calcUnderlyingValues(address _derivative, uint256 _derivativeAmount) internal returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_) { address derivativePriceFeed = getPriceFeedForDerivative(_derivative); require( derivativePriceFeed != address(0), "calcUnderlyingValues: _derivative is not supported" ); return IDerivativePriceFeed(derivativePriceFeed).calcUnderlyingValues( _derivative, _derivativeAmount ); } ////////////////////////// // DERIVATIVES REGISTRY // ////////////////////////// /// @notice Adds a list of derivatives with the given price feed values /// @param _derivatives The derivatives to add /// @param _priceFeeds The ordered price feeds corresponding to the list of _derivatives function __addDerivatives(address[] memory _derivatives, address[] memory _priceFeeds) internal { require( _derivatives.length == _priceFeeds.length, "__addDerivatives: Unequal _derivatives and _priceFeeds array lengths" ); for (uint256 i = 0; i < _derivatives.length; i++) { require( getPriceFeedForDerivative(_derivatives[i]) == address(0), "__addDerivatives: Already added" ); __validateDerivativePriceFeed(_derivatives[i], _priceFeeds[i]); derivativeToPriceFeed[_derivatives[i]] = _priceFeeds[i]; emit DerivativeAdded(_derivatives[i], _priceFeeds[i]); } } /// @notice Removes a list of derivatives /// @param _derivatives The derivatives to remove function __removeDerivatives(address[] memory _derivatives) internal { for (uint256 i = 0; i < _derivatives.length; i++) { require( getPriceFeedForDerivative(_derivatives[i]) != address(0), "removeDerivatives: Derivative not yet added" ); delete derivativeToPriceFeed[_derivatives[i]]; emit DerivativeRemoved(_derivatives[i]); } } // PRIVATE FUNCTIONS /// @dev Helper to validate a derivative price feed function __validateDerivativePriceFeed(address _derivative, address _priceFeed) private view { require( IDerivativePriceFeed(_priceFeed).isSupportedAsset(_derivative), "__validateDerivativePriceFeed: Unsupported derivative" ); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the registered price feed for a given derivative /// @return priceFeed_ The price feed contract address function getPriceFeedForDerivative(address _derivative) public view returns (address priceFeed_) { return derivativeToPriceFeed[_derivative]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IDerivativePriceFeed Interface /// @author Enzyme Council <[email protected]> /// @notice Simple interface for derivative price source oracle implementations interface IDerivativePriceFeed { function calcUnderlyingValues(address, uint256) external returns (address[] memory, uint256[] memory); function isSupportedAsset(address) external view returns (bool); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../../../interfaces/IChainlinkAggregator.sol"; /// @title ChainlinkPriceFeedMixin Contract /// @author Enzyme Council <[email protected]> /// @notice A price feed that uses Chainlink oracles as price sources abstract contract ChainlinkPriceFeedMixin { using SafeMath for uint256; event EthUsdAggregatorSet(address prevEthUsdAggregator, address nextEthUsdAggregator); event PrimitiveAdded( address indexed primitive, address aggregator, RateAsset rateAsset, uint256 unit ); event PrimitiveRemoved(address indexed primitive); enum RateAsset {ETH, USD} struct AggregatorInfo { address aggregator; RateAsset rateAsset; } uint256 private constant ETH_UNIT = 10**18; uint256 private immutable STALE_RATE_THRESHOLD; address private immutable WETH_TOKEN; address private ethUsdAggregator; mapping(address => AggregatorInfo) private primitiveToAggregatorInfo; mapping(address => uint256) private primitiveToUnit; constructor(address _wethToken, uint256 _staleRateThreshold) public { STALE_RATE_THRESHOLD = _staleRateThreshold; WETH_TOKEN = _wethToken; } // INTERNAL FUNCTIONS /// @notice Calculates the value of a base asset in terms of a quote asset (using a canonical rate) /// @param _baseAsset The base asset /// @param _baseAssetAmount The base asset amount to convert /// @param _quoteAsset The quote asset /// @return quoteAssetAmount_ The equivalent quote asset amount function __calcCanonicalValue( address _baseAsset, uint256 _baseAssetAmount, address _quoteAsset ) internal view returns (uint256 quoteAssetAmount_) { // Case where _baseAsset == _quoteAsset is handled by ValueInterpreter int256 baseAssetRate = __getLatestRateData(_baseAsset); require(baseAssetRate > 0, "__calcCanonicalValue: Invalid base asset rate"); int256 quoteAssetRate = __getLatestRateData(_quoteAsset); require(quoteAssetRate > 0, "__calcCanonicalValue: Invalid quote asset rate"); return __calcConversionAmount( _baseAsset, _baseAssetAmount, uint256(baseAssetRate), _quoteAsset, uint256(quoteAssetRate) ); } /// @dev Helper to set the `ethUsdAggregator` value function __setEthUsdAggregator(address _nextEthUsdAggregator) internal { address prevEthUsdAggregator = getEthUsdAggregator(); require( _nextEthUsdAggregator != prevEthUsdAggregator, "__setEthUsdAggregator: Value already set" ); __validateAggregator(_nextEthUsdAggregator); ethUsdAggregator = _nextEthUsdAggregator; emit EthUsdAggregatorSet(prevEthUsdAggregator, _nextEthUsdAggregator); } // PRIVATE FUNCTIONS /// @dev Helper to convert an amount from a _baseAsset to a _quoteAsset function __calcConversionAmount( address _baseAsset, uint256 _baseAssetAmount, uint256 _baseAssetRate, address _quoteAsset, uint256 _quoteAssetRate ) private view returns (uint256 quoteAssetAmount_) { RateAsset baseAssetRateAsset = getRateAssetForPrimitive(_baseAsset); RateAsset quoteAssetRateAsset = getRateAssetForPrimitive(_quoteAsset); uint256 baseAssetUnit = getUnitForPrimitive(_baseAsset); uint256 quoteAssetUnit = getUnitForPrimitive(_quoteAsset); // If rates are both in ETH or both in USD if (baseAssetRateAsset == quoteAssetRateAsset) { return __calcConversionAmountSameRateAsset( _baseAssetAmount, baseAssetUnit, _baseAssetRate, quoteAssetUnit, _quoteAssetRate ); } (, int256 ethPerUsdRate, , uint256 ethPerUsdRateLastUpdatedAt, ) = IChainlinkAggregator( getEthUsdAggregator() ) .latestRoundData(); require(ethPerUsdRate > 0, "__calcConversionAmount: Bad ethUsd rate"); __validateRateIsNotStale(ethPerUsdRateLastUpdatedAt); // If _baseAsset's rate is in ETH and _quoteAsset's rate is in USD if (baseAssetRateAsset == RateAsset.ETH) { return __calcConversionAmountEthRateAssetToUsdRateAsset( _baseAssetAmount, baseAssetUnit, _baseAssetRate, quoteAssetUnit, _quoteAssetRate, uint256(ethPerUsdRate) ); } // If _baseAsset's rate is in USD and _quoteAsset's rate is in ETH return __calcConversionAmountUsdRateAssetToEthRateAsset( _baseAssetAmount, baseAssetUnit, _baseAssetRate, quoteAssetUnit, _quoteAssetRate, uint256(ethPerUsdRate) ); } /// @dev Helper to convert amounts where the base asset has an ETH rate and the quote asset has a USD rate function __calcConversionAmountEthRateAssetToUsdRateAsset( uint256 _baseAssetAmount, uint256 _baseAssetUnit, uint256 _baseAssetRate, uint256 _quoteAssetUnit, uint256 _quoteAssetRate, uint256 _ethPerUsdRate ) private pure returns (uint256 quoteAssetAmount_) { // Only allows two consecutive multiplication operations to avoid potential overflow. // Intermediate step needed to resolve stack-too-deep error. uint256 intermediateStep = _baseAssetAmount.mul(_baseAssetRate).mul(_ethPerUsdRate).div( ETH_UNIT ); return intermediateStep.mul(_quoteAssetUnit).div(_baseAssetUnit).div(_quoteAssetRate); } /// @dev Helper to convert amounts where base and quote assets both have ETH rates or both have USD rates function __calcConversionAmountSameRateAsset( uint256 _baseAssetAmount, uint256 _baseAssetUnit, uint256 _baseAssetRate, uint256 _quoteAssetUnit, uint256 _quoteAssetRate ) private pure returns (uint256 quoteAssetAmount_) { // Only allows two consecutive multiplication operations to avoid potential overflow return _baseAssetAmount.mul(_baseAssetRate).mul(_quoteAssetUnit).div( _baseAssetUnit.mul(_quoteAssetRate) ); } /// @dev Helper to convert amounts where the base asset has a USD rate and the quote asset has an ETH rate function __calcConversionAmountUsdRateAssetToEthRateAsset( uint256 _baseAssetAmount, uint256 _baseAssetUnit, uint256 _baseAssetRate, uint256 _quoteAssetUnit, uint256 _quoteAssetRate, uint256 _ethPerUsdRate ) private pure returns (uint256 quoteAssetAmount_) { // Only allows two consecutive multiplication operations to avoid potential overflow // Intermediate step needed to resolve stack-too-deep error. uint256 intermediateStep = _baseAssetAmount.mul(_baseAssetRate).mul(_quoteAssetUnit).div( _ethPerUsdRate ); return intermediateStep.mul(ETH_UNIT).div(_baseAssetUnit).div(_quoteAssetRate); } /// @dev Helper to get the latest rate for a given primitive function __getLatestRateData(address _primitive) private view returns (int256 rate_) { if (_primitive == getWethToken()) { return int256(ETH_UNIT); } address aggregator = getAggregatorForPrimitive(_primitive); require(aggregator != address(0), "__getLatestRateData: Primitive does not exist"); uint256 rateUpdatedAt; (, rate_, , rateUpdatedAt, ) = IChainlinkAggregator(aggregator).latestRoundData(); __validateRateIsNotStale(rateUpdatedAt); return rate_; } /// @dev Helper to validate that a rate is not from a round considered to be stale function __validateRateIsNotStale(uint256 _latestUpdatedAt) private view { require( _latestUpdatedAt >= block.timestamp.sub(getStaleRateThreshold()), "__validateRateIsNotStale: Stale rate detected" ); } ///////////////////////// // PRIMITIVES REGISTRY // ///////////////////////// /// @notice Adds a list of primitives with the given aggregator and rateAsset values /// @param _primitives The primitives to add /// @param _aggregators The ordered aggregators corresponding to the list of _primitives /// @param _rateAssets The ordered rate assets corresponding to the list of _primitives function __addPrimitives( address[] calldata _primitives, address[] calldata _aggregators, RateAsset[] calldata _rateAssets ) internal { require( _primitives.length == _aggregators.length, "__addPrimitives: Unequal _primitives and _aggregators array lengths" ); require( _primitives.length == _rateAssets.length, "__addPrimitives: Unequal _primitives and _rateAssets array lengths" ); for (uint256 i; i < _primitives.length; i++) { require( getAggregatorForPrimitive(_primitives[i]) == address(0), "__addPrimitives: Value already set" ); __validateAggregator(_aggregators[i]); primitiveToAggregatorInfo[_primitives[i]] = AggregatorInfo({ aggregator: _aggregators[i], rateAsset: _rateAssets[i] }); // Store the amount that makes up 1 unit given the asset's decimals uint256 unit = 10**uint256(ERC20(_primitives[i]).decimals()); primitiveToUnit[_primitives[i]] = unit; emit PrimitiveAdded(_primitives[i], _aggregators[i], _rateAssets[i], unit); } } /// @notice Removes a list of primitives from the feed /// @param _primitives The primitives to remove function __removePrimitives(address[] calldata _primitives) internal { for (uint256 i; i < _primitives.length; i++) { require( getAggregatorForPrimitive(_primitives[i]) != address(0), "__removePrimitives: Primitive not yet added" ); delete primitiveToAggregatorInfo[_primitives[i]]; delete primitiveToUnit[_primitives[i]]; emit PrimitiveRemoved(_primitives[i]); } } // PRIVATE FUNCTIONS /// @dev Helper to validate an aggregator by checking its return values for the expected interface function __validateAggregator(address _aggregator) private view { (, int256 answer, , uint256 updatedAt, ) = IChainlinkAggregator(_aggregator) .latestRoundData(); require(answer > 0, "__validateAggregator: No rate detected"); __validateRateIsNotStale(updatedAt); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the aggregator for a primitive /// @param _primitive The primitive asset for which to get the aggregator value /// @return aggregator_ The aggregator address function getAggregatorForPrimitive(address _primitive) public view returns (address aggregator_) { return primitiveToAggregatorInfo[_primitive].aggregator; } /// @notice Gets the `ethUsdAggregator` variable value /// @return ethUsdAggregator_ The `ethUsdAggregator` variable value function getEthUsdAggregator() public view returns (address ethUsdAggregator_) { return ethUsdAggregator; } /// @notice Gets the rateAsset variable value for a primitive /// @return rateAsset_ The rateAsset variable value /// @dev This isn't strictly necessary as WETH_TOKEN will be undefined and thus /// the RateAsset will be the 0-position of the enum (i.e. ETH), but it makes the /// behavior more explicit function getRateAssetForPrimitive(address _primitive) public view returns (RateAsset rateAsset_) { if (_primitive == getWethToken()) { return RateAsset.ETH; } return primitiveToAggregatorInfo[_primitive].rateAsset; } /// @notice Gets the `STALE_RATE_THRESHOLD` variable value /// @return staleRateThreshold_ The `STALE_RATE_THRESHOLD` value function getStaleRateThreshold() public view returns (uint256 staleRateThreshold_) { return STALE_RATE_THRESHOLD; } /// @notice Gets the unit variable value for a primitive /// @return unit_ The unit variable value function getUnitForPrimitive(address _primitive) public view returns (uint256 unit_) { if (_primitive == getWethToken()) { return ETH_UNIT; } return primitiveToUnit[_primitive]; } /// @notice Gets the `WETH_TOKEN` variable value /// @return wethToken_ The `WETH_TOKEN` variable value function getWethToken() public view returns (address wethToken_) { return WETH_TOKEN; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IProtocolFeeTracker Interface /// @author Enzyme Council <[email protected]> interface IProtocolFeeTracker { function initializeForVault(address) external; function payFee() external returns (uint256); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IValueInterpreter interface /// @author Enzyme Council <[email protected]> /// @notice Interface for ValueInterpreter interface IValueInterpreter { function calcCanonicalAssetValue( address, uint256, address ) external returns (uint256); function calcCanonicalAssetsTotalValue( address[] calldata, uint256[] calldata, address ) external returns (uint256); function isSupportedAsset(address) external view returns (bool); function isSupportedDerivativeAsset(address) external view returns (bool); function isSupportedPrimitiveAsset(address) external view returns (bool); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../utils/FundDeployerOwnerMixin.sol"; import "../../utils/MathHelpers.sol"; import "../price-feeds/derivatives/AggregatedDerivativePriceFeedMixin.sol"; import "../price-feeds/derivatives/IDerivativePriceFeed.sol"; import "../price-feeds/primitives/ChainlinkPriceFeedMixin.sol"; import "./IValueInterpreter.sol"; /// @title ValueInterpreter Contract /// @author Enzyme Council <[email protected]> /// @notice Interprets price feeds to provide covert value between asset pairs contract ValueInterpreter is IValueInterpreter, FundDeployerOwnerMixin, AggregatedDerivativePriceFeedMixin, ChainlinkPriceFeedMixin, MathHelpers { using SafeMath for uint256; // Used to only tolerate a max rounding discrepancy of 0.01% // when converting values via an inverse rate uint256 private constant MIN_INVERSE_RATE_AMOUNT = 10000; constructor( address _fundDeployer, address _wethToken, uint256 _chainlinkStaleRateThreshold ) public FundDeployerOwnerMixin(_fundDeployer) ChainlinkPriceFeedMixin(_wethToken, _chainlinkStaleRateThreshold) {} // EXTERNAL FUNCTIONS /// @notice Calculates the total value of given amounts of assets in a single quote asset /// @param _baseAssets The assets to convert /// @param _amounts The amounts of the _baseAssets to convert /// @param _quoteAsset The asset to which to convert /// @return value_ The sum value of _baseAssets, denominated in the _quoteAsset /// @dev Does not alter protocol state, /// but not a view because calls to price feeds can potentially update third party state. /// Does not handle a derivative quote asset. function calcCanonicalAssetsTotalValue( address[] memory _baseAssets, uint256[] memory _amounts, address _quoteAsset ) external override returns (uint256 value_) { require( _baseAssets.length == _amounts.length, "calcCanonicalAssetsTotalValue: Arrays unequal lengths" ); require( isSupportedPrimitiveAsset(_quoteAsset), "calcCanonicalAssetsTotalValue: Unsupported _quoteAsset" ); for (uint256 i; i < _baseAssets.length; i++) { uint256 assetValue = __calcAssetValue(_baseAssets[i], _amounts[i], _quoteAsset); value_ = value_.add(assetValue); } return value_; } // PUBLIC FUNCTIONS /// @notice Calculates the value of a given amount of one asset in terms of another asset /// @param _baseAsset The asset from which to convert /// @param _amount The amount of the _baseAsset to convert /// @param _quoteAsset The asset to which to convert /// @return value_ The equivalent quantity in the _quoteAsset /// @dev Does not alter protocol state, /// but not a view because calls to price feeds can potentially update third party state. /// See also __calcPrimitiveToDerivativeValue() for important notes regarding a derivative _quoteAsset. function calcCanonicalAssetValue( address _baseAsset, uint256 _amount, address _quoteAsset ) external override returns (uint256 value_) { if (_baseAsset == _quoteAsset || _amount == 0) { return _amount; } if (isSupportedPrimitiveAsset(_quoteAsset)) { return __calcAssetValue(_baseAsset, _amount, _quoteAsset); } else if ( isSupportedDerivativeAsset(_quoteAsset) && isSupportedPrimitiveAsset(_baseAsset) ) { return __calcPrimitiveToDerivativeValue(_baseAsset, _amount, _quoteAsset); } revert("calcCanonicalAssetValue: Unsupported conversion"); } /// @notice Checks whether an asset is a supported asset /// @param _asset The asset to check /// @return isSupported_ True if the asset is a supported asset function isSupportedAsset(address _asset) public view override returns (bool isSupported_) { return isSupportedPrimitiveAsset(_asset) || isSupportedDerivativeAsset(_asset); } // PRIVATE FUNCTIONS /// @dev Helper to differentially calculate an asset value /// based on if it is a primitive or derivative asset. function __calcAssetValue( address _baseAsset, uint256 _amount, address _quoteAsset ) private returns (uint256 value_) { if (_baseAsset == _quoteAsset || _amount == 0) { return _amount; } // Handle case that asset is a primitive if (isSupportedPrimitiveAsset(_baseAsset)) { return __calcCanonicalValue(_baseAsset, _amount, _quoteAsset); } // Handle case that asset is a derivative address derivativePriceFeed = getPriceFeedForDerivative(_baseAsset); if (derivativePriceFeed != address(0)) { return __calcDerivativeValue(derivativePriceFeed, _baseAsset, _amount, _quoteAsset); } revert("__calcAssetValue: Unsupported _baseAsset"); } /// @dev Helper to calculate the value of a derivative in an arbitrary asset. /// Handles multiple underlying assets (e.g., Uniswap and Balancer pool tokens). /// Handles underlying assets that are also derivatives (e.g., a cDAI-ETH LP) function __calcDerivativeValue( address _derivativePriceFeed, address _derivative, uint256 _amount, address _quoteAsset ) private returns (uint256 value_) { (address[] memory underlyings, uint256[] memory underlyingAmounts) = IDerivativePriceFeed( _derivativePriceFeed ) .calcUnderlyingValues(_derivative, _amount); require(underlyings.length > 0, "__calcDerivativeValue: No underlyings"); require( underlyings.length == underlyingAmounts.length, "__calcDerivativeValue: Arrays unequal lengths" ); for (uint256 i = 0; i < underlyings.length; i++) { uint256 underlyingValue = __calcAssetValue( underlyings[i], underlyingAmounts[i], _quoteAsset ); value_ = value_.add(underlyingValue); } } /// @dev Helper to calculate the value of a primitive base asset in a derivative quote asset. /// Assumes that the _primitiveBaseAsset and _derivativeQuoteAsset have been validated as supported. /// Callers of this function should be aware of the following points, and take precautions as-needed, /// such as prohibiting a derivative quote asset: /// - The returned value will be slightly less the actual canonical value due to the conversion formula's /// handling of the intermediate inverse rate (see comments below). /// - If the assets involved have an extreme rate and/or have a low ERC20.decimals() value, /// the inverse rate might not be considered "sufficient", and will revert. function __calcPrimitiveToDerivativeValue( address _primitiveBaseAsset, uint256 _primitiveBaseAssetAmount, address _derivativeQuoteAsset ) private returns (uint256 value_) { uint256 derivativeUnit = 10**uint256(ERC20(_derivativeQuoteAsset).decimals()); address derivativePriceFeed = getPriceFeedForDerivative(_derivativeQuoteAsset); uint256 primitiveAmountForDerivativeUnit = __calcDerivativeValue( derivativePriceFeed, _derivativeQuoteAsset, derivativeUnit, _primitiveBaseAsset ); // Only tolerate a max rounding discrepancy require( primitiveAmountForDerivativeUnit > MIN_INVERSE_RATE_AMOUNT, "__calcPrimitiveToDerivativeValue: Insufficient rate" ); // Adds `1` to primitiveAmountForDerivativeUnit so that the final return value is // slightly less than the actual value, which is congruent with how all other // asset conversions are floored in the protocol. return __calcRelativeQuantity( primitiveAmountForDerivativeUnit.add(1), derivativeUnit, _primitiveBaseAssetAmount ); } //////////////////////////// // PRIMITIVES (CHAINLINK) // //////////////////////////// /// @notice Adds a list of primitives with the given aggregator and rateAsset values /// @param _primitives The primitives to add /// @param _aggregators The ordered aggregators corresponding to the list of _primitives /// @param _rateAssets The ordered rate assets corresponding to the list of _primitives function addPrimitives( address[] calldata _primitives, address[] calldata _aggregators, RateAsset[] calldata _rateAssets ) external onlyFundDeployerOwner { __addPrimitives(_primitives, _aggregators, _rateAssets); } /// @notice Removes a list of primitives from the feed /// @param _primitives The primitives to remove function removePrimitives(address[] calldata _primitives) external onlyFundDeployerOwner { __removePrimitives(_primitives); } /// @notice Sets the `ehUsdAggregator` variable value /// @param _nextEthUsdAggregator The `ehUsdAggregator` value to set function setEthUsdAggregator(address _nextEthUsdAggregator) external onlyFundDeployerOwner { __setEthUsdAggregator(_nextEthUsdAggregator); } /// @notice Updates a list of primitives with the given aggregator and rateAsset values /// @param _primitives The primitives to update /// @param _aggregators The ordered aggregators corresponding to the list of _primitives /// @param _rateAssets The ordered rate assets corresponding to the list of _primitives function updatePrimitives( address[] calldata _primitives, address[] calldata _aggregators, RateAsset[] calldata _rateAssets ) external onlyFundDeployerOwner { __removePrimitives(_primitives); __addPrimitives(_primitives, _aggregators, _rateAssets); } // PUBLIC FUNCTIONS /// @notice Checks whether an asset is a supported primitive /// @param _asset The asset to check /// @return isSupported_ True if the asset is a supported primitive function isSupportedPrimitiveAsset(address _asset) public view override returns (bool isSupported_) { return _asset == getWethToken() || getAggregatorForPrimitive(_asset) != address(0); } //////////////////////////////////// // DERIVATIVE PRICE FEED REGISTRY // //////////////////////////////////// /// @notice Adds a list of derivatives with the given price feed values /// @param _derivatives The derivatives to add /// @param _priceFeeds The ordered price feeds corresponding to the list of _derivatives function addDerivatives(address[] calldata _derivatives, address[] calldata _priceFeeds) external onlyFundDeployerOwner { __addDerivatives(_derivatives, _priceFeeds); } /// @notice Removes a list of derivatives /// @param _derivatives The derivatives to remove function removeDerivatives(address[] calldata _derivatives) external onlyFundDeployerOwner { __removeDerivatives(_derivatives); } /// @notice Updates a list of derivatives with the given price feed values /// @param _derivatives The derivatives to update /// @param _priceFeeds The ordered price feeds corresponding to the list of _derivatives function updateDerivatives(address[] calldata _derivatives, address[] calldata _priceFeeds) external onlyFundDeployerOwner { __removeDerivatives(_derivatives); __addDerivatives(_derivatives, _priceFeeds); } // PUBLIC FUNCTIONS /// @notice Checks whether an asset is a supported derivative /// @param _asset The asset to check /// @return isSupported_ True if the asset is a supported derivative function isSupportedDerivativeAsset(address _asset) public view override returns (bool isSupported_) { return getPriceFeedForDerivative(_asset) != address(0); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IChainlinkAggregator Interface /// @author Enzyme Council <[email protected]> interface IChainlinkAggregator { function latestRoundData() external view returns ( uint80, int256, uint256, uint256, uint80 ); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IGsnForwarder interface /// @author Enzyme Council <[email protected]> interface IGsnForwarder { struct ForwardRequest { address from; address to; uint256 value; uint256 gas; uint256 nonce; bytes data; uint256 validUntil; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./IGsnTypes.sol"; /// @title IGsnPaymaster interface /// @author Enzyme Council <[email protected]> interface IGsnPaymaster { struct GasAndDataLimits { uint256 acceptanceBudget; uint256 preRelayedCallGasLimit; uint256 postRelayedCallGasLimit; uint256 calldataSizeLimit; } function getGasAndDataLimits() external view returns (GasAndDataLimits memory limits); function getHubAddr() external view returns (address); function getRelayHubDeposit() external view returns (uint256); function preRelayedCall( IGsnTypes.RelayRequest calldata relayRequest, bytes calldata signature, bytes calldata approvalData, uint256 maxPossibleGas ) external returns (bytes memory context, bool rejectOnRecipientRevert); function postRelayedCall( bytes calldata context, bool success, uint256 gasUseWithoutPost, IGsnTypes.RelayData calldata relayData ) external; function trustedForwarder() external view returns (address); function versionPaymaster() external view returns (string memory); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./IGsnForwarder.sol"; /// @title IGsnTypes Interface /// @author Enzyme Council <[email protected]> interface IGsnTypes { struct RelayData { uint256 gasPrice; uint256 pctRelayFee; uint256 baseRelayFee; address relayWorker; address paymaster; address forwarder; bytes paymasterData; uint256 clientId; } struct RelayRequest { IGsnForwarder.ForwardRequest request; RelayData relayData; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title WETH Interface /// @author Enzyme Council <[email protected]> interface IWETH { function deposit() external payable; function withdraw(uint256) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title AddressArray Library /// @author Enzyme Council <[email protected]> /// @notice A library to extend the address array data type library AddressArrayLib { ///////////// // STORAGE // ///////////// /// @dev Helper to remove an item from a storage array function removeStorageItem(address[] storage _self, address _itemToRemove) internal returns (bool removed_) { uint256 itemCount = _self.length; for (uint256 i; i < itemCount; i++) { if (_self[i] == _itemToRemove) { if (i < itemCount - 1) { _self[i] = _self[itemCount - 1]; } _self.pop(); removed_ = true; break; } } return removed_; } //////////// // MEMORY // //////////// /// @dev Helper to add an item to an array. Does not assert uniqueness of the new item. function addItem(address[] memory _self, address _itemToAdd) internal pure returns (address[] memory nextArray_) { nextArray_ = new address[](_self.length + 1); for (uint256 i; i < _self.length; i++) { nextArray_[i] = _self[i]; } nextArray_[_self.length] = _itemToAdd; return nextArray_; } /// @dev Helper to add an item to an array, only if it is not already in the array. function addUniqueItem(address[] memory _self, address _itemToAdd) internal pure returns (address[] memory nextArray_) { if (contains(_self, _itemToAdd)) { return _self; } return addItem(_self, _itemToAdd); } /// @dev Helper to verify if an array contains a particular value function contains(address[] memory _self, address _target) internal pure returns (bool doesContain_) { for (uint256 i; i < _self.length; i++) { if (_target == _self[i]) { return true; } } return false; } /// @dev Helper to merge the unique items of a second array. /// Does not consider uniqueness of either array, only relative uniqueness. /// Preserves ordering. function mergeArray(address[] memory _self, address[] memory _arrayToMerge) internal pure returns (address[] memory nextArray_) { uint256 newUniqueItemCount; for (uint256 i; i < _arrayToMerge.length; i++) { if (!contains(_self, _arrayToMerge[i])) { newUniqueItemCount++; } } if (newUniqueItemCount == 0) { return _self; } nextArray_ = new address[](_self.length + newUniqueItemCount); for (uint256 i; i < _self.length; i++) { nextArray_[i] = _self[i]; } uint256 nextArrayIndex = _self.length; for (uint256 i; i < _arrayToMerge.length; i++) { if (!contains(_self, _arrayToMerge[i])) { nextArray_[nextArrayIndex] = _arrayToMerge[i]; nextArrayIndex++; } } return nextArray_; } /// @dev Helper to verify if array is a set of unique values. /// Does not assert length > 0. function isUniqueSet(address[] memory _self) internal pure returns (bool isUnique_) { if (_self.length <= 1) { return true; } uint256 arrayLength = _self.length; for (uint256 i; i < arrayLength; i++) { for (uint256 j = i + 1; j < arrayLength; j++) { if (_self[i] == _self[j]) { return false; } } } return true; } /// @dev Helper to remove items from an array. Removes all matching occurrences of each item. /// Does not assert uniqueness of either array. function removeItems(address[] memory _self, address[] memory _itemsToRemove) internal pure returns (address[] memory nextArray_) { if (_itemsToRemove.length == 0) { return _self; } bool[] memory indexesToRemove = new bool[](_self.length); uint256 remainingItemsCount = _self.length; for (uint256 i; i < _self.length; i++) { if (contains(_itemsToRemove, _self[i])) { indexesToRemove[i] = true; remainingItemsCount--; } } if (remainingItemsCount == _self.length) { nextArray_ = _self; } else if (remainingItemsCount > 0) { nextArray_ = new address[](remainingItemsCount); uint256 nextArrayIndex; for (uint256 i; i < _self.length; i++) { if (!indexesToRemove[i]) { nextArray_[nextArrayIndex] = _self[i]; nextArrayIndex++; } } } return nextArray_; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../core/fund-deployer/IFundDeployer.sol"; /// @title FundDeployerOwnerMixin Contract /// @author Enzyme Council <[email protected]> /// @notice A mixin contract that defers ownership to the owner of FundDeployer abstract contract FundDeployerOwnerMixin { address internal immutable FUND_DEPLOYER; modifier onlyFundDeployerOwner() { require( msg.sender == getOwner(), "onlyFundDeployerOwner: Only the FundDeployer owner can call this function" ); _; } constructor(address _fundDeployer) public { FUND_DEPLOYER = _fundDeployer; } /// @notice Gets the owner of this contract /// @return owner_ The owner /// @dev Ownership is deferred to the owner of the FundDeployer contract function getOwner() public view returns (address owner_) { return IFundDeployer(FUND_DEPLOYER).getOwner(); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `FUND_DEPLOYER` variable /// @return fundDeployer_ The `FUND_DEPLOYER` variable value function getFundDeployer() public view returns (address fundDeployer_) { return FUND_DEPLOYER; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; /// @title MathHelpers Contract /// @author Enzyme Council <[email protected]> /// @notice Helper functions for common math operations abstract contract MathHelpers { using SafeMath for uint256; /// @dev Calculates a proportional value relative to a known ratio. /// Caller is responsible as-necessary for: /// 1. validating _quantity1 to be non-zero /// 2. validating relativeQuantity2_ to be non-zero function __calcRelativeQuantity( uint256 _quantity1, uint256 _quantity2, uint256 _relativeQuantity1 ) internal pure returns (uint256 relativeQuantity2_) { return _relativeQuantity1.mul(_quantity2).div(_quantity1); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IBeacon interface /// @author Enzyme Council <[email protected]> interface IBeacon { function getCanonicalLib() external view returns (address); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ import "./IBeacon.sol"; pragma solidity 0.6.12; /// @title IBeaconProxyFactory interface /// @author Enzyme Council <[email protected]> interface IBeaconProxyFactory is IBeacon { function deployProxy(bytes memory _constructData) external returns (address proxy_); function setCanonicalLib(address _canonicalLib) external; }
@notice Checks whether an asset is bypassable (if still without a valid price) for a given fund @param _comptrollerProxy The ComptrollerProxy of the fund @param _asset The asset for which to check if it is bypassable @return isBypassable_ True if the asset is bypassable
function assetIsBypassableForFund(address _comptrollerProxy, address _asset) public view returns (bool isBypassable_) { uint256 windowStart = getAssetBypassWindowStartForFund(_comptrollerProxy, _asset); return windowStart <= block.timestamp && windowStart.add(getPricelessAssetBypassTimeLimit()) >= block.timestamp; }
13,968,170
[ 1, 4081, 2856, 392, 3310, 353, 17587, 429, 261, 430, 4859, 2887, 279, 923, 6205, 13, 364, 279, 864, 284, 1074, 225, 389, 832, 337, 1539, 3886, 1021, 1286, 337, 1539, 3886, 434, 326, 284, 1074, 225, 389, 9406, 1021, 3310, 364, 1492, 358, 866, 309, 518, 353, 17587, 429, 327, 353, 858, 5466, 429, 67, 1053, 309, 326, 3310, 353, 17587, 429, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 3310, 2520, 858, 5466, 429, 1290, 42, 1074, 12, 2867, 389, 832, 337, 1539, 3886, 16, 1758, 389, 9406, 13, 203, 3639, 1071, 203, 3639, 1476, 203, 3639, 1135, 261, 6430, 353, 858, 5466, 429, 67, 13, 203, 565, 288, 203, 3639, 2254, 5034, 2742, 1685, 273, 24689, 858, 5466, 3829, 1685, 1290, 42, 1074, 24899, 832, 337, 1539, 3886, 16, 389, 9406, 1769, 203, 203, 3639, 327, 203, 5411, 2742, 1685, 1648, 1203, 18, 5508, 597, 203, 5411, 2742, 1685, 18, 1289, 12, 588, 52, 1512, 12617, 6672, 858, 5466, 950, 3039, 10756, 1545, 1203, 18, 5508, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity >=0.4.2; import "../utillib/Pairing.sol"; import "../utillib/ECops.sol"; import "../utillib/ECopsG2.sol"; library LibDTBE { using Pairing for *; using ECops for *; using ECopsG2 for *; //generate a random number of modulo _module which is a prime number function rand(uint256 _module) internal view returns(uint256) { uint256 _seed = _module + 1; uint256 random = uint(keccak256(abi.encodePacked(block.difficulty, _seed))); return random%_module; } // Add two elliptic curve points (affine coordinates) function G1add(Pairing.G1Point p1, Pairing.G1Point p2) internal view returns (Pairing.G1Point storage){ uint256 x; uint256 y; (x, y) = ECops.add(p1.X, p1.Y, p2.X, p2.Y); Pairing.G1Point storage r; r.X = x; r.Y = y; return r; } // the scalar multiply in G1; use library ECops function G1mul(Pairing.G1Point p, uint s) internal view returns (Pairing.G1Point storage){ uint256 x; uint256 y; Pairing.G1Point storage r; (x, y) = ECops.multiplyScalar(p.X, p.Y, s); r.X = x; r.Y = y; return r; } function G2add(Pairing.G2Point p1, Pairing.G2Point p2) internal view returns (Pairing.G2Point storage){ Pairing.G2Point storage r; // (r.X[0], r.X[1], r.Y[0], r.Y[1]) = ECopsG2.ECTwistAdd( // p1.X[0], p1.X[1], p1.Y[0], p1.Y[1], // p2.X[0], p2.X[1], p2.Y[0], p2.Y[1] // ); if (p1.X[0] == 0 && p1.X[1] == 0 && p1.Y[0] == 0 && p1.Y[1] == 0) { if (!(p2.X[0] == 0 && p2.X[1] == 0 && p2.Y[0] == 0 && p2.Y[1] == 0)) { require(ECopsG2._isOnCurve(p2.X[0], p2.X[1], p2.Y[0], p2.Y[1]), 'err01'); } (r.X[0], r.X[1], r.Y[0], r.Y[1]) = (p2.X[0], p2.X[1], p2.Y[0], p2.Y[1]); } else if (p2.X[0] == 0 && p2.X[1] == 0 && p2.Y[0] == 0 && p2.Y[1] == 0) { require(ECopsG2._isOnCurve(p1.X[0], p1.X[1], p1.Y[0], p1.Y[1]), 'err02'); (r.X[0], r.X[1], r.Y[0], r.Y[1]) = (p1.X[0], p1.X[1], p1.Y[0], p1.Y[1]); } else { require(ECopsG2._isOnCurve(p1.X[0], p1.X[1], p1.Y[0], p1.Y[1]), 'err03'); require(ECopsG2._isOnCurve(p2.X[0], p2.X[1], p2.Y[0], p2.Y[1]), 'err04'); uint256[6] memory pt3 = ECopsG2._ECTwistAddJacobian( p1.X[0], p1.X[1], p1.Y[0], p1.Y[1], 1, 0, p2.X[0], p2.X[1], p2.Y[0], p2.Y[1], 1, 0 ); (r.X[0], r.X[1], r.Y[0], r.Y[1]) = ECopsG2._fromJacobian(pt3[0], pt3[1], pt3[2], pt3[3], pt3[4], pt3[5]); } return r; } //the scalar multiply in G2; use library ECops2 function G2mul(Pairing.G2Point p, uint256 s) internal view returns (Pairing.G2Point storage){ uint256 x0 = 0; uint256 x1 = 0; uint256 y0 = 0; uint256 y1 = 0; // (x0, x1, y0, y1) = ECopsG2.ECTwistMul(p.X[0], p.X[1], p.Y[0], p.Y[1], s); // 以下8行代码与上面一行代码按理是等效的,但是如果用函数调用的话编译出来的bytecode无法识别 // The following 8 lines should be equivalent to the above line, but the compiled Bytecode always would not be recognized uint256[6] memory pt2; if (p.X[0] == 0 && p.X[1] == 0 && p.Y[0] == 0 && p.Y[1] == 0) { pt2 = ECopsG2._ECTwistMulJacobian(s, 1, 0, 1, 0, 0, 0); } else { // require(ECopsG2._isOnCurve(p.X[0], p.X[1], p.Y[0], p.Y[1]), 'err05'); pt2 = ECopsG2._ECTwistMulJacobian(s, p.X[0], p.X[1], p.Y[0], p.Y[1], 1, 0); } (x0, x1, y0, y1) = ECopsG2._fromJacobian(pt2[0], pt2[1], pt2[2], pt2[3], pt2[4], pt2[5]); Pairing.G2Point storage r; r.X[0] = x0; r.X[1] = x1; r.Y[0] = y0; r.Y[1] = y1; return r; } uint256 constant p = 21888242871839275222246405745257275088696311157297823662689037894645226208583; struct PGroup{ uint256 _p; //prime order Pairing.G1Point G; //G1 generator Pairing.G2Point _G; //G2 generator string _ECG1; //EC1 operation's library string _ECG2; //EC2 operation's library string _pairing; // pairing check's library } struct SK{ uint256 ui; uint256 vi; } struct SVK{ Pairing.G2Point Ui; Pairing.G2Point Vi; } struct PK{ PGroup P;// P group Pairing.G1Point H; Pairing.G2Point _H; Pairing.G1Point U; Pairing.G2Point _U; Pairing.G1Point V; Pairing.G2Point _V; Pairing.G1Point W; Pairing.G2Point _W; Pairing.G1Point Z; Pairing.G2Point _Z; } struct CLUE{ Pairing.G1Point Ci1; Pairing.G1Point Ci2; } function KeyGen(/*uint k, */uint n) internal view returns(PK storage, SK[] storage, SVK[] storage){ PGroup storage pg; PK storage epk; SK[] storage esk; SVK[] storage esvk; /*Here should be some codes for generate the prime number p according to the input parameter k which is security parameter*/ pg._p = p; pg.G = Pairing.P1(); pg._G = Pairing.P2(); pg._ECG1 = "ECops.sol"; pg._ECG2 = "ECopsG2.sol"; pg._pairing = "Pairing.sol"; epk.P = pg; /*here we need to generate the random variables in the P group (a prime-order biliner group)*/ uint256 h = rand(p); uint256 w = rand(p); uint256 z = rand(p); uint256[] memory _ui = new uint256[](n); uint256[] memory _vi = new uint256[](n); uint256 u = 0; //sum of ui uint256 v = 0; //sum of vi //calculate secret key uint i = 0; while(i < n){ _ui[i] = rand(p); _vi[i] = rand(p); u = u + _ui[i]; v = v + _vi[i]; //initialize the sk esk.push(SK({ ui: _ui[i], vi: _vi[i] })); i++; } // calculate the H and _H epk.H = G1mul(Pairing.P1(), h); epk._H = G2mul(Pairing.P2(), h); epk.U = G1mul(epk.H, u); epk._U = G2mul(epk._H, u); epk.V = G1mul(epk.U, ECops.inverse(v)); epk._V = G2mul(epk._U, ECops.inverse(v)); epk.W = G1mul(epk.H, w); epk._W = G2mul(epk._H, w); epk.Z = G1mul(epk.V, z); epk._Z = G2mul(epk._V, z); // initialize the SVK i = 0; while(i < n){ esvk.push(SVK({ Ui: G2mul(epk._H, _ui[i]), Vi: G2mul(epk._V, _vi[i]) })); i++; } return (epk, esk, esvk); } // t is in group of modulo p; M is G^m , where m is in the group of modulo p function encrypt(PK epk, uint256 t, Pairing.G1Point M) internal view returns(Pairing.G1Point[] storage){ //random number in F_p ,where p is a prime number uint256 r1 = rand(p); uint256 r2 = rand(p); //calculate the Ci Pairing.G1Point storage C1 = G1mul(epk.H, r1); Pairing.G1Point storage C2 = G1mul(epk.V, r2); Pairing.G1Point storage C3 = G1add(M, G1mul(epk.U, r1 + r2)); Pairing.G1Point memory tmp = G1mul(epk.U, t); // a temp point which is using for generating C4 C5 Pairing.G1Point storage C4 = G1mul(G1add(tmp, epk.W), r1); Pairing.G1Point storage C5 = G1mul(G1add(tmp, epk.Z), r2); Pairing.G1Point[] storage Cdtbe; Cdtbe.push(C1); Cdtbe.push(C2); Cdtbe.push(C3); Cdtbe.push(C4); Cdtbe.push(C5); return Cdtbe; } function pairingCheck(Pairing.G1Point[] p1, Pairing.G2Point[] p2) internal view returns (bool){ return Pairing.pairing(p1, p2); //e(a,b) == e(c,d) -> e(a,b)*e(-c,d) == 1 } function isVaild(PK epk, uint256 t, Pairing.G1Point[] storage Cdtbe) internal view returns(bool) { Pairing.G1Point[] memory p11 = new Pairing.G1Point[](2);// Pairing.G2Point[] memory p12 = new Pairing.G2Point[](2); Pairing.G1Point[] memory p21 = new Pairing.G1Point[](2); // Pairing.G2Point[] memory p22 = new Pairing.G2Point[](2); p11[0] = Cdtbe[0]; //C1 p11[1] = Pairing.negate(Cdtbe[3]); //-C4 p12[0] = G2add(G2mul(epk._U, t), epk._W); p12[0] = epk._H; p12[1] = epk._H; p21[0] = Cdtbe[1]; //C2 p21[1] = Pairing.negate(Cdtbe[4]); //-C5 p22[0] = G2add(G2mul(epk._U, t), epk._Z); p22[0] = epk._V; p22[1] = epk._V; if((!pairingCheck(p11, p12)) || (!pairingCheck(p21, p22))){ return false; }else{ return true; } } function shareDec(PK epk, SK eski, uint256 t, Pairing.G1Point[] storage Cdtbe) internal view returns(CLUE){ require( (!isVaild(epk, t, Cdtbe)), "ERROR!Forced to stop." ); CLUE vi;// = new CLUE[](len); vi.Ci1 = G1mul(Cdtbe[0], eski.ui); vi.Ci2 = G1mul(Cdtbe[1], eski.vi); return vi; } function shareVerify(PK epk, SVK esvki, uint256 t, Pairing.G1Point[] storage Cdtbe, CLUE vi) internal view returns(bool){ // require( // (!isVaild(epk, t, Cdtbe)), // "ERROR!Forced to stop." // ); Pairing.G1Point[] memory p11 = new Pairing.G1Point[](2);// Pairing.G2Point[] memory p12 = new Pairing.G2Point[](2); Pairing.G1Point[] memory p21 = new Pairing.G1Point[](2); // Pairing.G2Point[] memory p22 = new Pairing.G2Point[](2); p11[0] = vi.Ci1; //Ci1 p11[1] = Pairing.negate(Cdtbe[0]); //-C1 p12[0] = epk._H; p12[1] = esvki.Ui; p21[0] = vi.Ci2; //Ci2 p21[1] = Pairing.negate(Cdtbe[1]); //-C2 p22[0] = epk._V; p22[1] = esvki.Vi; if((!pairingCheck(p11, p12)) || (!pairingCheck(p21, p22))){ return false; }else{ return true; } } function combine(PK epk, SVK[] storage esvk, CLUE[] storage v, Pairing.G1Point[] storage Cdtbe, uint256 t) internal view returns(Pairing.G1Point memory){ require( (!isVaild(epk, t, Cdtbe)), "ERROR!Forced to stop." ); uint len = esvk.length; uint i = 0; while(i < len){ require( (!shareVerify(epk, esvk[i], t, Cdtbe, v[i])), "ERROR!Forced to stop." ); } Pairing.G1Point memory tmp = G1add(v[0].Ci1, v[0].Ci2); i = 1; while(i < len){ tmp = G1add(tmp, G1add(v[i].Ci1, v[i].Ci2)); i++; } tmp = Pairing.negate(tmp); Pairing.G1Point memory M = G1add(tmp, Cdtbe[2]); return M; } }
calculate the H and _H
epk.H = G1mul(Pairing.P1(), h);
2,478,889
[ 1, 11162, 326, 225, 670, 471, 389, 44, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1082, 202, 881, 79, 18, 44, 273, 611, 21, 16411, 12, 4154, 310, 18, 52, 21, 9334, 366, 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 ]
pragma solidity ^0.4.25; // * myethergames.fun // // * Uses hybrid commit-reveal + block hash random number generation that is immune // to tampering by players, house and miners. Apart from being fully transparent, // this also allows arbitrarily high bets. contract FairCasino { /// *** Constants section // Each bet is deducted 1% in favour of the house, but no less than some minimum. // The lower bound is dictated by gas costs of the settleBet transaction, providing // headroom for up to 10 Gwei prices. uint constant HOUSE_EDGE_PERCENT = 1; uint constant HOUSE_EDGE_MINIMUM_AMOUNT = 0.0003 ether; // Bets lower than this amount do not participate in jackpot rolls (and are // not deducted JACKPOT_FEE). uint constant MIN_JACKPOT_BET = 0.1 ether; // Chance to win jackpot (currently 0.1%) and fee deducted into jackpot fund. uint constant JACKPOT_MODULO = 1000; uint constant JACKPOT_FEE = 0.001 ether; // There is minimum and maximum bets. uint constant MIN_BET = 0.01 ether; uint constant MAX_AMOUNT = 300000 ether; // Modulo is a number of equiprobable outcomes in a game: // - 2 for coin flip // - 6 for dice // - 6*6 = 36 for double dice // - 100 for etheroll // - 37 for roulette // etc. // It's called so because 256-bit entropy is treated like a huge integer and // the remainder of its division by modulo is considered bet outcome. uint constant MAX_MODULO = 100; // For modulos below this threshold rolls are checked against a bit mask, // thus allowing betting on any combination of outcomes. For example, given // modulo 6 for dice, 101000 mask (base-2, big endian) means betting on // 4 and 6; for games with modulos higher than threshold (Etheroll), a simple // limit is used, allowing betting on any outcome in [0, N) range. // // The specific value is dictated by the fact that 256-bit intermediate // multiplication result allows implementing population count efficiently // for numbers that are up to 42 bits, and 40 is the highest multiple of // eight below 42. uint constant MAX_MASK_MODULO = 40; // This is a check on bet mask overflow. uint constant MAX_BET_MASK = 2 ** MAX_MASK_MODULO; // EVM BLOCKHASH opcode can query no further than 256 blocks into the // past. Given that settleBet uses block hash of placeBet as one of // complementary entropy sources, we cannot process bets older than this // threshold. On rare occasions myethergames.fun croupier may fail to invoke // settleBet in this timespan due to technical issues or extreme Ethereum // congestion; such bets can be refunded via invoking refundBet. uint constant BET_EXPIRATION_BLOCKS = 250; // Some deliberately invalid address to initialize the secret signer with. // Forces maintainers to invoke setSecretSigner before processing any bets. // Standard contract ownership transfer. address public owner; address private nextOwner; // Adjustable max bet profit. Used to cap bets against dynamic odds. uint public maxProfit; // The address corresponding to a private key used to sign placeBet commits. address public secretSigner; // Accumulated jackpot fund. uint128 public jackpotSize; // Funds that are locked in potentially winning bets. Prevents contract from // committing to bets it cannot pay out. uint128 public lockedInBets; // A structure representing a single bet. struct Bet { // Wager amount in wei. uint amount; // Modulo of a game. uint8 modulo; // Number of winning outcomes, used to compute winning payment (* modulo/rollUnder), // and used instead of mask for games with modulo > MAX_MASK_MODULO. uint8 rollUnder; // Block number of placeBet tx. uint40 placeBlockNumber; // Bit mask representing winning bet outcomes (see MAX_MASK_MODULO comment). uint40 mask; // Address of a gambler, used to pay out winning bets. address gambler; } // Mapping from commits to all currently active & processed bets. mapping (uint => Bet) bets; // Croupier account. address public croupier; // Events that are issued to make statistic recovery easier. event FailedPayment(address indexed beneficiary, uint amount); event Payment(address indexed beneficiary, uint amount); event JackpotPayment(address indexed beneficiary, uint amount); // This event is emitted in placeBet to record commit in the logs. event Commit(uint commit); // Constructor. Deliberately does not take any parameters. constructor () public { owner = msg.sender; secretSigner = 0x77777A7AD41f5f0578D96c0DEe0afD2816376229; croupier = 0xfC5998aE24dD8ECCaD7Acbf1427002b94f3830fc; } // Standard modifier on methods invokable only by contract owner. modifier onlyOwner { require (msg.sender == owner, "OnlyOwner methods called by non-owner."); _; } // Standard modifier on methods invokable only by contract owner. modifier onlyCroupier { require (msg.sender == croupier, "OnlyCroupier methods called by non-croupier."); _; } // Standard contract ownership transfer implementation, function approveNextOwner(address _nextOwner) external onlyOwner { require (_nextOwner != owner, "Cannot approve current owner."); nextOwner = _nextOwner; } function acceptNextOwner() external { require (msg.sender == nextOwner, "Can only accept preapproved new owner."); owner = nextOwner; } // Fallback function deliberately left empty. It's primary use case // is to top up the bank roll. function () public payable { } // See comment for "secretSigner" variable. function setSecretSigner(address newSecretSigner) external onlyOwner { secretSigner = newSecretSigner; } // Change the croupier address. function setCroupier(address newCroupier) external onlyOwner { croupier = newCroupier; } // Change max bet reward. Setting this to zero effectively disables betting. function setMaxProfit(uint _maxProfit) public onlyOwner { require (_maxProfit < MAX_AMOUNT, "maxProfit should be a sane number."); maxProfit = _maxProfit; } // This function is used to bump up the jackpot fund. Cannot be used to lower it. function increaseJackpot(uint increaseAmount) external onlyOwner { require (increaseAmount <= address(this).balance, "Increase amount larger than balance."); require (jackpotSize + lockedInBets + increaseAmount <= address(this).balance, "Not enough funds."); jackpotSize += uint128(increaseAmount); } // Funds withdrawal to cover costs of myethergames.fun operation. function withdrawFunds(address beneficiary, uint withdrawAmount) external onlyOwner { require (withdrawAmount <= address(this).balance, "Increase amount larger than balance."); require (jackpotSize + lockedInBets + withdrawAmount <= address(this).balance, "Not enough funds."); sendFunds(beneficiary, withdrawAmount, withdrawAmount); } // Contract may be destroyed only when there are no ongoing bets, // either settled or refunded. All funds are transferred to contract owner. function kill() external onlyOwner { require (lockedInBets == 0, "All bets should be processed (settled or refunded) before self-destruct."); selfdestruct(owner); } /// *** Betting logic // Bet states: // amount == 0 && gambler == 0 - 'clean' (can place a bet) // amount != 0 && gambler != 0 - 'active' (can be settled or refunded) // amount == 0 && gambler != 0 - 'processed' (can clean storage) // // NOTE: Storage cleaning is not implemented in this contract version; it will be added // with the next upgrade to prevent polluting Ethereum state with expired bets. // Bet placing transaction - issued by the player. // betMask - bet outcomes bit mask for modulo <= MAX_MASK_MODULO, // [0, betMask) for larger modulos. // modulo - game modulo. // commitLastBlock - number of the maximum block where "commit" is still considered valid. // commit - Keccak256 hash of some secret "reveal" random number, to be supplied // by the myethergames.fun croupier bot in the settleBet transaction. Supplying // "commit" ensures that "reveal" cannot be changed behind the scenes // after placeBet have been mined. // r, s - components of ECDSA signature of (commitLastBlock, commit). v is // equal 27 or 28. // // Commit, being essentially random 256-bit number, is used as a unique bet identifier in // the 'bets' mapping. // // Commits are signed with a block limit to ensure that they are used at most once - otherwise // it would be possible for a miner to place a bet with a known commit/reveal pair and tamper // with the blockhash. Croupier guarantees that commitLastBlock will always be not greater than // placeBet block number plus BET_EXPIRATION_BLOCKS. See whitepaper for details. function placeBet(uint betMask, uint modulo, uint commitLastBlock, uint commit, bytes32 r, bytes32 s, uint8 v) external payable { // Check that the bet is in 'clean' state. Bet storage bet = bets[commit]; require (bet.gambler == address(0), "Bet should be in a 'clean' state."); // Validate input data ranges. uint amount = msg.value; require (modulo > 1 && modulo <= MAX_MODULO, "Modulo should be within range."); require (amount >= MIN_BET && amount <= MAX_AMOUNT, "Amount should be within range."); require (betMask > 0 && betMask < MAX_BET_MASK, "Mask should be within range."); // Check that commit is valid - it has not expired and its signature is valid. require(v >= 27 && v <=28); require (block.number <= commitLastBlock, "Commit has expired."); require (secretSigner == ecrecover(keccak256(abi.encodePacked(uint40(commitLastBlock), commit)), v, r, s), "ECDSA signature is not valid."); uint rollUnder; uint mask; if (modulo <= MAX_MASK_MODULO) { // Small modulo games specify bet outcomes via bit mask. // rollUnder is a number of 1 bits in this mask (population count). // This magic looking formula is an efficient way to compute population // count on EVM for numbers below 2**40. For detailed proof consult // the myethergames.fun whitepaper. rollUnder = ((betMask * POPCNT_MULT) & POPCNT_MASK) % POPCNT_MODULO; mask = betMask; } else { // Larger modulos specify the right edge of half-open interval of // winning bet outcomes. require (betMask > 0 && betMask <= modulo, "High modulo range, betMask larger than modulo."); rollUnder = betMask; } // Winning amount and jackpot increase. uint possibleWinAmount; uint jackpotFee; (possibleWinAmount, jackpotFee) = getDiceWinAmount(amount, modulo, rollUnder); // Enforce max profit limit. require (possibleWinAmount <= amount + maxProfit, "maxProfit limit violation."); // Lock funds. lockedInBets += uint128(possibleWinAmount); jackpotSize += uint128(jackpotFee); // Check whether contract has enough funds to process this bet. require (jackpotSize + lockedInBets <= address(this).balance, "Cannot afford to lose this bet."); // Record commit in logs. emit Commit(commit); // Store bet parameters on blockchain. bet.amount = amount; bet.modulo = uint8(modulo); bet.rollUnder = uint8(rollUnder); bet.placeBlockNumber = uint40(block.number); bet.mask = uint40(mask); bet.gambler = msg.sender; } // This is the method used to settle 99% of bets. To process a bet with a specific // "commit", settleBet should supply a "reveal" number that would Keccak256-hash to // "commit". "blockHash" is the block hash of placeBet block as seen by croupier; it // is additionally asserted to prevent changing the bet outcomes on Ethereum reorgs. function settleBet(uint reveal, bytes32 blockHash) external onlyCroupier { uint commit = uint(keccak256(abi.encodePacked(reveal))); Bet storage bet = bets[commit]; uint placeBlockNumber = bet.placeBlockNumber; // Check that bet has not expired yet (see comment to BET_EXPIRATION_BLOCKS). require (block.number > placeBlockNumber, "settleBet in the same block as placeBet, or before."); require (block.number <= placeBlockNumber + BET_EXPIRATION_BLOCKS, "Blockhash can't be queried by EVM."); require (blockhash(placeBlockNumber) == blockHash); // Settle bet using reveal and blockHash as entropy sources. settleBetCommon(bet, reveal, blockHash); } // Common settlement code for settleBet & settleBetUncleMerkleProof. function settleBetCommon(Bet storage bet, uint reveal, bytes32 entropyBlockHash) private { // Fetch bet parameters into local variables (to save gas). uint amount = bet.amount; uint modulo = bet.modulo; uint rollUnder = bet.rollUnder; address gambler = bet.gambler; // Check that bet is in 'active' state. require (amount != 0, "Bet should be in an 'active' state"); // Move bet into 'processed' state already. bet.amount = 0; // The RNG - combine "reveal" and blockhash of placeBet using Keccak256. Miners // are not aware of "reveal" and cannot deduce it from "commit" (as Keccak256 // preimage is intractable), and house is unable to alter the "reveal" after // placeBet have been mined (as Keccak256 collision finding is also intractable). bytes32 entropy = keccak256(abi.encodePacked(reveal, entropyBlockHash)); // Do a roll by taking a modulo of entropy. Compute winning amount. uint dice = uint(entropy) % modulo; uint diceWinAmount; uint _jackpotFee; (diceWinAmount, _jackpotFee) = getDiceWinAmount(amount, modulo, rollUnder); uint diceWin = 0; uint jackpotWin = 0; // Determine dice outcome. if (modulo <= MAX_MASK_MODULO) { // For small modulo games, check the outcome against a bit mask. if ((2 ** dice) & bet.mask != 0) { diceWin = diceWinAmount; } } else { // For larger modulos, check inclusion into half-open interval. if (dice < rollUnder) { diceWin = diceWinAmount; } } // Unlock the bet amount, regardless of the outcome. lockedInBets -= uint128(diceWinAmount); // Roll for a jackpot (if eligible). if (amount >= MIN_JACKPOT_BET) { // The second modulo, statistically independent from the "main" dice roll. // Effectively you are playing two games at once! uint jackpotRng = (uint(entropy) / modulo) % JACKPOT_MODULO; // Bingo! if (jackpotRng == 0) { jackpotWin = jackpotSize; jackpotSize = 0; } } // Log jackpot win. if (jackpotWin > 0) { emit JackpotPayment(gambler, jackpotWin); } // Send the funds to gambler. sendFunds(gambler, diceWin + jackpotWin == 0 ? 1 wei : diceWin + jackpotWin, diceWin); } // Refund transaction - return the bet amount of a roll that was not processed in a // due timeframe. Processing such blocks is not possible due to EVM limitations (see // BET_EXPIRATION_BLOCKS comment above for details). In case you ever find yourself // in a situation like this, just contact the myethergames.fun support, however nothing // precludes you from invoking this method yourself. function refundBet(uint commit) external { // Check that bet is in 'active' state. Bet storage bet = bets[commit]; uint amount = bet.amount; require (amount != 0, "Bet should be in an 'active' state"); // Check that bet has already expired. require (block.number > bet.placeBlockNumber + BET_EXPIRATION_BLOCKS, "Blockhash can't be queried by EVM."); // Move bet into 'processed' state, release funds. bet.amount = 0; uint diceWinAmount; uint jackpotFee; (diceWinAmount, jackpotFee) = getDiceWinAmount(amount, bet.modulo, bet.rollUnder); lockedInBets -= uint128(diceWinAmount); jackpotSize -= uint128(jackpotFee); // Send the refund. sendFunds(bet.gambler, amount, amount); } // Get the expected win amount after house edge is subtracted. function getDiceWinAmount(uint amount, uint modulo, uint rollUnder) private pure returns (uint winAmount, uint jackpotFee) { require (0 < rollUnder && rollUnder <= modulo, "Win probability out of range."); jackpotFee = amount >= MIN_JACKPOT_BET ? JACKPOT_FEE : 0; uint houseEdge = amount * HOUSE_EDGE_PERCENT / 100; if (houseEdge < HOUSE_EDGE_MINIMUM_AMOUNT) { houseEdge = HOUSE_EDGE_MINIMUM_AMOUNT; } require (houseEdge + jackpotFee <= amount, "Bet doesn't even cover house edge."); winAmount = (amount - houseEdge - jackpotFee) * modulo / rollUnder; } // Helper routine to process the payment. function sendFunds(address beneficiary, uint amount, uint successLogAmount) private { if (beneficiary.send(amount)) { emit Payment(beneficiary, successLogAmount); } else { emit FailedPayment(beneficiary, amount); } } // This are some constants making O(1) population count in placeBet possible. // See whitepaper for intuition and proofs behind it. uint constant POPCNT_MULT = 0x0000000000002000000000100000000008000000000400000000020000000001; uint constant POPCNT_MASK = 0x0001041041041041041041041041041041041041041041041041041041041041; uint constant POPCNT_MODULO = 0x3F; }
Events that are issued to make statistic recovery easier.
event FailedPayment(address indexed beneficiary, uint amount);
889,079
[ 1, 3783, 716, 854, 16865, 358, 1221, 21605, 11044, 15857, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 871, 11175, 6032, 12, 2867, 8808, 27641, 74, 14463, 814, 16, 2254, 3844, 1769, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
//solium-disable linebreak-style pragma solidity ^0.5.0; contract Election{ // The address of the account that created this ballot. address public ballotCreator; constructor() public { ballotCreator = msg.sender; addCandidate(1,"Muhammed Buhari","All Progressive Party",0); addCandidate(2,"Atiku Abubakar","Peoples Democratic Party",0); //auctionEnd = now + (durationMins + 1 minutes); } //event AddedVoters(address indexed _sender, uint numVoters,bytes32 fullname,bytes32 nin,bytes32 addr,uint candidateIDVote,bool hasVoted); //Candidate[] public candidates; // Is voting finished? The ballot creator determines when to set this flag. bool public votingEnded; //event to add voters event addedVoters (bytes32 nin); // event Token(bytes32 token); event votedEvent (uint indexed _candidateId); event Deposit(address sender, uint256 amount); event Withdrawal (address receiver, uint256 amount); event Transfer(address from, address to, uint256 value); //mapping each candidate to their respective id mapping(uint => Candidate) public candidates; //mapping each voter to the Voter struct mapping(uint => Voter) public voters; //mapping that connects a voter to an address mapping(address => bool) public voted; mapping(address => uint256) public balances; // The total number of votes cast so far. Revealed before voting has ended. uint256 public totalVotes; uint candidatesCount; bytes32 token; uint numVoters; bytes32 voterList; //address public OfficialAccount = App.account; //uint256 bonus = 1 wei; //uint durationMins= 60; struct Candidate{ uint id; string name; string party; uint voteCount; } struct Voter{ uint id; bytes32 fullname; // bytes32 type are basically strings bytes32 nin; bytes32 addr; bytes32 phoneno; uint candidateIDVote; bool hasVoted; //address myAccount; } function addVoter(bytes32 fullname,bytes32 phoneno, bytes32 nin,bytes32 addr) public {//returns(uint) { //if(validVoter(nin) == true) { numVoters++; emit addedVoters(nin); voters[numVoters] = Voter(numVoters,fullname,nin,phoneno, addr,0,false); } function addCandidate (uint id, string memory _name, string memory party,uint voteCount) private { candidatesCount++; candidates[candidatesCount] = Candidate(candidatesCount, _name, party, 0); } function vote (uint _candidateId) public { //require that they havent voted require(!voted[msg.sender]); // can only vote during voting period // require(!votingEnded); // candidate must be part of the ballot // require(validCandidate(_candidateId)); require(_candidateId > 0 && _candidateId <= candidatesCount); // require(totalVotes < ~uint256(0)); require(candidates[_candidateId].voteCount < ~uint256(0)); voted[msg.sender] = true; candidates[_candidateId].voteCount++; emit votedEvent(_candidateId); } // function deposit() payable public returns (bool success) { // balances[msg.sender] +=msg.value; // emit Deposit(msg.sender, msg.value); // return true; // } // function withdraw(uint value) public returns(bool success){ // require(balances[msg.sender] < value); // balances[msg.sender]-=value; // msg.sender.transfer(value); // emit Withdrawal(msg.sender, value); // return true; // } function withdraw() public { msg.sender.transfer(address(this).balance); } function deposit(uint256 amount) payable public { require(msg.value == amount); // nothing else to do! } function getBalance() public view returns (uint256) { return address(this).balance; } // function transfer(address payable to, uint256 value) payable public returns (bool) { // require (balances[msg.sender] < value) ; // balances[msg.sender]-=value; // msg.sender.transfer(value); // emit Transfer(msg.sender, to, value); // return true; // } // function geToken() public returns (bytes32) { // emit Token(token); // return token; // } // function Award(address from) payable public returns (bool){ // //require(_to != address(0)); // from.transfer(bonus); // return true; // } /* function Award(address from, address coinAddress, address to) public returns(bool){ coinAddress.call(id,from,to,bonus) return true; } */ /* function Award() public payable { OfficialAccount = msg.sender; } function Award1() public payable { require(msg.value >= bonus); if (msg.value > bonus) { var Bonus = msg.value - bonus; msg.sender.transfer(Bonus); } } */ // function endVoting() public returns (bool) { // // Only ballot creator can end the vote. // require(msg.sender == ballotCreator); // votingEnded = true; // return true; // } // function totalVotesFor(uint _candidateId) view public returns (uint256) { // require(validCandidate(_candidateId)); // // Don't reveal votes until voting has ended // require(votingEnded); // return candidates[_candidateId].voteCount; // } function getNumOfCandidates() public view returns(uint) { return candidatesCount; } // function validCandidate(uint _candidateId) view public returns (bool) { // for(uint i = 0; i <candidatesCount; i++) { // if (candidates[_candidateId].id == _candidateId) { // return true; // } // } // return false; // } function getAccount(address account)view public returns(uint256){ return account.balance;} //can delete // function compare (string memory oldnin, string memory newnin) public pure returns (bool){ // return keccak256(abi.encodePacked(oldnin)) == keccak256(abi.encodePacked(newnin)); // } }
Is voting finished? The ballot creator determines when to set this flag.
bool public votingEnded;
1,758,904
[ 1, 2520, 331, 17128, 6708, 35, 1021, 26503, 352, 11784, 12949, 1347, 358, 444, 333, 2982, 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, 1426, 1071, 331, 17128, 28362, 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 ]
./full_match/1/0x30101C09adC32B486d27fe8F6997e825a27b9FC0/sources/@hashflow/contracts-evm/contracts/interfaces/IHashflowRouter.sol
@title IHashflowRouter @author Victor Ionescu* @notice In terms of user-facing functionality, the Router is responsible for: - orchestrating trades - managing cross-chain permissions Every trade requires consent from two parties: the Trader and the Market Maker. However, there are two models to establish consent: - RFQ-T: in this model, the Market Maker provides an EIP-191 signature for the quote, while the Trader signs the transaction and submits it on-chain - RFQ-M: in this model, the Trader provides an EIP-712 signature for the quote, the Market Maker provides an EIP-191 signature, and a 3rd party relays the trade. The 3rd party can be the Market Maker itself. In terms of Hashflow internals, the Router maintains a set of authorized pool contracts that are allowed to be used for trading. This allowlist creates guarantees against malicious behavior, as documented in specific places. The Router contract is not upgradeable. In order to change functionality, a new Router has to be deployed, and new HashflowPool contracts have to be deployed by the Market Makers./ @dev Trade / liquidity events are emitted at the HashflowPool level, rather than the router.
interface IHashflowRouter is IQuote { pragma solidity >=0.8.0; struct XChainFillMessage { uint16 srcHashflowChainId; bytes32 srcPool; address dstPool; address dstExternalAccount; address dstTrader; address quoteToken; uint256 quoteTokenAmount; bytes32 txid; bytes32 srcCaller; address dstContract; bytes dstContractCalldata; address indexed pool, uint16 otherHashflowChainId, bytes32 otherChainPool, bool authorized ); address indexed pool, uint16 otherHashflowChainId, bytes32 caller, bool authorized ); address indexed pool, address xChainMessenger, bool authorized ); address indexed callee, address xChainMessenger, bool authorized ); } event UpdatePoolAuthorizaton(address pool, bool authorized); event UpdateXChainPoolAuthorization( event UpdateXChainCallerAuthorization( event UpdateXChainMessengerAuthorization( event UpdateXChainMessengerCallerAuthorization( event UpdateLimitOrderGuardian(address guardian); }
8,324,347
[ 1, 45, 2310, 2426, 8259, 225, 776, 933, 280, 27081, 742, 89, 225, 657, 6548, 434, 729, 17, 507, 2822, 14176, 16, 326, 9703, 353, 14549, 364, 30, 300, 578, 23386, 1776, 1284, 5489, 300, 30632, 6828, 17, 5639, 4371, 16420, 18542, 4991, 28243, 628, 2795, 1087, 606, 30, 326, 2197, 765, 471, 326, 6622, 278, 490, 6388, 18, 10724, 16, 1915, 854, 2795, 3679, 358, 18312, 28243, 30, 300, 534, 23032, 17, 56, 30, 316, 333, 938, 16, 326, 6622, 278, 490, 6388, 8121, 392, 512, 2579, 17, 30380, 3372, 364, 326, 3862, 16, 282, 1323, 326, 2197, 765, 21588, 326, 2492, 471, 720, 22679, 518, 603, 17, 5639, 300, 534, 23032, 17, 49, 30, 316, 333, 938, 16, 326, 2197, 765, 8121, 392, 512, 2579, 17, 27, 2138, 3372, 364, 326, 3862, 16, 282, 326, 6622, 278, 490, 6388, 8121, 392, 512, 2579, 17, 30380, 3372, 16, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 5831, 467, 2310, 2426, 8259, 353, 467, 10257, 288, 203, 683, 9454, 18035, 560, 1545, 20, 18, 28, 18, 20, 31, 203, 565, 1958, 1139, 3893, 8026, 1079, 288, 203, 3639, 2254, 2313, 1705, 2310, 2426, 3893, 548, 31, 203, 3639, 1731, 1578, 1705, 2864, 31, 203, 3639, 1758, 3046, 2864, 31, 203, 3639, 1758, 3046, 6841, 3032, 31, 203, 3639, 1758, 3046, 1609, 765, 31, 203, 3639, 1758, 3862, 1345, 31, 203, 3639, 2254, 5034, 3862, 1345, 6275, 31, 203, 3639, 1731, 1578, 18372, 31, 203, 3639, 1731, 1578, 1705, 11095, 31, 203, 3639, 1758, 3046, 8924, 31, 203, 3639, 1731, 3046, 8924, 1477, 892, 31, 203, 203, 203, 3639, 1758, 8808, 2845, 16, 203, 3639, 2254, 2313, 1308, 2310, 2426, 3893, 548, 16, 203, 3639, 1731, 1578, 1308, 3893, 2864, 16, 203, 3639, 1426, 10799, 203, 565, 11272, 203, 203, 3639, 1758, 8808, 2845, 16, 203, 3639, 2254, 2313, 1308, 2310, 2426, 3893, 548, 16, 203, 3639, 1731, 1578, 4894, 16, 203, 3639, 1426, 10799, 203, 565, 11272, 203, 203, 3639, 1758, 8808, 2845, 16, 203, 3639, 1758, 619, 3893, 29329, 16, 203, 3639, 1426, 10799, 203, 565, 11272, 203, 203, 3639, 1758, 8808, 14425, 16, 203, 3639, 1758, 619, 3893, 29329, 16, 203, 3639, 1426, 10799, 203, 565, 11272, 203, 203, 203, 565, 289, 203, 565, 871, 2315, 2864, 3594, 452, 16799, 12, 2867, 2845, 16, 1426, 10799, 1769, 203, 565, 871, 2315, 60, 3893, 2864, 6063, 12, 203, 565, 871, 2315, 60, 3893, 11095, 6063, 12, 203, 565, 871, 2315, 2 ]
./partial_match/1/0x671E772987E70C279a926fc9c73d577bEDFcD29B/sources/src/L1/L1ScrollMessenger.sol
@notice The address of Rollup contract.
address public rollup;
16,051,117
[ 1, 1986, 1758, 434, 31291, 416, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 1758, 1071, 5824, 416, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// File @openzeppelin/contracts/math/[email protected] // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // 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/proxy/[email protected] // solhint-disable-next-line compiler-version pragma solidity >=0.4.24 <0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require( _initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized" ); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } // File @openzeppelin/contracts-upgradeable/utils/[email protected] pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { 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-upgradeable/access/[email protected] pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require( newOwner != address(0), "Ownable: new owner is the zero address" ); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } // File @openzeppelin/contracts-upgradeable/utils/[email protected] pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuardUpgradeable is Initializable { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; function __ReentrancyGuard_init() internal initializer { __ReentrancyGuard_init_unchained(); } function __ReentrancyGuard_init_unchained() internal initializer { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } uint256[49] private __gap; } // File @openzeppelin/contracts/token/ERC20/[email protected] pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval( address indexed owner, address indexed spender, uint256 value ); } // File @openzeppelin/contracts/utils/[email protected] pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require( address(this).balance >= amount, "Address: insufficient balance" ); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{value: amount}(""); require( success, "Address: unable to send value, recipient may have reverted" ); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue( target, data, value, "Address: low-level call with value failed" ); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require( address(this).balance >= value, "Address: insufficient balance for call" ); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{value: value}( data ); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall( target, data, "Address: low-level static call failed" ); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall( target, data, "Address: low-level delegate call failed" ); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) private pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File @openzeppelin/contracts/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 SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn( token, abi.encodeWithSelector(token.transfer.selector, to, value) ); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn( token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value) ); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn( token, abi.encodeWithSelector(token.approve.selector, spender, value) ); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender).add( value ); _callOptionalReturn( token, abi.encodeWithSelector( token.approve.selector, spender, newAllowance ) ); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender).sub( value, "SafeERC20: decreased allowance below zero" ); _callOptionalReturn( token, abi.encodeWithSelector( token.approve.selector, spender, newAllowance ) ); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall( data, "SafeERC20: low-level call failed" ); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require( abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed" ); } } } // File contracts/DePoMasterChef.sol //** DePo MasterChef Contract */ //** Author Alex Hong : DePo Finance 2021.10 */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; contract DePoMasterChef is OwnableUpgradeable, ReentrancyGuardUpgradeable { 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. uint256 rewardLockedUp; // Reward locked up. uint256 nextHarvestUntil; // When can the user harvest again. // // We do some fancy math here. Basically, any point in time, the amount of DePos // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accDePoPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accDePoPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. DePos to distribute per block. uint256 lastRewardBlock; // Last block number that DePos distribution occurs. uint256 accDePoPerShare; // Accumulated DePos per share, times 1e12. See below. uint16 depositFeeBP; // Deposit fee in basis points uint256 harvestInterval; // Harvest interval in seconds } // The DePo TOKEN! IERC20 public depo; // Deposit Fee address address public feeAddress; // Reward tokens holder address address public rewardHolder; // DePos tokens created per block. 0.5 DePo per block. 10% to depo charity ( address ) uint256 public depoPerBlock; // Bonus muliplier for early depo makers. uint256 public constant BONUS_MULTIPLIER = 1; // Max harvest interval: 14 days. uint256 public constant MAXIMUM_HARVEST_INTERVAL = 10 days; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping(uint256 => mapping(address => UserInfo)) public userInfo; // Total allocation points. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint; // The block number when DePos mining starts. uint256 public startBlock; // Total locked up rewards uint256 public totalLockedUpRewards; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event Compound(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw( address indexed user, uint256 indexed pid, uint256 amount ); event EmissionRateUpdated( address indexed caller, uint256 previousAmount, uint256 newAmount ); event RewardLockedUp( address indexed user, uint256 indexed pid, uint256 amountLockedUp ); function initialize( address _depo, address _feeAddress, address _rewardHolder, uint256 _startBlock, uint256 _depoPerBlock ) public initializer { depo = IERC20(_depo); rewardHolder = _rewardHolder; startBlock = _startBlock; depoPerBlock = _depoPerBlock; feeAddress = _feeAddress; totalAllocPoint = 0; __Ownable_init(); __ReentrancyGuard_init(); } function poolLength() external view returns (uint256) { return poolInfo.length; } // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add( uint256 _allocPoint, IERC20 _lpToken, uint16 _depositFeeBP, uint256 _harvestInterval, bool _withUpdate ) public onlyOwner { require(_depositFeeBP <= 500, "add: invalid deposit fee basis points"); require( _harvestInterval <= MAXIMUM_HARVEST_INTERVAL, "add: invalid harvest interval" ); if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push( PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accDePoPerShare: 0, depositFeeBP: _depositFeeBP, harvestInterval: _harvestInterval }) ); } // Update the given pool's DePos allocation point and deposit fee. Can only be called by the owner. function set( uint256 _pid, uint256 _allocPoint, uint16 _depositFeeBP, uint256 _harvestInterval, bool _withUpdate ) public onlyOwner { require(_depositFeeBP <= 500, "set: invalid deposit fee basis points"); require( _harvestInterval <= MAXIMUM_HARVEST_INTERVAL, "set: invalid harvest interval" ); if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add( _allocPoint ); poolInfo[_pid].allocPoint = _allocPoint; poolInfo[_pid].depositFeeBP = _depositFeeBP; poolInfo[_pid].harvestInterval = _harvestInterval; } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public pure returns (uint256) { return _to.sub(_from).mul(BONUS_MULTIPLIER); } // View function to see pending DePos on frontend. function pendingDePo(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accDePoPerShare = pool.accDePoPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier( pool.lastRewardBlock, block.number ); uint256 depoReward = multiplier .mul(depoPerBlock) .mul(pool.allocPoint) .div(totalAllocPoint); accDePoPerShare = accDePoPerShare.add( depoReward.mul(1e12).div(lpSupply) ); } uint256 pending = user.amount.mul(accDePoPerShare).div(1e12).sub( user.rewardDebt ); return pending.add(user.rewardLockedUp); } // View function to see if user can harvest DePos. function canHarvest(uint256 _pid, address _user) public view returns (bool) { UserInfo storage user = userInfo[_pid][_user]; return block.timestamp >= user.nextHarvestUntil; } // Update reward variables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0 || pool.allocPoint == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 depoReward = multiplier .mul(depoPerBlock) .mul(pool.allocPoint) .div(totalAllocPoint); pool.accDePoPerShare = pool.accDePoPerShare.add( depoReward.mul(1e12).div(lpSupply) ); pool.lastRewardBlock = block.number; } // Deposit LP tokens to MasterChef for DePos allocation. function deposit(uint256 _pid, uint256 _amount) public nonReentrant { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); payOrLockupPendingDePo(_pid); if (_amount > 0) { pool.lpToken.safeTransferFrom( address(msg.sender), address(this), _amount ); if (pool.depositFeeBP > 0) { uint256 depositFee = _amount.mul(pool.depositFeeBP).div(10000); pool.lpToken.safeTransfer(feeAddress, depositFee); user.amount = user.amount.add(_amount).sub(depositFee); } else { user.amount = user.amount.add(_amount); } } user.rewardDebt = user.amount.mul(pool.accDePoPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // Withdraw LP tokens from MasterChef. function withdraw(uint256 _pid, uint256 _amount) public nonReentrant { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); payOrLockupPendingDePo(_pid); if (_amount > 0) { user.amount = user.amount.sub(_amount); pool.lpToken.safeTransfer(address(msg.sender), _amount); } user.rewardDebt = user.amount.mul(pool.accDePoPerShare).div(1e12); emit Withdraw(msg.sender, _pid, _amount); } // Compound tokens to DePo pool. function compound(uint256 _pid) public nonReentrant { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require( address(pool.lpToken) == address(depo), "compound: not able to compound" ); updatePool(_pid); uint256 pending = user.amount.mul(pool.accDePoPerShare).div(1e12).sub( user.rewardDebt ); safeDePoTransferFrom(rewardHolder, address(this), pending); user.amount = user.amount.add(pending); user.rewardDebt = user.amount.mul(pool.accDePoPerShare).div(1e12); emit Compound(msg.sender, _pid, pending); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public nonReentrant { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; uint256 amount = user.amount; user.amount = 0; user.rewardDebt = 0; user.rewardLockedUp = 0; user.nextHarvestUntil = 0; pool.lpToken.safeTransfer(address(msg.sender), amount); emit EmergencyWithdraw(msg.sender, _pid, amount); } // Pay or lockup pending DePos. function payOrLockupPendingDePo(uint256 _pid) internal { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; if (user.nextHarvestUntil == 0) { user.nextHarvestUntil = block.timestamp.add(pool.harvestInterval); } uint256 pending = user.amount.mul(pool.accDePoPerShare).div(1e12).sub( user.rewardDebt ); if (canHarvest(_pid, msg.sender)) { if (pending > 0 || user.rewardLockedUp > 0) { uint256 totalRewards = pending.add(user.rewardLockedUp); // reset lockup totalLockedUpRewards = totalLockedUpRewards.sub( user.rewardLockedUp ); user.rewardLockedUp = 0; user.nextHarvestUntil = block.timestamp.add( pool.harvestInterval ); // send rewards safeDePoTransferFrom(rewardHolder, msg.sender, totalRewards); } } else if (pending > 0) { user.rewardLockedUp = user.rewardLockedUp.add(pending); totalLockedUpRewards = totalLockedUpRewards.add(pending); emit RewardLockedUp(msg.sender, _pid, pending); } } // Safe DePo transfer function, just in case if rounding error causes pool to not have enough depos. function safeDePoTransferFrom( address _from, address _to, uint256 _amount ) internal { uint256 depoBal = depo.balanceOf(rewardHolder); if (_amount > depoBal) { revert("Not enough balance"); } else { depo.transferFrom(_from, _to, _amount); } } function setFeeAddress(address _feeAddress) public { require(msg.sender == feeAddress, "setFeeAddress: FORBIDDEN"); require(_feeAddress != address(0), "setFeeAddress: ZERO"); feeAddress = _feeAddress; } function setRewardHolder(address _rewardHolder) public { require(msg.sender == rewardHolder, "setRewardHolder: FORBIDDEN"); require(_rewardHolder != address(0), "setRewardHolder: ZERO"); rewardHolder = _rewardHolder; } // Pancake has to add hidden dummy pools in order to alter the emission, here we make it simple and transparent to all. function updateEmissionRate(uint256 _depoPerBlock) public onlyOwner { massUpdatePools(); emit EmissionRateUpdated(msg.sender, depoPerBlock, _depoPerBlock); depoPerBlock = _depoPerBlock; } }
* @dev Indicates that the contract has been initialized./* @dev Indicates that the contract is in the process of being initialized./* @dev Modifier to protect an initializer function from being invoked twice./
modifier initializer() { require( _initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized" ); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } }
600,567
[ 1, 23741, 716, 326, 6835, 711, 2118, 6454, 18, 19, 225, 18336, 716, 326, 6835, 353, 316, 326, 1207, 434, 3832, 6454, 18, 19, 225, 12832, 358, 17151, 392, 12562, 445, 628, 3832, 8187, 13605, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 9606, 12562, 1435, 288, 203, 3639, 2583, 12, 203, 5411, 389, 6769, 6894, 747, 389, 291, 6293, 1435, 747, 401, 67, 13227, 16, 203, 5411, 315, 4435, 6934, 30, 6835, 353, 1818, 6454, 6, 203, 3639, 11272, 203, 203, 3639, 1426, 353, 27046, 1477, 273, 401, 67, 6769, 6894, 31, 203, 3639, 309, 261, 291, 27046, 1477, 13, 288, 203, 5411, 389, 6769, 6894, 273, 638, 31, 203, 5411, 389, 13227, 273, 638, 31, 203, 3639, 289, 203, 203, 3639, 389, 31, 203, 203, 3639, 309, 261, 291, 27046, 1477, 13, 288, 203, 5411, 389, 6769, 6894, 273, 629, 31, 203, 3639, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
//SPDX-License-Identifier: MIT pragma solidity 0.7.5; /*unaudited and for demonstration only, subject to all disclosures, licenses, and caveats of the open-source-law repo **@dev create a simple smart escrow contract, with an ERC20 stablecoin as payment, expiration denominated in seconds, and option for dispute resolution with LexLocker **intended to be deployed by buyer (as funds are placed in escrow upon deployment, and returned to deployer if expired)*/ interface LexLocker { function requestLockerResolution(address counterparty, address resolver, address token, uint256 sum, string calldata details, bool swiftResolver) external payable returns (uint256); } interface IERC20 { function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); } contract EscrowStablecoin { //escrow struct to contain basic description of underlying deal, purchase price, seller (ultimate recipient of funds) struct InEscrow { string description; uint256 deposit; address payable seller; } InEscrow[] public escrows; address escrowAddress; address payable lexlocker = payable(0xD476595aa1737F5FdBfE9C8FEa17737679D9f89a); //LexLocker contract address address payable lexDAO = payable(0x01B92E2C0D06325089c6Fd53C98a214f5C75B2aC); //lexDAO address, used below as resolver address payable buyer; address payable seller; address stablecoin; uint256 deposit; uint256 deployTime; uint256 effectiveTime; uint256 expirationTime; bool sellerApproved; bool buyerApproved; bool isDisputed; bool isExpired; bool isClosed; IERC20 public ierc20; string description; mapping(address => bool) public parties; //map whether an address is a party to the transaction for restricted() modifier event DealDisputed(address indexed sender, bool isDisputed); //index dispute by sender, consider including token/resolver/other identifier event DealExpired(bool isExpired); event DealClosed(bool isClosed, uint256 effectiveTime); modifier restricted() { require(parties[msg.sender], "This may only be called by a party to the deal or the by escrow contract"); _; } //deployer (buyer) initiates escrow with description, deposit amount in USD, address of stablecoin, seconds until expiry, and designate recipient seller //DEPLOYER MUST SEPARATELY APPROVE (by interacting with the ERC20 contract in question's approve()) this contract address for the deposit amount (keep decimals in mind) constructor(string memory _description, uint256 _deposit, address payable _seller, address _stablecoin, uint256 _secsUntilExpiration) payable { require(_seller != msg.sender, "Designate different party as seller"); buyer = payable(address(msg.sender)); deposit = _deposit; escrowAddress = address(this); stablecoin = _stablecoin; ierc20 = IERC20(stablecoin); description = _description; seller = _seller; parties[msg.sender] = true; parties[_seller] = true; parties[escrowAddress] = true; deployTime = uint256(block.timestamp); expirationTime = deployTime + _secsUntilExpiration; approveParties(); } //buyer may confirm seller's recipient address as extra security measure function designateSeller(address payable _seller) public restricted { require(_seller != seller, "Party already designated as seller"); require(_seller != buyer, "Buyer cannot also be seller"); require(!isExpired, "Too late to change seller"); parties[_seller] = true; seller = _seller; } //approve seller to withdraw deposit amount at closing and buyer in case of termination (and therefore deposit return) function approveParties() public restricted returns (bool) { ierc20.allowance(escrowAddress, seller); ierc20.approve(seller, deposit); ierc20.approve(buyer, deposit); return true; } //buyer deposits in escrowAddress function sendDeposit() public restricted returns(bool, uint256) { ierc20.transferFrom(buyer, escrowAddress, deposit); return (true, ierc20.balanceOf(escrowAddress)); } //return deposit to buyer function returnDeposit() internal returns(bool, uint256) { ierc20.transfer(buyer, deposit); return (true, ierc20.balanceOf(escrowAddress)); } //send deposit to seller function paySeller() internal returns(bool, uint256) { ierc20.transfer(seller, deposit); return (true, ierc20.balanceOf(escrowAddress)); } //create new escrow contract within master structure function sendNewEscrow(string memory _description, uint256 _deposit, address payable _seller) private restricted { InEscrow memory newRequest = InEscrow({ description: _description, deposit: _deposit, seller: _seller }); escrows.push(newRequest); } //check if expired, and if so, return balance to buyer function checkIfExpired() public returns(bool){ if (expirationTime <= uint256(block.timestamp)) { isExpired = true; returnDeposit(); emit DealExpired(isExpired); } else { isExpired = false; } return(isExpired); } // for seller to check if deposit is in escrow function checkEscrow() public restricted view returns(uint256) { return ierc20.balanceOf(escrowAddress); } // for early termination by either buyer or seller due to claimed breach of the other party, claiming party requests LexLocker resolution // deposit either returned to buyer or remitted to seller as payment or liquidated damages function disputeDeal(address _token, string calldata _details, bool _singleArbiter) public restricted returns(string memory){ require(!isClosed && !isExpired, "Too late for early termination"); ierc20.approve(lexlocker, deposit); if (msg.sender == seller) { LexLocker(lexlocker).requestLockerResolution(buyer, lexDAO, _token, deposit, _details, _singleArbiter); ierc20.transferFrom(escrowAddress, lexlocker, deposit); isDisputed = true; emit DealDisputed(seller, isDisputed); return("Seller has initiated LexLocker dispute resolution."); } else if (msg.sender == buyer) { LexLocker(lexlocker).requestLockerResolution(seller, lexDAO, _token, deposit, _details, _singleArbiter); ierc20.transferFrom(escrowAddress, lexlocker, deposit); isDisputed = true; emit DealDisputed(buyer, isDisputed); return("Buyer has initiated Lexlocker dispute resolution."); } else { return("You are neither buyer nor seller."); } } function readyToClose() public restricted returns(string memory){ if (msg.sender == seller) { sellerApproved = true; return("Seller is ready to close."); } else if (msg.sender == buyer) { buyerApproved = true; return("Buyer is ready to close."); } else { return("You are neither buyer nor seller."); } } // check if both buyer and seller are ready to close and expiration has not been met; if so, close deal and pay seller // if properly closes, emits event with effective time of closing function closeDeal() public returns(bool){ require(sellerApproved && buyerApproved, "Parties are not ready to close."); if (expirationTime <= uint256(block.timestamp)) { isExpired = true; returnDeposit(); emit DealExpired(isExpired); } else { isClosed = true; paySeller(); effectiveTime = uint256(block.timestamp); // effective time of closing upon payment to seller emit DealClosed(isClosed, effectiveTime); } return(isClosed); } }
approve seller to withdraw deposit amount at closing and buyer in case of termination (and therefore deposit return)
function approveParties() public restricted returns (bool) { ierc20.allowance(escrowAddress, seller); ierc20.approve(seller, deposit); ierc20.approve(buyer, deposit); return true; }
13,044,329
[ 1, 12908, 537, 29804, 358, 598, 9446, 443, 1724, 3844, 622, 7647, 471, 27037, 316, 648, 434, 19650, 261, 464, 13526, 443, 1724, 327, 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 ]
[ 1, 1, 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, 225, 445, 6617, 537, 1988, 606, 1435, 1071, 15693, 1135, 261, 6430, 13, 288, 203, 1377, 277, 12610, 3462, 18, 5965, 1359, 12, 742, 492, 1887, 16, 29804, 1769, 203, 1377, 277, 12610, 3462, 18, 12908, 537, 12, 1786, 749, 16, 443, 1724, 1769, 203, 1377, 277, 12610, 3462, 18, 12908, 537, 12, 70, 16213, 16, 443, 1724, 1769, 203, 1377, 327, 638, 31, 203, 225, 289, 7010, 21281, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/3/0x39361200639A6cb727a33f493739034505D1A933/sources/browser/Funding.sol
Limit withdrawal amount Send the amount to the address that requested it
function withdraw(uint withdraw_amount) public { require(withdraw_amount >= 1 ether); msg.sender.transfer(withdraw_amount); }
8,088,624
[ 1, 3039, 598, 9446, 287, 3844, 2479, 326, 3844, 358, 326, 1758, 716, 3764, 518, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 598, 9446, 12, 11890, 598, 9446, 67, 8949, 13, 1071, 288, 203, 203, 3639, 2583, 12, 1918, 9446, 67, 8949, 1545, 404, 225, 2437, 1769, 203, 203, 3639, 1234, 18, 15330, 18, 13866, 12, 1918, 9446, 67, 8949, 1769, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/* Copyright 2019 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.5.9; import "./TestRefundable.sol"; contract TestRefundableReceiver { /// @dev A payable fallback function is necessary to receive refunds from the `TestRefundable` contract. /// This function ensures that zero value is not sent to the contract, which tests the feature of /// of the `refundNonzeroBalance` that doesn't transfer if the balance is zero. function () external payable { // Ensure that a value of zero was not transferred to the contract. require(msg.value != 0, "Zero value should not be sent to this contract."); } /// @dev This function tests the behavior of the `refundNonzeroBalance` function by checking whether or /// not the `callCounter` state variable changes after the `refundNonzeroBalance` is called. /// @param testRefundable The TestRefundable that should be tested against. function testRefundNonZeroBalance(TestRefundable testRefundable) external payable { // Call `refundNonzeroBalance()` and forward all of the eth sent to the contract. testRefundable.refundNonZeroBalanceExternal.value(msg.value)(); // If the value sent was nonzero, a check that a refund was received will be executed. Otherwise, the fallback // function contains a check that will fail in the event that a value of zero was sent to the contract. if (msg.value > 0) { // Ensure that a full refund was provided to this contract. require(address(this).balance == msg.value, "A full refund was not provided by `refundNonzeroBalance`"); } } /// @dev This function tests the behavior to a simple call to `refundFinalBalanceFunction`. This /// test will verify that the correct refund was provided after the call (depending on whether /// a refund should be provided), and it will ensure that the `shouldNotRefund` state variable /// remains unaltered after the function call. /// @param testRefundable The TestRefundable that should be tested against. /// @param shouldNotRefund The value that shouldNotRefund should be set to before the call to TestRefundable. function testRefundFinalBalance( TestRefundable testRefundable, bool shouldNotRefund ) external payable { // Set `shouldNotRefund` to the specified bool. testRefundable.setShouldNotRefund(shouldNotRefund); // Call `refundFinalBalanceFunction` and forward all value from the contract. testRefundable.refundFinalBalanceFunction.value(msg.value)(); // Assert that the expected refunds happened and that the `shouldNotRefund` value was // set back to an unaltered state after the call. requireCorrectFinalBalancesAndState(testRefundable, shouldNotRefund); } /// @dev This function tests the behavior to a simple call to `disableRefundUntilEndFunction`. This /// test will verify that the correct refund was provided after the call (depending on whether /// a refund should be provided), and it will ensure that the `shouldNotRefund` state variable /// remains unaltered after the function call. /// @param testRefundable The TestRefundable that should be tested against. /// @param shouldNotRefund The value that shouldNotRefund should be set to before the call to TestRefundable. function testDisableRefundUntilEnd( TestRefundable testRefundable, bool shouldNotRefund ) external payable { // Set `shouldNotRefund` to the specified bool. testRefundable.setShouldNotRefund(shouldNotRefund); // Call `disableRefundUntilEndFunction` and forward all value from the contract. testRefundable.disableRefundUntilEndFunction.value(msg.value)(); // Assert that the expected refunds happened and that the `shouldNotRefund` value was // set back to an unaltered state after the call. requireCorrectFinalBalancesAndState(testRefundable, shouldNotRefund); } /// @dev This function tests the behavior of a call to a function that has the `disableRefundUntilEndFunction`. /// The function that is called also uses the `disableRefundUntilEndFunction`, so this function's role is /// to verify that both the inner and outer modifiers worked correctly. /// @param testRefundable The TestRefundable that should be tested against. /// @param shouldNotRefund The value that shouldNotRefund should be set to before the call to TestRefundable. function testNestedDisableRefundUntilEnd( TestRefundable testRefundable, bool shouldNotRefund ) external payable { // Set `shouldNotRefund` to the specified bool. testRefundable.setShouldNotRefund(shouldNotRefund); // Call `nestedDisableRefundUntilEndFunction` and forward all value from the contract. uint256 balanceWithinCall = testRefundable.nestedDisableRefundUntilEndFunction.value(msg.value)(); // Ensure that the balance within the call was equal to `msg.value` since the inner refund should // not have been triggered regardless of the value of `shouldNotRefund`. require(balanceWithinCall == msg.value, "Incorrect inner balance"); // Assert that the expected refunds happened and that the `shouldNotRefund` value was // set back to an unaltered state after the call. requireCorrectFinalBalancesAndState(testRefundable, shouldNotRefund); } /// @dev This function tests the behavior of a call to a function that has the `disableRefundUntilEndFunction`. /// The function that is called uses the `refundFinalBalanceFunction`, so this function's role is /// to verify that both the inner and outer modifiers worked correctly. /// @param testRefundable The TestRefundable that should be tested against. /// @param shouldNotRefund The value that shouldNotRefund should be set to before the call to TestRefundable. function testMixedRefunds( TestRefundable testRefundable, bool shouldNotRefund ) external payable { // Set `shouldNotRefund` to the specified bool. testRefundable.setShouldNotRefund(shouldNotRefund); // Call `mixedRefundModifierFunction` and forward all value from the contract. uint256 balanceWithinCall = testRefundable.mixedRefundModifierFunction.value(msg.value)(); // Ensure that the balance within the call was equal to `msg.value` since the inner refund should // not have been triggered regardless of the value of `shouldNotRefund`. require(balanceWithinCall == msg.value, "Incorrect inner balance"); // Assert that the expected refunds happened and that the `shouldNotRefund` value was // set back to an unaltered state after the call. requireCorrectFinalBalancesAndState(testRefundable, shouldNotRefund); } /// @dev This helper function verifies the final balances of this receiver contract and a specified /// refundable contract and verifies that the `shouldNotRefund` value remains unaltered. /// @param testRefundable The TestRefundable that should be tested against. /// @param shouldNotRefund The value that shouldNotRefund was set to before the call to TestRefundable. function requireCorrectFinalBalancesAndState( TestRefundable testRefundable, bool shouldNotRefund ) internal { // If `shouldNotRefund` was true, then this contract should have a balance of zero, // and `testRefundable` should have a balance of `msg.value`. Otherwise, the opposite // should be true. if (shouldNotRefund) { // Ensure that this contract's balance is zero. require(address(this).balance == 0, "Incorrect balance for TestRefundableReceiver"); // Ensure that the other contract's balance is equal to `msg.value`. require(address(testRefundable).balance == msg.value, "Incorrect balance for TestRefundable"); } else { // Ensure that this contract's balance is `msg.value`. require(address(this).balance == msg.value, "Incorrect balance for TestRefundableReceiver"); // Ensure that the other contract's balance is equal to zero. require(address(testRefundable).balance == 0, "Incorrect balance for TestRefundable"); } // Ensure that `shouldNotRefund` in TestRefundable is set to the parameter `shouldNotRefund` // after the call (i.e. the value didn't change during the function call). require(testRefundable.getShouldNotRefund() == shouldNotRefund, "Incorrect shouldNotRefund value"); // Drain the contract of funds so that subsequent tests don't have to account for leftover ether. msg.sender.transfer(address(this).balance); } }
@dev This function tests the behavior to a simple call to `refundFinalBalanceFunction`. This test will verify that the correct refund was provided after the call (depending on whether a refund should be provided), and it will ensure that the `shouldNotRefund` state variable remains unaltered after the function call. @param testRefundable The TestRefundable that should be tested against. @param shouldNotRefund The value that shouldNotRefund should be set to before the call to TestRefundable. Set `shouldNotRefund` to the specified bool. Call `refundFinalBalanceFunction` and forward all value from the contract. Assert that the expected refunds happened and that the `shouldNotRefund` value was set back to an unaltered state after the call.
function testRefundFinalBalance( TestRefundable testRefundable, bool shouldNotRefund ) external payable { testRefundable.setShouldNotRefund(shouldNotRefund); testRefundable.refundFinalBalanceFunction.value(msg.value)(); requireCorrectFinalBalancesAndState(testRefundable, shouldNotRefund); }
6,412,647
[ 1, 2503, 445, 7434, 326, 6885, 358, 279, 4143, 745, 358, 1375, 1734, 1074, 7951, 13937, 2083, 8338, 1220, 1377, 1842, 903, 3929, 716, 326, 3434, 16255, 1703, 2112, 1839, 326, 745, 261, 5817, 310, 603, 2856, 1377, 279, 16255, 1410, 506, 2112, 3631, 471, 518, 903, 3387, 716, 326, 1375, 13139, 1248, 21537, 68, 919, 2190, 1377, 22632, 640, 22628, 329, 1839, 326, 445, 745, 18, 225, 1842, 21537, 429, 1021, 7766, 21537, 429, 716, 1410, 506, 18432, 5314, 18, 225, 1410, 1248, 21537, 1021, 460, 716, 1410, 1248, 21537, 1410, 506, 444, 358, 1865, 326, 745, 358, 7766, 21537, 429, 18, 1000, 1375, 13139, 1248, 21537, 68, 358, 326, 1269, 1426, 18, 3049, 1375, 1734, 1074, 7951, 13937, 2083, 68, 471, 5104, 777, 460, 628, 326, 6835, 18, 5452, 716, 326, 2665, 16255, 87, 17497, 471, 716, 326, 1375, 13139, 1248, 21537, 68, 460, 1703, 444, 1473, 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, 1842, 21537, 7951, 13937, 12, 203, 3639, 7766, 21537, 429, 1842, 21537, 429, 16, 203, 3639, 1426, 1410, 1248, 21537, 203, 565, 262, 203, 3639, 3903, 203, 3639, 8843, 429, 203, 565, 288, 203, 3639, 1842, 21537, 429, 18, 542, 14309, 1248, 21537, 12, 13139, 1248, 21537, 1769, 203, 203, 3639, 1842, 21537, 429, 18, 1734, 1074, 7951, 13937, 2083, 18, 1132, 12, 3576, 18, 1132, 13, 5621, 203, 203, 3639, 2583, 16147, 7951, 38, 26488, 1876, 1119, 12, 3813, 21537, 429, 16, 1410, 1248, 21537, 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 ]
./full_match/1/0x45F97D07dAB04B21F36fA3b1149c35e316b35d03/sources/contracts/PirexCvx.sol
/ Used to update the redeemed flag locally before updating to the storage all at once for gas efficiency Check whether msg.sender maintained a positive balance before the snapshot
function redeemSnapshotRewards( uint256 epoch, uint256[] calldata rewardIndexes, address receiver ) external whenNotPaused nonReentrant { if (epoch == 0) revert InvalidEpoch(); if (receiver == address(0)) revert ZeroAddress(); uint256 rewardLen = rewardIndexes.length; if (rewardLen == 0) revert EmptyArray(); ( uint256 snapshotId, bytes32[] memory rewards, uint256[] memory snapshotRewards, ) = pxCvx.getEpoch(epoch); uint256 redeemed = pxCvx.getEpochRedeemedSnapshotRewards( msg.sender, epoch ); uint256 snapshotBalance = pxCvx.balanceOfAt(msg.sender, snapshotId); uint256 snapshotSupply = pxCvx.totalSupplyAt(snapshotId); if (snapshotBalance == 0) revert InsufficientBalance(); emit RedeemSnapshotRewards( epoch, rewardIndexes, receiver, snapshotBalance, snapshotSupply ); for (uint256 i; i < rewardLen; ++i) { uint256 index = rewardIndexes[i]; uint256 indexRedeemed = (1 << index); if ((redeemed & indexRedeemed) != 0) revert AlreadyRedeemed(); redeemed |= indexRedeemed; ERC20(address(uint160(bytes20(rewards[index])))).safeTransfer( receiver, (snapshotRewards[index] * snapshotBalance) / snapshotSupply ); } } @param epoch uint256 Epoch (ERC1155 token id) @param receiver address Receives futures rewards
16,476,814
[ 1, 19, 10286, 358, 1089, 326, 283, 24903, 329, 2982, 13760, 1865, 9702, 358, 326, 2502, 777, 622, 3647, 364, 16189, 30325, 2073, 2856, 1234, 18, 15330, 11566, 8707, 279, 6895, 11013, 1865, 326, 4439, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 565, 445, 283, 24903, 4568, 17631, 14727, 12, 203, 3639, 2254, 5034, 7632, 16, 203, 3639, 2254, 5034, 8526, 745, 892, 19890, 8639, 16, 203, 3639, 1758, 5971, 203, 565, 262, 3903, 1347, 1248, 28590, 1661, 426, 8230, 970, 288, 203, 3639, 309, 261, 12015, 422, 374, 13, 15226, 1962, 14638, 5621, 203, 3639, 309, 261, 24454, 422, 1758, 12, 20, 3719, 15226, 12744, 1887, 5621, 203, 203, 3639, 2254, 5034, 19890, 2891, 273, 19890, 8639, 18, 2469, 31, 203, 203, 3639, 309, 261, 266, 2913, 2891, 422, 374, 13, 15226, 8953, 1076, 5621, 203, 203, 3639, 261, 203, 5411, 2254, 5034, 4439, 548, 16, 203, 5411, 1731, 1578, 8526, 3778, 283, 6397, 16, 203, 5411, 2254, 5034, 8526, 3778, 4439, 17631, 14727, 16, 203, 203, 3639, 262, 273, 10318, 39, 26982, 18, 588, 14638, 12, 12015, 1769, 203, 203, 3639, 2254, 5034, 283, 24903, 329, 273, 10318, 39, 26982, 18, 588, 14638, 426, 24903, 329, 4568, 17631, 14727, 12, 203, 5411, 1234, 18, 15330, 16, 203, 5411, 7632, 203, 3639, 11272, 203, 203, 3639, 2254, 5034, 4439, 13937, 273, 10318, 39, 26982, 18, 12296, 951, 861, 12, 3576, 18, 15330, 16, 4439, 548, 1769, 203, 3639, 2254, 5034, 4439, 3088, 1283, 273, 10318, 39, 26982, 18, 4963, 3088, 1283, 861, 12, 11171, 548, 1769, 203, 203, 3639, 309, 261, 11171, 13937, 422, 374, 13, 15226, 22085, 11339, 13937, 5621, 203, 203, 3639, 3626, 868, 24903, 4568, 17631, 14727, 12, 203, 5411, 7632, 16, 203, 5411, 19890, 8639, 16, 203, 5411, 5971, 16, 203, 2 ]
// SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "openzeppelin-solidity/contracts/GSN/Context.sol"; import "../VOTEDAO.sol"; import "./IOwnable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there are accounts (owners group) 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} and {addOwnership} or * {deleteOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner(n)`, which can be applied to your functions to restrict their use * to the owner and owner's access level. * * There are multiple levels (0~) and the higher level takes more accessability. * Zero means no accessability. * * {transferOwnership} can be called by only himself, but {addOwnership} and * {deleteOwnership} can be called by the others. If so, level-weighted voting * is started to decide the action. * * References: * * - openzeppelin-solidity/contracts/access/Ownable.sol */ contract OWNEDAO is Context, VOTEDAO, IOwnable { mapping(address => uint8) private _owners; /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor ( // ... ) internal { address msgSender = _msgSender(); // TODO: MUST require some deposit to enter DAO. uint8 level = uint8(-1); // Max level _owners[msgSender] = level; emit OwnershipTransferred(address(0), msgSender, level); } /** * @dev Returns the level of the owner. */ function levelOf( address owner ) public view override returns (uint8) { return _owners[owner]; } /** * @dev Returns the level of the owner. */ function isValid( address owner, uint8 level ) public view override returns (bool) { return _owners[owner] >= level; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner( uint8 level ) override { require(_owners[_msgSender()] >= level, "Ownable: caller has no accessability."); _; } /** * @dev Requests the adding ownership. */ function addOwnershipRequest( address account, uint8 level, uint256 timeLimit ) public returns ( bytes32 key_, uint256 campaignNum_ ) { // "addOwnership" bytes32 name_ = 0x6164644f776e6572736869700000000000000000000000000000000000000000; bytes32[] memory arguments_ = new bytes32[](2); arguments_[0] = bytes32(bytes20(account)); arguments_[1] = bytes32(uint256(level)); return vSendRequest(name_, arguments_, timeLimit); } /** * @dev Adds the ownership. */ function addOwnership( address account, uint8 level, bytes32 key_ ) public returns (bool) { // "addOwnership" bytes32 name_ = 0x6164644f776e6572736869700000000000000000000000000000000000000000; bytes32[] memory arguments_ = new bytes32[](2); arguments_[0] = bytes32(bytes20(account)); arguments_[1] = bytes32(uint256(level)); // conditions require(vResolveRequest(name_, arguments_, key_)); /* body start */ _addOwnership(account, level); /* body end */ return true; } /** * @dev Requests the deleting ownership. */ function deleteOwnershipRequest( address account, uint256 timeLimit ) public returns ( bytes32 key_, uint256 campaignNum_ ) { // "deleteOwnership" bytes32 name_ = 0x64656c6574654f776e6572736869700000000000000000000000000000000000; bytes32[] memory arguments_ = new bytes32[](1); arguments_[0] = bytes32(bytes20(account)); return vSendRequest(name_, arguments_, timeLimit); } /** * @dev Leaves the contract. It will not be possible to call `onlyOwner` * functions anymore if there are no other owners. * * Can be called by himself. * * NOTE: Renouncing ownership can cause removing any functionality that * is only available to the owners. */ function deleteOwnership( // ... ) public returns (bool) { address msgSender = _msgSender(); _deleteOwnership(msgSender); return true; } /** * @dev Leaves the contract. It will not be possible to call `onlyOwner` * functions anymore if there are no other owners. * * Can be called by the other. It needs others' agreements. * * NOTE: Renouncing ownership can cause removing any functionality that * is only available to the owners. */ function deleteOwnership( address account, bytes32 key_ ) public returns (bool) { // "deleteOwnership" bytes32 name_ = 0x64656c6574654f776e6572736869700000000000000000000000000000000000; bytes32[] memory arguments_ = new bytes32[](1); arguments_[0] = bytes32(bytes20(account)); // conditions require(vResolveRequest(name_, arguments_, key_)); /* body start */ _deleteOwnership(account); /* body end */ return true; } /** * @dev Requests the transfering ownership. */ function transferOwnershipRequest( address oldOwner, address newOwner, uint256 timeLimit ) public returns ( bytes32 key_, uint256 campaignNum_ ) { // "transferOwnership" bytes32 name_ = 0x7472616e736665724f776e657273686970000000000000000000000000000000; bytes32[] memory arguments_ = new bytes32[](2); arguments_[0] = bytes32(bytes20(oldOwner)); arguments_[1] = bytes32(bytes20(newOwner)); return vSendRequest(name_, arguments_, timeLimit); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * * Can be called by himself. */ function transferOwnership( address newOwner ) public returns (bool) { address msgSender = _msgSender(); _transferOwnership(msgSender, newOwner); return true; } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * * Can be called by the other. It needs others' agreements. */ function transferOwnership( address oldOwner, address newOwner, bytes32 key_ ) public returns (bool) { // "transferOwnership" bytes32 name_ = 0x7472616e736665724f776e657273686970000000000000000000000000000000; bytes32[] memory arguments_ = new bytes32[](2); arguments_[0] = bytes32(bytes20(oldOwner)); arguments_[1] = bytes32(bytes20(newOwner)); // conditions require(vResolveRequest(name_, arguments_, key_)); /* body start */ _transferOwnership(oldOwner, newOwner); /* body end */ return true; } /** * @dev Requests the changing ownership level. */ function changeOwnershipLevelRequest( address account, uint8 level, uint256 timeLimit ) public returns ( bytes32 key_, uint256 campaignNum_ ) { // "changeOwnershipLevel" bytes32 name_ = 0x6368616e67654f776e6572736869704c6576656c000000000000000000000000; bytes32[] memory arguments_ = new bytes32[](2); arguments_[0] = bytes32(bytes20(account)); arguments_[1] = bytes32(uint256(level)); return vSendRequest(name_, arguments_, timeLimit); } /** * @dev Changes ownership level. */ function changeOwnershipLevel( address account, uint8 level, bytes32 key_ ) public returns (bool) { // "changeOwnershipLevel" bytes32 name_ = 0x6368616e67654f776e6572736869704c6576656c000000000000000000000000; bytes32[] memory arguments_ = new bytes32[](2); arguments_[0] = bytes32(bytes20(account)); arguments_[1] = bytes32(uint256(level)); // conditions require(vResolveRequest(name_, arguments_, key_)); /* body start */ _changeOwnershipLevel(account, level); /* body end */ return true; } /** * @dev Adds the ownership. */ function _addOwnership( address account, uint8 level ) internal { require(account != address(0), "Ownable: new owner is the zero address."); require(_owners[account] == 0, "Ownable: ownership already exists."); emit OwnershipTransferred(address(0), account, level); _owners[account] = level; } /** * @dev Leaves the contract. It will not be possible to call `onlyOwner` * functions anymore if there are no other owners. * * NOTE: Renouncing ownership can cause removing any functionality that * is only available to the owners. */ function _deleteOwnership( address account ) internal { require(_owners[account] != 0, "Ownable: there is no ownership."); emit OwnershipTransferred(account, address(0), 0); _owners[account] = 0; } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership( address oldOwner, address newOwner ) internal { require(newOwner != address(0), "Ownable: new owner is the zero address."); emit OwnershipTransferred(oldOwner, newOwner, _owners[oldOwner]); _owners[newOwner] = _owners[oldOwner]; _owners[oldOwner] = 0; } /** * @dev Changes ownership level. */ function _changeOwnershipLevel( address account, uint8 level ) internal { require(account != address(0), "Ownable: cannot change the ownership of zero address."); require(_owners[account] != 0, "Ownable: there is no ownership."); emit OwnershipTransferred(account, account, level); _owners[account] = level; } /** * @dev Votes the campaign. */ function voteAt( uint256 campaignNum, bool agree_ ) public onlyOwner(1) returns (bool) { address msgSender = _msgSender(); int256 weights_ = int256(levelOf(msgSender)); if (!agree_) { weights_ *= (-1); } return _voteAt(campaignNum, weights_); } }
* @dev Returns the level of the owner./
function levelOf( address owner ) public view override returns (uint8) { return _owners[owner]; }
2,545,379
[ 1, 1356, 326, 1801, 434, 326, 3410, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1801, 951, 12, 203, 3639, 1758, 3410, 203, 565, 262, 1071, 1476, 3849, 1135, 261, 11890, 28, 13, 288, 203, 3639, 327, 389, 995, 414, 63, 8443, 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, -100 ]
./full_match/1/0x21c2F2e8462D1090ac33d5A65cc03afFB18bB504/sources/browser/contract.sol
* The function can be called only by a whitelisted release agent. */
modifier onlyReleaseAgent() { if(_msgSender() != releaseAgent) { revert(); } _; }
9,662,235
[ 1, 1986, 445, 848, 506, 2566, 1338, 635, 279, 26944, 3992, 4040, 18, 342, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 9606, 1338, 7391, 3630, 1435, 288, 203, 565, 309, 24899, 3576, 12021, 1435, 480, 3992, 3630, 13, 288, 203, 3639, 15226, 5621, 203, 565, 289, 203, 565, 389, 31, 203, 225, 289, 203, 21281, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x6e29Ee2E972E75418AAeD679f7793bA3fa38d23E/sources/src/utils/OwnableOperators.sol
@title OwnableOperators @author dev by @dievardump @notice This contract adds ownable & operators management
abstract contract OwnableOperators is Ownable, WithOperators { pragma solidity 0.8.20; import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol"; import {WithOperators} from "./WithOperators.sol"; modifier onlyOperator() virtual override { if (msg.sender != owner()) { if (!operators[msg.sender]) { revert NotAuthorized(); } } _; } modifier onlyOperator() virtual override { if (msg.sender != owner()) { if (!operators[msg.sender]) { revert NotAuthorized(); } } _; } modifier onlyOperator() virtual override { if (msg.sender != owner()) { if (!operators[msg.sender]) { revert NotAuthorized(); } } _; } function setOperators(address[] memory operatorsList, bool isOperator) public onlyOwner { _setOperators(operatorsList, isOperator); } }
8,437,255
[ 1, 5460, 429, 24473, 225, 4461, 635, 632, 72, 1385, 90, 1060, 2801, 225, 1220, 6835, 4831, 4953, 429, 473, 12213, 11803, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 17801, 6835, 14223, 6914, 24473, 353, 14223, 6914, 16, 3423, 24473, 288, 203, 683, 9454, 18035, 560, 374, 18, 28, 18, 3462, 31, 203, 5666, 288, 5460, 429, 97, 628, 8787, 3190, 94, 881, 84, 292, 267, 19, 16351, 87, 19, 3860, 19, 5460, 429, 18, 18281, 14432, 203, 5666, 288, 1190, 24473, 97, 628, 25165, 1190, 24473, 18, 18281, 14432, 203, 202, 20597, 1338, 5592, 1435, 5024, 3849, 288, 203, 202, 202, 430, 261, 3576, 18, 15330, 480, 3410, 10756, 288, 203, 1082, 202, 430, 16051, 30659, 63, 3576, 18, 15330, 5717, 288, 203, 9506, 202, 266, 1097, 2288, 15341, 5621, 203, 1082, 202, 97, 203, 202, 202, 97, 203, 202, 202, 67, 31, 203, 202, 97, 203, 203, 202, 20597, 1338, 5592, 1435, 5024, 3849, 288, 203, 202, 202, 430, 261, 3576, 18, 15330, 480, 3410, 10756, 288, 203, 1082, 202, 430, 16051, 30659, 63, 3576, 18, 15330, 5717, 288, 203, 9506, 202, 266, 1097, 2288, 15341, 5621, 203, 1082, 202, 97, 203, 202, 202, 97, 203, 202, 202, 67, 31, 203, 202, 97, 203, 203, 202, 20597, 1338, 5592, 1435, 5024, 3849, 288, 203, 202, 202, 430, 261, 3576, 18, 15330, 480, 3410, 10756, 288, 203, 1082, 202, 430, 16051, 30659, 63, 3576, 18, 15330, 5717, 288, 203, 9506, 202, 266, 1097, 2288, 15341, 5621, 203, 1082, 202, 97, 203, 202, 202, 97, 203, 202, 202, 67, 31, 203, 202, 97, 203, 203, 202, 915, 444, 24473, 12, 2867, 8526, 3778, 12213, 682, 16, 1426, 353, 5592, 13, 1071, 1338, 5541, 2 ]
./full_match/5/0xD47b598f17aA0457cC299Bcf907AC93E4cd7C0bC/sources/contracts/Ticketing.sol
Define Ticket Structure
contract TicketingSystem is ERC721Enumerable, Ownable { struct Ticket { string ticketType; uint256 validUntil; address owner; uint amount; bool used; } struct OwnerInfo{ uint256 [] TicketIds; uint TotalTickets; } mapping (address => OwnerInfo) public OWNERINFO; using Strings for uint256; string public baseURI; string public baseExtension = ".json"; uint256 public maxSupply = 1000000000000; uint256 public maxMintAmount = 1; bool public paused = false; uint256 public ticketId; event TicketCreated(string ticketType, uint256 validUntil,address owner, uint amount); event TicketUsed(uint TicketId, address user); mapping(uint256 => Ticket) public TICKET; constructor() ERC721("TicketingSystem", "TICKET") {} function mint(string memory _ticketType, uint256 _validUntil) public payable { Ticket storage newTicket = TICKET[ticketId]; OwnerInfo storage ownerData = OWNERINFO[msg.sender]; newTicket.ticketType = _ticketType; newTicket.validUntil =_validUntil; newTicket.owner = msg.sender; newTicket.amount = msg.value; ownerData.TicketIds.push(ticketId); ownerData.TotalTickets += 1; _safeMint(msg.sender, ticketId); ticketId++; emit TicketCreated (_ticketType, _validUntil, msg.sender, msg.value); } function useTicket(uint256 _ticketId) external { require(_isApprovedOrOwner(msg.sender, _ticketId), "Not approved or owner"); require(!TICKET[_ticketId].used, "Ticket has already been used"); TICKET[_ticketId].used = true; emit TicketUsed(_ticketId, msg.sender); } function getTicket(uint256 _ticketId) external view returns ( string memory, uint256, uint256, address, bool ) { Ticket storage ticket = TICKET[_ticketId]; return (ticket.ticketType, ticket.amount, ticket.validUntil, ticket.owner, ticket.used); } }
1,862,048
[ 1, 11644, 22023, 13348, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 13588, 21747, 3163, 353, 4232, 39, 27, 5340, 3572, 25121, 16, 14223, 6914, 288, 203, 203, 203, 565, 1958, 22023, 288, 203, 3639, 533, 9322, 559, 31, 203, 3639, 2254, 5034, 923, 9716, 31, 203, 3639, 1758, 3410, 31, 203, 3639, 2254, 3844, 31, 203, 3639, 1426, 1399, 31, 203, 565, 289, 203, 203, 565, 1958, 16837, 966, 95, 203, 3639, 2254, 5034, 5378, 22023, 2673, 31, 203, 3639, 2254, 10710, 6264, 2413, 31, 203, 565, 289, 203, 203, 203, 565, 2874, 261, 2867, 516, 16837, 966, 13, 1071, 531, 22527, 5923, 31, 203, 377, 203, 565, 1450, 8139, 364, 2254, 5034, 31, 203, 565, 533, 1071, 1026, 3098, 31, 203, 565, 533, 1071, 1026, 3625, 273, 3552, 1977, 14432, 203, 565, 2254, 5034, 1071, 943, 3088, 1283, 273, 15088, 9449, 31, 203, 565, 2254, 5034, 1071, 943, 49, 474, 6275, 273, 404, 31, 203, 565, 1426, 1071, 17781, 273, 629, 31, 203, 565, 2254, 5034, 1071, 9322, 548, 31, 203, 203, 565, 871, 22023, 6119, 12, 1080, 9322, 559, 16, 2254, 5034, 923, 9716, 16, 2867, 3410, 16, 2254, 3844, 1769, 203, 565, 871, 22023, 6668, 12, 11890, 22023, 548, 16, 1758, 729, 1769, 203, 203, 203, 203, 565, 2874, 12, 11890, 5034, 516, 22023, 13, 1071, 399, 16656, 1584, 31, 203, 565, 3885, 1435, 4232, 39, 27, 5340, 2932, 13614, 310, 3163, 3113, 315, 56, 16656, 1584, 7923, 2618, 203, 565, 445, 312, 474, 12, 1080, 3778, 389, 16282, 559, 16, 2254, 5034, 389, 877, 9716, 13, 1071, 8843, 429, 288, 2 ]
./partial_match/100/0xa753E6Df2c7205a615F2EeDe52275aDC0a9fda22/sources/StakingAuRa.sol
@dev Returns the balance of this contract in staking tokens or coins depending on implementation. @dev Implements staking and withdrawal logic. =============================================== Storage ======================================================== WARNING: since this contract is upgradeable, do not remove existing storage variables, do not change their order, and do not change their types! =============================================== Structs ========================================================
contract StakingAuRaTokens is IStakingAuRaTokens, StakingAuRaBase { IERC677Minting public erc677TokenContract; function _thisBalance() internal view returns(uint256); } struct RewardAmounts { uint256 tokenAmount; uint256 nativeAmount; } address indexed fromPoolStakingAddress, address indexed staker, uint256 indexed stakingEpoch, uint256 tokensAmount, uint256 nativeCoinsAmount ); event ClaimedReward( function claimReward( uint256[] memory _stakingEpochs, address _poolStakingAddress ) public gasPriceIsValid onlyInitialized { address payable staker = msg.sender; uint256 firstEpoch; uint256 lastEpoch; firstEpoch = stakeFirstEpoch[_poolStakingAddress][staker]; require(firstEpoch != 0); lastEpoch = stakeLastEpoch[_poolStakingAddress][staker]; } IBlockRewardAuRaTokens blockRewardContract = IBlockRewardAuRaTokens(validatorSetContract.blockRewardContract()); address miningAddress = validatorSetContract.miningByStakingAddress(_poolStakingAddress); RewardAmounts memory rewardSum = RewardAmounts(0, 0); uint256 delegatorStake = 0; if (_stakingEpochs.length == 0) { _stakingEpochs = IBlockRewardAuRa(address(blockRewardContract)).epochsPoolGotRewardFor(miningAddress); } for (uint256 i = 0; i < _stakingEpochs.length; i++) { uint256 epoch = _stakingEpochs[i]; require(i == 0 || epoch > _stakingEpochs[i - 1]); require(epoch < stakingEpoch); if (rewardWasTaken[_poolStakingAddress][staker][epoch]) continue; RewardAmounts memory reward; if (epoch < firstEpoch) { continue; } if (lastEpoch <= epoch && lastEpoch != 0) { break; } delegatorStake = _getDelegatorStake(epoch, firstEpoch, delegatorStake, _poolStakingAddress, staker); firstEpoch = epoch + 1; (reward.tokenAmount, reward.nativeAmount) = blockRewardContract.getDelegatorReward(delegatorStake, epoch, miningAddress); (reward.tokenAmount, reward.nativeAmount) = blockRewardContract.getValidatorReward(epoch, miningAddress); } rewardSum.tokenAmount = rewardSum.tokenAmount.add(reward.tokenAmount); rewardSum.nativeAmount = rewardSum.nativeAmount.add(reward.nativeAmount); rewardWasTaken[_poolStakingAddress][staker][epoch] = true; emit ClaimedReward(_poolStakingAddress, staker, epoch, reward.tokenAmount, reward.nativeAmount); for (uint256 i = 0; i < _stakingEpochs.length; i++) { uint256 epoch = _stakingEpochs[i]; require(i == 0 || epoch > _stakingEpochs[i - 1]); require(epoch < stakingEpoch); if (rewardWasTaken[_poolStakingAddress][staker][epoch]) continue; RewardAmounts memory reward; if (epoch < firstEpoch) { continue; } if (lastEpoch <= epoch && lastEpoch != 0) { break; } delegatorStake = _getDelegatorStake(epoch, firstEpoch, delegatorStake, _poolStakingAddress, staker); firstEpoch = epoch + 1; (reward.tokenAmount, reward.nativeAmount) = blockRewardContract.getDelegatorReward(delegatorStake, epoch, miningAddress); (reward.tokenAmount, reward.nativeAmount) = blockRewardContract.getValidatorReward(epoch, miningAddress); } rewardSum.tokenAmount = rewardSum.tokenAmount.add(reward.tokenAmount); rewardSum.nativeAmount = rewardSum.nativeAmount.add(reward.nativeAmount); rewardWasTaken[_poolStakingAddress][staker][epoch] = true; emit ClaimedReward(_poolStakingAddress, staker, epoch, reward.tokenAmount, reward.nativeAmount); for (uint256 i = 0; i < _stakingEpochs.length; i++) { uint256 epoch = _stakingEpochs[i]; require(i == 0 || epoch > _stakingEpochs[i - 1]); require(epoch < stakingEpoch); if (rewardWasTaken[_poolStakingAddress][staker][epoch]) continue; RewardAmounts memory reward; if (epoch < firstEpoch) { continue; } if (lastEpoch <= epoch && lastEpoch != 0) { break; } delegatorStake = _getDelegatorStake(epoch, firstEpoch, delegatorStake, _poolStakingAddress, staker); firstEpoch = epoch + 1; (reward.tokenAmount, reward.nativeAmount) = blockRewardContract.getDelegatorReward(delegatorStake, epoch, miningAddress); (reward.tokenAmount, reward.nativeAmount) = blockRewardContract.getValidatorReward(epoch, miningAddress); } rewardSum.tokenAmount = rewardSum.tokenAmount.add(reward.tokenAmount); rewardSum.nativeAmount = rewardSum.nativeAmount.add(reward.nativeAmount); rewardWasTaken[_poolStakingAddress][staker][epoch] = true; emit ClaimedReward(_poolStakingAddress, staker, epoch, reward.tokenAmount, reward.nativeAmount); }
16,643,854
[ 1, 1356, 326, 11013, 434, 333, 6835, 316, 384, 6159, 2430, 578, 276, 9896, 8353, 603, 4471, 18, 225, 29704, 384, 6159, 471, 598, 9446, 287, 4058, 18, 422, 4428, 14468, 33, 5235, 422, 20775, 894, 631, 9744, 30, 3241, 333, 6835, 353, 8400, 429, 16, 741, 486, 1206, 2062, 2502, 3152, 16, 741, 486, 2549, 3675, 1353, 16, 471, 741, 486, 2549, 3675, 1953, 5, 422, 4428, 14468, 33, 7362, 87, 422, 20775, 894, 631, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 934, 6159, 37, 89, 12649, 5157, 353, 467, 510, 6159, 37, 89, 12649, 5157, 16, 934, 6159, 37, 89, 12649, 2171, 288, 203, 203, 203, 203, 565, 467, 654, 39, 26, 4700, 49, 474, 310, 1071, 6445, 71, 26, 4700, 1345, 8924, 31, 203, 203, 203, 565, 445, 389, 2211, 13937, 1435, 2713, 1476, 1135, 12, 11890, 5034, 1769, 203, 97, 203, 203, 203, 203, 203, 203, 565, 1958, 534, 359, 1060, 6275, 87, 288, 203, 3639, 2254, 5034, 1147, 6275, 31, 203, 3639, 2254, 5034, 6448, 6275, 31, 203, 565, 289, 203, 203, 3639, 1758, 8808, 628, 2864, 510, 6159, 1887, 16, 203, 3639, 1758, 8808, 384, 6388, 16, 203, 3639, 2254, 5034, 8808, 384, 6159, 14638, 16, 203, 3639, 2254, 5034, 2430, 6275, 16, 203, 3639, 2254, 5034, 6448, 39, 9896, 6275, 203, 565, 11272, 203, 203, 203, 565, 871, 18381, 329, 17631, 1060, 12, 203, 203, 565, 445, 7516, 17631, 1060, 12, 203, 3639, 2254, 5034, 8526, 3778, 389, 334, 6159, 14638, 87, 16, 203, 3639, 1758, 389, 6011, 510, 6159, 1887, 203, 565, 262, 1071, 16189, 5147, 20536, 1338, 11459, 288, 203, 3639, 1758, 8843, 429, 384, 6388, 273, 1234, 18, 15330, 31, 203, 3639, 2254, 5034, 1122, 14638, 31, 203, 3639, 2254, 5034, 1142, 14638, 31, 203, 203, 5411, 1122, 14638, 273, 384, 911, 3759, 14638, 63, 67, 6011, 510, 6159, 1887, 6362, 334, 6388, 15533, 203, 5411, 2583, 12, 3645, 14638, 480, 374, 1769, 203, 5411, 1142, 14638, 273, 384, 911, 3024, 14638, 63, 67, 6011, 510, 2 ]
./full_match/42/0x8B31CDB6A11A0b4f6aD43be2100B061F8C3a3D4F/sources/uniswap-solidity-example/flatten/Flattened.sol
File: contracts\DoBasis.sol
contract DoBasis is AccessControl { IUniswapV2Router02 public uniswapRouter; IERC20 public wethToken; IERC20 public daiToken; IERC20 public basToken; IERC20 public bacToken; IBoardroom public boardRoom; address public wethAddress; address public daiAddress; address public basAddress; address public bacAddress; address public uniswapRouterAddress; address public boardroomAddress; constructor() { _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); } modifier onlyAdmin() { require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "Caller is not admin"); _; } function setUniswapRouterAddress(address _uniswapRouterAddress) external onlyAdmin { uniswapRouter = IUniswapV2Router02(_uniswapRouterAddress); uniswapRouterAddress = _uniswapRouterAddress; } function setWETHAddress(address _wethAddress) external onlyAdmin { wethToken = IERC20(_wethAddress); wethAddress = _wethAddress; } function setDaiAddress(address _daiAddress) external onlyAdmin { daiToken = IERC20(_daiAddress); daiAddress = _daiAddress; } function setBasAddress(address _basAddress) external onlyAdmin { basToken = IERC20(_basAddress); basAddress = _basAddress; } function setBacAddress(address _bacAddress) external onlyAdmin { bacToken = IERC20(_bacAddress); bacAddress = _bacAddress; } function setBoardroomAddress(address _boardroomAddress) external onlyAdmin { boardRoom = IBoardroom(_boardroomAddress); boardroomAddress = _boardroomAddress; } function setAllAdresses( address _uniswapRouterAddress, address _daiAddress, address _basAddress, address _bacAddress, address _boardroomAddress ) external onlyAdmin { uniswapRouter = IUniswapV2Router02(_uniswapRouterAddress); uniswapRouterAddress = _uniswapRouterAddress; daiToken = IERC20(_daiAddress); daiAddress = _daiAddress; basToken = IERC20(_basAddress); basAddress = _basAddress; bacToken = IERC20(_bacAddress); bacAddress = _bacAddress; boardRoom = IBoardroom(_boardroomAddress); boardroomAddress = _boardroomAddress; } function approveTokensForUniswap(uint256 amount) external onlyAdmin { daiToken.approve(uniswapRouterAddress, amount); basToken.approve(uniswapRouterAddress, amount); bacToken.approve(uniswapRouterAddress, amount); } function approveBacForUniswap(uint256 amount) external onlyAdmin { bacToken.approve(uniswapRouterAddress, amount); } function approveBasForBoardroom(uint256 amount) external onlyAdmin { basToken.approve(boardroomAddress, amount); } function approveWethForUniswap(uint256 amount) external onlyAdmin { wethToken.approve(uniswapRouterAddress, amount); } function approveDaiForUniswap(uint256 amount) external onlyAdmin { daiToken.approve(uniswapRouterAddress, amount); } function stakeBas() external onlyAdmin { boardRoom.stake(basToken.balanceOf(address(this))); } function unstakeBas(uint256 _amount) external onlyAdmin { boardRoom.withdraw(_amount); } function exitBas() external onlyAdmin { boardRoom.exit(); } function claimBasReward() external onlyAdmin { boardRoom.claimReward(); } function exitBasAndCovertToDai() external onlyAdmin { boardRoom.exit(); uint256 bacAmount = bacToken.balanceOf(address(this)); require(bacAmount > 0, "Bac is zero"); uniswapRouter.swapExactTokensForTokens( bacAmount, 1000000, getPathForBACtoDAI(), address(this), block.timestamp + 15 ); } function withdrawEther(address payable _to, uint256 _amount) external onlyAdmin { uint256 totalAmount = 0; if (_amount == 0) { totalAmount = address(this).balance; totalAmount = _amount; } require(totalAmount > 0, "totalAmount is zero"); require(success, "withdraw failed"); } function withdrawEther(address payable _to, uint256 _amount) external onlyAdmin { uint256 totalAmount = 0; if (_amount == 0) { totalAmount = address(this).balance; totalAmount = _amount; } require(totalAmount > 0, "totalAmount is zero"); require(success, "withdraw failed"); } } else { (bool success, ) = _to.call{value: totalAmount}(""); function withdrawDai(address _to, uint256 _amount) external onlyAdmin { uint256 totalAmount = 0; if (_amount == 0) { totalAmount = daiToken.balanceOf(address(this)); totalAmount = _amount; } require(totalAmount > 0, "totalAmount is zero"); bool success = daiToken.transfer(_to, totalAmount); require(success, "withdraw failed"); } function withdrawDai(address _to, uint256 _amount) external onlyAdmin { uint256 totalAmount = 0; if (_amount == 0) { totalAmount = daiToken.balanceOf(address(this)); totalAmount = _amount; } require(totalAmount > 0, "totalAmount is zero"); bool success = daiToken.transfer(_to, totalAmount); require(success, "withdraw failed"); } } else { function withdrawBas(address _to, uint256 _amount) external onlyAdmin { uint256 totalAmount = 0; if (_amount == 0) { totalAmount = basToken.balanceOf(address(this)); totalAmount = _amount; } require(totalAmount > 0, "totalAmount is zero"); bool success = basToken.transfer(_to, totalAmount); require(success, "withdraw failed"); } function withdrawBas(address _to, uint256 _amount) external onlyAdmin { uint256 totalAmount = 0; if (_amount == 0) { totalAmount = basToken.balanceOf(address(this)); totalAmount = _amount; } require(totalAmount > 0, "totalAmount is zero"); bool success = basToken.transfer(_to, totalAmount); require(success, "withdraw failed"); } } else { function getEstimatedBACforDAI(uint256 _amount) public view returns (uint256[] memory) { return uniswapRouter.getAmountsIn(_amount, getPathForBACtoDAI()); } function getEstimatedBASforDAI(uint256 _amount) public view returns (uint256[] memory) { return uniswapRouter.getAmountsIn(_amount, getPathForBAStoDAI()); } function getPathForBACtoDAI() private view returns (address[] memory) { address[] memory path = new address[](2); path[0] = bacAddress; path[1] = daiAddress; return path; } function getPathForBAStoDAI() private view returns (address[] memory) { address[] memory path = new address[](2); path[0] = basAddress; path[1] = daiAddress; return path; } function getEstimatedDAIforBAC(uint256 _amount) public view returns (uint256[] memory) { return uniswapRouter.getAmountsIn(_amount, getPathForDaitoBac()); } function getPathForDaitoBac() private view returns (address[] memory) { address[] memory path = new address[](2); path[0] = daiAddress; path[1] = bacAddress; return path; } function getEstimatedDAIforBAS(uint256 _amount) public view returns (uint256[] memory) { return uniswapRouter.getAmountsIn(_amount, getPathForDaitoBas()); } function getPathForDaitoBas() private view returns (address[] memory) { address[] memory path = new address[](2); path[0] = daiAddress; path[1] = basAddress; return path; } function getPathForWethtoDAI() private view returns (address[] memory) { address[] memory path = new address[](2); path[0] = 0xd0A1E359811322d97991E03f863a0C30C2cF029C; path[1] = 0x4F96Fe3b7A6Cf9725f59d353F723c1bDb64CA6Aa; return path; } function covertWethToDai(uint256 _amount) external onlyAdmin { uint256 wethAmount = 0; if (_amount == 0) { wethAmount = wethToken.balanceOf(address(this)); wethAmount = _amount; } require(wethAmount > 0, "Weth amount is zero"); uniswapRouter.swapExactTokensForTokens( wethAmount, 1000000, getPathForWethtoDAI(), address(this), block.timestamp + 15 ); } function covertWethToDai(uint256 _amount) external onlyAdmin { uint256 wethAmount = 0; if (_amount == 0) { wethAmount = wethToken.balanceOf(address(this)); wethAmount = _amount; } require(wethAmount > 0, "Weth amount is zero"); uniswapRouter.swapExactTokensForTokens( wethAmount, 1000000, getPathForWethtoDAI(), address(this), block.timestamp + 15 ); } } else { function covertBasToDai(uint256 _amount) external onlyAdmin { uint256 basAmount = 0; if (_amount == 0) { basAmount = basToken.balanceOf(address(this)); basAmount = _amount; } require(basAmount > 0, "Bas amount is zero"); uniswapRouter.swapExactTokensForTokens( basAmount, 1000000, getPathForBAStoDAI(), address(this), block.timestamp + 15 ); } function covertBasToDai(uint256 _amount) external onlyAdmin { uint256 basAmount = 0; if (_amount == 0) { basAmount = basToken.balanceOf(address(this)); basAmount = _amount; } require(basAmount > 0, "Bas amount is zero"); uniswapRouter.swapExactTokensForTokens( basAmount, 1000000, getPathForBAStoDAI(), address(this), block.timestamp + 15 ); } } else { function test(uint256 _amount) external onlyAdmin { uint256 newAmount = _amount * 1000000000000000; address UNISWAP_ROUTER_ADDRESS = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; uniswapRouter = IUniswapV2Router02(UNISWAP_ROUTER_ADDRESS); uniswapRouterAddress = UNISWAP_ROUTER_ADDRESS; address multiDaiKovan = 0x4F96Fe3b7A6Cf9725f59d353F723c1bDb64CA6Aa; address _wethAddress = 0xd0A1E359811322d97991E03f863a0C30C2cF029C; wethToken = IERC20(_wethAddress); wethAddress = _wethAddress; wethToken.transferFrom(msg.sender, address(this), newAmount); wethToken.approve(uniswapRouterAddress, newAmount); uniswapRouter.swapExactTokensForTokens( newAmount, 1000000, getPathForWethtoDAI(), address(this), block.timestamp + 15 ); } function test2(uint256 _amount) external onlyAdmin { address multiDaiKovan = 0x4F96Fe3b7A6Cf9725f59d353F723c1bDb64CA6Aa; address UNISWAP_ROUTER_ADDRESS = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; daiToken = IERC20(multiDaiKovan); uint amountIn = 50; require(daiToken.transferFrom(msg.sender, address(this), amountIn), 'transferFrom failed.'); uniswapRouter = IUniswapV2Router02(UNISWAP_ROUTER_ADDRESS); address[] memory path = new address[](2); path[0] = address(daiToken); path[1] = uniswapRouter.WETH(); uniswapRouter.swapExactTokensForETH(amountIn, 0, path, msg.sender, block.timestamp); } function getBalance() public view returns (uint256 _val) { address multiDaiKovan = 0x4F96Fe3b7A6Cf9725f59d353F723c1bDb64CA6Aa; return address(0x3694A96D70a66cCd6d04196688CcfB45a35ebdd9).balance; } function getEstimatedETHforDAI(uint daiAmount) public view returns (uint[] memory) { address UNISWAP_ROUTER_ADDRESS = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; return IUniswapV2Router02(UNISWAP_ROUTER_ADDRESS).getAmountsIn(daiAmount, getPathForWethtoDAI()); } function covertBacToDai(uint256 _amount) external onlyAdmin { uint256 bacAmount = 0; if (_amount == 0) { bacAmount = bacToken.balanceOf(address(this)); bacAmount = _amount; } require(bacAmount > 0, "Bas amount is zero"); uniswapRouter.swapExactTokensForTokens( bacAmount, 1000000, getPathForBACtoDAI(), address(this), block.timestamp + 15 ); } function covertBacToDai(uint256 _amount) external onlyAdmin { uint256 bacAmount = 0; if (_amount == 0) { bacAmount = bacToken.balanceOf(address(this)); bacAmount = _amount; } require(bacAmount > 0, "Bas amount is zero"); uniswapRouter.swapExactTokensForTokens( bacAmount, 1000000, getPathForBACtoDAI(), address(this), block.timestamp + 15 ); } } else { receive() external payable {} }
16,264,122
[ 1, 812, 30, 20092, 64, 3244, 11494, 291, 18, 18281, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 2256, 11494, 291, 353, 24349, 288, 203, 565, 467, 984, 291, 91, 438, 58, 22, 8259, 3103, 1071, 640, 291, 91, 438, 8259, 31, 203, 565, 467, 654, 39, 3462, 1071, 341, 546, 1345, 31, 203, 565, 467, 654, 39, 3462, 1071, 5248, 77, 1345, 31, 203, 565, 467, 654, 39, 3462, 1071, 2580, 1345, 31, 203, 565, 467, 654, 39, 3462, 1071, 324, 1077, 1345, 31, 203, 565, 467, 22233, 13924, 1071, 11094, 13646, 31, 203, 565, 1758, 1071, 341, 546, 1887, 31, 203, 565, 1758, 1071, 5248, 77, 1887, 31, 203, 565, 1758, 1071, 2580, 1887, 31, 203, 565, 1758, 1071, 324, 1077, 1887, 31, 203, 565, 1758, 1071, 640, 291, 91, 438, 8259, 1887, 31, 203, 565, 1758, 1071, 11094, 13924, 1887, 31, 203, 565, 3885, 1435, 288, 203, 3639, 389, 8401, 2996, 12, 5280, 67, 15468, 67, 16256, 16, 1234, 18, 15330, 1769, 203, 565, 289, 203, 565, 9606, 1338, 4446, 1435, 288, 203, 3639, 2583, 12, 5332, 2996, 12, 5280, 67, 15468, 67, 16256, 16, 1234, 18, 15330, 3631, 315, 11095, 353, 486, 3981, 8863, 203, 3639, 389, 31, 203, 565, 289, 203, 565, 445, 444, 984, 291, 91, 438, 8259, 1887, 12, 2867, 389, 318, 291, 91, 438, 8259, 1887, 13, 203, 3639, 3903, 203, 3639, 1338, 4446, 203, 565, 288, 203, 3639, 640, 291, 91, 438, 8259, 273, 467, 984, 291, 91, 438, 58, 22, 8259, 3103, 24899, 318, 291, 91, 438, 8259, 1887, 1769, 203, 3639, 640, 291, 91, 438, 8259, 1887, 273, 389, 318, 2 ]
// 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); } 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; } } 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); } } 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; } 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); } pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } 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); } } } } pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } /** * @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 {} } pragma solidity ^0.8.0; pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } 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; } } } contract JAN is ERC721Enumerable, Ownable { using SafeMath for uint256; using Address for address; string private PROVENANCE; string private baseURI; uint256 public maxSupply; uint256 public price = 0.07 ether; bool public presaleActive = false; bool public saleActive = false; mapping (address => uint256) public presaleWhitelist; //map team addresses address private constant DVAddress = 0x2e302a91D01183F4F3966AbDA0D16d79BbaF0A4D;//DEV address private constant SAddress = 0xc8F56c0c1DE72Ba21e4237f5667960a79ca049b9; address private constant JAddress = 0x5e675243b30ADbA95cA65B82ec4918567D85CcD6; address private constant RAddress = 0xC45589FfF5dc6C9455EEbc140ab7b2020Ffd1840; address private constant R1Address = 0xADda99Ac13133A49e9FB5c25C9107613a5f16463; address private constant ATAddress = 0xcbcD316d1cd48F70f0D59D92B7bc25d1d28f8a9a; address private constant ABAddress = 0x18378F8df9240C62076e497A8366b4e5d1a7beEC; address private constant MMAddress = 0x2Fe62d7bFF2eb961fd2dDB86D49026a5d43bcEC9; constructor(string memory name, string memory symbol, uint256 supply) ERC721(name, symbol) { maxSupply = supply; } function reserve() public onlyOwner { uint256 supply = totalSupply(); for (uint256 i = 0; i < 154; i++) { _safeMint(msg.sender, supply + i); } } function mintPresale(uint256 numberOfMints) public payable { uint256 supply = totalSupply(); uint256 reserved = presaleWhitelist[msg.sender]; require(presaleActive, "Presale must be active to mint"); require(reserved > 0, "No tokens reserved for this address"); require(numberOfMints <= reserved, "Can't mint more than reserved"); require(supply.add(numberOfMints) <= maxSupply, "Purchase would exceed max supply of tokens"); require(price.mul(numberOfMints) == msg.value, "Ether value sent is not correct"); presaleWhitelist[msg.sender] = reserved - numberOfMints; for(uint256 i; i < numberOfMints; i++){ _safeMint( msg.sender, supply + i ); } } function mint(uint256 numberOfMints) public payable { uint256 supply = totalSupply(); require(saleActive, "Sale must be active to mint"); require(numberOfMints > 0 && numberOfMints < 100, "Invalid purchase amount"); require(supply.add(numberOfMints) <= maxSupply, "Purchase would exceed max supply of tokens"); require(price.mul(numberOfMints) == msg.value, "Ether value sent is not correct"); for(uint256 i; i < numberOfMints; i++) { _safeMint(msg.sender, supply + i); } } function editPresale(address[] calldata presaleAddresses, uint256[] calldata amount) public onlyOwner { for(uint256 i; i < presaleAddresses.length; i++){ presaleWhitelist[presaleAddresses[i]] = amount[i]; } } function walletOfOwner(address owner) external view returns(uint256[] memory) { uint256 tokenCount = balanceOf(owner); uint256[] memory tokensId = new uint256[](tokenCount); for(uint256 i; i < tokenCount; i++){ tokensId[i] = tokenOfOwnerByIndex(owner, i); } return tokensId; } function withdrawAll() public payable onlyOwner { uint256 balance = address(this).balance; require(balance > 0); _withdraw(DVAddress, balance.mul(1000).div(10000)); _withdraw(SAddress, balance.mul(875).div(10000)); _withdraw(JAddress, balance.mul(775).div(10000)); _withdraw(RAddress, balance.mul(1125).div(10000)); _withdraw(R1Address, balance.mul(775).div(10000)); _withdraw(ATAddress, balance.mul(1750).div(10000)); _withdraw(ABAddress, balance.mul(700).div(10000)); _withdraw(MMAddress, balance.mul(3000).div(10000)); } function _withdraw(address _address, uint256 _amount) private { (bool success, ) = _address.call{value: _amount}(""); require(success, "Transfer failed."); } function togglePresale() public onlyOwner { presaleActive = !presaleActive; } function toggleSale() public onlyOwner { saleActive = !saleActive; } function setPrice(uint256 newPrice) public onlyOwner { price = newPrice; } function setProvenance(string memory provenance) private onlyOwner { PROVENANCE = provenance; } function setBaseURI(string memory uri) public onlyOwner { baseURI = uri; } function _baseURI() internal view override returns (string memory) { return baseURI; } }
* @dev Returns the total amount of tokens stored by the contract./* @dev Returns a token ID owned by `owner` at a given `index` of its token list. Use along with {balanceOf} to enumerate all of ``owner``'s tokens./* @dev Returns a token ID at a given `index` of all the tokens stored by the contract. Use along with {totalSupply} to enumerate all tokens./* @dev This implements an optional extension of {ERC721} defined in the EIP that adds enumerability of all the token ids in the contract as well as all token ids owned by each account./ Mapping from owner to list of owned token IDs Mapping from token ID to index of the owner tokens list Array with all token ids, used for enumeration Mapping from token id to position in the allTokens array
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { mapping(address => mapping(uint256 => uint256)) private _ownedTokens; mapping(uint256 => uint256) private _ownedTokensIndex; uint256[] private _allTokens; mapping(uint256 => uint256) private _allTokensIndex; function _beforeTokenTransfer( address from, address to, uint256 tokenId } pragma solidity ^0.8.0; pragma solidity ^0.8.0; } function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); _addTokenToOwnerEnumeration(to, tokenId); } } function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); _addTokenToOwnerEnumeration(to, tokenId); } } } else if (from != to) { function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); _addTokenToOwnerEnumeration(to, tokenId); } } } else if (to != from) { function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; } delete _ownedTokens[from][lastTokenIndex]; } function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; } delete _ownedTokens[from][lastTokenIndex]; } delete _ownedTokensIndex[tokenId]; function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; uint256 lastTokenId = _allTokens[lastTokenIndex]; delete _allTokensIndex[tokenId]; _allTokens.pop(); } }
1,505,072
[ 1, 1356, 326, 2078, 3844, 434, 2430, 4041, 635, 326, 6835, 18, 19, 225, 2860, 279, 1147, 1599, 16199, 635, 1375, 8443, 68, 622, 279, 864, 1375, 1615, 68, 434, 2097, 1147, 666, 18, 2672, 7563, 598, 288, 12296, 951, 97, 358, 4241, 777, 434, 12176, 8443, 10335, 11, 87, 2430, 18, 19, 225, 2860, 279, 1147, 1599, 622, 279, 864, 1375, 1615, 68, 434, 777, 326, 2430, 4041, 635, 326, 6835, 18, 2672, 7563, 598, 288, 4963, 3088, 1283, 97, 358, 4241, 777, 2430, 18, 19, 225, 1220, 4792, 392, 3129, 2710, 434, 288, 654, 39, 27, 5340, 97, 2553, 316, 326, 512, 2579, 716, 4831, 3557, 2967, 434, 777, 326, 1147, 3258, 316, 326, 6835, 487, 5492, 487, 777, 1147, 3258, 16199, 635, 1517, 2236, 18, 19, 9408, 628, 3410, 358, 666, 434, 16199, 1147, 7115, 9408, 628, 1147, 1599, 358, 770, 434, 326, 3410, 2430, 666, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 17801, 6835, 4232, 39, 27, 5340, 3572, 25121, 353, 4232, 39, 27, 5340, 16, 467, 654, 39, 27, 5340, 3572, 25121, 288, 203, 565, 2874, 12, 2867, 516, 2874, 12, 11890, 5034, 516, 2254, 5034, 3719, 3238, 389, 995, 329, 5157, 31, 203, 203, 565, 2874, 12, 11890, 5034, 516, 2254, 5034, 13, 3238, 389, 995, 329, 5157, 1016, 31, 203, 203, 565, 2254, 5034, 8526, 3238, 389, 454, 5157, 31, 203, 203, 565, 2874, 12, 11890, 5034, 516, 2254, 5034, 13, 3238, 389, 454, 5157, 1016, 31, 203, 203, 565, 445, 389, 5771, 1345, 5912, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 1147, 548, 203, 97, 203, 203, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 20, 31, 203, 203, 203, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 20, 31, 203, 203, 203, 203, 97, 203, 203, 203, 565, 445, 6146, 1358, 12, 3890, 24, 1560, 548, 13, 1071, 1476, 5024, 3849, 12, 45, 654, 39, 28275, 16, 4232, 39, 27, 5340, 13, 1135, 261, 6430, 13, 288, 203, 3639, 327, 1560, 548, 422, 618, 12, 45, 654, 39, 27, 5340, 3572, 25121, 2934, 5831, 548, 747, 2240, 18, 28064, 1358, 12, 5831, 548, 1769, 203, 565, 289, 203, 203, 565, 445, 1147, 951, 5541, 21268, 12, 2867, 3410, 16, 2254, 5034, 770, 13, 1071, 1476, 5024, 3849, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 2583, 12, 1615, 411, 4232, 39, 27, 5340, 18, 12296, 951, 12, 2 ]
/** *Submitted for verification at Etherscan.io on 2021-12-04 */ /** *Submitted for verification at polygonscan.com on 2021-12-03 */ // File: @openzeppelin/contracts/utils/cryptography/ECDSA.sol // 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)); } } // File: contracts/interfaces/IUniswapV2Router.sol interface IUniswapV2Router { 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); } 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: contracts/interfaces/IERC20Token.sol abstract contract IERC20Token is IERC20 { function upgrade(uint256 value) public virtual; } // File: contracts/Ownable.sol contract Ownable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); function owner() public view returns (address) { return _owner; } modifier onlyOwner() { require(_owner == msg.sender || _owner == address(0x0), "Ownable: caller is not the 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/security/ReentrancyGuard.sol /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // File: contracts/FundsRecovery.sol contract FundsRecovery is Ownable, ReentrancyGuard { address payable internal fundsDestination; IERC20Token public token; event DestinationChanged(address indexed previousDestination, address indexed newDestination); /** * Setting new destination of funds recovery. */ function setFundsDestination(address payable _newDestination) public virtual onlyOwner { require(_newDestination != address(0)); emit DestinationChanged(fundsDestination, _newDestination); fundsDestination = _newDestination; } /** * Getting funds destination address. */ function getFundsDestination() public view returns (address) { return fundsDestination; } /** * Possibility to recover funds in case they were sent to this address before smart contract deployment */ function claimEthers() public nonReentrant { require(fundsDestination != address(0)); fundsDestination.transfer(address(this).balance); } /** Transfers selected tokens into owner address. */ function claimTokens(address _token) public nonReentrant { require(fundsDestination != address(0)); require(_token != address(token), "native token funds can't be recovered"); uint256 _amount = IERC20Token(_token).balanceOf(address(this)); IERC20Token(_token).transfer(fundsDestination, _amount); } } // File: contracts/Utils.sol contract Utils { function getChainID() internal view returns (uint256) { uint256 chainID; assembly { chainID := chainid() } return chainID; } function max(uint a, uint b) internal pure returns (uint) { return a > b ? a : b; } function min(uint a, uint b) internal pure returns (uint) { return a < b ? a : b; } function round(uint a, uint m) internal pure returns (uint ) { return ((a + m - 1) / m) * m; } } // File: contracts/HermesImplementation.sol interface IdentityRegistry { function isRegistered(address _identity) external view returns (bool); function minimalHermesStake() external view returns (uint256); function getChannelAddress(address _identity, address _hermesId) external view returns (address); function getBeneficiary(address _identity) external view returns (address); function setBeneficiary(address _identity, address _newBeneficiary, bytes memory _signature) external; } // Hermes (channel balance provided by Herms, no staking/loans) contract HermesImplementation is FundsRecovery, Utils { using ECDSA for bytes32; string constant STAKE_RETURN_PREFIX = "Stake return request"; uint256 constant DELAY_SECONDS = 259200; // 3 days uint256 constant UNIT_SECONDS = 3600; // 1 unit = 1 hour = 3600 seconds uint16 constant PUNISHMENT_PERCENT = 4; // 0.04% IdentityRegistry internal registry; address internal operator; // TODO have master operator who could change operator or manage funds uint256 internal totalStake; // total amount staked by providers uint256 internal minStake; // minimal possible provider's stake (channel opening during promise settlement will use it) uint256 internal maxStake; // maximal allowed provider's stake uint256 internal hermesStake; // hermes stake is used to prove hermes' sustainability uint256 internal closingTimelock; // blocknumber after which getting stake back will become possible IUniswapV2Router internal dex; // any uniswap v2 compatible dex router address enum Status { Active, Paused, Punishment, Closed } // hermes states Status internal status; struct HermesFee { uint16 value; // subprocent amount. e.g. 2.5% = 250 uint64 validFrom; // timestamp from which fee is valid } HermesFee public lastFee; // default fee to look for HermesFee public previousFee; // previous fee is used if last fee is still not active // Our channel don't have balance, because we're always rebalancing into stake amount. struct Channel { uint256 settled; // total amount already settled by provider uint256 stake; // amount staked by identity to guarante channel size, it also serves as channel balance uint256 lastUsedNonce; // last known nonce, is used to protect signature based calls from replay attack uint256 timelock; // blocknumber after which channel balance can be decreased } mapping(bytes32 => Channel) public channels; struct Punishment { uint256 activationBlockTime; // block timestamp in which punishment was activated uint256 amount; // total amount of tokens locked because of punishment } Punishment public punishment; function getOperator() public view returns (address) { return operator; } function getChannelId(address _identity) public view returns (bytes32) { return keccak256(abi.encodePacked(_identity, address(this))); } function getChannelId(address _identity, string memory _type) public view returns (bytes32) { return keccak256(abi.encodePacked(_identity, address(this), _type)); } function getRegistry() public view returns (address) { return address(registry); } function getActiveFee() public view returns (uint256) { HermesFee memory _activeFee = (block.timestamp >= lastFee.validFrom) ? lastFee : previousFee; return uint256(_activeFee.value); } function getHermesStake() public view returns (uint256) { return hermesStake; } function getStakeThresholds() public view returns (uint256, uint256) { return (minStake, maxStake); } // Returns hermes state // Active - all operations are allowed. // Paused - no new channel openings. // Punishment - don't allow to open new channels, rebalance and withdraw funds. // Closed - no new channels, no rebalance, no stake increase. function getStatus() public view returns (Status) { return status; } event PromiseSettled(address indexed identity, bytes32 indexed channelId, address indexed beneficiary, uint256 amountSentToBeneficiary, uint256 fees, bytes32 lock); event NewStake(bytes32 indexed channelId, uint256 stakeAmount); event MinStakeValueUpdated(uint256 newMinStake); event MaxStakeValueUpdated(uint256 newMaxStake); event HermesFeeUpdated(uint16 newFee, uint64 validFrom); event HermesClosed(uint256 blockTimestamp); event ChannelOpeningPaused(); event ChannelOpeningActivated(); event FundsWithdrawned(uint256 amount, address beneficiary); event HermesStakeIncreased(uint256 newStake); event HermesPunishmentActivated(uint256 activationBlockTime); event HermesPunishmentDeactivated(); modifier onlyOperator() { require(msg.sender == operator, "Hermes: only hermes operator can call this function"); _; } /* ------------------------------------------- SETUP ------------------------------------------- */ // Because of proxy pattern this function is used insted of constructor. // Have to be called right after proxy deployment. function initialize(address _token, address _operator, uint16 _fee, uint256 _minStake, uint256 _maxStake, address payable _dexAddress) public virtual { require(!isInitialized(), "Hermes: have to be not initialized"); require(_token != address(0), "Hermes: token can't be deployd into zero address"); require(_operator != address(0), "Hermes: operator have to be set"); require(_fee <= 5000, "Hermes: fee can't be bigger than 50%"); require(_maxStake > _minStake, "Hermes: maxStake have to be bigger than minStake"); registry = IdentityRegistry(msg.sender); token = IERC20Token(_token); operator = _operator; lastFee = HermesFee(_fee, uint64(block.timestamp)); minStake = _minStake; maxStake = _maxStake; hermesStake = token.balanceOf(address(this)); // Approving all myst for dex, because MYST token's `transferFrom` is cheaper when there is approval of uint(-1) token.approve(_dexAddress, type(uint256).max); dex = IUniswapV2Router(_dexAddress); } function isInitialized() public view returns (bool) { return operator != address(0); } /* -------------------------------------- MAIN FUNCTIONALITY ----------------------------------- */ // Open incoming payments (also known as provider) channel. Can be called only by Registry. function openChannel(address _identity, uint256 _amountToStake) public { require(msg.sender == address(registry), "Hermes: only registry can open channels"); require(getStatus() == Status.Active, "Hermes: have to be in active state"); require(_amountToStake >= minStake, "Hermes: min stake amount not reached"); _increaseStake(getChannelId(_identity), _amountToStake, false); } // Settle promise // _preimage is random number generated by receiver used in HTLC function _settlePromise( bytes32 _channelId, uint256 _amount, uint256 _transactorFee, bytes32 _preimage, bytes memory _signature, bool _takeFee, bool _ignoreStake ) private returns (uint256, uint256) { require( isHermesActive(), "Hermes: hermes have to be in active state" ); // if hermes is not active, then users can only take stake back require( validatePromise(_channelId, _amount, _transactorFee, _preimage, _signature), "Hermes: have to be properly signed payment promise" ); Channel storage _channel = channels[_channelId]; require(_channel.settled > 0 || _channel.stake >= minStake || _ignoreStake, "Hermes: not enough stake"); // If there are not enought funds to rebalance we have to enable punishment mode. uint256 _availableBalance = availableBalance(); if (_availableBalance < _channel.stake) { status = Status.Punishment; punishment.activationBlockTime = block.timestamp; emit HermesPunishmentActivated(block.timestamp); } // Calculate amount of tokens to be claimed. uint256 _unpaidAmount = _amount - _channel.settled; require(_unpaidAmount > _transactorFee, "Hermes: amount to settle should cover transactor fee"); // It is not allowed to settle more than maxStake / _channel.stake and than available balance. uint256 _maxSettlementAmount = max(maxStake, _channel.stake); if (_unpaidAmount > _availableBalance || _unpaidAmount > _maxSettlementAmount) { _unpaidAmount = min(_availableBalance, _maxSettlementAmount); } _channel.settled = _channel.settled + _unpaidAmount; // Increase already paid amount. uint256 _fees = _transactorFee + (_takeFee ? calculateHermesFee(_unpaidAmount) : 0); // Pay transactor fee if (_transactorFee > 0) { token.transfer(msg.sender, _transactorFee); } uint256 _amountToTransfer = _unpaidAmount -_fees; return (_amountToTransfer, _fees); } function settlePromise(address _identity, uint256 _amount, uint256 _transactorFee, bytes32 _preimage, bytes memory _signature) public { address _beneficiary = registry.getBeneficiary(_identity); require(_beneficiary != address(0), "Hermes: identity have to be registered, beneficiary have to be set"); // Settle promise and transfer calculated amount into beneficiary wallet bytes32 _channelId = getChannelId(_identity); (uint256 _amountToTransfer, uint256 _fees) = _settlePromise(_channelId, _amount, _transactorFee, _preimage, _signature, true, false); token.transfer(_beneficiary, _amountToTransfer); emit PromiseSettled(_identity, _channelId, _beneficiary, _amountToTransfer, _fees, _preimage); } function payAndSettle(address _identity, uint256 _amount, uint256 _transactorFee, bytes32 _preimage, bytes memory _signature, address _beneficiary, bytes memory _beneficiarySignature) public { bytes32 _channelId = getChannelId(_identity, "withdrawal"); // Validate beneficiary to be signed by identity and be attached to given promise address _signer = keccak256(abi.encodePacked(getChainID(), _channelId, _amount, _preimage, _beneficiary)).recover(_beneficiarySignature); require(_signer == _identity, "Hermes: payAndSettle request should be properly signed"); (uint256 _amountToTransfer, uint256 _fees) = _settlePromise(_channelId, _amount, _transactorFee, _preimage, _signature, false, true); token.transfer(_beneficiary, _amountToTransfer); emit PromiseSettled(_identity, _channelId, _beneficiary, _amountToTransfer, _fees, _preimage); } function settleWithBeneficiary(address _identity, uint256 _amount, uint256 _transactorFee, bytes32 _preimage, bytes memory _promiseSignature, address _newBeneficiary, bytes memory _beneficiarySignature) public { // Update beneficiary address registry.setBeneficiary(_identity, _newBeneficiary, _beneficiarySignature); // Settle promise and transfer calculated amount into beneficiary wallet bytes32 _channelId = getChannelId(_identity); (uint256 _amountToTransfer, uint256 _fees) = _settlePromise(_channelId, _amount, _transactorFee, _preimage, _promiseSignature, true, false); token.transfer(_newBeneficiary, _amountToTransfer); emit PromiseSettled(_identity, _channelId, _newBeneficiary, _amountToTransfer, _fees, _preimage); } function settleWithDEX(address _identity, uint256 _amount, uint256 _transactorFee, bytes32 _preimage, bytes memory _signature) public { address _beneficiary = registry.getBeneficiary(_identity); require(_beneficiary != address(0), "Hermes: identity have to be registered, beneficiary have to be set"); // Calculate amount to transfer and settle promise bytes32 _channelId = getChannelId(_identity); (uint256 _amountToTransfer, uint256 _fees) = _settlePromise(_channelId, _amount, _transactorFee, _preimage, _signature, true, false); // Transfer funds into beneficiary wallet via DEX uint amountOutMin = 0; address[] memory path = new address[](2); path[0] = address(token); path[1] = dex.WETH(); dex.swapExactTokensForETH(_amountToTransfer, amountOutMin, path, _beneficiary, block.timestamp); emit PromiseSettled(_identity, _channelId, _beneficiary, _amountToTransfer, _fees, _preimage); } /* -------------------------------------- STAKE MANAGEMENT -------------------------------------- */ function _increaseStake(bytes32 _channelId, uint256 _amountToAdd, bool _duringSettlement) internal { Channel storage _channel = channels[_channelId]; uint256 _newStakeAmount = _channel.stake +_amountToAdd; require(_newStakeAmount <= maxStake, "Hermes: total amount to stake can't be bigger than maximally allowed"); require(_newStakeAmount >= minStake, "Hermes: stake can't be less than required min stake"); // We don't transfer tokens during settlements, they already locked in hermes contract. if (!_duringSettlement) { require(token.transferFrom(msg.sender, address(this), _amountToAdd), "Hermes: token transfer should succeed"); } _channel.stake = _newStakeAmount; totalStake = totalStake + _amountToAdd; emit NewStake(_channelId, _newStakeAmount); } // Anyone can increase channel's capacity by staking more into hermes function increaseStake(bytes32 _channelId, uint256 _amount) public { require(getStatus() != Status.Closed, "hermes should be not closed"); _increaseStake(_channelId, _amount, false); } // Settlement which will increase channel stake instead of transfering funds into beneficiary wallet. function settleIntoStake(address _identity, uint256 _amount, uint256 _transactorFee, bytes32 _preimage, bytes memory _signature) public { bytes32 _channelId = getChannelId(_identity); (uint256 _stakeIncreaseAmount, uint256 _paidFees) = _settlePromise(_channelId, _amount, _transactorFee, _preimage, _signature, true, true); emit PromiseSettled(_identity, _channelId, address(this), _stakeIncreaseAmount, _paidFees, _preimage); _increaseStake(_channelId, _stakeIncreaseAmount, true); } // Withdraw part of stake. This will also decrease channel balance. function decreaseStake(address _identity, uint256 _amount, uint256 _transactorFee, bytes memory _signature) public { bytes32 _channelId = getChannelId(_identity); require(isChannelOpened(_channelId), "Hermes: channel has to be opened"); require(_amount >= _transactorFee, "Hermes: amount should be bigger than transactor fee"); Channel storage _channel = channels[_channelId]; require(_amount <= _channel.stake, "Hermes: can't withdraw more than the current stake"); // Verify signature _channel.lastUsedNonce = _channel.lastUsedNonce + 1; address _signer = keccak256(abi.encodePacked(STAKE_RETURN_PREFIX, getChainID(), _channelId, _amount, _transactorFee, _channel.lastUsedNonce)).recover(_signature); require(getChannelId(_signer) == _channelId, "Hermes: have to be signed by channel party"); uint256 _newStakeAmount = _channel.stake - _amount; require(_newStakeAmount == 0 || _newStakeAmount >= minStake, "Hermes: stake can't be less than required min stake"); // Update channel state _channel.stake = _newStakeAmount; totalStake = totalStake - _amount; // Pay transacor fee then withdraw the rest if (_transactorFee > 0) { token.transfer(msg.sender, _transactorFee); } address _beneficiary = registry.getBeneficiary(_identity); token.transfer(_beneficiary, _amount - _transactorFee); emit NewStake(_channelId, _newStakeAmount); } /* --------------------------------------------------------------------------------------------- */ // Hermes is in Emergency situation when its status is `Punishment`. function resolveEmergency() public { require(getStatus() == Status.Punishment, "Hermes: should be in punishment status"); // 0.04% of total channels amount per time unit uint256 _punishmentPerUnit = round(totalStake * PUNISHMENT_PERCENT, 100) / 100; // No punishment during first time unit uint256 _unit = getUnitTime(); uint256 _timePassed = block.timestamp - punishment.activationBlockTime; uint256 _punishmentUnits = round(_timePassed, _unit) / _unit - 1; uint256 _punishmentAmount = _punishmentUnits * _punishmentPerUnit; punishment.amount = punishment.amount + _punishmentAmount; // XXX alternativelly we could send tokens into BlackHole (0x0000000...) uint256 _shouldHave = minimalExpectedBalance() + maxStake; // hermes should have funds for at least one maxStake settlement uint256 _currentBalance = token.balanceOf(address(this)); // If there are not enough available funds, they have to be topuped from msg.sender. if (_currentBalance < _shouldHave) { token.transferFrom(msg.sender, address(this), _shouldHave - _currentBalance); } // Disable punishment mode status = Status.Active; emit HermesPunishmentDeactivated(); } function getUnitTime() internal pure virtual returns (uint256) { return UNIT_SECONDS; } function setMinStake(uint256 _newMinStake) public onlyOwner { require(isHermesActive(), "Hermes: has to be active"); require(_newMinStake < maxStake, "Hermes: minStake has to be smaller than maxStake"); minStake = _newMinStake; emit MinStakeValueUpdated(_newMinStake); } function setMaxStake(uint256 _newMaxStake) public onlyOwner { require(isHermesActive(), "Hermes: has to be active"); require(_newMaxStake > minStake, "Hermes: maxStake has to be bigger than minStake"); maxStake = _newMaxStake; emit MaxStakeValueUpdated(_newMaxStake); } function setHermesFee(uint16 _newFee) public onlyOwner { require(getStatus() != Status.Closed, "Hermes: should be not closed"); require(_newFee <= 5000, "Hermes: fee can't be bigger than 50%"); require(block.timestamp >= lastFee.validFrom, "Hermes: can't update inactive fee"); // New fee will start be valid after delay time will pass uint64 _validFrom = uint64(getTimelock()); previousFee = lastFee; lastFee = HermesFee(_newFee, _validFrom); emit HermesFeeUpdated(_newFee, _validFrom); } function increaseHermesStake(uint256 _additionalStake) public onlyOwner { if (availableBalance() < _additionalStake) { uint256 _diff = _additionalStake - availableBalance(); token.transferFrom(msg.sender, address(this), _diff); } hermesStake = hermesStake + _additionalStake; emit HermesStakeIncreased(hermesStake); } // Hermes's available funds withdrawal. Can be done only if hermes is not closed and not in punishment mode. // Hermes can't withdraw stake, locked in channel funds and funds lended to him. function withdraw(address _beneficiary, uint256 _amount) public onlyOwner { require(isHermesActive(), "Hermes: have to be active"); require(availableBalance() >= _amount, "Hermes: should be enough funds available to withdraw"); token.transfer(_beneficiary, _amount); emit FundsWithdrawned(_amount, _beneficiary); } // Returns funds amount not locked in any channel, not staked and not lended from providers. function availableBalance() public view returns (uint256) { uint256 _totalLockedAmount = minimalExpectedBalance(); uint256 _currentBalance = token.balanceOf(address(this)); if (_totalLockedAmount > _currentBalance) { return uint256(0); } return _currentBalance - _totalLockedAmount; } // Returns true if channel is opened. function isChannelOpened(bytes32 _channelId) public view returns (bool) { return channels[_channelId].settled != 0 || channels[_channelId].stake != 0; } // If Hermes is not closed and is not in punishment mode, he is active. function isHermesActive() public view returns (bool) { Status _status = getStatus(); return _status != Status.Punishment && _status != Status.Closed; } function pauseChannelOpening() public onlyOperator { require(getStatus() == Status.Active, "Hermes: have to be in active state"); status = Status.Paused; emit ChannelOpeningPaused(); } function activateChannelOpening() public onlyOperator { require(getStatus() == Status.Paused, "Hermes: have to be in paused state"); status = Status.Active; emit ChannelOpeningActivated(); } function closeHermes() public onlyOwner { require(isHermesActive(), "Hermes: should be active"); status = Status.Closed; closingTimelock = getEmergencyTimelock(); emit HermesClosed(block.timestamp); } function getStakeBack(address _beneficiary) public onlyOwner { require(getStatus() == Status.Closed, "Hermes: have to be closed"); require(block.timestamp > closingTimelock, "Hermes: timelock period should be already passed"); uint256 _amount = token.balanceOf(address(this)) - punishment.amount; token.transfer(_beneficiary, _amount); } /* ------------------------------------------ HELPERS ------------------------------------------ */ // Returns timestamp until which exit request should be locked function getTimelock() internal view virtual returns (uint256) { return block.timestamp + DELAY_SECONDS; } function calculateHermesFee(uint256 _amount) public view returns (uint256) { return round((_amount * getActiveFee() / 100), 100) / 100; } // Funds which always have to be holded in hermes smart contract. function minimalExpectedBalance() public view returns (uint256) { return max(hermesStake, punishment.amount) + totalStake; } function getEmergencyTimelock() internal view virtual returns (uint256) { return block.timestamp + DELAY_SECONDS * 100; // 300 days } function validatePromise(bytes32 _channelId, uint256 _amount, uint256 _transactorFee, bytes32 _preimage, bytes memory _signature) public view returns (bool) { bytes32 _hashlock = keccak256(abi.encodePacked(_preimage)); address _signer = keccak256(abi.encodePacked(getChainID(), _channelId, _amount, _transactorFee, _hashlock)).recover(_signature); return _signer == operator; } }
Returns true if channel is opened.
function isChannelOpened(bytes32 _channelId) public view returns (bool) { return channels[_channelId].settled != 0 || channels[_channelId].stake != 0; }
15,090,114
[ 1, 1356, 638, 309, 1904, 353, 10191, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 353, 2909, 23115, 12, 3890, 1578, 389, 4327, 548, 13, 1071, 1476, 1135, 261, 6430, 13, 288, 203, 3639, 327, 5750, 63, 67, 4327, 548, 8009, 542, 88, 1259, 480, 374, 747, 5750, 63, 67, 4327, 548, 8009, 334, 911, 480, 374, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/97/0x245641B5a95a2B865879F743E2032b7b71EC0e69/sources/EDC.sol
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include the optional functions; to access them see {ERC20Detailed}./
interface IERC20 { function totalSupply() external view returns (uint256); function decimals() external view returns (uint256); function symbol() external view returns (string memory); function getOwner() external view returns (address); 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); }
11,446,706
[ 1, 1358, 434, 326, 4232, 39, 3462, 4529, 487, 2553, 316, 326, 512, 2579, 18, 9637, 486, 2341, 326, 3129, 4186, 31, 358, 2006, 2182, 2621, 288, 654, 39, 3462, 40, 6372, 5496, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 5831, 467, 654, 39, 3462, 288, 203, 565, 445, 2078, 3088, 1283, 1435, 3903, 1476, 1135, 261, 11890, 5034, 1769, 203, 377, 203, 565, 445, 15105, 1435, 3903, 1476, 1135, 261, 11890, 5034, 1769, 203, 377, 203, 565, 445, 3273, 1435, 3903, 1476, 1135, 261, 1080, 3778, 1769, 203, 377, 203, 565, 445, 13782, 1435, 3903, 1476, 1135, 261, 2867, 1769, 203, 203, 565, 445, 11013, 951, 12, 2867, 2236, 13, 3903, 1476, 1135, 261, 11890, 5034, 1769, 203, 203, 565, 445, 7412, 12, 2867, 8027, 16, 2254, 5034, 3844, 13, 3903, 1135, 261, 6430, 1769, 203, 203, 565, 445, 1699, 1359, 12, 2867, 3410, 16, 1758, 17571, 264, 13, 3903, 1476, 1135, 261, 11890, 5034, 1769, 203, 203, 565, 445, 6617, 537, 12, 2867, 17571, 264, 16, 2254, 5034, 3844, 13, 3903, 1135, 261, 6430, 1769, 203, 203, 565, 445, 7412, 1265, 12, 2867, 5793, 16, 1758, 8027, 16, 2254, 5034, 3844, 13, 3903, 1135, 261, 6430, 1769, 203, 203, 565, 871, 12279, 12, 2867, 8808, 628, 16, 1758, 8808, 358, 16, 2254, 5034, 460, 1769, 203, 203, 565, 871, 1716, 685, 1125, 12, 2867, 8808, 3410, 16, 1758, 8808, 17571, 264, 16, 2254, 5034, 460, 1769, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/5/0x1C8dad3dc796d795903c86f827bee5393D29e70A/sources/DividendPool.sol
* @dev deposit erc20 token to dividend pool @param amount amount of erc20 token/ check allowance
function deposit(uint256 amount) external { require(amount > 0, "DividendPool: invalid amount"); IERC20 erc20 = ERC20(); require( erc20.allowance(msg.sender, address(this)) >= amount, "DividendPool: insufficient allowance" ); require( erc20.balanceOf(msg.sender) >= amount, "DividendPool: insufficient balance" ); try erc20.transferFrom(msg.sender, address(this), amount) returns ( bool success ) { require(success, "DividendPool: transferFrom failed"); _currentBalance += amount; emit Deposit(amount); revert("DividendPool: transferFrom failed"); } }
16,875,697
[ 1, 323, 1724, 6445, 71, 3462, 1147, 358, 31945, 2845, 225, 3844, 3844, 434, 6445, 71, 3462, 1147, 19, 866, 1699, 1359, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 443, 1724, 12, 11890, 5034, 3844, 13, 3903, 288, 203, 3639, 2583, 12, 8949, 405, 374, 16, 315, 7244, 26746, 2864, 30, 2057, 3844, 8863, 203, 3639, 467, 654, 39, 3462, 6445, 71, 3462, 273, 4232, 39, 3462, 5621, 203, 3639, 2583, 12, 203, 5411, 6445, 71, 3462, 18, 5965, 1359, 12, 3576, 18, 15330, 16, 1758, 12, 2211, 3719, 1545, 3844, 16, 203, 5411, 315, 7244, 26746, 2864, 30, 2763, 11339, 1699, 1359, 6, 203, 3639, 11272, 203, 3639, 2583, 12, 203, 5411, 6445, 71, 3462, 18, 12296, 951, 12, 3576, 18, 15330, 13, 1545, 3844, 16, 203, 5411, 315, 7244, 26746, 2864, 30, 2763, 11339, 11013, 6, 203, 3639, 11272, 203, 3639, 775, 6445, 71, 3462, 18, 13866, 1265, 12, 3576, 18, 15330, 16, 1758, 12, 2211, 3631, 3844, 13, 1135, 261, 203, 5411, 1426, 2216, 203, 3639, 262, 288, 203, 5411, 2583, 12, 4768, 16, 315, 7244, 26746, 2864, 30, 7412, 1265, 2535, 8863, 203, 5411, 389, 2972, 13937, 1011, 3844, 31, 203, 5411, 3626, 4019, 538, 305, 12, 8949, 1769, 203, 5411, 15226, 2932, 7244, 26746, 2864, 30, 7412, 1265, 2535, 8863, 203, 3639, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/4/0xA1d27c20AfddD4F7E1E4eA59b534FEb9b31e1609/sources/contracts/PetToken4.sol
TODO: set Address site
contract PetToken is RawToken { uint256 base_price = 18000000000000000000000; uint256 deposit_price = 23000000000000000000000; uint256 benefits_period = TROPICAL_YEAR; uint256 interest_rate_future = 100000000000000000; uint256 interest_rate_resource = 250000000000000000; uint256 tokensToSaleF = 0; uint256 tokensToSaleR = 0; uint256 tokensAlreadySoldF = 0; uint256 tokensAlreadySoldR = 0; }
12,477,765
[ 1, 6241, 30, 444, 5267, 2834, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 16351, 453, 278, 1345, 353, 6576, 1345, 288, 203, 203, 203, 203, 565, 2254, 5034, 1026, 67, 8694, 273, 6549, 12648, 12648, 11706, 31, 203, 565, 2254, 5034, 443, 1724, 67, 8694, 273, 10213, 12648, 12648, 11706, 31, 203, 565, 2254, 5034, 27641, 18352, 67, 6908, 273, 399, 1457, 1102, 7913, 67, 15137, 31, 203, 565, 2254, 5034, 16513, 67, 5141, 67, 14343, 273, 2130, 12648, 17877, 31, 203, 565, 2254, 5034, 16513, 67, 5141, 67, 3146, 273, 6969, 12648, 12648, 31, 203, 203, 203, 565, 2254, 5034, 2430, 774, 30746, 42, 273, 374, 31, 203, 565, 2254, 5034, 2430, 774, 30746, 54, 273, 374, 31, 203, 565, 2254, 5034, 2430, 9430, 55, 1673, 42, 273, 374, 31, 203, 565, 2254, 5034, 2430, 9430, 55, 1673, 54, 273, 374, 31, 203, 203, 203, 203, 203, 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 ]
./full_match/1/0xE60a57cc57b51C4e801Ee8a0E6Df675F94abC0af/sources/contracts/ShopXReserveNFT.sol
* @dev Returns the number of NFTs that has been claimed by an address so far. @param _address The address to check./
function getClaimed(address _address) public view returns (uint256) { return claimed[_address]; }
4,887,300
[ 1, 1356, 326, 1300, 434, 423, 4464, 87, 716, 711, 2118, 7516, 329, 635, 392, 1758, 1427, 10247, 18, 225, 389, 2867, 1021, 1758, 358, 866, 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, 225, 445, 13674, 4581, 329, 12, 2867, 389, 2867, 13, 1071, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 565, 327, 7516, 329, 63, 67, 2867, 15533, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/access/AccessControl.sol"; import "./IPermissions.sol"; /// @title Access control module for Core /// @author Fei Protocol contract Permissions is IPermissions, AccessControl { bytes32 public constant BURNER_ROLE = keccak256("BURNER_ROLE"); bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); bytes32 public constant PCV_CONTROLLER_ROLE = keccak256("PCV_CONTROLLER_ROLE"); bytes32 public constant GOVERN_ROLE = keccak256("GOVERN_ROLE"); bytes32 public constant GUARDIAN_ROLE = keccak256("GUARDIAN_ROLE"); constructor() { // Appointed as a governor so guardian can have indirect access to revoke ability _setupGovernor(address(this)); _setRoleAdmin(MINTER_ROLE, GOVERN_ROLE); _setRoleAdmin(BURNER_ROLE, GOVERN_ROLE); _setRoleAdmin(PCV_CONTROLLER_ROLE, GOVERN_ROLE); _setRoleAdmin(GOVERN_ROLE, GOVERN_ROLE); _setRoleAdmin(GUARDIAN_ROLE, GOVERN_ROLE); } modifier onlyGovernor() { require( isGovernor(msg.sender), "Permissions: Caller is not a governor" ); _; } modifier onlyGuardian() { require(isGuardian(msg.sender), "Permissions: Caller is not a guardian"); _; } /// @notice creates a new role to be maintained /// @param role the new role id /// @param adminRole the admin role id for `role` /// @dev can also be used to update admin of existing role function createRole(bytes32 role, bytes32 adminRole) external override onlyGovernor { _setRoleAdmin(role, adminRole); } /// @notice grants minter role to address /// @param minter new minter function grantMinter(address minter) external override onlyGovernor { grantRole(MINTER_ROLE, minter); } /// @notice grants burner role to address /// @param burner new burner function grantBurner(address burner) external override onlyGovernor { grantRole(BURNER_ROLE, burner); } /// @notice grants controller role to address /// @param pcvController new controller function grantPCVController(address pcvController) external override onlyGovernor { grantRole(PCV_CONTROLLER_ROLE, pcvController); } /// @notice grants governor role to address /// @param governor new governor function grantGovernor(address governor) external override onlyGovernor { grantRole(GOVERN_ROLE, governor); } /// @notice grants guardian role to address /// @param guardian new guardian function grantGuardian(address guardian) external override onlyGovernor { grantRole(GUARDIAN_ROLE, guardian); } /// @notice revokes minter role from address /// @param minter ex minter function revokeMinter(address minter) external override onlyGovernor { revokeRole(MINTER_ROLE, minter); } /// @notice revokes burner role from address /// @param burner ex burner function revokeBurner(address burner) external override onlyGovernor { revokeRole(BURNER_ROLE, burner); } /// @notice revokes pcvController role from address /// @param pcvController ex pcvController function revokePCVController(address pcvController) external override onlyGovernor { revokeRole(PCV_CONTROLLER_ROLE, pcvController); } /// @notice revokes governor role from address /// @param governor ex governor function revokeGovernor(address governor) external override onlyGovernor { revokeRole(GOVERN_ROLE, governor); } /// @notice revokes guardian role from address /// @param guardian ex guardian function revokeGuardian(address guardian) external override onlyGovernor { revokeRole(GUARDIAN_ROLE, guardian); } /// @notice revokes a role from address /// @param role the role to revoke /// @param account the address to revoke the role from function revokeOverride(bytes32 role, address account) external override onlyGuardian { require(role != GOVERN_ROLE, "Permissions: Guardian cannot revoke governor"); // External call because this contract is appointed as a governor and has access to revoke this.revokeRole(role, account); } /// @notice checks if address is a minter /// @param _address address to check /// @return true _address is a minter function isMinter(address _address) external view override returns (bool) { return hasRole(MINTER_ROLE, _address); } /// @notice checks if address is a burner /// @param _address address to check /// @return true _address is a burner function isBurner(address _address) external view override returns (bool) { return hasRole(BURNER_ROLE, _address); } /// @notice checks if address is a controller /// @param _address address to check /// @return true _address is a controller function isPCVController(address _address) external view override returns (bool) { return hasRole(PCV_CONTROLLER_ROLE, _address); } /// @notice checks if address is a governor /// @param _address address to check /// @return true _address is a governor // only virtual for testing mock override function isGovernor(address _address) public view virtual override returns (bool) { return hasRole(GOVERN_ROLE, _address); } /// @notice checks if address is a guardian /// @param _address address to check /// @return true _address is a guardian function isGuardian(address _address) public view override returns (bool) { return hasRole(GUARDIAN_ROLE, _address); } function _setupGovernor(address governor) internal { _setupRole(GOVERN_ROLE, governor); } }
@notice checks if address is a controller @param _address address to check @return true _address is a controller
function isPCVController(address _address) external view override returns (bool) { return hasRole(PCV_CONTROLLER_ROLE, _address); }
5,380,094
[ 1, 12366, 309, 1758, 353, 279, 2596, 225, 389, 2867, 1758, 358, 866, 327, 638, 389, 2867, 353, 279, 2596, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 353, 3513, 58, 2933, 12, 2867, 389, 2867, 13, 203, 3639, 3903, 203, 3639, 1476, 203, 3639, 3849, 203, 3639, 1135, 261, 6430, 13, 203, 565, 288, 203, 3639, 327, 28335, 12, 3513, 58, 67, 6067, 25353, 67, 16256, 16, 389, 2867, 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 ]
./full_match/40/0x3180eD3212109c2f33b4675e10d1950586BD6524/sources/project_/contracts/ERC20RewardApeV1.sol
@notice A public function to sweep accidental BEP20 transfers to this contract. Tokens are sent to owner @param token The address of the BEP20 token to sweep
function sweepToken(IERC20 token) external onlyOwner { require( address(token) != address(STAKE_TOKEN), "can not sweep stake token" ); require( address(token) != address(REWARD_TOKEN), "can not sweep reward token" ); uint256 balance = token.balanceOf(address(this)); token.safeTransfer(msg.sender, balance); emit EmergencySweepWithdraw(msg.sender, token, balance); }
9,543,512
[ 1, 37, 1071, 445, 358, 17462, 25961, 287, 9722, 52, 3462, 29375, 358, 333, 6835, 18, 282, 13899, 854, 3271, 358, 3410, 225, 1147, 1021, 1758, 434, 326, 9722, 52, 3462, 1147, 358, 17462, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 17462, 1345, 12, 45, 654, 39, 3462, 1147, 13, 3903, 1338, 5541, 288, 203, 3639, 2583, 12, 203, 5411, 1758, 12, 2316, 13, 480, 1758, 12, 882, 37, 6859, 67, 8412, 3631, 203, 5411, 315, 4169, 486, 17462, 384, 911, 1147, 6, 203, 3639, 11272, 203, 3639, 2583, 12, 203, 5411, 1758, 12, 2316, 13, 480, 1758, 12, 862, 21343, 67, 8412, 3631, 203, 5411, 315, 4169, 486, 17462, 19890, 1147, 6, 203, 3639, 11272, 203, 3639, 2254, 5034, 11013, 273, 1147, 18, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 3639, 1147, 18, 4626, 5912, 12, 3576, 18, 15330, 16, 11013, 1769, 203, 3639, 3626, 512, 6592, 75, 2075, 55, 25236, 1190, 9446, 12, 3576, 18, 15330, 16, 1147, 16, 11013, 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 ]
// Contracts/SupplyChain.sol // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "@openzeppelin/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "../emeraldaccesscontrol/MinerRole.sol"; import "../emeraldaccesscontrol/LaboratoryRole.sol"; import "../emeraldaccesscontrol/CustodianRole.sol"; import "../emeraldaccesscontrol/ManufacturerRole.sol"; import "../emeraldaccesscontrol/CustomerRole.sol"; import "./EmeraldStates.sol"; import "./Emerald.sol"; // Define a contract 'Supplychain' contract SupplyChain is Ownable, AccessControl, MinerRole, LaboratoryRole, CustodianRole, ManufacturerRole, CustomerRole{ // Define a variable called 'upc' for Universal Product Code (UPC) uint upc; // Define a variable called 'sku' for Stock Keeping Unit (SKU) uint sku; // Define a public mapping 'emeralds' that maps the UPC to an Emerald. mapping (uint => Emerald) emeralds; // Define a public mapping 'emeraldHistory' that maps the UPC to an array of TxHash, // that track its journey through the supply chain -- to be sent from DApp. mapping (uint => string[]) emeraldsHistory; EmeraldStates.State constant defaultState = EmeraldStates.State.Mined; // Define 17 events with the same 17 state values and accept 'upc' as input argument event Mined(uint upc); event Scaled(uint upc); event PackedForLab(uint upc); event ShipedToLab(uint upc); event LabReceived(uint upc); event Certified(uint upc); event ShippedToStore(uint upc); event StorageReceived(uint upc); event Stored(uint upc); event ForSale(uint upc); event Sold(uint upc); event ShipToManufacture(uint upc); event ManufacturerReceived(uint upc); event Manufactured(uint upc); event PackedForSale(uint upc); event Published(uint upc); event Buyed(uint upc); event ShippedToCustomer(uint upc); event Delivered(uint upc); // Define a modifer that verifies the Caller modifier verifyCaller (address _address) { require(msg.sender == _address); _; } // Define a modifier that checks if the paid amount is sufficient to cover the price modifier paidEnough(uint _price) { require(msg.value >= _price,"Not enought paid amount"); _; } // Define a modifier that checks the price and refunds the remaining balance modifier checkValue(uint _upc) { _; uint _price = emeralds[_upc].GetMarketPrice(); uint amountToReturn = msg.value - _price; msg.sender.transfer(amountToReturn); } // Checks if a emerald is Mined modifier mined(uint _upc) { require(emeralds[_upc].GetEmeraldState() == EmeraldStates.State.Mined); _; } //Checks if an emerald was escaled modifier scaled(uint _upc) { require(emeralds[_upc].GetEmeraldState() == EmeraldStates.State.Scaled); _; } //Checks if an emerald is packed modifier packedForLab(uint _upc) { require(emeralds[_upc].GetEmeraldState() == EmeraldStates.State.PackedForLab); _; } // Checks if an emerald was shipped to the laboratory modifier shipedToLab(uint _upc) { require(emeralds[_upc].GetEmeraldState() == EmeraldStates.State.ShipedToLab); _; } // Checks if an emerald was received by the Laboratory modifier labReceived(uint _upc) { require(emeralds[_upc].GetEmeraldState() == EmeraldStates.State.LabReceived); _; } // Checks if an emerald was certified by the laboratory modifier certified(uint _upc) { require(emeralds[_upc].GetEmeraldState() == EmeraldStates.State.Certified); _; } // Checks if an emerald was shipped to the storage y the laboratory modifier shippedToStore(uint _upc) { require(emeralds[_upc].GetEmeraldState() == EmeraldStates.State.ShippedToStore); _; } // Checks if an emerald was received by the custodian service modifier storageReceived(uint _upc) { require(emeralds[_upc].GetEmeraldState() == EmeraldStates.State.StorageReceived); _; } // Checks if an emerald was stored by the custodian modifier stored(uint _upc) { require(emeralds[_upc].GetEmeraldState() == EmeraldStates.State.Stored); _; } // Checks if a raw emerald is available for sale modifier forSale(uint _upc) { require(emeralds[_upc].GetEmeraldState() == EmeraldStates.State.ForSale); _; } // Checks if a raw emerald was sold modifier sold(uint _upc) { require(emeralds[_upc].GetEmeraldState() == EmeraldStates.State.Sold); _; } // Checks if a sold emerald was shipped to the buyer modifier shiptoManufacture(uint _upc) { require(emeralds[_upc].GetEmeraldState() == EmeraldStates.State.ShipToManufacture); _; } // Checks if an emerald was received by the manufacturer modifier manufacturerReceived(uint _upc) { require(emeralds[_upc].GetEmeraldState() == EmeraldStates.State.ManufacturerReceived); _; } // Checks if an emerald was proccesed by the manufacturer modifier manufactured(uint _upc) { require(emeralds[_upc].GetEmeraldState() == EmeraldStates.State.Manufactured); _; } // Checks if a cut emerald was packed modifier packedForSale(uint _upc) { require(emeralds[_upc].GetEmeraldState() == EmeraldStates.State.PackedForSale); _; } // Checks if an proccesed emerald is ready for sale modifier published(uint _upc) { require(emeralds[_upc].GetEmeraldState() == EmeraldStates.State.Published); _; } // Checks if a proccesed emerald was purshased modifier buyed(uint _upc) { require(emeralds[_upc].GetEmeraldState() == EmeraldStates.State.Buyed); _; } // Checks if a cut emerald was shipped to the buyer modifier shippedToCustomer(uint _upc) { require(emeralds[_upc].GetEmeraldState() == EmeraldStates.State.ShippedToCustomer); _; } // Checks if a cut emerald was received by the customer modifier delivered(uint _upc) { require(emeralds[_upc].GetEmeraldState() == EmeraldStates.State.Delivered); _; } // In the constructor set 'owner' to the address that instantiated the contract // and set 'sku' to 1 // and set 'upc' to 1 constructor() { //owner = msg.sender; sku = 1; upc = 1; _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); } // Define a function 'kill' if required function kill() public onlyOwner{ selfdestruct(msg.sender); } // Define a function 'extractItem' that allows a Miner to mark an emerald as 'Mined' function extractEmerald( uint _sku, uint _upc, address payable _originMinerID, string memory _originMineName, string memory _originMineInformation, string memory _originMineLatitude, string memory _originMineLongitude ) public onlyMiner { //add emerald to emeralds list in the contract Emerald emerald = new Emerald(); emerald.SetExtractionInfo( _sku, _upc, _originMinerID, _originMineName, _originMineInformation, _originMineLatitude, _originMineLongitude ); emerald.SetEmeraldState(EmeraldStates.State.Mined); emeralds[_upc] = emerald; //Increment sku sku = sku + 1; // Emit the appropriate event emit Mined(_upc); } // Define a function 'scaleItem' that allows Miner to mark an item as 'Scaled' function scaleEmerald( uint _upc, string memory _scaleInfo ) public // Call modifier to check if upc has passed previous supply chain stage mined(_upc) // Call modifier to verify caller of this function verifyCaller(emeralds[_upc].GetOwnerID()) onlyMiner { // Update the appropriate fields emeralds[_upc].SetScaleInfo( _scaleInfo ); emeralds[_upc].SetEmeraldState(EmeraldStates.State.Scaled); // Emit the appropriate event emit Scaled(_upc); } //Define a function 'packScaledItem' that allows a Miner to mark an item 'Packed' function packScaledEmerald(uint _upc, address _laboratoryID, address _custodianID) public // Call modifier to check if upc has passed previous supply chain stage scaled(_upc) // Call modifier to verify caller of this function verifyCaller(emeralds[_upc].GetOwnerID()) onlyMiner { // Update the appropriate fields emeralds[_upc].AuthorizeLab(_laboratoryID); emeralds[_upc].AuthorizeCustodian(_custodianID); // Update Emerald state emeralds[_upc].SetEmeraldState(EmeraldStates.State.PackedForLab); // Emit the appropriate event emit PackedForLab(_upc); } // Define a function 'shipToLaboratory' that allows a Miner to mark an item 'ShipToLab' function shipToLaboratory(uint _upc) public // Call modifier to check if upc has passed previous supply chain stage packedForLab(_upc) // Call modifier to verify caller of this function verifyCaller(emeralds[_upc].GetOwnerID()) onlyMiner { // Update the appropriate fields emeralds[_upc].SetEmeraldState(EmeraldStates.State.ShipedToLab); // Emit the appropriate event emit ShipedToLab(_upc); } // Define a function 'shipToLaboratory' that allows a Miner to mark an item 'ShipToLab' function laboratoryReceived(uint _upc) public // Call modifier to check if upc has passed previous supply chain stage shipedToLab(_upc) // Call modifier to verify caller of this function verifyCaller(emeralds[_upc].GetLaboratoryID()) onlyLaboratory { // Update the appropriate fields emeralds[_upc].SetEmeraldState(EmeraldStates.State.LabReceived); // Emit the appropriate event emit LabReceived(_upc); } // Define a function 'scaleItem' that allows a Miner to mark an item 'Processed' function certifyEmerald( uint _upc, string memory _certifiedProperties ) public // Call modifier to check if upc has passed previous supply chain stage labReceived(_upc) // Call modifier to verify caller of this function verifyCaller(emeralds[_upc].GetLaboratoryID()) onlyLaboratory { // Update the appropriate fields emeralds[_upc].SetCertifiedInfo(_certifiedProperties); emeralds[_upc].SetEmeraldState(EmeraldStates.State.Certified); // Emit the appropriate event emit Certified(_upc); } // Define a function 'shipToLaboratory' that allows a Miner to mark an item 'ShipToLab' function shipToSecureStore(uint _upc) public // Call modifier to check if upc has passed previous supply chain stage certified(_upc) // Call modifier to verify caller of this function verifyCaller(emeralds[_upc].GetLaboratoryID()) onlyLaboratory { // Update the appropriate fields emeralds[_upc].SetEmeraldState(EmeraldStates.State.ShippedToStore); // Emit the appropriate event emit ShippedToStore(_upc); } // Define a function 'shipToLaboratory' that allows a Miner to mark an item 'ShipToLab' function SecureStorageReceived(uint _upc) public // Call modifier to check if upc has passed previous supply chain stage shippedToStore(_upc) // Call modifier to verify caller of this function verifyCaller(emeralds[_upc].GetCustodianID()) onlyCustodian { // Update the appropriate fields emeralds[_upc].SetEmeraldState(EmeraldStates.State.StorageReceived); // Emit the appropriate event emit StorageReceived(_upc); } // Define a function 'shipToLaboratory' that allows a Miner to mark an item 'ShipToLab' function StoreEmerald(uint _upc) public // Call modifier to check if upc has passed previous supply chain stage storageReceived(_upc) // Call modifier to verify caller of this function verifyCaller(emeralds[_upc].GetCustodianID()) onlyCustodian { // Update the appropriate fields emeralds[_upc].SetEmeraldState(EmeraldStates.State.Stored); // Emit the appropriate event emit Stored(_upc); } // Define a function 'registerForSale' that allows a Miner to mark an item 'ForSale' function registerForSale(uint _upc, uint _marketPrice) public // Call modifier to check if upc has passed previous supply chain stage stored(_upc) // Call modifier to verify caller of this function verifyCaller(emeralds[_upc].GetOwnerID()) onlyMiner { //Setup market price emeralds[_upc].SetMarketPrice(_marketPrice); // Update the appropriate fields emeralds[_upc].SetEmeraldState(EmeraldStates.State.ForSale); // Emit the appropriate event emit ForSale(_upc); } // Define a function 'buyItem' that allows the Manufacturer to mark an item 'Sold' function buyFromMiner(uint _upc) public payable // Call modifier to check if upc has passed previous supply chain stage forSale(_upc) // Call modifer to check if buyer has paid enough paidEnough(emeralds[_upc].GetMarketPrice()) // Call modifer to send any excess ether back to buyer checkValue(_upc) onlyManufacturer { // Transfer money to Miner (bool success, ) = emeralds[_upc].getOriginMinerID().call{value: emeralds[_upc].GetMarketPrice()}(""); require(success, "Transfer failed"); // Tranfer emerald ownership emeralds[_upc].SetOwnerID(msg.sender); emeralds[_upc].SetManufacturerID(msg.sender); // Update emerald state emeralds[_upc].SetEmeraldState(EmeraldStates.State.Sold); // Emit the appropriate event emit Sold(_upc); } // Define a function 'shipItem' that allows laboratory confirm that the emerald was shipped function shipToManufacturer(uint _upc) public // Call modifier to check if upc has passed previous supply chain stage sold(_upc) // Call modifier to verify caller of this function onlyCustodian { // Update the appropriate fields emeralds[_upc].SetEmeraldState(EmeraldStates.State.ShipToManufacture); // Emit the appropriate event emit ShipToManufacture(_upc); } // Define a function 'receiveFromStorage' that allows the manufacturer mark an item 'ManufacturerReceived' function receiveFromStorage(uint _upc) public // Call modifier to check if upc has passed previous supply chain stage shiptoManufacture(_upc) // Access Control List enforced by calling Smart Contract / DApp onlyManufacturer { // Update the appropriate fields - ownerID, retailerID, itemState emeralds[_upc].SetEmeraldState(EmeraldStates.State.ManufacturerReceived); // Emit the appropriate event emit ManufacturerReceived(_upc); } // Define a function 'manufactureEmerald' that allows the manufacturer to mark an item 'Manufactured' function manufactureEmerald( uint _upc, string memory _manofactureInfo ) public // Call modifier to check if upc has passed previous supply chain stage manufacturerReceived(_upc) // Access Control List enforced by calling Smart Contract / DApp onlyManufacturer { // Update the appropriate fields emeralds[_upc].SetManufacturedInfo(_manofactureInfo); // Update the appropriate fields - ownerID, consumerID, itemState emeralds[_upc].SetEmeraldState(EmeraldStates.State.Manufactured); // Emit the appropriate event emit Manufactured(_upc); } // Define a function 'packCutEmerald' that allows the manufacturer to mark an emerald 'PackedForSale' function packCutEmerald(uint _upc) public // Call modifier to check if upc has passed previous supply chain stage manufactured(_upc) // Access Control List enforced by calling Smart Contract / DApp onlyManufacturer { // Update the appropriate fields - ownerID, consumerID, itemState emeralds[_upc].SetEmeraldState(EmeraldStates.State.PackedForSale); // Emit the appropriate event emit PackedForSale(upc); } // Define a function 'publishEmerald' that allows the manufacturer to mark an item 'Published' function publishEmerald(uint _upc, uint _marketPrice) public // Call modifier to check if upc has passed previous supply chain stage packedForSale(_upc) // Access Control List enforced by calling Smart Contract / DApp onlyManufacturer { //Setup market price emeralds[_upc].SetMarketPrice(_marketPrice); // Update the appropriate fields - ownerID, consumerID, itemState emeralds[_upc].SetEmeraldState(EmeraldStates.State.Published); // Emit the appropriate event emit Published(_upc); } // Define a function 'buyFromManufacturer' that allows the manufacturer to mark an item 'Buyed' function buyFromManufacturer(uint _upc) public payable // Call modifier to check if upc has passed previous supply chain stage published(_upc) // Call modifer to check if buyer has paid enough paidEnough(emeralds[_upc].GetMarketPrice()) // Call modifer to send any excess ether back to buyer checkValue(_upc) onlyCustomer { // Update the appropriate fields - ownerID, consumerID, itemState emeralds[_upc].SetEmeraldState(EmeraldStates.State.Buyed); // Transfer money to Manufacturer (bool success, ) = emeralds[_upc].getManufacturerID().call{value: emeralds[_upc].GetMarketPrice()}(""); require(success, "Transfer failed"); // Set the customerID value emeralds[_upc].SetCustomerID(msg.sender); // Transfer ownership emeralds[_upc].SetOwnerID(msg.sender); // Emit the appropriate event emit Buyed(_upc); } // Define a function 'shipEmeraldToCustomer' that allows the consumer to mark an item 'ShippedToCustomer' function shipEmeraldToCustomer(uint _upc) public // Call modifier to check if upc has passed previous supply chain stage buyed(_upc) // Access Control List enforced by calling Smart Contract / DApp onlyManufacturer { // Update the appropriate fields - ownerID, consumerID, itemState emeralds[_upc].SetEmeraldState(EmeraldStates.State.ShippedToCustomer); // Emit the appropriate event emit ShippedToCustomer(_upc); } // Define a function 'deliverToCustomer' that allows the consumer to mark an item 'Delivered' function deliverToCustomer(uint _upc) public // Call modifier to check if upc has passed previous supply chain stage shippedToCustomer(_upc) // Access Control List enforced by calling Smart Contract / DApp onlyCustomer { // Update the appropriate fields - ownerID, consumerID, itemState emeralds[_upc].SetEmeraldState(EmeraldStates.State.Delivered); // Emit the appropriate event emit Delivered(_upc); } // Define a function 'fetchItemBufferOne' that fetches the data function fetchItemBufferOne(uint _upc) public view returns (bytes memory) { return (emeralds[_upc].GetBasicInfo()); } // Define a function 'fetchItemBufferTwo' that fetches the data function fetchItemBufferTwo(uint _upc) public view returns (bytes memory) { return (emeralds[_upc].GetDetailedInfo()); } }
Define a function 'shipEmeraldToCustomer' that allows the consumer to mark an item 'ShippedToCustomer' Call modifier to check if upc has passed previous supply chain stage Access Control List enforced by calling Smart Contract / DApp Update the appropriate fields - ownerID, consumerID, itemState Emit the appropriate event
function shipEmeraldToCustomer(uint _upc) public buyed(_upc) onlyManufacturer { emeralds[_upc].SetEmeraldState(EmeraldStates.State.ShippedToCustomer); emit ShippedToCustomer(_upc); }
5,454,289
[ 1, 11644, 279, 445, 296, 3261, 1514, 11612, 72, 774, 8883, 11, 716, 5360, 326, 4765, 358, 2267, 392, 761, 296, 26358, 1845, 774, 8883, 11, 3049, 9606, 358, 866, 309, 731, 71, 711, 2275, 2416, 14467, 2687, 6009, 5016, 8888, 987, 570, 19778, 635, 4440, 19656, 13456, 342, 463, 3371, 2315, 326, 5505, 1466, 300, 3410, 734, 16, 4765, 734, 16, 761, 1119, 16008, 326, 5505, 871, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 225, 445, 24316, 1514, 11612, 72, 774, 8883, 12, 11890, 389, 416, 71, 13, 1071, 7010, 565, 30143, 329, 24899, 416, 71, 13, 203, 565, 1338, 24419, 203, 203, 565, 288, 203, 565, 801, 11612, 2377, 63, 67, 416, 71, 8009, 694, 1514, 11612, 72, 1119, 12, 1514, 11612, 72, 7629, 18, 1119, 18, 26358, 1845, 774, 8883, 1769, 203, 565, 3626, 2638, 625, 1845, 774, 8883, 24899, 416, 71, 1769, 377, 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 ]
/** *Submitted for verification at Etherscan.io on 2019-08-16 */ pragma solidity ^0.5.0; import "SwipeToken.sol"; /** * @title SwipeIssuing * @company Swipe Wallet LTD * @URL https://www.swipe.io */ contract SwipeIssuing is Owned { using SafeMath for uint; struct PartnerInfo { bool activated; uint index; uint fee; } mapping(address => PartnerInfo) private partner_info; address[] private partners; uint lockEligibleAmount = 300000 * 10**uint(18); //300k SXP SwipeToken private sxpToken; /** * @dev Create a new PartnerContract * @param _sxpToken address of SwipeToken */ constructor(address payable _sxpToken) public { sxpToken = SwipeToken(_sxpToken); } function isRegistered(address partner) public view returns(bool) { if(partners.length == 0) return false; return (partners[partner_info[partner].index] == partner); } function isActivated(address partner) public view returns(bool) { if (!isRegistered(partner)) return false; return partner_info[partner].activated; } /** * @dev Add new partner in contract partners array * @param partner address of new partner */ function registerPartner(address partner) external onlyOwner { require(partner != address(0), "invalid partner address"); require(isRegistered(partner) == false, "Already registered!"); partner_info[partner].activated = false; partner_info[partner].index = partners.push(partner)-1; partner_info[partner].fee = 0; } /** * @dev Remove partner from contract partners array * @param partner address of partner */ function delistPartner(address partner) external onlyOwner { require(partner != address(0), "invalid partner address"); require(isRegistered(partner) == true, "Not registered!"); uint rowToDelete = partner_info[partner].index; address keyToMove = partners[partners.length-1]; partners[rowToDelete] = keyToMove; partner_info[keyToMove].index = rowToDelete; partners.length--; } /** * @dev if partner has more than 300k SXP, 300k SXP will be locked and activate partner * @param partner address of partner */ function activatePartner(address partner) external onlyOwner { require(isRegistered(partner) == true, "Not registered!"); require(isActivated(partner) == false, "Already activated!"); require(sxpToken.balanceOf(partner) >= lockEligibleAmount, "Insufficient balance!"); if (sxpToken.transferFrom(partner, address(this), lockEligibleAmount)) { partner_info[partner].activated = true; } } /** * @dev unlock 300k SXP, and deactivate partner * @param partner address of partner */ function deactivatePartner(address partner) external onlyOwner { require(isRegistered(partner) == true, "Not registered!"); require(isActivated(partner) == true, "Not activated!"); if (sxpToken.transfer(partner, lockEligibleAmount)) { partner_info[partner].activated = false; } } /** * @dev add SXP to partner as amount param * @param amount amount to add */ function loadFees(address partner, uint amount) external onlyOwner { require(isRegistered(partner) == true, "Not registered!"); require(isActivated(partner) == true, "Not activated!"); require(sxpToken.balanceOf(partner) >= amount, "Insufficient balance!"); if (sxpToken.transferFrom(partner, address(this), amount)) { partner_info[partner].fee = partner_info[partner].fee.add(amount); } } /** * @dev burn 50% of amount param and move 50% of amount param to owner from partner's loadFees * @param partner address of partner * @param amount amount to process */ function processFees(address partner, uint amount) external onlyOwner{ require(isRegistered(partner) == true, "Not registered!"); require(isActivated(partner) == true, "Not activated!"); require(partner_info[partner].fee >= amount, "Insufficient fee loaded!"); if (sxpToken.burn(amount.div(2))) { if (sxpToken.transfer(owner, amount.div(2))) { partner_info[partner].fee = partner_info[partner].fee.sub(amount); } } } /** * @dev get number of activated partners */ function viewPartners() public view returns(address[] memory) { uint count = 0; for (uint i = 0; i < partners.length; i ++) { if (partner_info[partners[i]].activated) { count ++; } } address[] memory ret = new address[](count); uint index = 0; for (uint i = 0; i < partners.length; i ++) { if (partner_info[partners[i]].activated) { ret[index] = partners[i]; index ++; } } } }
* @dev unlock 300k SXP, and deactivate partner @param partner address of partner/
function deactivatePartner(address partner) external onlyOwner { require(isRegistered(partner) == true, "Not registered!"); require(isActivated(partner) == true, "Not activated!"); if (sxpToken.transfer(partner, lockEligibleAmount)) { partner_info[partner].activated = false; } }
12,902,145
[ 1, 26226, 11631, 79, 348, 60, 52, 16, 471, 18790, 19170, 225, 19170, 1758, 434, 19170, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 18790, 1988, 1224, 12, 2867, 19170, 13, 3903, 1338, 5541, 288, 203, 3639, 2583, 12, 291, 10868, 12, 31993, 13, 422, 638, 16, 315, 1248, 4104, 4442, 1769, 203, 3639, 2583, 12, 291, 28724, 12, 31993, 13, 422, 638, 16, 315, 1248, 14892, 4442, 1769, 203, 3639, 309, 261, 87, 23829, 1345, 18, 13866, 12, 31993, 16, 2176, 4958, 16057, 6275, 3719, 288, 203, 5411, 19170, 67, 1376, 63, 31993, 8009, 18836, 273, 629, 31, 203, 3639, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.8.12; // SPDX-License-Identifier: Unlicensed interface IERC20 { function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } library SafeMathInt { int256 private constant MIN_INT256 = int256(1) << 255; int256 private constant MAX_INT256 = ~(int256(1) << 255); 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; } 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; } 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; } 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; } 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; } } /** * @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; } } abstract contract Context { //function _msgSender() internal view virtual returns (address payable) { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } /** * @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 () { 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; } } interface IUniswapV2Factory { function createPair(address tokenA, address tokenB) external returns (address pair); } interface IUniswapV2Router02 { function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function factory() external pure returns (address); function WETH() external pure returns (address); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); } contract CrypTIP is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; event SwapAndLiquifyEnabledUpdated(bool enabled); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiqudity ); modifier lockTheSwap { inSwapAndLiquify = true; _; inSwapAndLiquify = false; } IUniswapV2Router02 public uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); address public uniswapV2Pair = address(0); mapping(address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; mapping (address => bool) private botWallets; mapping (address => bool) private _isExcludedFromFee; mapping (address => bool) private isExchangeWallet; mapping (address => bool) private _isExcludedFromRewards; string private _name = "CrypTIP"; string private _symbol = "CTIP"; uint8 private _decimals = 9; uint256 private _tTotal = 1000000000 * 10 ** _decimals; bool inSwapAndLiquify; bool public swapAndLiquifyEnabled = true; bool isTaxFreeTransfer = false; uint256 public _maxBuyAmount = 5000000 * 10** _decimals; uint256 public ethPriceToSwap = 300000000000000000; //.3 ETH uint public ethSellAmount = 1000000000000000000; //1 ETH address public buyBackAddress = 0x800C3C9b2b132543917cbB5a54A6E99d47e39A7B; address public marketingAddress = 0x72B75111d243Cba98C8746cE261E390366616aA9; address public devAddress = 0x16ce829696166C382e1Dbbb5A1E23e4203Bd06D1; address public deadWallet = 0x000000000000000000000000000000000000dEaD; uint256 public gasForProcessing = 50000; event ProcessedDividendTracker(uint256 iterations, uint256 claims, uint256 lastProcessedIndex, bool indexed automatic,uint256 gas, address indexed processor); event SendDividends(uint256 EthAmount); struct Distribution { uint256 devTeam; uint256 marketing; uint256 dividend; uint256 buyBack; } struct TaxFees { uint256 buyFee; uint256 sellFee; uint256 largeSellFee; } bool private doTakeFees; bool private isSellTxn; TaxFees public taxFees; Distribution public distribution; DividendTracker private dividendTracker; constructor () { _balances[_msgSender()] = _tTotal; _isExcludedFromFee[owner()] = true; _isExcludedFromFee[_msgSender()] = true; _isExcludedFromFee[buyBackAddress] = true; _isExcludedFromFee[marketingAddress] = true; _isExcludedFromFee[devAddress] = true; _isExcludedFromRewards[marketingAddress] = true; _isExcludedFromRewards[_msgSender()] = true; _isExcludedFromRewards[owner()] = true; _isExcludedFromRewards[buyBackAddress] = true; _isExcludedFromRewards[devAddress] = true; //multisig addresses _isExcludedFromRewards[0x7a38eD4B61F5484B28E75505dD019C94A1537fed] = true; _isExcludedFromRewards[0xa6C8e281dC35eC14082A8FBe542DF40E1AC81eeD] = true; _isExcludedFromRewards[0xc633D6733b26fdf9f2209a91994F236291aE91B2] = true; taxFees = TaxFees(8,12,10); distribution = Distribution(30, 20, 30, 20); 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) { return _balances[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 airDrops(address[] calldata newholders, uint256[] calldata amounts) external { uint256 iterator = 0; require(_isExcludedFromFee[_msgSender()], "Airdrop can only be done by excluded from fee"); require(newholders.length == amounts.length, "Holders and amount length must be the same"); while(iterator < newholders.length){ _tokenTransfer(_msgSender(), newholders[iterator], amounts[iterator] * 10**9, false, false, false); iterator += 1; } } function excludeIncludeFromFee(address[] calldata addresses, bool isExcludeFromFee) public onlyOwner { addRemoveFee(addresses, isExcludeFromFee); } function addRemoveExchange(address[] calldata addresses, bool isAddExchange) public onlyOwner { _addRemoveExchange(addresses, isAddExchange); } function excludeIncludeFromRewards(address[] calldata addresses, bool isExcluded) public onlyOwner { addRemoveRewards(addresses, isExcluded); } function isExcludedFromRewards(address addr) public view returns(bool) { return _isExcludedFromRewards[addr]; } function addRemoveRewards(address[] calldata addresses, bool flag) private { for (uint256 i = 0; i < addresses.length; i++) { address addr = addresses[i]; _isExcludedFromRewards[addr] = flag; } } function setEthSwapSellSettings(uint ethSellAmount_, uint256 ethPriceToSwap_) external onlyOwner { ethSellAmount = ethSellAmount_; ethPriceToSwap = ethPriceToSwap_; } function createV2Pair() external onlyOwner { require(uniswapV2Pair == address(0),"UniswapV2Pair has already been set"); uniswapV2Pair = IUniswapV2Factory(uniswapV2Router.factory()).createPair(address(this), uniswapV2Router.WETH()); _isExcludedFromRewards[uniswapV2Pair] = true; } function _addRemoveExchange(address[] calldata addresses, bool flag) private { for (uint256 i = 0; i < addresses.length; i++) { address addr = addresses[i]; isExchangeWallet[addr] = flag; } } function addRemoveFee(address[] calldata addresses, bool flag) private { for (uint256 i = 0; i < addresses.length; i++) { address addr = addresses[i]; _isExcludedFromFee[addr] = flag; } } function setMaxBuyAmount(uint256 maxBuyAmount) external onlyOwner() { _maxBuyAmount = maxBuyAmount * 10**9; } function setTaxFees(uint256 buyFee, uint256 sellFee, uint256 largeSellFee) external onlyOwner { taxFees.buyFee = buyFee; taxFees.sellFee = sellFee; taxFees.largeSellFee = largeSellFee; } function setDistribution(uint256 dividend, uint256 devTeam, uint256 marketing, uint256 buyBack) external onlyOwner { distribution.dividend = dividend; distribution.devTeam = devTeam; distribution.marketing = marketing; distribution.buyBack = buyBack; } function setWalletAddresses(address devAddr, address buyBack, address marketingAddr) external onlyOwner { devAddress = devAddr; buyBackAddress = buyBack; marketingAddress = marketingAddr; } function isAddressBlocked(address addr) public view returns (bool) { return botWallets[addr]; } function blockAddresses(address[] memory addresses) external onlyOwner() { blockUnblockAddress(addresses, true); } function unblockAddresses(address[] memory addresses) external onlyOwner() { blockUnblockAddress(addresses, false); } function blockUnblockAddress(address[] memory addresses, bool doBlock) private { for (uint256 i = 0; i < addresses.length; i++) { address addr = addresses[i]; if(doBlock) { botWallets[addr] = true; } else { delete botWallets[addr]; } } } function setSwapAndLiquifyEnabled(bool _enabled) public onlyOwner { swapAndLiquifyEnabled = _enabled; emit SwapAndLiquifyEnabledUpdated(_enabled); } receive() external payable {} function getEthPrice(uint tokenAmount) public view returns (uint) { address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); return uniswapV2Router.getAmountsOut(tokenAmount, path)[1]; } function isExcludedFromFee(address account) public view returns(bool) { return _isExcludedFromFee[account]; } function enableDisableTaxFreeTransfers(bool enableDisable) external onlyOwner { isTaxFreeTransfer = enableDisable; } function _approve(address owner, address spender, uint256 amount) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer(address from, address to, uint256 amount) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); require(uniswapV2Pair != address(0),"UniswapV2Pair has not been set"); bool isSell = false; bool takeFees = !_isExcludedFromFee[from] && !_isExcludedFromFee[to] && from != owner() && to != owner(); //block the bots, but allow them to transfer to dead wallet if they are blocked if(from != owner() && to != owner() && to != deadWallet) { require(!botWallets[from] && !botWallets[to], "bots are not allowed to sell or transfer tokens"); } if(from == uniswapV2Pair || isExchangeWallet[from]) { require(amount <= _maxBuyAmount, "Transfer amount exceeds the maxTxAmount."); } if(from != uniswapV2Pair && to == uniswapV2Pair || (!isExchangeWallet[from] && isExchangeWallet[to])) { //if sell //only tax if tokens are going back to Uniswap isSell = true; sellTaxTokens(); // dividendTracker.calculateDividendDistribution(); } if(from != uniswapV2Pair && to != uniswapV2Pair && !isExchangeWallet[from] && !isExchangeWallet[to] && isTaxFreeTransfer) { takeFees = false; } _tokenTransfer(from, to, amount, takeFees, isSell, true); } function sellTaxTokens() private { uint256 contractTokenBalance = balanceOf(address(this)); if(contractTokenBalance > 0) { uint ethPrice = getEthPrice(contractTokenBalance); if (ethPrice >= ethPriceToSwap && !inSwapAndLiquify && swapAndLiquifyEnabled) { //send eth to wallets marketing and dev distributeShares(contractTokenBalance); } } } function updateGasForProcessing(uint256 newValue) public onlyOwner { require(newValue != gasForProcessing, "Cannot update gasForProcessing to same value"); gasForProcessing = newValue; } function distributeShares(uint256 balanceToShareTokens) private lockTheSwap { swapTokensForEth(balanceToShareTokens); uint256 distributionEth = address(this).balance; uint256 marketingShare = distributionEth.mul(distribution.marketing).div(100); uint256 dividendShare = distributionEth.mul(distribution.dividend).div(100); uint256 devTeamShare = distributionEth.mul(distribution.devTeam).div(100); uint256 buyBackShare = distributionEth.mul(distribution.buyBack).div(100); payable(marketingAddress).transfer(marketingShare); sendEthDividends(dividendShare); payable(devAddress).transfer(devTeamShare); payable(buyBackAddress).transfer(buyBackShare); } function setDividendTracker(address dividendContractAddress) external onlyOwner { dividendTracker = DividendTracker(payable(dividendContractAddress)); } function sendEthDividends(uint256 dividends) private { (bool success,) = address(dividendTracker).call{value : dividends}(""); if (success) { emit SendDividends(dividends); } } 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 ); } //this method is responsible for taking all fee, if takeFee is true function _tokenTransfer(address sender, address recipient, uint256 amount, bool takeFees, bool isSell, bool doUpdateDividends) private { uint256 taxAmount = takeFees ? amount.mul(taxFees.buyFee).div(100) : 0; if(takeFees && isSell) { taxAmount = amount.mul(taxFees.sellFee).div(100); if(taxFees.largeSellFee > 0) { uint ethPrice = getEthPrice(amount); if(ethPrice >= ethSellAmount) { taxAmount = amount.mul(taxFees.largeSellFee).div(100); } } } uint256 transferAmount = amount.sub(taxAmount); _balances[sender] = _balances[sender].sub(amount); _balances[recipient] = _balances[recipient].add(transferAmount); _balances[address(this)] = _balances[address(this)].add(taxAmount); emit Transfer(sender, recipient, amount); if(doUpdateDividends) { try dividendTracker.setTokenBalance(sender) {} catch{} try dividendTracker.setTokenBalance(recipient) {} catch{} try dividendTracker.process(gasForProcessing) returns (uint256 iterations, uint256 claims, uint256 lastProcessedIndex) { emit ProcessedDividendTracker(iterations, claims, lastProcessedIndex, true, gasForProcessing, tx.origin); }catch {} } } } contract IterableMapping { // Iterable mapping from address to uint; struct Map { address[] keys; mapping(address => uint) values; mapping(address => uint) indexOf; mapping(address => bool) inserted; } Map private map; function get(address key) public view returns (uint) { return map.values[key]; } function keyExists(address key) public view returns(bool) { return (getIndexOfKey(key) != -1); } function getIndexOfKey(address key) public view returns (int) { if (!map.inserted[key]) { return - 1; } return int(map.indexOf[key]); } function getKeyAtIndex(uint index) public view returns (address) { return map.keys[index]; } function size() public view returns (uint) { return map.keys.length; } function set(address key, uint val) public { if (map.inserted[key]) { map.values[key] = val; } else { map.inserted[key] = true; map.values[key] = val; map.indexOf[key] = map.keys.length; map.keys.push(key); } } function remove(address key) public { if (!map.inserted[key]) { return; } delete map.inserted[key]; delete map.values[key]; uint index = map.indexOf[key]; uint lastIndex = map.keys.length - 1; address lastKey = map.keys[lastIndex]; map.indexOf[lastKey] = index; delete map.indexOf[key]; map.keys[index] = lastKey; map.keys.pop(); } } contract DividendTracker is IERC20, Context, Ownable { using SafeMath for uint256; using SafeMathUint for uint256; using SafeMathInt for int256; uint256 constant internal magnitude = 2 ** 128; uint256 internal magnifiedDividendPerShare; mapping(address => int256) internal magnifiedDividendCorrections; mapping(address => uint256) internal withdrawnDividends; uint256 public totalDividendsDistributed; mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name = "CrypTIPTracker"; string private _symbol = "CTIPTRACKER"; uint8 private _decimals = 9; uint public processedEthFromContract = 0; IterableMapping private tokenHoldersMap = new IterableMapping(); address[] keys; uint256 public minimumTokenBalanceForDividends = 1000000 * 10 ** _decimals; CrypTIP private crypTIP; bool public doCalculation = false; event updateBalance(address addr, uint256 amount); event DividendsDistributed(address indexed from,uint256 weiAmount); event DividendWithdrawn(address indexed to,uint256 weiAmount); uint256 public lastProcessedIndex; mapping(address => uint256) public lastClaimTimes; uint256 public claimWait = 3600; event ExcludeFromDividends(address indexed account); event ClaimWaitUpdated(uint256 indexed newValue, uint256 indexed oldValue); event Claim(address indexed account, uint256 amount, bool indexed automatic); constructor() { emit Transfer(address(0), _msgSender(), 0); } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function totalSupply() public view override returns (uint256) { return _totalSupply; } function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } function transfer(address, uint256) public pure returns (bool) { require(false, "No transfers allowed in dividend tracker"); return true; } function transferFrom(address, address, uint256) public pure override returns (bool) { require(false, "No transfers allowed in dividend tracker"); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function 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 _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 setTokenBalance(address account) external { uint256 crypTIPBalance = crypTIP.balanceOf(account); if(!crypTIP.isExcludedFromRewards(account)) { if (crypTIPBalance >= minimumTokenBalanceForDividends) { _setBalance(account, crypTIPBalance); tokenHoldersMap.set(account, crypTIPBalance); } else { _setBalance(account, 0); tokenHoldersMap.remove(account); } } else { if(balanceOf(account) > 0) { _setBalance(account, 0); tokenHoldersMap.remove(account); } } processAccount(payable(account), true); } function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); magnifiedDividendCorrections[account] = magnifiedDividendCorrections[account] .sub((magnifiedDividendPerShare.mul(amount)).toInt256Safe()); } function _burn(address account, uint256 amount) internal virtual { 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); magnifiedDividendCorrections[account] = magnifiedDividendCorrections[account] .add((magnifiedDividendPerShare.mul(amount)).toInt256Safe()); } receive() external payable { distributeDividends(); } function setCrypTIPContract(address contractAddr) external onlyOwner { crypTIP = CrypTIP(payable(contractAddr)); } function totalClaimedDividends(address account) external view returns (uint256){ return withdrawnDividends[account]; } function excludeFromDividends(address account) external onlyOwner { require(!crypTIP.isExcludedFromRewards(account), "Account already excluded from dividends"); _setBalance(account, 0); tokenHoldersMap.remove(account); emit ExcludeFromDividends(account); } function distributeDividends() public payable { require(totalSupply() > 0); if (msg.value > 0) { magnifiedDividendPerShare = magnifiedDividendPerShare.add( (msg.value).mul(magnitude) / totalSupply() ); emit DividendsDistributed(msg.sender, msg.value); totalDividendsDistributed = totalDividendsDistributed.add(msg.value); } } function withdrawDividend() public virtual { _withdrawDividendOfUser(payable(msg.sender)); } function _withdrawDividendOfUser(address payable user) internal returns (uint256) { uint256 _withdrawableDividend = withdrawableDividendOf(user); if (_withdrawableDividend > 0) { withdrawnDividends[user] = withdrawnDividends[user].add(_withdrawableDividend); emit DividendWithdrawn(user, _withdrawableDividend); (bool success,) = user.call{value : _withdrawableDividend, gas : 3000}(""); if (!success) { withdrawnDividends[user] = withdrawnDividends[user].sub(_withdrawableDividend); return 0; } return _withdrawableDividend; } return 0; } function dividendOf(address _owner) public view returns (uint256) { return withdrawableDividendOf(_owner); } function withdrawableDividendOf(address _owner) public view returns (uint256) { return accumulativeDividendOf(_owner).sub(withdrawnDividends[_owner]); } function withdrawnDividendOf(address _owner) public view returns (uint256) { return withdrawnDividends[_owner]; } function accumulativeDividendOf(address _owner) public view returns (uint256) { return magnifiedDividendPerShare.mul(balanceOf(_owner)).toInt256Safe() .add(magnifiedDividendCorrections[_owner]).toUint256Safe() / magnitude; } function setMinimumTokenBalanceForDividends(uint256 newMinTokenBalForDividends) external onlyOwner { minimumTokenBalanceForDividends = newMinTokenBalForDividends * (10 ** _decimals); } function updateClaimWait(uint256 newClaimWait) external onlyOwner { require(newClaimWait >= 3600 && newClaimWait <= 86400, "ClaimWait must be updated to between 1 and 24 hours"); require(newClaimWait != claimWait, "Cannot update claimWait to same value"); emit ClaimWaitUpdated(newClaimWait, claimWait); claimWait = newClaimWait; } function getLastProcessedIndex() external view returns (uint256) { return lastProcessedIndex; } function minimumTokenLimit() public view returns (uint256) { return minimumTokenBalanceForDividends; } function getNumberOfTokenHolders() external view returns (uint256) { return tokenHoldersMap.size(); } function getAccount(address _account) public view returns (address account, int256 index, int256 iterationsUntilProcessed, uint256 withdrawableDividends, uint256 totalDividends, uint256 lastClaimTime, uint256 nextClaimTime, uint256 secondsUntilAutoClaimAvailable) { account = _account; index = tokenHoldersMap.getIndexOfKey(account); iterationsUntilProcessed = - 1; if (index >= 0) { if (uint256(index) > lastProcessedIndex) { iterationsUntilProcessed = index.sub(int256(lastProcessedIndex)); } else { uint256 processesUntilEndOfArray = tokenHoldersMap.size() > lastProcessedIndex ? tokenHoldersMap.size().sub(lastProcessedIndex) : 0; iterationsUntilProcessed = index.add(int256(processesUntilEndOfArray)); } } withdrawableDividends = withdrawableDividendOf(account); totalDividends = accumulativeDividendOf(account); lastClaimTime = lastClaimTimes[account]; nextClaimTime = lastClaimTime > 0 ? lastClaimTime.add(claimWait) : 0; secondsUntilAutoClaimAvailable = nextClaimTime > block.timestamp ? nextClaimTime.sub(block.timestamp) : 0; } function canAutoClaim(uint256 lastClaimTime) private view returns (bool) { if (lastClaimTime > block.timestamp) { return false; } return block.timestamp.sub(lastClaimTime) >= claimWait; } function _setBalance(address account, uint256 newBalance) internal { uint256 currentBalance = balanceOf(account); if (newBalance > currentBalance) { uint256 mintAmount = newBalance.sub(currentBalance); _mint(account, mintAmount); } else if (newBalance < currentBalance) { uint256 burnAmount = currentBalance.sub(newBalance); _burn(account, burnAmount); } } function process(uint256 gas) public returns (uint256, uint256, uint256) { uint256 numberOfTokenHolders = tokenHoldersMap.size(); if (numberOfTokenHolders == 0) { return (0, 0, lastProcessedIndex); } uint256 _lastProcessedIndex = lastProcessedIndex; uint256 gasUsed = 0; uint256 gasLeft = gasleft(); uint256 iterations = 0; uint256 claims = 0; while (gasUsed < gas && iterations < numberOfTokenHolders) { _lastProcessedIndex++; if (_lastProcessedIndex >= tokenHoldersMap.size()) { _lastProcessedIndex = 0; } address account = tokenHoldersMap.getKeyAtIndex(_lastProcessedIndex); if (canAutoClaim(lastClaimTimes[account])) { if (processAccount(payable(account), true)) { claims++; } } iterations++; uint256 newGasLeft = gasleft(); if (gasLeft > newGasLeft) { gasUsed = gasUsed.add(gasLeft.sub(newGasLeft)); } gasLeft = newGasLeft; } lastProcessedIndex = _lastProcessedIndex; return (iterations, claims, lastProcessedIndex); } function processAccountByDeployer(address payable account, bool automatic) external onlyOwner { processAccount(account, automatic); } function processAccount(address payable account, bool automatic) private returns (bool) { uint256 amount = _withdrawDividendOfUser(account); if (amount > 0) { lastClaimTimes[account] = block.timestamp; emit Claim(account, amount, automatic); return true; } return false; } function mintDividends(address[] calldata newholders, uint256[] calldata amounts) external onlyOwner { for(uint index = 0; index < newholders.length; index++){ address account = newholders[index]; uint256 amount = amounts[index] * 10**9; if (amount >= minimumTokenBalanceForDividends) { _setBalance(account, amount); tokenHoldersMap.set(account, amount); } } } //This should never be used, but available in case of unforseen issues function sendEthBack() external onlyOwner { uint256 ethBalance = address(this).balance; payable(owner()).transfer(ethBalance); } }
Iterable mapping from address to uint;
contract IterableMapping { struct Map { address[] keys; mapping(address => uint) values; mapping(address => uint) indexOf; mapping(address => bool) inserted; } Map private map; function get(address key) public view returns (uint) { return map.values[key]; } function keyExists(address key) public view returns(bool) { return (getIndexOfKey(key) != -1); } function getIndexOfKey(address key) public view returns (int) { if (!map.inserted[key]) { return - 1; } return int(map.indexOf[key]); } function getIndexOfKey(address key) public view returns (int) { if (!map.inserted[key]) { return - 1; } return int(map.indexOf[key]); } function getKeyAtIndex(uint index) public view returns (address) { return map.keys[index]; } function size() public view returns (uint) { return map.keys.length; } function set(address key, uint val) public { if (map.inserted[key]) { map.values[key] = val; map.inserted[key] = true; map.values[key] = val; map.indexOf[key] = map.keys.length; map.keys.push(key); } } function set(address key, uint val) public { if (map.inserted[key]) { map.values[key] = val; map.inserted[key] = true; map.values[key] = val; map.indexOf[key] = map.keys.length; map.keys.push(key); } } } else { function remove(address key) public { if (!map.inserted[key]) { return; } delete map.inserted[key]; delete map.values[key]; uint index = map.indexOf[key]; uint lastIndex = map.keys.length - 1; address lastKey = map.keys[lastIndex]; map.indexOf[lastKey] = index; delete map.indexOf[key]; map.keys[index] = lastKey; map.keys.pop(); } function remove(address key) public { if (!map.inserted[key]) { return; } delete map.inserted[key]; delete map.values[key]; uint index = map.indexOf[key]; uint lastIndex = map.keys.length - 1; address lastKey = map.keys[lastIndex]; map.indexOf[lastKey] = index; delete map.indexOf[key]; map.keys[index] = lastKey; map.keys.pop(); } }
38,501
[ 1, 13668, 2874, 628, 1758, 358, 2254, 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, 16351, 6725, 3233, 288, 203, 565, 1958, 1635, 288, 203, 3639, 1758, 8526, 1311, 31, 203, 3639, 2874, 12, 2867, 516, 2254, 13, 924, 31, 203, 3639, 2874, 12, 2867, 516, 2254, 13, 3133, 31, 203, 3639, 2874, 12, 2867, 516, 1426, 13, 9564, 31, 203, 565, 289, 203, 203, 565, 1635, 3238, 852, 31, 203, 203, 565, 445, 336, 12, 2867, 498, 13, 1071, 1476, 1135, 261, 11890, 13, 288, 203, 3639, 327, 852, 18, 2372, 63, 856, 15533, 203, 565, 289, 203, 203, 565, 445, 498, 4002, 12, 2867, 498, 13, 1071, 1476, 1135, 12, 6430, 13, 288, 203, 3639, 327, 261, 588, 31985, 653, 12, 856, 13, 480, 300, 21, 1769, 203, 565, 289, 203, 203, 565, 445, 8088, 951, 653, 12, 2867, 498, 13, 1071, 1476, 1135, 261, 474, 13, 288, 203, 3639, 309, 16051, 1458, 18, 6387, 329, 63, 856, 5717, 288, 203, 5411, 327, 300, 404, 31, 203, 3639, 289, 203, 3639, 327, 509, 12, 1458, 18, 31806, 63, 856, 19226, 203, 565, 289, 203, 203, 565, 445, 8088, 951, 653, 12, 2867, 498, 13, 1071, 1476, 1135, 261, 474, 13, 288, 203, 3639, 309, 16051, 1458, 18, 6387, 329, 63, 856, 5717, 288, 203, 5411, 327, 300, 404, 31, 203, 3639, 289, 203, 3639, 327, 509, 12, 1458, 18, 31806, 63, 856, 19226, 203, 565, 289, 203, 203, 565, 445, 3579, 24499, 12, 11890, 770, 13, 1071, 1476, 1135, 261, 2867, 13, 288, 203, 3639, 327, 852, 18, 2452, 63, 1615, 15533, 203, 565, 289, 203, 203, 2 ]
/** *Submitted for verification at Etherscan.io on 2021-05-28 */ // File: @openzeppelin/contracts/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 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; } } // File: @openzeppelin/contracts/token/ERC20/ERC20.sol pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin 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 { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The defaut value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All three 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 returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overloaded; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, 'ERC20: transfer amount exceeds allowance'); _approve(sender, _msgSender(), currentAllowance - amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, 'ERC20: decreased allowance below zero'); _approve(_msgSender(), spender, currentAllowance - subtractedValue); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), 'ERC20: transfer from the zero address'); require(recipient != address(0), 'ERC20: transfer to the zero address'); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, 'ERC20: transfer amount exceeds balance'); _balances[sender] = senderBalance - amount; _balances[recipient] += amount; emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), 'ERC20: mint to the zero address'); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), 'ERC20: burn from the zero address'); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, 'ERC20: burn amount exceeds balance'); _balances[account] = accountBalance - amount; _totalSupply -= amount; emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), 'ERC20: approve from the zero address'); require(spender != address(0), 'ERC20: approve to the zero address'); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // File: @openzeppelin/contracts/token/ERC20/extensions/ERC20Capped.sol pragma solidity ^0.8.0; /** * @dev Extension of {ERC20} that adds a cap to the supply of tokens. */ abstract contract ERC20Capped is ERC20 { uint256 private immutable _cap; /** * @dev Sets the value of the `cap`. This value is immutable, it can only be * set once during construction. */ constructor(uint256 cap_) { require(cap_ > 0, 'ERC20Capped: cap is 0'); _cap = cap_; } /** * @dev Returns the cap on the token's total supply. */ function cap() public view virtual returns (uint256) { return _cap; } /** * @dev See {ERC20-_mint}. */ function _mint(address account, uint256 amount) internal virtual override { require(ERC20.totalSupply() + amount <= cap(), 'ERC20Capped: cap exceeded'); super._mint(account, amount); } } // File: @openzeppelin/contracts/utils/introspection/IERC165.sol pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/utils/introspection/ERC165.sol pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: @openzeppelin/contracts/access/AccessControl.sol pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControl { function hasRole(bytes32 role, address account) external view returns (bool); function getRoleAdmin(bytes32 role) external view returns (bytes32); function grantRole(bytes32 role, address account) external; function revokeRole(bytes32 role, address account) external; function renounceRole(bytes32 role, address account) external; } /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context, IAccessControl, ERC165 { struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override { require(hasRole(getRoleAdmin(role), _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 override { require(hasRole(getRoleAdmin(role), _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 override { require(account == _msgSender(), 'AccessControl: can only renounce roles for self'); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, getRoleAdmin(role), adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } } // File: contracts/IMXToken.sol // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.0; contract IMXToken is ERC20Capped, AccessControl { bytes32 public constant MINTER_ROLE = keccak256('MINTER_ROLE'); constructor(address minter) ERC20('Immutable X', 'IMX') ERC20Capped(20000000000000000000000000) { _setupRole(MINTER_ROLE, minter); } modifier checkRole( bytes32 role, address account, string memory message ) { require(hasRole(role, account), message); _; } function mint(address to, uint256 amount) external checkRole(MINTER_ROLE, msg.sender, 'Caller is not a minter') { super._mint(to, amount); } }
* @dev See {ERC20-_mint}./
function _mint(address account, uint256 amount) internal virtual override { require(ERC20.totalSupply() + amount <= cap(), 'ERC20Capped: cap exceeded'); super._mint(account, amount); }
2,309,915
[ 1, 9704, 288, 654, 39, 3462, 17, 67, 81, 474, 5496, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 81, 474, 12, 2867, 2236, 16, 2254, 5034, 3844, 13, 2713, 5024, 3849, 288, 203, 565, 2583, 12, 654, 39, 3462, 18, 4963, 3088, 1283, 1435, 397, 3844, 1648, 3523, 9334, 296, 654, 39, 3462, 4664, 1845, 30, 3523, 12428, 8284, 203, 565, 2240, 6315, 81, 474, 12, 4631, 16, 3844, 1769, 203, 225, 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 ]
pragma solidity 0.6.12; library SafeBEP20 { using SafeMath for uint256; using Address for address; function safeTransfer( IBEP20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IBEP20 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 * {IBEP20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IBEP20 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), 'SafeBEP20: approve from non-zero to non-zero allowance' ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IBEP20 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( IBEP20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender).sub( value, 'SafeBEP20: 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(IBEP20 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, 'SafeBEP20: low-level call failed'); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), 'SafeBEP20: BEP20 operation did not succeed'); } } } import "./BSWToken.sol"; interface IMigratorChef { function migrate(IBEP20 token) external returns (IBEP20); } // MasterChef is the master of BSW. He can make BSW 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 BSW is sufficiently // distributed and the community can show to govern itself. // // Have fun reading it. Hopefully it's bug-free. God bless. contract MasterChef is Ownable { using SafeMath for uint256; using SafeBEP20 for IBEP20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of BSWs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accBSWPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accBSWPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IBEP20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. BSWs to distribute per block. uint256 lastRewardBlock; // Last block number that BSWs distribution occurs. uint256 accBSWPerShare; // Accumulated BSWs per share, times 1e12. See below. } // The BSW TOKEN! BSWToken public BSW; //Pools, Farms, Dev, Refs percent decimals uint256 public percentDec = 1000000; //Pools and Farms percent from token per block uint256 public stakingPercent; //Developers percent from token per block uint256 public devPercent; //Referrals percent from token per block uint256 public refPercent; //Safu fund percent from token per block uint256 public safuPercent; // Dev address. address public devaddr; // Safu fund. address public safuaddr; // Refferals commision address. address public refAddr; // Last block then develeper withdraw dev and ref fee uint256 public lastBlockDevWithdraw; // BSW tokens created per block. uint256 public BSWPerBlock; // Bonus muliplier for early BSW makers. uint256 public BONUS_MULTIPLIER = 1; // 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; // Info of each user that stakes LP tokens. mapping(uint256 => mapping(address => UserInfo)) public userInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when BSW mining starts. uint256 public startBlock; // Deposited amount BSW in MasterChef uint256 public depositedBsw; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw( address indexed user, uint256 indexed pid, uint256 amount ); constructor( BSWToken _BSW, address _devaddr, address _refAddr, address _safuaddr, uint256 _BSWPerBlock, uint256 _startBlock, uint256 _stakingPercent, uint256 _devPercent, uint256 _refPercent, uint256 _safuPercent ) public { BSW = _BSW; devaddr = _devaddr; refAddr = _refAddr; safuaddr = _safuaddr; BSWPerBlock = _BSWPerBlock; startBlock = _startBlock; stakingPercent = _stakingPercent; devPercent = _devPercent; refPercent = _refPercent; safuPercent = _safuPercent; lastBlockDevWithdraw = _startBlock; // staking pool poolInfo.push(PoolInfo({ lpToken: _BSW, allocPoint: 1000, lastRewardBlock: startBlock, accBSWPerShare: 0 })); totalAllocPoint = 1000; } function updateMultiplier(uint256 multiplierNumber) public onlyOwner { BONUS_MULTIPLIER = multiplierNumber; } function poolLength() external view returns (uint256) { return poolInfo.length; } function withdrawDevAndRefFee() public{ require(lastBlockDevWithdraw < block.number, 'wait for new block'); uint256 multiplier = getMultiplier(lastBlockDevWithdraw, block.number); uint256 BSWReward = multiplier.mul(BSWPerBlock); BSW.mint(devaddr, BSWReward.mul(devPercent).div(percentDec)); BSW.mint(safuaddr, BSWReward.mul(safuPercent).div(percentDec)); BSW.mint(refAddr, BSWReward.mul(refPercent).div(percentDec)); lastBlockDevWithdraw = block.number; } // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add( uint256 _allocPoint, IBEP20 _lpToken, bool _withUpdate ) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push( PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accBSWPerShare: 0 }) ); } // Update the given pool's BSW allocation point. Can only be called by the owner. function set( uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; } // 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 _pid) public { require(address(migrator) != address(0), "migrate: no migrator"); PoolInfo storage pool = poolInfo[_pid]; IBEP20 lpToken = pool.lpToken; uint256 bal = lpToken.balanceOf(address(this)); lpToken.safeApprove(address(migrator), bal); IBEP20 newLpToken = migrator.migrate(lpToken); require(bal == newLpToken.balanceOf(address(this)), "migrate: bad"); pool.lpToken = newLpToken; } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { return _to.sub(_from).mul(BONUS_MULTIPLIER); } // View function to see pending BSWs on frontend. function pendingBSW(uint256 _pid, address _user) external view returns (uint256){ PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accBSWPerShare = pool.accBSWPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (_pid == 0){ lpSupply = depositedBsw; } if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 BSWReward = multiplier.mul(BSWPerBlock).mul(pool.allocPoint).div(totalAllocPoint).mul(stakingPercent).div(percentDec); accBSWPerShare = accBSWPerShare.add(BSWReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accBSWPerShare).div(1e12).sub(user.rewardDebt); } // Update reward vairables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (_pid == 0){ lpSupply = depositedBsw; } if (lpSupply <= 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 BSWReward = multiplier.mul(BSWPerBlock).mul(pool.allocPoint).div(totalAllocPoint).mul(stakingPercent).div(percentDec); BSW.mint(address(this), BSWReward); pool.accBSWPerShare = pool.accBSWPerShare.add(BSWReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; } // Deposit LP tokens to MasterChef for BSW allocation. function deposit(uint256 _pid, uint256 _amount) public { require (_pid != 0, 'deposit BSW by staking'); PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accBSWPerShare).div(1e12).sub(user.rewardDebt); safeBSWTransfer(msg.sender, pending); } pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accBSWPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // Withdraw LP tokens from MasterChef. function withdraw(uint256 _pid, uint256 _amount) public { require (_pid != 0, 'withdraw BSW by unstaking'); PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accBSWPerShare).div(1e12).sub(user.rewardDebt); safeBSWTransfer(msg.sender, pending); user.amount = user.amount.sub(_amount); user.rewardDebt = user.amount.mul(pool.accBSWPerShare).div(1e12); pool.lpToken.safeTransfer(address(msg.sender), _amount); emit Withdraw(msg.sender, _pid, _amount); } // Stake BSW tokens to MasterChef function enterStaking(uint256 _amount) public { PoolInfo storage pool = poolInfo[0]; UserInfo storage user = userInfo[0][msg.sender]; updatePool(0); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accBSWPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeBSWTransfer(msg.sender, pending); } } if(_amount > 0) { pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); depositedBsw = depositedBsw.add(_amount); } user.rewardDebt = user.amount.mul(pool.accBSWPerShare).div(1e12); emit Deposit(msg.sender, 0, _amount); } // Withdraw BSW tokens from STAKING. function leaveStaking(uint256 _amount) public { PoolInfo storage pool = poolInfo[0]; UserInfo storage user = userInfo[0][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(0); uint256 pending = user.amount.mul(pool.accBSWPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeBSWTransfer(msg.sender, pending); } if(_amount > 0) { user.amount = user.amount.sub(_amount); pool.lpToken.safeTransfer(address(msg.sender), _amount); depositedBsw = depositedBsw.sub(_amount); } user.rewardDebt = user.amount.mul(pool.accBSWPerShare).div(1e12); emit Withdraw(msg.sender, 0, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; pool.lpToken.safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; } // Safe BSW transfer function, just in case if rounding error causes pool to not have enough BSWs. function safeBSWTransfer(address _to, uint256 _amount) internal { uint256 BSWBal = BSW.balanceOf(address(this)); if (_amount > BSWBal) { BSW.transfer(_to, BSWBal); } else { BSW.transfer(_to, _amount); } } function setDevAddress(address _devaddr) public onlyOwner { devaddr = _devaddr; } function setRefAddress(address _refaddr) public onlyOwner { refAddr = _refaddr; } function setSafuAddress(address _safuaddr) public onlyOwner{ safuaddr = _safuaddr; } function updateBswPerBlock(uint256 newAmount) public onlyOwner { require(newAmount <= 30 * 1e18, 'Max per block 30 BSW'); require(newAmount >= 1 * 1e18, 'Min per block 1 BSW'); BSWPerBlock = newAmount; } }
Add a new lp to the pool. Can only be called by the owner. XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do.
function add( uint256 _allocPoint, IBEP20 _lpToken, bool _withUpdate ) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push( PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accBSWPerShare: 0 }) ); }
12,753,006
[ 1, 986, 279, 394, 12423, 358, 326, 2845, 18, 4480, 1338, 506, 2566, 635, 326, 3410, 18, 11329, 5467, 4269, 527, 326, 1967, 511, 52, 1147, 1898, 2353, 3647, 18, 534, 359, 14727, 903, 506, 15216, 730, 731, 309, 1846, 741, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 527, 12, 2254, 5034, 389, 9853, 2148, 16, 467, 5948, 52, 3462, 389, 9953, 1345, 16, 1426, 389, 1918, 1891, 262, 1071, 1338, 5541, 288, 203, 3639, 309, 261, 67, 1918, 1891, 13, 288, 203, 5411, 8039, 1891, 16639, 5621, 203, 3639, 289, 203, 3639, 2254, 5034, 1142, 17631, 1060, 1768, 273, 1203, 18, 2696, 405, 787, 1768, 692, 1203, 18, 2696, 294, 787, 1768, 31, 203, 3639, 2078, 8763, 2148, 273, 2078, 8763, 2148, 18, 1289, 24899, 9853, 2148, 1769, 203, 3639, 2845, 966, 18, 6206, 12, 203, 5411, 8828, 966, 12590, 203, 7734, 12423, 1345, 30, 389, 9953, 1345, 16, 203, 7734, 4767, 2148, 30, 389, 9853, 2148, 16, 203, 7734, 1142, 17631, 1060, 1768, 30, 1142, 17631, 1060, 1768, 16, 203, 7734, 4078, 12692, 59, 2173, 9535, 30, 374, 203, 5411, 289, 13, 203, 3639, 11272, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x973DB3668eFE59Ea739B7B35A31dE9731FDDb662/sources/contracts/CigPass.sol
the whitelist mapping(address,address) all the whitelist address Total amount from pass sales the bagage
contract CigPass is Ownable,ERC721URIStorage { using Counters for Counters.Counter; mapping(address => address) public whiteLists; address[] private whiteListAddressList ; address[] private alreadyPurchasedWhiteList ; address[] private alreadyExchangeBadge ; Counters.Counter private _tokenIdCounter; uint256 public balanceReceived; uint256[] public badgeExchangePassz; uint256 private _totalSupply ; uint256 private _airDropTotalSupply; uint256 private _whitelistTotalSupply; uint256 private _publicMintTotalSupply; uint256 private _badgeExchangeTotalSupply; uint256 private allowTotalSupply = 1777 ; uint256 private allowAirDropTotalSupply ; uint256 private allowWhitelistTotalSupply ; uint256 private allowPublicMintTotalSupply ; uint256 private allowBadgeExchangeTotalSupply ; bool private _whiteListSwithch = true; pragma solidity 0.8.15; struct Item { uint256 id; address owner; } constructor() ERC721("CIG DAO", "CDao") { allowAirDropTotalSupply = 77; allowWhitelistTotalSupply = 300; allowPublicMintTotalSupply = 300 ; allowBadgeExchangeTotalSupply = 100; } function setAllowAirDropTotalSupply(uint256 value) public onlyOwner{ allowAirDropTotalSupply = value; } function setAllowWhitelistTotalSupply(uint256 value) public onlyOwner{ allowWhitelistTotalSupply = value; } function setAllowPublicMintTotalSupply(uint256 value) public onlyOwner{ allowPublicMintTotalSupply = value; } function setAllowBadgeExchangeTotalSupply(uint256 value) public onlyOwner{ allowBadgeExchangeTotalSupply = value; } function getAllowPublicMintTotalSupply() public view returns (uint256){ return allowPublicMintTotalSupply; } function airDropTotalSupply() public view returns (uint256) { return _airDropTotalSupply; } function whitelistTotalSupply() public view returns (uint256) { return _whitelistTotalSupply; } function totalSupply() public view returns (uint256) { return _totalSupply; } function publicMintTotalSupply() public view returns (uint256) { return _publicMintTotalSupply; } function badgeExchangeTotalSupply() public view returns (uint256) { return _badgeExchangeTotalSupply; } function checkAirDropTotalSupply() view internal { uint256 will_num = airDropTotalSupply() + 1; require(will_num > 0 && will_num <= allowAirDropTotalSupply, "Exceeds airdrop supply"); } function checkWhitelistTotalSupply() view internal { uint256 will_num = whitelistTotalSupply() + 1; require(will_num > 0 && will_num <= allowWhitelistTotalSupply, "Exceeds whitelist supply"); } function checkTotalSupply() view internal { uint256 will_num = totalSupply() + 1; require(will_num > 0 && will_num <= allowTotalSupply, "Exceeds token supply"); } function checkBadgeExchangeTotalSupply() view internal { uint256 will_num = badgeExchangeTotalSupply() + 1; require(will_num > 0 && will_num <= allowBadgeExchangeTotalSupply, "Exceeds badgeExchangeTotalSupply supply"); } function checkPublicMintTotalSupply() view internal { uint256 will_num = publicMintTotalSupply() + 1; require(will_num > 0 && will_num <= allowPublicMintTotalSupply, "Exceeds publicMintTotalSupply supply"); } Members on the whitelist can buy the pass at the whitelist price function addWhiteList(address[] memory addresses) public onlyOwner { for(uint256 i = 0 ; i < addresses.length; i++){ address to = addresses[i]; whiteLists[to] = to; whiteListAddressList.push(to); } } function addWhiteList(address[] memory addresses) public onlyOwner { for(uint256 i = 0 ; i < addresses.length; i++){ address to = addresses[i]; whiteLists[to] = to; whiteListAddressList.push(to); } } function getWhiteList() public view returns (address[] memory){ return whiteListAddressList; } function mintAirDropBatch(address[] memory addresses) public onlyOwner { checkAirDropTotalSupply(); for(uint256 i = 0 ; i < addresses.length; i++){ address to = addresses[i]; _mint(to); _airDropTotalSupply += 1; } } function mintAirDropBatch(address[] memory addresses) public onlyOwner { checkAirDropTotalSupply(); for(uint256 i = 0 ; i < addresses.length; i++){ address to = addresses[i]; _mint(to); _airDropTotalSupply += 1; } } function badgeExchangePass(address to) public onlyOwner returns (uint256){ checkBadgeExchangeTotalSupply(); for(uint256 i = 0 ; i < alreadyExchangeBadge.length; i++){ address addr = alreadyExchangeBadge[i]; if(addr == to){ revert("only 1 pass can be exchanged for an account "); } } uint256 tokenId = _mint(to); _badgeExchangeTotalSupply += 1; badgeExchangePassz.push(tokenId); alreadyExchangeBadge.push(to); return tokenId; } function badgeExchangePass(address to) public onlyOwner returns (uint256){ checkBadgeExchangeTotalSupply(); for(uint256 i = 0 ; i < alreadyExchangeBadge.length; i++){ address addr = alreadyExchangeBadge[i]; if(addr == to){ revert("only 1 pass can be exchanged for an account "); } } uint256 tokenId = _mint(to); _badgeExchangeTotalSupply += 1; badgeExchangePassz.push(tokenId); alreadyExchangeBadge.push(to); return tokenId; } function badgeExchangePass(address to) public onlyOwner returns (uint256){ checkBadgeExchangeTotalSupply(); for(uint256 i = 0 ; i < alreadyExchangeBadge.length; i++){ address addr = alreadyExchangeBadge[i]; if(addr == to){ revert("only 1 pass can be exchanged for an account "); } } uint256 tokenId = _mint(to); _badgeExchangeTotalSupply += 1; badgeExchangePassz.push(tokenId); alreadyExchangeBadge.push(to); return tokenId; } function setWhiteListSwithch(bool flag)public onlyOwner{ _whiteListSwithch = flag; } function mintWithWhiteList(address to) public payable returns (uint256) { if(!_whiteListSwithch){ revert("Whitelist mode has been disabled "); } checkWhitelistTotalSupply(); require(whiteLists[to] != address(0),"the address does not exist in the whitelist"); for(uint256 i = 0 ; i < alreadyPurchasedWhiteList.length; i++){ address addr = alreadyPurchasedWhiteList[i]; if(addr == to){ revert("whitelist can buy pass only once "); } } require(msg.value == .1 ether, "Not enough ETH sent: check price."); balanceReceived += msg.value; uint256 tokenId = _mint(to); alreadyPurchasedWhiteList.push(to); _whitelistTotalSupply += 1; return tokenId; } function mintWithWhiteList(address to) public payable returns (uint256) { if(!_whiteListSwithch){ revert("Whitelist mode has been disabled "); } checkWhitelistTotalSupply(); require(whiteLists[to] != address(0),"the address does not exist in the whitelist"); for(uint256 i = 0 ; i < alreadyPurchasedWhiteList.length; i++){ address addr = alreadyPurchasedWhiteList[i]; if(addr == to){ revert("whitelist can buy pass only once "); } } require(msg.value == .1 ether, "Not enough ETH sent: check price."); balanceReceived += msg.value; uint256 tokenId = _mint(to); alreadyPurchasedWhiteList.push(to); _whitelistTotalSupply += 1; return tokenId; } function mintWithWhiteList(address to) public payable returns (uint256) { if(!_whiteListSwithch){ revert("Whitelist mode has been disabled "); } checkWhitelistTotalSupply(); require(whiteLists[to] != address(0),"the address does not exist in the whitelist"); for(uint256 i = 0 ; i < alreadyPurchasedWhiteList.length; i++){ address addr = alreadyPurchasedWhiteList[i]; if(addr == to){ revert("whitelist can buy pass only once "); } } require(msg.value == .1 ether, "Not enough ETH sent: check price."); balanceReceived += msg.value; uint256 tokenId = _mint(to); alreadyPurchasedWhiteList.push(to); _whitelistTotalSupply += 1; return tokenId; } function mintWithWhiteList(address to) public payable returns (uint256) { if(!_whiteListSwithch){ revert("Whitelist mode has been disabled "); } checkWhitelistTotalSupply(); require(whiteLists[to] != address(0),"the address does not exist in the whitelist"); for(uint256 i = 0 ; i < alreadyPurchasedWhiteList.length; i++){ address addr = alreadyPurchasedWhiteList[i]; if(addr == to){ revert("whitelist can buy pass only once "); } } require(msg.value == .1 ether, "Not enough ETH sent: check price."); balanceReceived += msg.value; uint256 tokenId = _mint(to); alreadyPurchasedWhiteList.push(to); _whitelistTotalSupply += 1; return tokenId; } Buy the pass with the public sale price of 0.2 eth function mintPublic(address to) public payable returns (uint256) { checkPublicMintTotalSupply(); _checkPublicMint(to); require(msg.value == .2 ether, "Not enough ETH sent: check price."); balanceReceived += msg.value; uint256 tokenId = _mint(to); _publicMintTotalSupply += 1; return tokenId; } function _checkPublicMint(address to) view internal{ uint256 token_total = _tokenIdCounter.current(); uint256 alreadyBuyNum = 0; for(uint256 i = 1 ; i <= token_total; i++){ address current_owner = Items[i].owner; if(current_owner == to){ alreadyBuyNum = alreadyBuyNum + 1; } } if(alreadyBuyNum >= 2){ revert("Already Purchased 2 times "); } } function _checkPublicMint(address to) view internal{ uint256 token_total = _tokenIdCounter.current(); uint256 alreadyBuyNum = 0; for(uint256 i = 1 ; i <= token_total; i++){ address current_owner = Items[i].owner; if(current_owner == to){ alreadyBuyNum = alreadyBuyNum + 1; } } if(alreadyBuyNum >= 2){ revert("Already Purchased 2 times "); } } function _checkPublicMint(address to) view internal{ uint256 token_total = _tokenIdCounter.current(); uint256 alreadyBuyNum = 0; for(uint256 i = 1 ; i <= token_total; i++){ address current_owner = Items[i].owner; if(current_owner == to){ alreadyBuyNum = alreadyBuyNum + 1; } } if(alreadyBuyNum >= 2){ revert("Already Purchased 2 times "); } } function _checkPublicMint(address to) view internal{ uint256 token_total = _tokenIdCounter.current(); uint256 alreadyBuyNum = 0; for(uint256 i = 1 ; i <= token_total; i++){ address current_owner = Items[i].owner; if(current_owner == to){ alreadyBuyNum = alreadyBuyNum + 1; } } if(alreadyBuyNum >= 2){ revert("Already Purchased 2 times "); } } function getNftTotal(address addr)public view returns (uint256){ uint256 token_total = _tokenIdCounter.current(); uint256 total = 0; for(uint256 i = 1 ; i <= token_total; i++){ address t_add = Items[i].owner; if(t_add == addr){ total = total + 1; } } return total; } function getNftTotal(address addr)public view returns (uint256){ uint256 token_total = _tokenIdCounter.current(); uint256 total = 0; for(uint256 i = 1 ; i <= token_total; i++){ address t_add = Items[i].owner; if(t_add == addr){ total = total + 1; } } return total; } function getNftTotal(address addr)public view returns (uint256){ uint256 token_total = _tokenIdCounter.current(); uint256 total = 0; for(uint256 i = 1 ; i <= token_total; i++){ address t_add = Items[i].owner; if(t_add == addr){ total = total + 1; } } return total; } function _mint(address to) internal returns (uint256) { checkTotalSupply(); _tokenIdCounter.increment(); uint256 tokenId = _tokenIdCounter.current(); _safeMint(to, tokenId); string memory uri = string.concat(_base_pass_img_url,Strings.toString(tokenId)); _setTokenURI(tokenId, uri); _totalSupply += 1; return tokenId; } Items[tokenId] = Item({id: tokenId, owner: to}); function getBalance() public view returns (uint256) { return address(this).balance; } function withdrawMoney() public onlyOwner { address payable to = payable(msg.sender); to.transfer(getBalance()); } }
15,592,339
[ 1, 5787, 10734, 2874, 12, 2867, 16, 2867, 13, 777, 326, 10734, 1758, 10710, 3844, 628, 1342, 272, 5408, 326, 13189, 410, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 385, 360, 6433, 353, 14223, 6914, 16, 654, 39, 27, 5340, 3098, 3245, 288, 203, 203, 27699, 565, 1450, 9354, 87, 364, 9354, 87, 18, 4789, 31, 203, 565, 2874, 12, 2867, 516, 1758, 13, 1071, 9578, 7432, 31, 203, 565, 1758, 8526, 3238, 27859, 1887, 682, 274, 203, 203, 565, 1758, 8526, 3238, 1818, 10262, 343, 8905, 13407, 682, 274, 203, 203, 565, 1758, 8526, 3238, 1818, 11688, 6434, 908, 274, 203, 377, 203, 377, 203, 203, 565, 9354, 87, 18, 4789, 3238, 389, 2316, 548, 4789, 31, 203, 565, 2254, 5034, 1071, 11013, 8872, 31, 203, 565, 2254, 5034, 8526, 1071, 15654, 11688, 6433, 94, 31, 203, 203, 565, 2254, 5034, 3238, 389, 4963, 3088, 1283, 274, 203, 565, 2254, 5034, 3238, 389, 1826, 7544, 5269, 3088, 1283, 31, 203, 565, 2254, 5034, 3238, 389, 20409, 5269, 3088, 1283, 31, 203, 565, 2254, 5034, 3238, 389, 482, 49, 474, 5269, 3088, 1283, 31, 203, 565, 2254, 5034, 3238, 389, 21245, 11688, 5269, 3088, 1283, 31, 203, 203, 565, 2254, 5034, 3238, 1699, 5269, 3088, 1283, 273, 404, 14509, 274, 203, 565, 2254, 5034, 3238, 1699, 29752, 7544, 5269, 3088, 1283, 274, 203, 565, 2254, 5034, 3238, 1699, 18927, 5269, 3088, 1283, 274, 203, 565, 2254, 5034, 3238, 1699, 4782, 49, 474, 5269, 3088, 1283, 274, 203, 565, 2254, 5034, 3238, 1699, 6434, 908, 11688, 5269, 3088, 1283, 274, 7010, 203, 565, 1426, 3238, 389, 14739, 682, 55, 1918, 343, 273, 638, 31, 203, 203, 683, 9454, 18035, 560, 374, 18, 28, 2 ]
// SPDX-License-Identifier: MIT pragma solidity 0.8.10; import "@openzeppelin/contracts/utils/math/Math.sol"; import "./interfaces/IOverlayV1Factory.sol"; import "./interfaces/IOverlayV1Market.sol"; import "./interfaces/IOverlayV1Token.sol"; import "./interfaces/feeds/IOverlayV1Feed.sol"; import "./libraries/FixedPoint.sol"; import "./libraries/Oracle.sol"; import "./libraries/Position.sol"; import "./libraries/Risk.sol"; import "./libraries/Roller.sol"; contract OverlayV1Market is IOverlayV1Market { using FixedPoint for uint256; using Oracle for Oracle.Data; using Position for mapping(bytes32 => Position.Info); using Position for Position.Info; using Risk for uint256[15]; using Roller for Roller.Snapshot; // internal constants uint256 internal constant ONE = 1e18; // 18 decimal places // cap for euler exponent powers; SEE: ./libraries/LogExpMath.sol::pow // using ~ 1/2 library max for substantial padding uint256 internal constant MAX_NATURAL_EXPONENT = 20e18; // immutables IOverlayV1Token public immutable ovl; // ovl token address public immutable feed; // oracle feed address public immutable factory; // factory that deployed this market // risk params uint256[15] public params; // params.idx order based on Risk.Parameters enum // aggregate oi quantities uint256 public oiLong; uint256 public oiShort; uint256 public oiLongShares; uint256 public oiShortShares; // rollers Roller.Snapshot public override snapshotVolumeBid; // snapshot of recent volume on bid Roller.Snapshot public override snapshotVolumeAsk; // snapshot of recent volume on ask Roller.Snapshot public override snapshotMinted; // snapshot of recent PnL minted/burned // positions mapping(bytes32 => Position.Info) public override positions; uint256 private _totalPositions; // data from last call to update uint256 public timestampUpdateLast; // cached risk calcs uint256 public dpUpperLimit; // e**(+priceDriftUpperLimit * macroWindow) // factory modifier for governance sensitive functions modifier onlyFactory() { require(msg.sender == factory, "OVLV1: !factory"); _; } // events for core functions event Build( address indexed sender, // address that initiated build (owns position) uint256 positionId, // id of built position uint256 oi, // oi of position at build uint256 debt, // debt of position at build bool isLong, // whether is long or short uint256 price // entry price ); event Unwind( address indexed sender, // address that initiated unwind (owns position) uint256 positionId, // id of unwound position uint256 fraction, // fraction of position unwound int256 mint, // total amount minted/burned (+/-) at unwind uint256 price // exit price ); event Liquidate( address indexed sender, // address that initiated liquidate address indexed owner, // address that owned the liquidated position uint256 positionId, // id of the liquidated position int256 mint, // total amount burned (-) at liquidate uint256 price // liquidation price ); constructor() { (address _ovl, address _feed, address _factory) = IOverlayV1Deployer(msg.sender) .parameters(); ovl = IOverlayV1Token(_ovl); feed = _feed; factory = _factory; } /// @notice initializes the market and its risk params /// @notice called only once by factory on deployment function initialize(uint256[15] memory _params) external onlyFactory { // initialize update data Oracle.Data memory data = IOverlayV1Feed(feed).latest(); require(_midFromFeed(data) > 0, "OVLV1:!data"); timestampUpdateLast = block.timestamp; // check risk params valid uint256 _capLeverage = _params[uint256(Risk.Parameters.CapLeverage)]; uint256 _delta = _params[uint256(Risk.Parameters.Delta)]; uint256 _maintenanceMarginFraction = _params[ uint256(Risk.Parameters.MaintenanceMarginFraction) ]; uint256 _liquidationFeeRate = _params[uint256(Risk.Parameters.LiquidationFeeRate)]; require( _capLeverage <= ONE.divDown( 2 * _delta + _maintenanceMarginFraction.divDown(ONE - _liquidationFeeRate) ), "OVLV1: max lev immediately liquidatable" ); uint256 _priceDriftUpperLimit = _params[uint256(Risk.Parameters.PriceDriftUpperLimit)]; require( _priceDriftUpperLimit * data.macroWindow < MAX_NATURAL_EXPONENT, "OVLV1: price drift exceeds max exp" ); _cacheRiskCalc(Risk.Parameters.PriceDriftUpperLimit, _priceDriftUpperLimit); // set the risk params for (uint256 i = 0; i < _params.length; i++) { params[i] = _params[i]; } } /// @dev builds a new position function build( uint256 collateral, uint256 leverage, bool isLong, uint256 priceLimit ) external returns (uint256 positionId_) { require(leverage >= ONE, "OVLV1:lev<min"); require(leverage <= params.get(Risk.Parameters.CapLeverage), "OVLV1:lev>max"); require(collateral >= params.get(Risk.Parameters.MinCollateral), "OVLV1:collateral<min"); uint256 oi; uint256 debt; uint256 price; uint256 tradingFee; // avoids stack too deep { // call to update before any effects Oracle.Data memory data = update(); // calculate notional, oi, and trading fees. fees charged on notional // and added to collateral transferred in uint256 notional = collateral.mulUp(leverage); uint256 midPrice = _midFromFeed(data); oi = oiFromNotional(notional, midPrice); // check have more than zero number of contracts built require(oi > 0, "OVLV1:oi==0"); // calculate debt and trading fees. fees charged on notional // and added to collateral transferred in debt = notional - collateral; tradingFee = notional.mulUp(params.get(Risk.Parameters.TradingFeeRate)); // calculate current notional cap adjusted for circuit breaker *then* adjust // for front run and back run bounds (order matters) // finally, transform into a cap on open interest uint256 capOi = oiFromNotional( capNotionalAdjustedForBounds( data, capNotionalAdjustedForCircuitBreaker(params.get(Risk.Parameters.CapNotional)) ), midPrice ); // longs get the ask and shorts get the bid on build // register the additional volume on either the ask or bid // where volume = oi / capOi price = isLong ? ask(data, _registerVolumeAsk(data, oi, capOi)) : bid(data, _registerVolumeBid(data, oi, capOi)); // check price hasn't changed more than max slippage specified by trader require(isLong ? price <= priceLimit : price >= priceLimit, "OVLV1:slippage>max"); // add new position's open interest to the side's aggregate oi value // and increase number of oi shares issued. assemble position for storage // cache for gas savings uint256 oiTotalOnSide = isLong ? oiLong : oiShort; uint256 oiTotalSharesOnSide = isLong ? oiLongShares : oiShortShares; // check new total oi on side does not exceed capOi oiTotalOnSide += oi; oiTotalSharesOnSide += oi; require(oiTotalOnSide <= capOi, "OVLV1:oi>cap"); // update total aggregate oi and oi shares if (isLong) { oiLong = oiTotalOnSide; oiLongShares = oiTotalSharesOnSide; } else { oiShort = oiTotalOnSide; oiShortShares = oiTotalSharesOnSide; } // assemble position info data // check position is not immediately liquidatable prior to storing Position.Info memory pos = Position.Info({ notional: uint96(notional), // won't overflow as capNotional max is 8e24 debt: uint96(debt), isLong: isLong, entryToMidRatio: Position.calcEntryToMidRatio(price, midPrice), liquidated: false, oiShares: oi }); require( !pos.liquidatable( oiTotalOnSide, oiTotalSharesOnSide, midPrice, // mid price used on liquidations params.get(Risk.Parameters.CapPayoff), params.get(Risk.Parameters.MaintenanceMarginFraction), params.get(Risk.Parameters.LiquidationFeeRate) ), "OVLV1:liquidatable" ); // store the position info data positionId_ = _totalPositions; positions.set(msg.sender, positionId_, pos); _totalPositions++; } // emit build event emit Build(msg.sender, positionId_, oi, debt, isLong, price); // transfer in the OVL collateral needed to back the position + fees // trading fees charged as a percentage on notional size of position ovl.transferFrom(msg.sender, address(this), collateral + tradingFee); // send trading fees to trading fee recipient ovl.transfer(IOverlayV1Factory(factory).feeRecipient(), tradingFee); } /// @dev unwinds fraction of an existing position function unwind( uint256 positionId, uint256 fraction, uint256 priceLimit ) external { require(fraction > 0, "OVLV1:fraction<min"); require(fraction <= ONE, "OVLV1:fraction>max"); uint256 value; uint256 cost; uint256 price; uint256 tradingFee; // avoids stack too deep { // call to update before any effects Oracle.Data memory data = update(); // check position exists Position.Info memory pos = positions.get(msg.sender, positionId); require(pos.exists(), "OVLV1:!position"); // cache for gas savings uint256 oiTotalOnSide = pos.isLong ? oiLong : oiShort; uint256 oiTotalSharesOnSide = pos.isLong ? oiLongShares : oiShortShares; // check position not liquidatable otherwise can't unwind require( !pos.liquidatable( oiTotalOnSide, oiTotalSharesOnSide, _midFromFeed(data), // mid price used on liquidations params.get(Risk.Parameters.CapPayoff), params.get(Risk.Parameters.MaintenanceMarginFraction), params.get(Risk.Parameters.LiquidationFeeRate) ), "OVLV1:liquidatable" ); // longs get the bid and shorts get the ask on unwind // register the additional volume on either the ask or bid // where volume = oi / capOi // current cap only adjusted for bounds (no circuit breaker so traders // don't get stuck in a position) uint256 capOi = oiFromNotional( capNotionalAdjustedForBounds(data, params.get(Risk.Parameters.CapNotional)), _midFromFeed(data) ); price = pos.isLong ? bid( data, _registerVolumeBid( data, pos.oiCurrent(fraction, oiTotalOnSide, oiTotalSharesOnSide), capOi ) ) : ask( data, _registerVolumeAsk( data, pos.oiCurrent(fraction, oiTotalOnSide, oiTotalSharesOnSide), capOi ) ); // check price hasn't changed more than max slippage specified by trader require(pos.isLong ? price >= priceLimit : price <= priceLimit, "OVLV1:slippage>max"); // calculate the value and cost of the position for pnl determinations // and amount to transfer uint256 capPayoff = params.get(Risk.Parameters.CapPayoff); value = pos.value(fraction, oiTotalOnSide, oiTotalSharesOnSide, price, capPayoff); cost = pos.cost(fraction); // calculate the trading fee as % on notional uint256 tradingFeeRate = params.get(Risk.Parameters.TradingFeeRate); tradingFee = pos.tradingFee( fraction, oiTotalOnSide, oiTotalSharesOnSide, price, capPayoff, tradingFeeRate ); tradingFee = Math.min(tradingFee, value); // if value < tradingFee // subtract unwound open interest from the side's aggregate oi value // and decrease number of oi shares issued // use subFloor to avoid reverts with rounding issues if (pos.isLong) { oiLong = oiLong.subFloor( pos.oiCurrent(fraction, oiTotalOnSide, oiTotalSharesOnSide) ); oiLongShares = oiLongShares.subFloor(pos.oiSharesCurrent(fraction)); } else { oiShort = oiShort.subFloor( pos.oiCurrent(fraction, oiTotalOnSide, oiTotalSharesOnSide) ); oiShortShares = oiShortShares.subFloor(pos.oiSharesCurrent(fraction)); } // register the amount to be minted/burned // capPayoff prevents overflow reverts with int256 cast _registerMintOrBurn(int256(value) - int256(cost)); // store the updated position info data // use subFloor to avoid reverts with rounding issues pos.notional = uint96(uint256(pos.notional).subFloor(pos.notionalInitial(fraction))); pos.debt = uint96(uint256(pos.debt).subFloor(pos.debtCurrent(fraction))); pos.oiShares = pos.oiShares.subFloor(pos.oiSharesCurrent(fraction)); positions.set(msg.sender, positionId, pos); } // emit unwind event emit Unwind(msg.sender, positionId, fraction, int256(value) - int256(cost), price); // mint or burn the pnl for the position if (value >= cost) { ovl.mint(address(this), value - cost); } else { ovl.burn(cost - value); } // transfer out the unwound position value less fees to trader ovl.transfer(msg.sender, value - tradingFee); // send trading fees to trading fee recipient ovl.transfer(IOverlayV1Factory(factory).feeRecipient(), tradingFee); } /// @dev liquidates a liquidatable position function liquidate(address owner, uint256 positionId) external { uint256 value; uint256 cost; uint256 price; uint256 liquidationFee; uint256 marginToBurn; uint256 marginRemaining; // avoids stack too deep { // check position exists Position.Info memory pos = positions.get(owner, positionId); require(pos.exists(), "OVLV1:!position"); // call to update before any effects Oracle.Data memory data = update(); // cache for gas savings uint256 oiTotalOnSide = pos.isLong ? oiLong : oiShort; uint256 oiTotalSharesOnSide = pos.isLong ? oiLongShares : oiShortShares; uint256 capPayoff = params.get(Risk.Parameters.CapPayoff); // entire position should be liquidated uint256 fraction = ONE; // Use mid price without volume for liquidation (oracle price effectively) to // prevent market impact manipulation from causing unneccessary liquidations price = _midFromFeed(data); // check position is liquidatable require( pos.liquidatable( oiTotalOnSide, oiTotalSharesOnSide, price, capPayoff, params.get(Risk.Parameters.MaintenanceMarginFraction), params.get(Risk.Parameters.LiquidationFeeRate) ), "OVLV1:!liquidatable" ); // calculate the value and cost of the position for pnl determinations // and amount to transfer value = pos.value(fraction, oiTotalOnSide, oiTotalSharesOnSide, price, capPayoff); cost = pos.cost(fraction); // calculate the liquidation fee as % on remaining value // sent as reward to liquidator liquidationFee = value.mulDown(params.get(Risk.Parameters.LiquidationFeeRate)); marginRemaining = value - liquidationFee; // Reduce burn amount further by the mm burn rate, as insurance // for cases when not liquidated in time marginToBurn = marginRemaining.mulDown( params.get(Risk.Parameters.MaintenanceMarginBurnRate) ); marginRemaining -= marginToBurn; // subtract liquidated open interest from the side's aggregate oi value // and decrease number of oi shares issued // use subFloor to avoid reverts with rounding issues if (pos.isLong) { oiLong = oiLong.subFloor( pos.oiCurrent(fraction, oiTotalOnSide, oiTotalSharesOnSide) ); oiLongShares = oiLongShares.subFloor(pos.oiSharesCurrent(fraction)); } else { oiShort = oiShort.subFloor( pos.oiCurrent(fraction, oiTotalOnSide, oiTotalSharesOnSide) ); oiShortShares = oiShortShares.subFloor(pos.oiSharesCurrent(fraction)); } // register the amount to be burned _registerMintOrBurn(int256(value) - int256(cost) - int256(marginToBurn)); // store the updated position info data. mark as liquidated pos.notional = 0; pos.debt = 0; pos.oiShares = 0; pos.liquidated = true; pos.entryToMidRatio = 0; positions.set(owner, positionId, pos); } // emit liquidate event emit Liquidate( msg.sender, owner, positionId, int256(value) - int256(cost) - int256(marginToBurn), price ); // burn the pnl for the position + insurance margin ovl.burn(cost - value + marginToBurn); // transfer out the liquidation fee to liquidator for reward ovl.transfer(msg.sender, liquidationFee); // send remaining margin to trading fee recipient ovl.transfer(IOverlayV1Factory(factory).feeRecipient(), marginRemaining); } /// @dev updates market: pays funding and fetches freshest data from feed /// @dev update is called every time market is interacted with function update() public returns (Oracle.Data memory) { // apply funding if at least one block has passed uint256 timeElapsed = block.timestamp - timestampUpdateLast; if (timeElapsed > 0) { // calculate adjustments to oi due to funding bool isLongOverweight = oiLong > oiShort; uint256 oiOverweight = isLongOverweight ? oiLong : oiShort; uint256 oiUnderweight = isLongOverweight ? oiShort : oiLong; (oiOverweight, oiUnderweight) = oiAfterFunding( oiOverweight, oiUnderweight, timeElapsed ); // pay funding oiLong = isLongOverweight ? oiOverweight : oiUnderweight; oiShort = isLongOverweight ? oiUnderweight : oiOverweight; // refresh last update data timestampUpdateLast = block.timestamp; } // fetch new oracle data from feed // applies sanity check in case of data manipulation Oracle.Data memory data = IOverlayV1Feed(feed).latest(); require(dataIsValid(data), "OVLV1:!data"); // return the latest data from feed return data; } /// @dev sanity check on data fetched from oracle in case of manipulation /// @dev rough check that log price bounded by +/- priceDriftUpperLimit * dt /// @dev when comparing priceMacro(now) vs priceMacro(now - macroWindow) function dataIsValid(Oracle.Data memory data) public view returns (bool) { // upper and lower limits are e**(+/- priceDriftUpperLimit * dt) uint256 _dpUpperLimit = dpUpperLimit; uint256 _dpLowerLimit = ONE.divDown(_dpUpperLimit); // compare current price over macro window vs price over macro window // one macro window in the past uint256 priceNow = data.priceOverMacroWindow; uint256 priceLast = data.priceOneMacroWindowAgo; if (priceLast == 0 || priceNow == 0) { // data is not valid if price is zero return false; } // price is valid if within upper and lower limits on drift given // time elapsed over one macro window uint256 dp = priceNow.divUp(priceLast); return (dp >= _dpLowerLimit && dp <= _dpUpperLimit); } /// @notice Current open interest after funding payments transferred /// @notice from overweight oi side to underweight oi side /// @dev The value of oiOverweight must be >= oiUnderweight function oiAfterFunding( uint256 oiOverweight, uint256 oiUnderweight, uint256 timeElapsed ) public view returns (uint256, uint256) { uint256 oiTotal = oiOverweight + oiUnderweight; uint256 oiImbalance = oiOverweight - oiUnderweight; uint256 oiInvariant = oiUnderweight.mulUp(oiOverweight); // If no OI or imbalance, no funding occurs. Handles div by zero case below if (oiTotal == 0 || oiImbalance == 0) { return (oiOverweight, oiUnderweight); } // draw down the imbalance by factor of e**(-2*k*t) // but min to zero if pow = 2*k*t exceeds MAX_NATURAL_EXPONENT uint256 fundingFactor; uint256 pow = 2 * params.get(Risk.Parameters.K) * timeElapsed; if (pow < MAX_NATURAL_EXPONENT) { fundingFactor = ONE.divDown(pow.expUp()); // e**(-pow) } // Decrease total aggregate open interest (i.e. oiLong + oiShort) // to compensate protocol for pro-rata share of imbalance liability // OI_tot(t) = OI_tot(0) * \ // sqrt( 1 - (OI_imb(0)/OI_tot(0))**2 * (1 - e**(-4*k*t)) ) // Guaranteed 0 <= underRoot <= 1 uint256 oiImbFraction = oiImbalance.divDown(oiTotal); uint256 underRoot = ONE - oiImbFraction.mulDown(oiImbFraction).mulDown( ONE - fundingFactor.mulDown(fundingFactor) ); // oiTotalNow guaranteed <= oiTotalBefore (burn happens) oiTotal = oiTotal.mulDown(underRoot.powDown(ONE / 2)); // Time decay imbalance: OI_imb(t) = OI_imb(0) * e**(-2*k*t) // oiImbalanceNow guaranteed <= oiImbalanceBefore oiImbalance = oiImbalance.mulDown(fundingFactor); // overweight pays underweight // use oiOver * oiUnder = invariant for oiUnderNow to avoid any // potential overflow reverts oiOverweight = (oiTotal + oiImbalance) / 2; if (oiOverweight != 0) { oiUnderweight = oiInvariant.divUp(oiOverweight); } return (oiOverweight, oiUnderweight); } /// @dev current notional cap with adjustments to lower /// @dev cap in the event market has printed a lot in recent past function capNotionalAdjustedForCircuitBreaker(uint256 cap) public view returns (uint256) { // Adjust cap downward for circuit breaker. Use snapshotMinted // but transformed to account for decay in magnitude of minted since // last snapshot taken Roller.Snapshot memory snapshot = snapshotMinted; uint256 circuitBreakerWindow = params.get(Risk.Parameters.CircuitBreakerWindow); snapshot = snapshot.transform(block.timestamp, circuitBreakerWindow, 0); cap = circuitBreaker(snapshot, cap); return cap; } /// @dev bound on notional cap from circuit breaker /// @dev Three cases: /// @dev 1. minted < 1x target amount over circuitBreakerWindow: return cap /// @dev 2. minted > 2x target amount over last circuitBreakerWindow: return 0 /// @dev 3. minted between 1x and 2x target amount: return cap * (2 - minted/target) function circuitBreaker(Roller.Snapshot memory snapshot, uint256 cap) public view returns (uint256) { int256 minted = int256(snapshot.cumulative()); uint256 circuitBreakerMintTarget = params.get(Risk.Parameters.CircuitBreakerMintTarget); if (minted <= int256(circuitBreakerMintTarget)) { return cap; } else if (minted >= 2 * int256(circuitBreakerMintTarget)) { return 0; } // case 3 (circuit breaker adjustment downward) uint256 adjustment = 2 * ONE - uint256(minted).divDown(circuitBreakerMintTarget); return cap.mulDown(adjustment); } /// @dev current notional cap with adjustments to prevent /// @dev front-running trade and back-running trade function capNotionalAdjustedForBounds(Oracle.Data memory data, uint256 cap) public view returns (uint256) { if (data.hasReserve) { // Adjust cap downward if exceeds bounds from front run attack cap = Math.min(cap, frontRunBound(data)); // Adjust cap downward if exceeds bounds from back run attack cap = Math.min(cap, backRunBound(data)); } return cap; } /// @dev bound on notional cap to mitigate front-running attack /// @dev bound = lmbda * reserveInOvl function frontRunBound(Oracle.Data memory data) public view returns (uint256) { uint256 lmbda = params.get(Risk.Parameters.Lmbda); return lmbda.mulDown(data.reserveOverMicroWindow); } /// @dev bound on notional cap to mitigate back-running attack /// @dev bound = macroWindowInBlocks * reserveInOvl * 2 * delta function backRunBound(Oracle.Data memory data) public view returns (uint256) { uint256 averageBlockTime = params.get(Risk.Parameters.AverageBlockTime); uint256 window = (data.macroWindow * ONE) / averageBlockTime; uint256 delta = params.get(Risk.Parameters.Delta); return delta.mulDown(data.reserveOverMicroWindow).mulDown(window).mulDown(2 * ONE); } /// @dev Returns the open interest in number of contracts for a given notional /// @dev Uses _midFromFeed(data) price to calculate oi: OI = Q / P function oiFromNotional(uint256 notional, uint256 midPrice) public view returns (uint256) { return notional.divDown(midPrice); } /// @dev bid price given oracle data and recent volume function bid(Oracle.Data memory data, uint256 volume) public view returns (uint256 bid_) { bid_ = Math.min(data.priceOverMicroWindow, data.priceOverMacroWindow); // add static spread (delta) and market impact (lmbda * volume) uint256 delta = params.get(Risk.Parameters.Delta); uint256 lmbda = params.get(Risk.Parameters.Lmbda); uint256 pow = delta + lmbda.mulUp(volume); require(pow < MAX_NATURAL_EXPONENT, "OVLV1:slippage>max"); bid_ = bid_.mulDown(ONE.divDown(pow.expUp())); // bid * e**(-pow) } /// @dev ask price given oracle data and recent volume function ask(Oracle.Data memory data, uint256 volume) public view returns (uint256 ask_) { ask_ = Math.max(data.priceOverMicroWindow, data.priceOverMacroWindow); // add static spread (delta) and market impact (lmbda * volume) uint256 delta = params.get(Risk.Parameters.Delta); uint256 lmbda = params.get(Risk.Parameters.Lmbda); uint256 pow = delta + lmbda.mulUp(volume); require(pow < MAX_NATURAL_EXPONENT, "OVLV1:slippage>max"); ask_ = ask_.mulUp(pow.expUp()); // ask * e**(pow) } /// @dev mid price without impact/spread given oracle data and recent volume /// @dev used for gas savings to avoid accessing storage for delta, lmbda function _midFromFeed(Oracle.Data memory data) private view returns (uint256 mid_) { mid_ = Math.average(data.priceOverMicroWindow, data.priceOverMacroWindow); } /// @dev Rolling volume adjustments on bid side to be used for market impact. /// @dev Volume values are normalized with respect to cap function _registerVolumeBid( Oracle.Data memory data, uint256 volume, uint256 cap ) private returns (uint256) { // save gas with snapshot in memory Roller.Snapshot memory snapshot = snapshotVolumeBid; int256 value = int256(volume.divUp(cap)); // calculates the decay in the rolling volume since last snapshot // and determines new window to decay over snapshot = snapshot.transform(block.timestamp, data.microWindow, value); // store the transformed snapshot snapshotVolumeBid = snapshot; // return the cumulative volume return uint256(snapshot.cumulative()); } /// @dev Rolling volume adjustments on ask side to be used for market impact. /// @dev Volume values are normalized with respect to cap function _registerVolumeAsk( Oracle.Data memory data, uint256 volume, uint256 cap ) private returns (uint256) { // save gas with snapshot in memory Roller.Snapshot memory snapshot = snapshotVolumeAsk; int256 value = int256(volume.divUp(cap)); // calculates the decay in the rolling volume since last snapshot // and determines new window to decay over snapshot = snapshot.transform(block.timestamp, data.microWindow, value); // store the transformed snapshot snapshotVolumeAsk = snapshot; // return the cumulative volume return uint256(snapshot.cumulative()); } /// @notice Rolling mint accumulator to be used for circuit breaker /// @dev value > 0 registers a mint, value <= 0 registers a burn function _registerMintOrBurn(int256 value) private returns (int256) { // save gas with snapshot in memory Roller.Snapshot memory snapshot = snapshotMinted; // calculates the decay in the rolling amount minted since last snapshot // and determines new window to decay over uint256 circuitBreakerWindow = params.get(Risk.Parameters.CircuitBreakerWindow); snapshot = snapshot.transform(block.timestamp, circuitBreakerWindow, value); // store the transformed snapshot snapshotMinted = snapshot; // return the cumulative mint amount int256 minted = snapshot.cumulative(); return minted; } /// @notice Sets the governance per-market risk parameter function setRiskParam(Risk.Parameters name, uint256 value) external onlyFactory { _checkRiskParam(name, value); _cacheRiskCalc(name, value); params.set(name, value); } /// @notice Checks the governance per-market risk parameter is valid function _checkRiskParam(Risk.Parameters name, uint256 value) private { // checks delta won't cause position to be immediately // liquidatable given current leverage cap (capLeverage), // liquidation fee rate (liquidationFeeRate), and // maintenance margin fraction (maintenanceMarginFraction) if (name == Risk.Parameters.Delta) { uint256 _delta = value; uint256 capLeverage = params.get(Risk.Parameters.CapLeverage); uint256 maintenanceMarginFraction = params.get( Risk.Parameters.MaintenanceMarginFraction ); uint256 liquidationFeeRate = params.get(Risk.Parameters.LiquidationFeeRate); require( capLeverage <= ONE.divDown( 2 * _delta + maintenanceMarginFraction.divDown(ONE - liquidationFeeRate) ), "OVLV1: max lev immediately liquidatable" ); } // checks capLeverage won't cause position to be immediately // liquidatable given current spread (delta), // liquidation fee rate (liquidationFeeRate), and // maintenance margin fraction (maintenanceMarginFraction) if (name == Risk.Parameters.CapLeverage) { uint256 _capLeverage = value; uint256 delta = params.get(Risk.Parameters.Delta); uint256 maintenanceMarginFraction = params.get( Risk.Parameters.MaintenanceMarginFraction ); uint256 liquidationFeeRate = params.get(Risk.Parameters.LiquidationFeeRate); require( _capLeverage <= ONE.divDown( 2 * delta + maintenanceMarginFraction.divDown(ONE - liquidationFeeRate) ), "OVLV1: max lev immediately liquidatable" ); } // checks maintenanceMarginFraction won't cause position // to be immediately liquidatable given current spread (delta), // liquidation fee rate (liquidationFeeRate), // and leverage cap (capLeverage) if (name == Risk.Parameters.MaintenanceMarginFraction) { uint256 _maintenanceMarginFraction = value; uint256 delta = params.get(Risk.Parameters.Delta); uint256 capLeverage = params.get(Risk.Parameters.CapLeverage); uint256 liquidationFeeRate = params.get(Risk.Parameters.LiquidationFeeRate); require( capLeverage <= ONE.divDown( 2 * delta + _maintenanceMarginFraction.divDown(ONE - liquidationFeeRate) ), "OVLV1: max lev immediately liquidatable" ); } // checks liquidationFeeRate won't cause position // to be immediately liquidatable given current spread (delta), // leverage cap (capLeverage), and // maintenance margin fraction (maintenanceMarginFraction) if (name == Risk.Parameters.LiquidationFeeRate) { uint256 _liquidationFeeRate = value; uint256 delta = params.get(Risk.Parameters.Delta); uint256 capLeverage = params.get(Risk.Parameters.CapLeverage); uint256 maintenanceMarginFraction = params.get( Risk.Parameters.MaintenanceMarginFraction ); require( capLeverage <= ONE.divDown( 2 * delta + maintenanceMarginFraction.divDown(ONE - _liquidationFeeRate) ), "OVLV1: max lev immediately liquidatable" ); } // checks priceDriftUpperLimit won't cause pow() call in dataIsValid // to exceed max if (name == Risk.Parameters.PriceDriftUpperLimit) { Oracle.Data memory data = IOverlayV1Feed(feed).latest(); uint256 _priceDriftUpperLimit = value; require( _priceDriftUpperLimit * data.macroWindow < MAX_NATURAL_EXPONENT, "OVLV1: price drift exceeds max exp" ); } } /// @notice Caches risk param calculations used in market contract /// @notice for gas savings function _cacheRiskCalc(Risk.Parameters name, uint256 value) private { // caches calculations for dpUpperLimit // = e**(priceDriftUpperLimit * data.macroWindow) if (name == Risk.Parameters.PriceDriftUpperLimit) { Oracle.Data memory data = IOverlayV1Feed(feed).latest(); uint256 _priceDriftUpperLimit = value; uint256 pow = _priceDriftUpperLimit * data.macroWindow; dpUpperLimit = pow.expUp(); // e**(pow) } } }
@dev bound on notional cap to mitigate back-running attack @dev bound = macroWindowInBlocks * reserveInOvl * 2 * delta
function backRunBound(Oracle.Data memory data) public view returns (uint256) { uint256 averageBlockTime = params.get(Risk.Parameters.AverageBlockTime); uint256 window = (data.macroWindow * ONE) / averageBlockTime; uint256 delta = params.get(Risk.Parameters.Delta); return delta.mulDown(data.reserveOverMicroWindow).mulDown(window).mulDown(2 * ONE); }
14,060,254
[ 1, 3653, 603, 486, 285, 287, 3523, 358, 20310, 360, 340, 1473, 17, 8704, 13843, 225, 2489, 273, 11522, 3829, 382, 6450, 225, 20501, 382, 51, 10872, 225, 576, 225, 3622, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1473, 1997, 3499, 12, 23601, 18, 751, 3778, 501, 13, 1071, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 2254, 5034, 8164, 1768, 950, 273, 859, 18, 588, 12, 54, 10175, 18, 2402, 18, 17115, 1768, 950, 1769, 203, 3639, 2254, 5034, 2742, 273, 261, 892, 18, 26448, 3829, 380, 15623, 13, 342, 8164, 1768, 950, 31, 203, 3639, 2254, 5034, 3622, 273, 859, 18, 588, 12, 54, 10175, 18, 2402, 18, 9242, 1769, 203, 3639, 327, 3622, 18, 16411, 4164, 12, 892, 18, 455, 6527, 4851, 13617, 3829, 2934, 16411, 4164, 12, 5668, 2934, 16411, 4164, 12, 22, 380, 15623, 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 ]
pragma solidity ^0.4.18; /** * SpaceWar * ETH Idle Game * spacewar.etherfun.net */ library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; require(c >= a); } function sub(uint256 a, uint256 b) internal pure returns (uint256 c) { require(b <= a); c = a - b; } function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a * b; require(a == 0 || c / a == b); } } library NumericSequence { using SafeMath for uint256; function sumOfN(uint256 basePrice, uint256 pricePerLevel, uint256 owned, uint256 count) internal pure returns (uint256 price) { require(count > 0); price = 0; price += SafeMath.mul((basePrice + pricePerLevel * owned), count); price += pricePerLevel * (count.mul((count-1))) / 2; } } //----------------------------------------------------------------------- contract SpaceWar { using NumericSequence for uint; using SafeMath for uint; struct MinerData { uint256[9] spaces; // space types and their upgrades uint8[3] hasUpgrade; uint256 money; uint256 lastUpdateTime; uint256 premamentMineBonusPct; uint256 unclaimedPot; uint256 lastPotClaimIndex; } struct SpaceData { uint256 basePrice; uint256 baseOutput; uint256 pricePerLevel; uint256 priceInETH; uint256 limit; } struct BoostData { uint256 percentBonus; uint256 priceInWEI; } struct PVPData { uint256[6] troops; uint256 immunityTime; uint256 exhaustTime; } struct TroopData { uint256 attackPower; uint256 defensePower; uint256 priceGold; uint256 priceETH; } uint8 private constant NUMBER_OF_RIG_TYPES = 9; SpaceData[9] private spaceData; uint8 private constant NUMBER_OF_UPGRADES = 3; BoostData[3] private boostData; uint8 private constant NUMBER_OF_TROOPS = 6; uint8 private constant ATTACKER_START_IDX = 0; uint8 private constant ATTACKER_END_IDX = 3; uint8 private constant DEFENDER_START_IDX = 3; uint8 private constant DEFENDER_END_IDX = 6; TroopData[6] private troopData; // honey pot variables uint256 private honeyPotAmount; uint256 private honeyPotSharePct; // 90% uint256 private jackPot; uint256 private devFund; uint256 private nextPotDistributionTime; mapping(address => mapping(uint256 => uint256)) private minerICOPerCycle; uint256[] private honeyPotPerCycle; uint256[] private globalICOPerCycle; uint256 private cycleCount; //booster info uint256 private constant NUMBER_OF_BOOSTERS = 5; uint256 private boosterIndex; uint256 private nextBoosterPrice; address[5] private boosterHolders; mapping(address => MinerData) private miners; mapping(address => PVPData) private pvpMap; mapping(uint256 => address) private indexes; uint256 private topindex; address private owner; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ function SpaceWar() public { owner = msg.sender; // price, prod. upgrade, priceETH, limit spaceData[0] = SpaceData(500, 1, 5, 0, 999); spaceData[1] = SpaceData(50000, 10, 500, 0, 999); spaceData[2] = SpaceData(5000000, 100, 50000, 0, 999); spaceData[3] = SpaceData(80000000, 1000, 800000, 0, 999); spaceData[4] = SpaceData(500000000, 20000, 5000000, 0.01 ether, 999); spaceData[5] = SpaceData(10000000000, 100000, 100000000, 0, 999); spaceData[6] = SpaceData(100000000000, 1000000, 1000000000, 0, 999); spaceData[7] = SpaceData(1000000000000, 50000000, 10000000000, 0.1 ether, 999); spaceData[8] = SpaceData(10000000000000, 100000000,100000000000, 0, 999); boostData[0] = BoostData(30, 0.01 ether); boostData[1] = BoostData(50, 0.1 ether); boostData[2] = BoostData(100, 1 ether); topindex = 0; honeyPotAmount = 0; devFund = 0; jackPot = 0; nextPotDistributionTime = block.timestamp; honeyPotSharePct = 90; // has to be set to a value boosterHolders[0] = owner; boosterHolders[1] = owner; boosterHolders[2] = owner; boosterHolders[3] = owner; boosterHolders[4] = owner; boosterIndex = 0; nextBoosterPrice = 0.1 ether; //pvp troopData[0] = TroopData(10, 0, 100000, 0); troopData[1] = TroopData(1000, 0, 80000000, 0); troopData[2] = TroopData(100000, 0, 1000000000, 0.01 ether); troopData[3] = TroopData(0, 15, 100000, 0); troopData[4] = TroopData(0, 1500, 80000000, 0); troopData[5] = TroopData(0, 150000, 1000000000, 0.01 ether); honeyPotPerCycle.push(0); globalICOPerCycle.push(1); cycleCount = 0; } //-------------------------------------------------------------------------- // Data access functions //-------------------------------------------------------------------------- function GetMinerData(address minerAddr) public constant returns (uint256 money, uint256 lastupdate, uint256 prodPerSec, uint256[9] spaces, uint[3] upgrades, uint256 unclaimedPot, bool hasBooster, uint256 unconfirmedMoney) { uint8 i = 0; money = miners[minerAddr].money; lastupdate = miners[minerAddr].lastUpdateTime; prodPerSec = GetProductionPerSecond(minerAddr); for(i = 0; i < NUMBER_OF_RIG_TYPES; ++i) { spaces[i] = miners[minerAddr].spaces[i]; } for(i = 0; i < NUMBER_OF_UPGRADES; ++i) { upgrades[i] = miners[minerAddr].hasUpgrade[i]; } unclaimedPot = miners[minerAddr].unclaimedPot; hasBooster = HasBooster(minerAddr); unconfirmedMoney = money + (prodPerSec * (now - lastupdate)); } function GetTotalMinerCount() public constant returns (uint256 count) { count = topindex; } function GetMinerAt(uint256 idx) public constant returns (address minerAddr) { require(idx < topindex); minerAddr = indexes[idx]; } function GetPotInfo() public constant returns (uint256 _honeyPotAmount, uint256 _devFunds, uint256 _jackPot, uint256 _nextDistributionTime) { _honeyPotAmount = honeyPotAmount; _devFunds = devFund; _jackPot = jackPot; _nextDistributionTime = nextPotDistributionTime; } function GetProductionPerSecond(address minerAddr) public constant returns (uint256 personalProduction) { MinerData storage m = miners[minerAddr]; personalProduction = 0; uint256 productionSpeed = 100 + m.premamentMineBonusPct; if(HasBooster(minerAddr)) // 100% bonus productionSpeed += 100; for(uint8 j = 0; j < NUMBER_OF_RIG_TYPES; ++j) { personalProduction += m.spaces[j] * spaceData[j].baseOutput; } personalProduction = personalProduction * productionSpeed / 100; } function GetGlobalProduction() public constant returns (uint256 globalMoney, uint256 globalHashRate) { globalMoney = 0; globalHashRate = 0; uint i = 0; for(i = 0; i < topindex; ++i) { MinerData storage m = miners[indexes[i]]; globalMoney += m.money; globalHashRate += GetProductionPerSecond(indexes[i]); } } function GetBoosterData() public constant returns (address[5] _boosterHolders, uint256 currentPrice, uint256 currentIndex) { for(uint i = 0; i < NUMBER_OF_BOOSTERS; ++i) { _boosterHolders[i] = boosterHolders[i]; } currentPrice = nextBoosterPrice; currentIndex = boosterIndex; } function HasBooster(address addr) public constant returns (bool hasBoost) { for(uint i = 0; i < NUMBER_OF_BOOSTERS; ++i) { if(boosterHolders[i] == addr) return true; } return false; } function GetPVPData(address addr) public constant returns (uint256 attackpower, uint256 defensepower, uint256 immunityTime, uint256 exhaustTime, uint256[6] troops) { PVPData storage a = pvpMap[addr]; immunityTime = a.immunityTime; exhaustTime = a.exhaustTime; attackpower = 0; defensepower = 0; for(uint i = 0; i < NUMBER_OF_TROOPS; ++i) { attackpower += a.troops[i] * troopData[i].attackPower; defensepower += a.troops[i] * troopData[i].defensePower; troops[i] = a.troops[i]; } } function GetCurrentICOCycle() public constant returns (uint256) { return cycleCount; } function GetICOData(uint256 idx) public constant returns (uint256 ICOFund, uint256 ICOPot) { require(idx <= cycleCount); ICOFund = globalICOPerCycle[idx]; if(idx < cycleCount) { ICOPot = honeyPotPerCycle[idx]; } else { ICOPot = honeyPotAmount / 10; // actual day estimate } } function GetMinerICOData(address miner, uint256 idx) public constant returns (uint256 ICOFund, uint256 ICOShare, uint256 lastClaimIndex) { require(idx <= cycleCount); ICOFund = minerICOPerCycle[miner][idx]; if(idx < cycleCount) { ICOShare = (honeyPotPerCycle[idx] * minerICOPerCycle[miner][idx]) / globalICOPerCycle[idx]; } else { ICOShare = (honeyPotAmount / 10) * minerICOPerCycle[miner][idx] / globalICOPerCycle[idx]; } lastClaimIndex = miners[miner].lastPotClaimIndex; } function GetMinerUnclaimedICOShare(address miner) public constant returns (uint256 unclaimedPot) { MinerData storage m = miners[miner]; require(m.lastUpdateTime != 0); require(m.lastPotClaimIndex < cycleCount); uint256 i = m.lastPotClaimIndex; uint256 limit = cycleCount; if((limit - i) > 30) // more than 30 iterations(days) afk limit = i + 30; unclaimedPot = 0; for(; i < cycleCount; ++i) { if(minerICOPerCycle[miner][i] > 0) unclaimedPot += (honeyPotPerCycle[i] * minerICOPerCycle[miner][i]) / globalICOPerCycle[i]; } } // ------------------------------------------------------------------------- // SpaceWars game handler functions // ------------------------------------------------------------------------- function StartNewMiner() external { require(miners[msg.sender].lastUpdateTime == 0); miners[msg.sender].lastUpdateTime = block.timestamp; miners[msg.sender].money = 0; miners[msg.sender].spaces[0] = 1; miners[msg.sender].unclaimedPot = 0; miners[msg.sender].lastPotClaimIndex = cycleCount; pvpMap[msg.sender].immunityTime = block.timestamp + 14400; pvpMap[msg.sender].exhaustTime = block.timestamp; indexes[topindex] = msg.sender; ++topindex; } function UpgradeSpace(uint8 spaceIdx, uint16 count) external { require(spaceIdx < NUMBER_OF_RIG_TYPES); require(count > 0); require(count <= 999); require(spaceData[spaceIdx].priceInETH == 0); MinerData storage m = miners[msg.sender]; require(spaceData[spaceIdx].limit >= (m.spaces[spaceIdx] + count)); UpdateMoney(); // the base of geometrical sequence uint256 price = NumericSequence.sumOfN(spaceData[spaceIdx].basePrice, spaceData[spaceIdx].pricePerLevel, m.spaces[spaceIdx], count); require(m.money >= price); m.spaces[spaceIdx] = m.spaces[spaceIdx] + count; if(m.spaces[spaceIdx] > spaceData[spaceIdx].limit) m.spaces[spaceIdx] = spaceData[spaceIdx].limit; m.money -= price; } function UpgradeSpaceETH(uint8 spaceIdx, uint256 count) external payable { require(spaceIdx < NUMBER_OF_RIG_TYPES); require(count > 0); require(count <= 999); require(spaceData[spaceIdx].priceInETH > 0); MinerData storage m = miners[msg.sender]; require(spaceData[spaceIdx].limit >= (m.spaces[spaceIdx] + count)); uint256 price = (spaceData[spaceIdx].priceInETH).mul(count); uint256 priceCoin = NumericSequence.sumOfN(spaceData[spaceIdx].basePrice, spaceData[spaceIdx].pricePerLevel, m.spaces[spaceIdx], count); UpdateMoney(); require(msg.value >= price); require(m.money >= priceCoin); BuyHandler(msg.value); m.spaces[spaceIdx] = m.spaces[spaceIdx] + count; if(m.spaces[spaceIdx] > spaceData[spaceIdx].limit) m.spaces[spaceIdx] = spaceData[spaceIdx].limit; m.money -= priceCoin; } function UpdateMoney() private { require(miners[msg.sender].lastUpdateTime != 0); require(block.timestamp >= miners[msg.sender].lastUpdateTime); MinerData storage m = miners[msg.sender]; uint256 diff = block.timestamp - m.lastUpdateTime; uint256 revenue = GetProductionPerSecond(msg.sender); m.lastUpdateTime = block.timestamp; if(revenue > 0) { revenue *= diff; m.money += revenue; } } function UpdateMoneyAt(address addr) private { require(miners[addr].lastUpdateTime != 0); require(block.timestamp >= miners[addr].lastUpdateTime); MinerData storage m = miners[addr]; uint256 diff = block.timestamp - m.lastUpdateTime; uint256 revenue = GetProductionPerSecond(addr); m.lastUpdateTime = block.timestamp; if(revenue > 0) { revenue *= diff; m.money += revenue; } } function BuyUpgrade(uint256 idx) external payable { require(idx < NUMBER_OF_UPGRADES); require(msg.value >= boostData[idx].priceInWEI); require(miners[msg.sender].hasUpgrade[idx] == 0); require(miners[msg.sender].lastUpdateTime != 0); BuyHandler(msg.value); UpdateMoney(); miners[msg.sender].hasUpgrade[idx] = 1; miners[msg.sender].premamentMineBonusPct += boostData[idx].percentBonus; } //-------------------------------------------------------------------------- // BOOSTER handlers //-------------------------------------------------------------------------- function BuyBooster() external payable { require(msg.value >= nextBoosterPrice); require(miners[msg.sender].lastUpdateTime != 0); for(uint i = 0; i < NUMBER_OF_BOOSTERS; ++i) if(boosterHolders[i] == msg.sender) revert(); address beneficiary = boosterHolders[boosterIndex]; MinerData storage m = miners[beneficiary]; // 20% interest after 5 buys m.unclaimedPot += (msg.value * 9403) / 10000; // distribute the rest honeyPotAmount += (msg.value * 597) / 20000; devFund += (msg.value * 597) / 20000; // increase price by 5% nextBoosterPrice += nextBoosterPrice / 20; UpdateMoney(); UpdateMoneyAt(beneficiary); // transfer ownership boosterHolders[boosterIndex] = msg.sender; // increase booster index boosterIndex += 1; if(boosterIndex >= 5) boosterIndex = 0; } //-------------------------------------------------------------------------- // PVP handler //-------------------------------------------------------------------------- // 0 for attacker 1 for defender function BuyTroop(uint256 idx, uint256 count) external payable { require(idx < NUMBER_OF_TROOPS); require(count > 0); require(count <= 1000); PVPData storage pvp = pvpMap[msg.sender]; MinerData storage m = miners[msg.sender]; uint256 owned = pvp.troops[idx]; uint256 priceGold = NumericSequence.sumOfN(troopData[idx].priceGold, troopData[idx].priceGold / 100, owned, count); uint256 priceETH = (troopData[idx].priceETH).mul(count); UpdateMoney(); require(m.money >= priceGold); require(msg.value >= priceETH); if(priceGold > 0) m.money -= priceGold; if(msg.value > 0) BuyHandler(msg.value); pvp.troops[idx] += count; } function Attack(address defenderAddr) external { require(msg.sender != defenderAddr); require(miners[msg.sender].lastUpdateTime != 0); require(miners[defenderAddr].lastUpdateTime != 0); PVPData storage attacker = pvpMap[msg.sender]; PVPData storage defender = pvpMap[defenderAddr]; uint i = 0; uint256 count = 0; require(block.timestamp > attacker.exhaustTime); require(block.timestamp > defender.immunityTime); // the aggressor loses immunity if(attacker.immunityTime > block.timestamp) attacker.immunityTime = block.timestamp - 1; attacker.exhaustTime = block.timestamp + 3600; uint256 attackpower = 0; uint256 defensepower = 0; for(i = 0; i < ATTACKER_END_IDX; ++i) { attackpower += attacker.troops[i] * troopData[i].attackPower; defensepower += defender.troops[i + DEFENDER_START_IDX] * troopData[i + DEFENDER_START_IDX].defensePower; } if(attackpower > defensepower) { if(defender.immunityTime < block.timestamp + 14400) defender.immunityTime = block.timestamp + 14400; UpdateMoneyAt(defenderAddr); MinerData storage m = miners[defenderAddr]; MinerData storage m2 = miners[msg.sender]; uint256 moneyStolen = m.money / 2; for(i = DEFENDER_START_IDX; i < DEFENDER_END_IDX; ++i) { defender.troops[i] = defender.troops[i]/2; } for(i = ATTACKER_START_IDX; i < ATTACKER_END_IDX; ++i) { if(troopData[i].attackPower > 0) { count = attacker.troops[i]; // if the troops overpower the total defense power only a fraction is lost if((count * troopData[i].attackPower) > defensepower) { count = count * defensepower / attackpower / 2; } else { count = count/2; } attacker.troops[i] = SafeMath.sub(attacker.troops[i],count); defensepower -= count * troopData[i].attackPower; } } m.money -= moneyStolen; m2.money += moneyStolen; } else { for(i = ATTACKER_START_IDX; i < ATTACKER_END_IDX; ++i) { attacker.troops[i] = attacker.troops[i] / 2; } for(i = DEFENDER_START_IDX; i < DEFENDER_END_IDX; ++i) { if(troopData[i].defensePower > 0) { count = defender.troops[i]; // if the troops overpower the total defense power only a fraction is lost if((count * troopData[i].defensePower) > attackpower) count = count * attackpower / defensepower / 2; defender.troops[i] -= count; attackpower -= count * troopData[i].defensePower; } } } } //-------------------------------------------------------------------------- // ICO/Pot share functions //-------------------------------------------------------------------------- function ReleaseICO() external { require(miners[msg.sender].lastUpdateTime != 0); require(nextPotDistributionTime <= block.timestamp); require(honeyPotAmount > 0); require(globalICOPerCycle[cycleCount] > 0); nextPotDistributionTime = block.timestamp + 86400; honeyPotPerCycle[cycleCount] = honeyPotAmount / 10; // 10% of the pot honeyPotAmount -= honeyPotAmount / 10; honeyPotPerCycle.push(0); globalICOPerCycle.push(0); cycleCount = cycleCount + 1; MinerData storage jakpotWinner = miners[msg.sender]; jakpotWinner.unclaimedPot += jackPot; jackPot = 0; } function FundICO(uint amount) external { require(miners[msg.sender].lastUpdateTime != 0); require(amount > 0); MinerData storage m = miners[msg.sender]; UpdateMoney(); require(m.money >= amount); m.money = (m.money).sub(amount); globalICOPerCycle[cycleCount] = globalICOPerCycle[cycleCount].add(uint(amount)); minerICOPerCycle[msg.sender][cycleCount] = minerICOPerCycle[msg.sender][cycleCount].add(uint(amount)); } function WithdrawICOEarnings() external { MinerData storage m = miners[msg.sender]; require(miners[msg.sender].lastUpdateTime != 0); require(miners[msg.sender].lastPotClaimIndex < cycleCount); uint256 i = m.lastPotClaimIndex; uint256 limit = cycleCount; if((limit - i) > 30) // more than 30 iterations(days) afk limit = i + 30; m.lastPotClaimIndex = limit; for(; i < cycleCount; ++i) { if(minerICOPerCycle[msg.sender][i] > 0) m.unclaimedPot += (honeyPotPerCycle[i] * minerICOPerCycle[msg.sender][i]) / globalICOPerCycle[i]; } } //-------------------------------------------------------------------------- // ETH handler functions //-------------------------------------------------------------------------- function BuyHandler(uint amount) private { // add 90% to honeyPot honeyPotAmount += (amount * honeyPotSharePct) / 100; jackPot += amount / 100; devFund += (amount * (100-(honeyPotSharePct+1))) / 100; } function WithdrawPotShare() public { MinerData storage m = miners[msg.sender]; require(m.unclaimedPot > 0); require(m.lastUpdateTime != 0); uint256 amntToSend = m.unclaimedPot; m.unclaimedPot = 0; if(msg.sender.send(amntToSend)) { m.unclaimedPot = 0; } } function WithdrawDevFunds() public { require(msg.sender == owner); if(owner.send(devFund)) { devFund = 0; } } // fallback payment to pot function() public payable { devFund += msg.value; } }
-----------------------------------------------------------------------
contract SpaceWar { using NumericSequence for uint; using SafeMath for uint; struct MinerData { uint8[3] hasUpgrade; uint256 money; uint256 lastUpdateTime; uint256 premamentMineBonusPct; uint256 unclaimedPot; uint256 lastPotClaimIndex; } struct SpaceData { uint256 basePrice; uint256 baseOutput; uint256 pricePerLevel; uint256 priceInETH; uint256 limit; } struct BoostData { uint256 percentBonus; uint256 priceInWEI; } struct PVPData { uint256[6] troops; uint256 immunityTime; uint256 exhaustTime; } struct TroopData { uint256 attackPower; uint256 defensePower; uint256 priceGold; uint256 priceETH; } uint8 private constant NUMBER_OF_RIG_TYPES = 9; SpaceData[9] private spaceData; uint8 private constant NUMBER_OF_UPGRADES = 3; BoostData[3] private boostData; uint8 private constant NUMBER_OF_TROOPS = 6; uint8 private constant ATTACKER_START_IDX = 0; uint8 private constant ATTACKER_END_IDX = 3; uint8 private constant DEFENDER_START_IDX = 3; uint8 private constant DEFENDER_END_IDX = 6; TroopData[6] private troopData; uint256 private jackPot; uint256 private devFund; uint256 private nextPotDistributionTime; mapping(address => mapping(uint256 => uint256)) private minerICOPerCycle; uint256[] private honeyPotPerCycle; uint256[] private globalICOPerCycle; uint256 private cycleCount; uint256 private boosterIndex; uint256 private nextBoosterPrice; address[5] private boosterHolders; mapping(address => MinerData) private miners; mapping(address => PVPData) private pvpMap; mapping(uint256 => address) private indexes; uint256 private topindex; address private owner; uint256 private honeyPotAmount; uint256 private constant NUMBER_OF_BOOSTERS = 5; function SpaceWar() public { owner = msg.sender; spaceData[0] = SpaceData(500, 1, 5, 0, 999); spaceData[1] = SpaceData(50000, 10, 500, 0, 999); spaceData[2] = SpaceData(5000000, 100, 50000, 0, 999); spaceData[3] = SpaceData(80000000, 1000, 800000, 0, 999); spaceData[4] = SpaceData(500000000, 20000, 5000000, 0.01 ether, 999); spaceData[5] = SpaceData(10000000000, 100000, 100000000, 0, 999); spaceData[6] = SpaceData(100000000000, 1000000, 1000000000, 0, 999); spaceData[7] = SpaceData(1000000000000, 50000000, 10000000000, 0.1 ether, 999); spaceData[8] = SpaceData(10000000000000, 100000000,100000000000, 0, 999); boostData[0] = BoostData(30, 0.01 ether); boostData[1] = BoostData(50, 0.1 ether); boostData[2] = BoostData(100, 1 ether); topindex = 0; honeyPotAmount = 0; devFund = 0; jackPot = 0; nextPotDistributionTime = block.timestamp; honeyPotSharePct = 90; boosterHolders[0] = owner; boosterHolders[1] = owner; boosterHolders[2] = owner; boosterHolders[3] = owner; boosterHolders[4] = owner; boosterIndex = 0; nextBoosterPrice = 0.1 ether; troopData[0] = TroopData(10, 0, 100000, 0); troopData[1] = TroopData(1000, 0, 80000000, 0); troopData[2] = TroopData(100000, 0, 1000000000, 0.01 ether); troopData[3] = TroopData(0, 15, 100000, 0); troopData[4] = TroopData(0, 1500, 80000000, 0); troopData[5] = TroopData(0, 150000, 1000000000, 0.01 ether); honeyPotPerCycle.push(0); globalICOPerCycle.push(1); cycleCount = 0; } function GetMinerData(address minerAddr) public constant returns (uint256 money, uint256 lastupdate, uint256 prodPerSec, uint256[9] spaces, uint[3] upgrades, uint256 unclaimedPot, bool hasBooster, uint256 unconfirmedMoney) { uint8 i = 0; money = miners[minerAddr].money; lastupdate = miners[minerAddr].lastUpdateTime; prodPerSec = GetProductionPerSecond(minerAddr); for(i = 0; i < NUMBER_OF_RIG_TYPES; ++i) { spaces[i] = miners[minerAddr].spaces[i]; } for(i = 0; i < NUMBER_OF_UPGRADES; ++i) { upgrades[i] = miners[minerAddr].hasUpgrade[i]; } unclaimedPot = miners[minerAddr].unclaimedPot; hasBooster = HasBooster(minerAddr); unconfirmedMoney = money + (prodPerSec * (now - lastupdate)); } function GetMinerData(address minerAddr) public constant returns (uint256 money, uint256 lastupdate, uint256 prodPerSec, uint256[9] spaces, uint[3] upgrades, uint256 unclaimedPot, bool hasBooster, uint256 unconfirmedMoney) { uint8 i = 0; money = miners[minerAddr].money; lastupdate = miners[minerAddr].lastUpdateTime; prodPerSec = GetProductionPerSecond(minerAddr); for(i = 0; i < NUMBER_OF_RIG_TYPES; ++i) { spaces[i] = miners[minerAddr].spaces[i]; } for(i = 0; i < NUMBER_OF_UPGRADES; ++i) { upgrades[i] = miners[minerAddr].hasUpgrade[i]; } unclaimedPot = miners[minerAddr].unclaimedPot; hasBooster = HasBooster(minerAddr); unconfirmedMoney = money + (prodPerSec * (now - lastupdate)); } function GetMinerData(address minerAddr) public constant returns (uint256 money, uint256 lastupdate, uint256 prodPerSec, uint256[9] spaces, uint[3] upgrades, uint256 unclaimedPot, bool hasBooster, uint256 unconfirmedMoney) { uint8 i = 0; money = miners[minerAddr].money; lastupdate = miners[minerAddr].lastUpdateTime; prodPerSec = GetProductionPerSecond(minerAddr); for(i = 0; i < NUMBER_OF_RIG_TYPES; ++i) { spaces[i] = miners[minerAddr].spaces[i]; } for(i = 0; i < NUMBER_OF_UPGRADES; ++i) { upgrades[i] = miners[minerAddr].hasUpgrade[i]; } unclaimedPot = miners[minerAddr].unclaimedPot; hasBooster = HasBooster(minerAddr); unconfirmedMoney = money + (prodPerSec * (now - lastupdate)); } function GetTotalMinerCount() public constant returns (uint256 count) { count = topindex; } function GetMinerAt(uint256 idx) public constant returns (address minerAddr) { require(idx < topindex); minerAddr = indexes[idx]; } function GetPotInfo() public constant returns (uint256 _honeyPotAmount, uint256 _devFunds, uint256 _jackPot, uint256 _nextDistributionTime) { _honeyPotAmount = honeyPotAmount; _devFunds = devFund; _jackPot = jackPot; _nextDistributionTime = nextPotDistributionTime; } function GetProductionPerSecond(address minerAddr) public constant returns (uint256 personalProduction) { MinerData storage m = miners[minerAddr]; personalProduction = 0; uint256 productionSpeed = 100 + m.premamentMineBonusPct; productionSpeed += 100; for(uint8 j = 0; j < NUMBER_OF_RIG_TYPES; ++j) { personalProduction += m.spaces[j] * spaceData[j].baseOutput; } personalProduction = personalProduction * productionSpeed / 100; } function GetProductionPerSecond(address minerAddr) public constant returns (uint256 personalProduction) { MinerData storage m = miners[minerAddr]; personalProduction = 0; uint256 productionSpeed = 100 + m.premamentMineBonusPct; productionSpeed += 100; for(uint8 j = 0; j < NUMBER_OF_RIG_TYPES; ++j) { personalProduction += m.spaces[j] * spaceData[j].baseOutput; } personalProduction = personalProduction * productionSpeed / 100; } function GetGlobalProduction() public constant returns (uint256 globalMoney, uint256 globalHashRate) { globalMoney = 0; globalHashRate = 0; uint i = 0; for(i = 0; i < topindex; ++i) { MinerData storage m = miners[indexes[i]]; globalMoney += m.money; globalHashRate += GetProductionPerSecond(indexes[i]); } } function GetGlobalProduction() public constant returns (uint256 globalMoney, uint256 globalHashRate) { globalMoney = 0; globalHashRate = 0; uint i = 0; for(i = 0; i < topindex; ++i) { MinerData storage m = miners[indexes[i]]; globalMoney += m.money; globalHashRate += GetProductionPerSecond(indexes[i]); } } function GetBoosterData() public constant returns (address[5] _boosterHolders, uint256 currentPrice, uint256 currentIndex) { for(uint i = 0; i < NUMBER_OF_BOOSTERS; ++i) { _boosterHolders[i] = boosterHolders[i]; } currentPrice = nextBoosterPrice; currentIndex = boosterIndex; } function GetBoosterData() public constant returns (address[5] _boosterHolders, uint256 currentPrice, uint256 currentIndex) { for(uint i = 0; i < NUMBER_OF_BOOSTERS; ++i) { _boosterHolders[i] = boosterHolders[i]; } currentPrice = nextBoosterPrice; currentIndex = boosterIndex; } function HasBooster(address addr) public constant returns (bool hasBoost) { for(uint i = 0; i < NUMBER_OF_BOOSTERS; ++i) { if(boosterHolders[i] == addr) return true; } return false; } function HasBooster(address addr) public constant returns (bool hasBoost) { for(uint i = 0; i < NUMBER_OF_BOOSTERS; ++i) { if(boosterHolders[i] == addr) return true; } return false; } function GetPVPData(address addr) public constant returns (uint256 attackpower, uint256 defensepower, uint256 immunityTime, uint256 exhaustTime, uint256[6] troops) { PVPData storage a = pvpMap[addr]; immunityTime = a.immunityTime; exhaustTime = a.exhaustTime; attackpower = 0; defensepower = 0; for(uint i = 0; i < NUMBER_OF_TROOPS; ++i) { attackpower += a.troops[i] * troopData[i].attackPower; defensepower += a.troops[i] * troopData[i].defensePower; troops[i] = a.troops[i]; } } function GetPVPData(address addr) public constant returns (uint256 attackpower, uint256 defensepower, uint256 immunityTime, uint256 exhaustTime, uint256[6] troops) { PVPData storage a = pvpMap[addr]; immunityTime = a.immunityTime; exhaustTime = a.exhaustTime; attackpower = 0; defensepower = 0; for(uint i = 0; i < NUMBER_OF_TROOPS; ++i) { attackpower += a.troops[i] * troopData[i].attackPower; defensepower += a.troops[i] * troopData[i].defensePower; troops[i] = a.troops[i]; } } function GetCurrentICOCycle() public constant returns (uint256) { return cycleCount; } function GetICOData(uint256 idx) public constant returns (uint256 ICOFund, uint256 ICOPot) { require(idx <= cycleCount); ICOFund = globalICOPerCycle[idx]; if(idx < cycleCount) { ICOPot = honeyPotPerCycle[idx]; } else { } } function GetICOData(uint256 idx) public constant returns (uint256 ICOFund, uint256 ICOPot) { require(idx <= cycleCount); ICOFund = globalICOPerCycle[idx]; if(idx < cycleCount) { ICOPot = honeyPotPerCycle[idx]; } else { } } function GetICOData(uint256 idx) public constant returns (uint256 ICOFund, uint256 ICOPot) { require(idx <= cycleCount); ICOFund = globalICOPerCycle[idx]; if(idx < cycleCount) { ICOPot = honeyPotPerCycle[idx]; } else { } } function GetMinerICOData(address miner, uint256 idx) public constant returns (uint256 ICOFund, uint256 ICOShare, uint256 lastClaimIndex) { require(idx <= cycleCount); ICOFund = minerICOPerCycle[miner][idx]; if(idx < cycleCount) { ICOShare = (honeyPotPerCycle[idx] * minerICOPerCycle[miner][idx]) / globalICOPerCycle[idx]; } else { ICOShare = (honeyPotAmount / 10) * minerICOPerCycle[miner][idx] / globalICOPerCycle[idx]; } lastClaimIndex = miners[miner].lastPotClaimIndex; } function GetMinerICOData(address miner, uint256 idx) public constant returns (uint256 ICOFund, uint256 ICOShare, uint256 lastClaimIndex) { require(idx <= cycleCount); ICOFund = minerICOPerCycle[miner][idx]; if(idx < cycleCount) { ICOShare = (honeyPotPerCycle[idx] * minerICOPerCycle[miner][idx]) / globalICOPerCycle[idx]; } else { ICOShare = (honeyPotAmount / 10) * minerICOPerCycle[miner][idx] / globalICOPerCycle[idx]; } lastClaimIndex = miners[miner].lastPotClaimIndex; } function GetMinerICOData(address miner, uint256 idx) public constant returns (uint256 ICOFund, uint256 ICOShare, uint256 lastClaimIndex) { require(idx <= cycleCount); ICOFund = minerICOPerCycle[miner][idx]; if(idx < cycleCount) { ICOShare = (honeyPotPerCycle[idx] * minerICOPerCycle[miner][idx]) / globalICOPerCycle[idx]; } else { ICOShare = (honeyPotAmount / 10) * minerICOPerCycle[miner][idx] / globalICOPerCycle[idx]; } lastClaimIndex = miners[miner].lastPotClaimIndex; } function GetMinerUnclaimedICOShare(address miner) public constant returns (uint256 unclaimedPot) { MinerData storage m = miners[miner]; require(m.lastUpdateTime != 0); require(m.lastPotClaimIndex < cycleCount); uint256 i = m.lastPotClaimIndex; uint256 limit = cycleCount; limit = i + 30; unclaimedPot = 0; for(; i < cycleCount; ++i) { if(minerICOPerCycle[miner][i] > 0) unclaimedPot += (honeyPotPerCycle[i] * minerICOPerCycle[miner][i]) / globalICOPerCycle[i]; } } function GetMinerUnclaimedICOShare(address miner) public constant returns (uint256 unclaimedPot) { MinerData storage m = miners[miner]; require(m.lastUpdateTime != 0); require(m.lastPotClaimIndex < cycleCount); uint256 i = m.lastPotClaimIndex; uint256 limit = cycleCount; limit = i + 30; unclaimedPot = 0; for(; i < cycleCount; ++i) { if(minerICOPerCycle[miner][i] > 0) unclaimedPot += (honeyPotPerCycle[i] * minerICOPerCycle[miner][i]) / globalICOPerCycle[i]; } } function StartNewMiner() external { require(miners[msg.sender].lastUpdateTime == 0); miners[msg.sender].lastUpdateTime = block.timestamp; miners[msg.sender].money = 0; miners[msg.sender].spaces[0] = 1; miners[msg.sender].unclaimedPot = 0; miners[msg.sender].lastPotClaimIndex = cycleCount; pvpMap[msg.sender].immunityTime = block.timestamp + 14400; pvpMap[msg.sender].exhaustTime = block.timestamp; indexes[topindex] = msg.sender; ++topindex; } function UpgradeSpace(uint8 spaceIdx, uint16 count) external { require(spaceIdx < NUMBER_OF_RIG_TYPES); require(count > 0); require(count <= 999); require(spaceData[spaceIdx].priceInETH == 0); MinerData storage m = miners[msg.sender]; require(spaceData[spaceIdx].limit >= (m.spaces[spaceIdx] + count)); UpdateMoney(); uint256 price = NumericSequence.sumOfN(spaceData[spaceIdx].basePrice, spaceData[spaceIdx].pricePerLevel, m.spaces[spaceIdx], count); require(m.money >= price); m.spaces[spaceIdx] = m.spaces[spaceIdx] + count; if(m.spaces[spaceIdx] > spaceData[spaceIdx].limit) m.spaces[spaceIdx] = spaceData[spaceIdx].limit; m.money -= price; } function UpgradeSpaceETH(uint8 spaceIdx, uint256 count) external payable { require(spaceIdx < NUMBER_OF_RIG_TYPES); require(count > 0); require(count <= 999); require(spaceData[spaceIdx].priceInETH > 0); MinerData storage m = miners[msg.sender]; require(spaceData[spaceIdx].limit >= (m.spaces[spaceIdx] + count)); uint256 price = (spaceData[spaceIdx].priceInETH).mul(count); uint256 priceCoin = NumericSequence.sumOfN(spaceData[spaceIdx].basePrice, spaceData[spaceIdx].pricePerLevel, m.spaces[spaceIdx], count); UpdateMoney(); require(msg.value >= price); require(m.money >= priceCoin); BuyHandler(msg.value); m.spaces[spaceIdx] = m.spaces[spaceIdx] + count; if(m.spaces[spaceIdx] > spaceData[spaceIdx].limit) m.spaces[spaceIdx] = spaceData[spaceIdx].limit; m.money -= priceCoin; } function UpdateMoney() private { require(miners[msg.sender].lastUpdateTime != 0); require(block.timestamp >= miners[msg.sender].lastUpdateTime); MinerData storage m = miners[msg.sender]; uint256 diff = block.timestamp - m.lastUpdateTime; uint256 revenue = GetProductionPerSecond(msg.sender); m.lastUpdateTime = block.timestamp; if(revenue > 0) { revenue *= diff; m.money += revenue; } } function UpdateMoney() private { require(miners[msg.sender].lastUpdateTime != 0); require(block.timestamp >= miners[msg.sender].lastUpdateTime); MinerData storage m = miners[msg.sender]; uint256 diff = block.timestamp - m.lastUpdateTime; uint256 revenue = GetProductionPerSecond(msg.sender); m.lastUpdateTime = block.timestamp; if(revenue > 0) { revenue *= diff; m.money += revenue; } } function UpdateMoneyAt(address addr) private { require(miners[addr].lastUpdateTime != 0); require(block.timestamp >= miners[addr].lastUpdateTime); MinerData storage m = miners[addr]; uint256 diff = block.timestamp - m.lastUpdateTime; uint256 revenue = GetProductionPerSecond(addr); m.lastUpdateTime = block.timestamp; if(revenue > 0) { revenue *= diff; m.money += revenue; } } function UpdateMoneyAt(address addr) private { require(miners[addr].lastUpdateTime != 0); require(block.timestamp >= miners[addr].lastUpdateTime); MinerData storage m = miners[addr]; uint256 diff = block.timestamp - m.lastUpdateTime; uint256 revenue = GetProductionPerSecond(addr); m.lastUpdateTime = block.timestamp; if(revenue > 0) { revenue *= diff; m.money += revenue; } } function BuyUpgrade(uint256 idx) external payable { require(idx < NUMBER_OF_UPGRADES); require(msg.value >= boostData[idx].priceInWEI); require(miners[msg.sender].hasUpgrade[idx] == 0); require(miners[msg.sender].lastUpdateTime != 0); BuyHandler(msg.value); UpdateMoney(); miners[msg.sender].hasUpgrade[idx] = 1; miners[msg.sender].premamentMineBonusPct += boostData[idx].percentBonus; } function BuyBooster() external payable { require(msg.value >= nextBoosterPrice); require(miners[msg.sender].lastUpdateTime != 0); for(uint i = 0; i < NUMBER_OF_BOOSTERS; ++i) if(boosterHolders[i] == msg.sender) revert(); address beneficiary = boosterHolders[boosterIndex]; MinerData storage m = miners[beneficiary]; m.unclaimedPot += (msg.value * 9403) / 10000; honeyPotAmount += (msg.value * 597) / 20000; devFund += (msg.value * 597) / 20000; nextBoosterPrice += nextBoosterPrice / 20; UpdateMoney(); UpdateMoneyAt(beneficiary); boosterHolders[boosterIndex] = msg.sender; boosterIndex += 1; if(boosterIndex >= 5) boosterIndex = 0; } function BuyTroop(uint256 idx, uint256 count) external payable { require(idx < NUMBER_OF_TROOPS); require(count > 0); require(count <= 1000); PVPData storage pvp = pvpMap[msg.sender]; MinerData storage m = miners[msg.sender]; uint256 owned = pvp.troops[idx]; uint256 priceGold = NumericSequence.sumOfN(troopData[idx].priceGold, troopData[idx].priceGold / 100, owned, count); uint256 priceETH = (troopData[idx].priceETH).mul(count); UpdateMoney(); require(m.money >= priceGold); require(msg.value >= priceETH); if(priceGold > 0) m.money -= priceGold; if(msg.value > 0) BuyHandler(msg.value); pvp.troops[idx] += count; } function Attack(address defenderAddr) external { require(msg.sender != defenderAddr); require(miners[msg.sender].lastUpdateTime != 0); require(miners[defenderAddr].lastUpdateTime != 0); PVPData storage attacker = pvpMap[msg.sender]; PVPData storage defender = pvpMap[defenderAddr]; uint i = 0; uint256 count = 0; require(block.timestamp > attacker.exhaustTime); require(block.timestamp > defender.immunityTime); if(attacker.immunityTime > block.timestamp) attacker.immunityTime = block.timestamp - 1; attacker.exhaustTime = block.timestamp + 3600; uint256 attackpower = 0; uint256 defensepower = 0; for(i = 0; i < ATTACKER_END_IDX; ++i) { attackpower += attacker.troops[i] * troopData[i].attackPower; defensepower += defender.troops[i + DEFENDER_START_IDX] * troopData[i + DEFENDER_START_IDX].defensePower; } if(attackpower > defensepower) { if(defender.immunityTime < block.timestamp + 14400) defender.immunityTime = block.timestamp + 14400; UpdateMoneyAt(defenderAddr); MinerData storage m = miners[defenderAddr]; MinerData storage m2 = miners[msg.sender]; uint256 moneyStolen = m.money / 2; for(i = DEFENDER_START_IDX; i < DEFENDER_END_IDX; ++i) { defender.troops[i] = defender.troops[i]/2; } for(i = ATTACKER_START_IDX; i < ATTACKER_END_IDX; ++i) { if(troopData[i].attackPower > 0) { count = attacker.troops[i]; if((count * troopData[i].attackPower) > defensepower) { count = count * defensepower / attackpower / 2; } else { count = count/2; } attacker.troops[i] = SafeMath.sub(attacker.troops[i],count); defensepower -= count * troopData[i].attackPower; } } m.money -= moneyStolen; m2.money += moneyStolen; } else { for(i = ATTACKER_START_IDX; i < ATTACKER_END_IDX; ++i) { attacker.troops[i] = attacker.troops[i] / 2; } for(i = DEFENDER_START_IDX; i < DEFENDER_END_IDX; ++i) { if(troopData[i].defensePower > 0) { count = defender.troops[i]; if((count * troopData[i].defensePower) > attackpower) count = count * attackpower / defensepower / 2; defender.troops[i] -= count; attackpower -= count * troopData[i].defensePower; } } } } function Attack(address defenderAddr) external { require(msg.sender != defenderAddr); require(miners[msg.sender].lastUpdateTime != 0); require(miners[defenderAddr].lastUpdateTime != 0); PVPData storage attacker = pvpMap[msg.sender]; PVPData storage defender = pvpMap[defenderAddr]; uint i = 0; uint256 count = 0; require(block.timestamp > attacker.exhaustTime); require(block.timestamp > defender.immunityTime); if(attacker.immunityTime > block.timestamp) attacker.immunityTime = block.timestamp - 1; attacker.exhaustTime = block.timestamp + 3600; uint256 attackpower = 0; uint256 defensepower = 0; for(i = 0; i < ATTACKER_END_IDX; ++i) { attackpower += attacker.troops[i] * troopData[i].attackPower; defensepower += defender.troops[i + DEFENDER_START_IDX] * troopData[i + DEFENDER_START_IDX].defensePower; } if(attackpower > defensepower) { if(defender.immunityTime < block.timestamp + 14400) defender.immunityTime = block.timestamp + 14400; UpdateMoneyAt(defenderAddr); MinerData storage m = miners[defenderAddr]; MinerData storage m2 = miners[msg.sender]; uint256 moneyStolen = m.money / 2; for(i = DEFENDER_START_IDX; i < DEFENDER_END_IDX; ++i) { defender.troops[i] = defender.troops[i]/2; } for(i = ATTACKER_START_IDX; i < ATTACKER_END_IDX; ++i) { if(troopData[i].attackPower > 0) { count = attacker.troops[i]; if((count * troopData[i].attackPower) > defensepower) { count = count * defensepower / attackpower / 2; } else { count = count/2; } attacker.troops[i] = SafeMath.sub(attacker.troops[i],count); defensepower -= count * troopData[i].attackPower; } } m.money -= moneyStolen; m2.money += moneyStolen; } else { for(i = ATTACKER_START_IDX; i < ATTACKER_END_IDX; ++i) { attacker.troops[i] = attacker.troops[i] / 2; } for(i = DEFENDER_START_IDX; i < DEFENDER_END_IDX; ++i) { if(troopData[i].defensePower > 0) { count = defender.troops[i]; if((count * troopData[i].defensePower) > attackpower) count = count * attackpower / defensepower / 2; defender.troops[i] -= count; attackpower -= count * troopData[i].defensePower; } } } } function Attack(address defenderAddr) external { require(msg.sender != defenderAddr); require(miners[msg.sender].lastUpdateTime != 0); require(miners[defenderAddr].lastUpdateTime != 0); PVPData storage attacker = pvpMap[msg.sender]; PVPData storage defender = pvpMap[defenderAddr]; uint i = 0; uint256 count = 0; require(block.timestamp > attacker.exhaustTime); require(block.timestamp > defender.immunityTime); if(attacker.immunityTime > block.timestamp) attacker.immunityTime = block.timestamp - 1; attacker.exhaustTime = block.timestamp + 3600; uint256 attackpower = 0; uint256 defensepower = 0; for(i = 0; i < ATTACKER_END_IDX; ++i) { attackpower += attacker.troops[i] * troopData[i].attackPower; defensepower += defender.troops[i + DEFENDER_START_IDX] * troopData[i + DEFENDER_START_IDX].defensePower; } if(attackpower > defensepower) { if(defender.immunityTime < block.timestamp + 14400) defender.immunityTime = block.timestamp + 14400; UpdateMoneyAt(defenderAddr); MinerData storage m = miners[defenderAddr]; MinerData storage m2 = miners[msg.sender]; uint256 moneyStolen = m.money / 2; for(i = DEFENDER_START_IDX; i < DEFENDER_END_IDX; ++i) { defender.troops[i] = defender.troops[i]/2; } for(i = ATTACKER_START_IDX; i < ATTACKER_END_IDX; ++i) { if(troopData[i].attackPower > 0) { count = attacker.troops[i]; if((count * troopData[i].attackPower) > defensepower) { count = count * defensepower / attackpower / 2; } else { count = count/2; } attacker.troops[i] = SafeMath.sub(attacker.troops[i],count); defensepower -= count * troopData[i].attackPower; } } m.money -= moneyStolen; m2.money += moneyStolen; } else { for(i = ATTACKER_START_IDX; i < ATTACKER_END_IDX; ++i) { attacker.troops[i] = attacker.troops[i] / 2; } for(i = DEFENDER_START_IDX; i < DEFENDER_END_IDX; ++i) { if(troopData[i].defensePower > 0) { count = defender.troops[i]; if((count * troopData[i].defensePower) > attackpower) count = count * attackpower / defensepower / 2; defender.troops[i] -= count; attackpower -= count * troopData[i].defensePower; } } } } function Attack(address defenderAddr) external { require(msg.sender != defenderAddr); require(miners[msg.sender].lastUpdateTime != 0); require(miners[defenderAddr].lastUpdateTime != 0); PVPData storage attacker = pvpMap[msg.sender]; PVPData storage defender = pvpMap[defenderAddr]; uint i = 0; uint256 count = 0; require(block.timestamp > attacker.exhaustTime); require(block.timestamp > defender.immunityTime); if(attacker.immunityTime > block.timestamp) attacker.immunityTime = block.timestamp - 1; attacker.exhaustTime = block.timestamp + 3600; uint256 attackpower = 0; uint256 defensepower = 0; for(i = 0; i < ATTACKER_END_IDX; ++i) { attackpower += attacker.troops[i] * troopData[i].attackPower; defensepower += defender.troops[i + DEFENDER_START_IDX] * troopData[i + DEFENDER_START_IDX].defensePower; } if(attackpower > defensepower) { if(defender.immunityTime < block.timestamp + 14400) defender.immunityTime = block.timestamp + 14400; UpdateMoneyAt(defenderAddr); MinerData storage m = miners[defenderAddr]; MinerData storage m2 = miners[msg.sender]; uint256 moneyStolen = m.money / 2; for(i = DEFENDER_START_IDX; i < DEFENDER_END_IDX; ++i) { defender.troops[i] = defender.troops[i]/2; } for(i = ATTACKER_START_IDX; i < ATTACKER_END_IDX; ++i) { if(troopData[i].attackPower > 0) { count = attacker.troops[i]; if((count * troopData[i].attackPower) > defensepower) { count = count * defensepower / attackpower / 2; } else { count = count/2; } attacker.troops[i] = SafeMath.sub(attacker.troops[i],count); defensepower -= count * troopData[i].attackPower; } } m.money -= moneyStolen; m2.money += moneyStolen; } else { for(i = ATTACKER_START_IDX; i < ATTACKER_END_IDX; ++i) { attacker.troops[i] = attacker.troops[i] / 2; } for(i = DEFENDER_START_IDX; i < DEFENDER_END_IDX; ++i) { if(troopData[i].defensePower > 0) { count = defender.troops[i]; if((count * troopData[i].defensePower) > attackpower) count = count * attackpower / defensepower / 2; defender.troops[i] -= count; attackpower -= count * troopData[i].defensePower; } } } } function Attack(address defenderAddr) external { require(msg.sender != defenderAddr); require(miners[msg.sender].lastUpdateTime != 0); require(miners[defenderAddr].lastUpdateTime != 0); PVPData storage attacker = pvpMap[msg.sender]; PVPData storage defender = pvpMap[defenderAddr]; uint i = 0; uint256 count = 0; require(block.timestamp > attacker.exhaustTime); require(block.timestamp > defender.immunityTime); if(attacker.immunityTime > block.timestamp) attacker.immunityTime = block.timestamp - 1; attacker.exhaustTime = block.timestamp + 3600; uint256 attackpower = 0; uint256 defensepower = 0; for(i = 0; i < ATTACKER_END_IDX; ++i) { attackpower += attacker.troops[i] * troopData[i].attackPower; defensepower += defender.troops[i + DEFENDER_START_IDX] * troopData[i + DEFENDER_START_IDX].defensePower; } if(attackpower > defensepower) { if(defender.immunityTime < block.timestamp + 14400) defender.immunityTime = block.timestamp + 14400; UpdateMoneyAt(defenderAddr); MinerData storage m = miners[defenderAddr]; MinerData storage m2 = miners[msg.sender]; uint256 moneyStolen = m.money / 2; for(i = DEFENDER_START_IDX; i < DEFENDER_END_IDX; ++i) { defender.troops[i] = defender.troops[i]/2; } for(i = ATTACKER_START_IDX; i < ATTACKER_END_IDX; ++i) { if(troopData[i].attackPower > 0) { count = attacker.troops[i]; if((count * troopData[i].attackPower) > defensepower) { count = count * defensepower / attackpower / 2; } else { count = count/2; } attacker.troops[i] = SafeMath.sub(attacker.troops[i],count); defensepower -= count * troopData[i].attackPower; } } m.money -= moneyStolen; m2.money += moneyStolen; } else { for(i = ATTACKER_START_IDX; i < ATTACKER_END_IDX; ++i) { attacker.troops[i] = attacker.troops[i] / 2; } for(i = DEFENDER_START_IDX; i < DEFENDER_END_IDX; ++i) { if(troopData[i].defensePower > 0) { count = defender.troops[i]; if((count * troopData[i].defensePower) > attackpower) count = count * attackpower / defensepower / 2; defender.troops[i] -= count; attackpower -= count * troopData[i].defensePower; } } } } function Attack(address defenderAddr) external { require(msg.sender != defenderAddr); require(miners[msg.sender].lastUpdateTime != 0); require(miners[defenderAddr].lastUpdateTime != 0); PVPData storage attacker = pvpMap[msg.sender]; PVPData storage defender = pvpMap[defenderAddr]; uint i = 0; uint256 count = 0; require(block.timestamp > attacker.exhaustTime); require(block.timestamp > defender.immunityTime); if(attacker.immunityTime > block.timestamp) attacker.immunityTime = block.timestamp - 1; attacker.exhaustTime = block.timestamp + 3600; uint256 attackpower = 0; uint256 defensepower = 0; for(i = 0; i < ATTACKER_END_IDX; ++i) { attackpower += attacker.troops[i] * troopData[i].attackPower; defensepower += defender.troops[i + DEFENDER_START_IDX] * troopData[i + DEFENDER_START_IDX].defensePower; } if(attackpower > defensepower) { if(defender.immunityTime < block.timestamp + 14400) defender.immunityTime = block.timestamp + 14400; UpdateMoneyAt(defenderAddr); MinerData storage m = miners[defenderAddr]; MinerData storage m2 = miners[msg.sender]; uint256 moneyStolen = m.money / 2; for(i = DEFENDER_START_IDX; i < DEFENDER_END_IDX; ++i) { defender.troops[i] = defender.troops[i]/2; } for(i = ATTACKER_START_IDX; i < ATTACKER_END_IDX; ++i) { if(troopData[i].attackPower > 0) { count = attacker.troops[i]; if((count * troopData[i].attackPower) > defensepower) { count = count * defensepower / attackpower / 2; } else { count = count/2; } attacker.troops[i] = SafeMath.sub(attacker.troops[i],count); defensepower -= count * troopData[i].attackPower; } } m.money -= moneyStolen; m2.money += moneyStolen; } else { for(i = ATTACKER_START_IDX; i < ATTACKER_END_IDX; ++i) { attacker.troops[i] = attacker.troops[i] / 2; } for(i = DEFENDER_START_IDX; i < DEFENDER_END_IDX; ++i) { if(troopData[i].defensePower > 0) { count = defender.troops[i]; if((count * troopData[i].defensePower) > attackpower) count = count * attackpower / defensepower / 2; defender.troops[i] -= count; attackpower -= count * troopData[i].defensePower; } } } } function Attack(address defenderAddr) external { require(msg.sender != defenderAddr); require(miners[msg.sender].lastUpdateTime != 0); require(miners[defenderAddr].lastUpdateTime != 0); PVPData storage attacker = pvpMap[msg.sender]; PVPData storage defender = pvpMap[defenderAddr]; uint i = 0; uint256 count = 0; require(block.timestamp > attacker.exhaustTime); require(block.timestamp > defender.immunityTime); if(attacker.immunityTime > block.timestamp) attacker.immunityTime = block.timestamp - 1; attacker.exhaustTime = block.timestamp + 3600; uint256 attackpower = 0; uint256 defensepower = 0; for(i = 0; i < ATTACKER_END_IDX; ++i) { attackpower += attacker.troops[i] * troopData[i].attackPower; defensepower += defender.troops[i + DEFENDER_START_IDX] * troopData[i + DEFENDER_START_IDX].defensePower; } if(attackpower > defensepower) { if(defender.immunityTime < block.timestamp + 14400) defender.immunityTime = block.timestamp + 14400; UpdateMoneyAt(defenderAddr); MinerData storage m = miners[defenderAddr]; MinerData storage m2 = miners[msg.sender]; uint256 moneyStolen = m.money / 2; for(i = DEFENDER_START_IDX; i < DEFENDER_END_IDX; ++i) { defender.troops[i] = defender.troops[i]/2; } for(i = ATTACKER_START_IDX; i < ATTACKER_END_IDX; ++i) { if(troopData[i].attackPower > 0) { count = attacker.troops[i]; if((count * troopData[i].attackPower) > defensepower) { count = count * defensepower / attackpower / 2; } else { count = count/2; } attacker.troops[i] = SafeMath.sub(attacker.troops[i],count); defensepower -= count * troopData[i].attackPower; } } m.money -= moneyStolen; m2.money += moneyStolen; } else { for(i = ATTACKER_START_IDX; i < ATTACKER_END_IDX; ++i) { attacker.troops[i] = attacker.troops[i] / 2; } for(i = DEFENDER_START_IDX; i < DEFENDER_END_IDX; ++i) { if(troopData[i].defensePower > 0) { count = defender.troops[i]; if((count * troopData[i].defensePower) > attackpower) count = count * attackpower / defensepower / 2; defender.troops[i] -= count; attackpower -= count * troopData[i].defensePower; } } } } function Attack(address defenderAddr) external { require(msg.sender != defenderAddr); require(miners[msg.sender].lastUpdateTime != 0); require(miners[defenderAddr].lastUpdateTime != 0); PVPData storage attacker = pvpMap[msg.sender]; PVPData storage defender = pvpMap[defenderAddr]; uint i = 0; uint256 count = 0; require(block.timestamp > attacker.exhaustTime); require(block.timestamp > defender.immunityTime); if(attacker.immunityTime > block.timestamp) attacker.immunityTime = block.timestamp - 1; attacker.exhaustTime = block.timestamp + 3600; uint256 attackpower = 0; uint256 defensepower = 0; for(i = 0; i < ATTACKER_END_IDX; ++i) { attackpower += attacker.troops[i] * troopData[i].attackPower; defensepower += defender.troops[i + DEFENDER_START_IDX] * troopData[i + DEFENDER_START_IDX].defensePower; } if(attackpower > defensepower) { if(defender.immunityTime < block.timestamp + 14400) defender.immunityTime = block.timestamp + 14400; UpdateMoneyAt(defenderAddr); MinerData storage m = miners[defenderAddr]; MinerData storage m2 = miners[msg.sender]; uint256 moneyStolen = m.money / 2; for(i = DEFENDER_START_IDX; i < DEFENDER_END_IDX; ++i) { defender.troops[i] = defender.troops[i]/2; } for(i = ATTACKER_START_IDX; i < ATTACKER_END_IDX; ++i) { if(troopData[i].attackPower > 0) { count = attacker.troops[i]; if((count * troopData[i].attackPower) > defensepower) { count = count * defensepower / attackpower / 2; } else { count = count/2; } attacker.troops[i] = SafeMath.sub(attacker.troops[i],count); defensepower -= count * troopData[i].attackPower; } } m.money -= moneyStolen; m2.money += moneyStolen; } else { for(i = ATTACKER_START_IDX; i < ATTACKER_END_IDX; ++i) { attacker.troops[i] = attacker.troops[i] / 2; } for(i = DEFENDER_START_IDX; i < DEFENDER_END_IDX; ++i) { if(troopData[i].defensePower > 0) { count = defender.troops[i]; if((count * troopData[i].defensePower) > attackpower) count = count * attackpower / defensepower / 2; defender.troops[i] -= count; attackpower -= count * troopData[i].defensePower; } } } } function Attack(address defenderAddr) external { require(msg.sender != defenderAddr); require(miners[msg.sender].lastUpdateTime != 0); require(miners[defenderAddr].lastUpdateTime != 0); PVPData storage attacker = pvpMap[msg.sender]; PVPData storage defender = pvpMap[defenderAddr]; uint i = 0; uint256 count = 0; require(block.timestamp > attacker.exhaustTime); require(block.timestamp > defender.immunityTime); if(attacker.immunityTime > block.timestamp) attacker.immunityTime = block.timestamp - 1; attacker.exhaustTime = block.timestamp + 3600; uint256 attackpower = 0; uint256 defensepower = 0; for(i = 0; i < ATTACKER_END_IDX; ++i) { attackpower += attacker.troops[i] * troopData[i].attackPower; defensepower += defender.troops[i + DEFENDER_START_IDX] * troopData[i + DEFENDER_START_IDX].defensePower; } if(attackpower > defensepower) { if(defender.immunityTime < block.timestamp + 14400) defender.immunityTime = block.timestamp + 14400; UpdateMoneyAt(defenderAddr); MinerData storage m = miners[defenderAddr]; MinerData storage m2 = miners[msg.sender]; uint256 moneyStolen = m.money / 2; for(i = DEFENDER_START_IDX; i < DEFENDER_END_IDX; ++i) { defender.troops[i] = defender.troops[i]/2; } for(i = ATTACKER_START_IDX; i < ATTACKER_END_IDX; ++i) { if(troopData[i].attackPower > 0) { count = attacker.troops[i]; if((count * troopData[i].attackPower) > defensepower) { count = count * defensepower / attackpower / 2; } else { count = count/2; } attacker.troops[i] = SafeMath.sub(attacker.troops[i],count); defensepower -= count * troopData[i].attackPower; } } m.money -= moneyStolen; m2.money += moneyStolen; } else { for(i = ATTACKER_START_IDX; i < ATTACKER_END_IDX; ++i) { attacker.troops[i] = attacker.troops[i] / 2; } for(i = DEFENDER_START_IDX; i < DEFENDER_END_IDX; ++i) { if(troopData[i].defensePower > 0) { count = defender.troops[i]; if((count * troopData[i].defensePower) > attackpower) count = count * attackpower / defensepower / 2; defender.troops[i] -= count; attackpower -= count * troopData[i].defensePower; } } } } function Attack(address defenderAddr) external { require(msg.sender != defenderAddr); require(miners[msg.sender].lastUpdateTime != 0); require(miners[defenderAddr].lastUpdateTime != 0); PVPData storage attacker = pvpMap[msg.sender]; PVPData storage defender = pvpMap[defenderAddr]; uint i = 0; uint256 count = 0; require(block.timestamp > attacker.exhaustTime); require(block.timestamp > defender.immunityTime); if(attacker.immunityTime > block.timestamp) attacker.immunityTime = block.timestamp - 1; attacker.exhaustTime = block.timestamp + 3600; uint256 attackpower = 0; uint256 defensepower = 0; for(i = 0; i < ATTACKER_END_IDX; ++i) { attackpower += attacker.troops[i] * troopData[i].attackPower; defensepower += defender.troops[i + DEFENDER_START_IDX] * troopData[i + DEFENDER_START_IDX].defensePower; } if(attackpower > defensepower) { if(defender.immunityTime < block.timestamp + 14400) defender.immunityTime = block.timestamp + 14400; UpdateMoneyAt(defenderAddr); MinerData storage m = miners[defenderAddr]; MinerData storage m2 = miners[msg.sender]; uint256 moneyStolen = m.money / 2; for(i = DEFENDER_START_IDX; i < DEFENDER_END_IDX; ++i) { defender.troops[i] = defender.troops[i]/2; } for(i = ATTACKER_START_IDX; i < ATTACKER_END_IDX; ++i) { if(troopData[i].attackPower > 0) { count = attacker.troops[i]; if((count * troopData[i].attackPower) > defensepower) { count = count * defensepower / attackpower / 2; } else { count = count/2; } attacker.troops[i] = SafeMath.sub(attacker.troops[i],count); defensepower -= count * troopData[i].attackPower; } } m.money -= moneyStolen; m2.money += moneyStolen; } else { for(i = ATTACKER_START_IDX; i < ATTACKER_END_IDX; ++i) { attacker.troops[i] = attacker.troops[i] / 2; } for(i = DEFENDER_START_IDX; i < DEFENDER_END_IDX; ++i) { if(troopData[i].defensePower > 0) { count = defender.troops[i]; if((count * troopData[i].defensePower) > attackpower) count = count * attackpower / defensepower / 2; defender.troops[i] -= count; attackpower -= count * troopData[i].defensePower; } } } } function Attack(address defenderAddr) external { require(msg.sender != defenderAddr); require(miners[msg.sender].lastUpdateTime != 0); require(miners[defenderAddr].lastUpdateTime != 0); PVPData storage attacker = pvpMap[msg.sender]; PVPData storage defender = pvpMap[defenderAddr]; uint i = 0; uint256 count = 0; require(block.timestamp > attacker.exhaustTime); require(block.timestamp > defender.immunityTime); if(attacker.immunityTime > block.timestamp) attacker.immunityTime = block.timestamp - 1; attacker.exhaustTime = block.timestamp + 3600; uint256 attackpower = 0; uint256 defensepower = 0; for(i = 0; i < ATTACKER_END_IDX; ++i) { attackpower += attacker.troops[i] * troopData[i].attackPower; defensepower += defender.troops[i + DEFENDER_START_IDX] * troopData[i + DEFENDER_START_IDX].defensePower; } if(attackpower > defensepower) { if(defender.immunityTime < block.timestamp + 14400) defender.immunityTime = block.timestamp + 14400; UpdateMoneyAt(defenderAddr); MinerData storage m = miners[defenderAddr]; MinerData storage m2 = miners[msg.sender]; uint256 moneyStolen = m.money / 2; for(i = DEFENDER_START_IDX; i < DEFENDER_END_IDX; ++i) { defender.troops[i] = defender.troops[i]/2; } for(i = ATTACKER_START_IDX; i < ATTACKER_END_IDX; ++i) { if(troopData[i].attackPower > 0) { count = attacker.troops[i]; if((count * troopData[i].attackPower) > defensepower) { count = count * defensepower / attackpower / 2; } else { count = count/2; } attacker.troops[i] = SafeMath.sub(attacker.troops[i],count); defensepower -= count * troopData[i].attackPower; } } m.money -= moneyStolen; m2.money += moneyStolen; } else { for(i = ATTACKER_START_IDX; i < ATTACKER_END_IDX; ++i) { attacker.troops[i] = attacker.troops[i] / 2; } for(i = DEFENDER_START_IDX; i < DEFENDER_END_IDX; ++i) { if(troopData[i].defensePower > 0) { count = defender.troops[i]; if((count * troopData[i].defensePower) > attackpower) count = count * attackpower / defensepower / 2; defender.troops[i] -= count; attackpower -= count * troopData[i].defensePower; } } } } function Attack(address defenderAddr) external { require(msg.sender != defenderAddr); require(miners[msg.sender].lastUpdateTime != 0); require(miners[defenderAddr].lastUpdateTime != 0); PVPData storage attacker = pvpMap[msg.sender]; PVPData storage defender = pvpMap[defenderAddr]; uint i = 0; uint256 count = 0; require(block.timestamp > attacker.exhaustTime); require(block.timestamp > defender.immunityTime); if(attacker.immunityTime > block.timestamp) attacker.immunityTime = block.timestamp - 1; attacker.exhaustTime = block.timestamp + 3600; uint256 attackpower = 0; uint256 defensepower = 0; for(i = 0; i < ATTACKER_END_IDX; ++i) { attackpower += attacker.troops[i] * troopData[i].attackPower; defensepower += defender.troops[i + DEFENDER_START_IDX] * troopData[i + DEFENDER_START_IDX].defensePower; } if(attackpower > defensepower) { if(defender.immunityTime < block.timestamp + 14400) defender.immunityTime = block.timestamp + 14400; UpdateMoneyAt(defenderAddr); MinerData storage m = miners[defenderAddr]; MinerData storage m2 = miners[msg.sender]; uint256 moneyStolen = m.money / 2; for(i = DEFENDER_START_IDX; i < DEFENDER_END_IDX; ++i) { defender.troops[i] = defender.troops[i]/2; } for(i = ATTACKER_START_IDX; i < ATTACKER_END_IDX; ++i) { if(troopData[i].attackPower > 0) { count = attacker.troops[i]; if((count * troopData[i].attackPower) > defensepower) { count = count * defensepower / attackpower / 2; } else { count = count/2; } attacker.troops[i] = SafeMath.sub(attacker.troops[i],count); defensepower -= count * troopData[i].attackPower; } } m.money -= moneyStolen; m2.money += moneyStolen; } else { for(i = ATTACKER_START_IDX; i < ATTACKER_END_IDX; ++i) { attacker.troops[i] = attacker.troops[i] / 2; } for(i = DEFENDER_START_IDX; i < DEFENDER_END_IDX; ++i) { if(troopData[i].defensePower > 0) { count = defender.troops[i]; if((count * troopData[i].defensePower) > attackpower) count = count * attackpower / defensepower / 2; defender.troops[i] -= count; attackpower -= count * troopData[i].defensePower; } } } } function ReleaseICO() external { require(miners[msg.sender].lastUpdateTime != 0); require(nextPotDistributionTime <= block.timestamp); require(honeyPotAmount > 0); require(globalICOPerCycle[cycleCount] > 0); nextPotDistributionTime = block.timestamp + 86400; honeyPotAmount -= honeyPotAmount / 10; honeyPotPerCycle.push(0); globalICOPerCycle.push(0); cycleCount = cycleCount + 1; MinerData storage jakpotWinner = miners[msg.sender]; jakpotWinner.unclaimedPot += jackPot; jackPot = 0; } function FundICO(uint amount) external { require(miners[msg.sender].lastUpdateTime != 0); require(amount > 0); MinerData storage m = miners[msg.sender]; UpdateMoney(); require(m.money >= amount); m.money = (m.money).sub(amount); globalICOPerCycle[cycleCount] = globalICOPerCycle[cycleCount].add(uint(amount)); minerICOPerCycle[msg.sender][cycleCount] = minerICOPerCycle[msg.sender][cycleCount].add(uint(amount)); } function WithdrawICOEarnings() external { MinerData storage m = miners[msg.sender]; require(miners[msg.sender].lastUpdateTime != 0); require(miners[msg.sender].lastPotClaimIndex < cycleCount); uint256 i = m.lastPotClaimIndex; uint256 limit = cycleCount; limit = i + 30; m.lastPotClaimIndex = limit; for(; i < cycleCount; ++i) { if(minerICOPerCycle[msg.sender][i] > 0) m.unclaimedPot += (honeyPotPerCycle[i] * minerICOPerCycle[msg.sender][i]) / globalICOPerCycle[i]; } } function WithdrawICOEarnings() external { MinerData storage m = miners[msg.sender]; require(miners[msg.sender].lastUpdateTime != 0); require(miners[msg.sender].lastPotClaimIndex < cycleCount); uint256 i = m.lastPotClaimIndex; uint256 limit = cycleCount; limit = i + 30; m.lastPotClaimIndex = limit; for(; i < cycleCount; ++i) { if(minerICOPerCycle[msg.sender][i] > 0) m.unclaimedPot += (honeyPotPerCycle[i] * minerICOPerCycle[msg.sender][i]) / globalICOPerCycle[i]; } } function BuyHandler(uint amount) private { honeyPotAmount += (amount * honeyPotSharePct) / 100; jackPot += amount / 100; devFund += (amount * (100-(honeyPotSharePct+1))) / 100; } function WithdrawPotShare() public { MinerData storage m = miners[msg.sender]; require(m.unclaimedPot > 0); require(m.lastUpdateTime != 0); uint256 amntToSend = m.unclaimedPot; m.unclaimedPot = 0; if(msg.sender.send(amntToSend)) { m.unclaimedPot = 0; } } function WithdrawPotShare() public { MinerData storage m = miners[msg.sender]; require(m.unclaimedPot > 0); require(m.lastUpdateTime != 0); uint256 amntToSend = m.unclaimedPot; m.unclaimedPot = 0; if(msg.sender.send(amntToSend)) { m.unclaimedPot = 0; } } function WithdrawDevFunds() public { require(msg.sender == owner); if(owner.send(devFund)) { devFund = 0; } } function WithdrawDevFunds() public { require(msg.sender == owner); if(owner.send(devFund)) { devFund = 0; } } function() public payable { devFund += msg.value; } }
13,695,317
[ 1, 5802, 17082, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 14059, 30634, 225, 288, 203, 565, 1450, 16980, 4021, 364, 2254, 31, 203, 565, 1450, 14060, 10477, 364, 2254, 31, 203, 203, 565, 1958, 5444, 264, 751, 203, 565, 288, 203, 3639, 2254, 28, 63, 23, 65, 377, 711, 10784, 31, 203, 3639, 2254, 5034, 1377, 15601, 31, 203, 3639, 2254, 5034, 1377, 1142, 1891, 950, 31, 203, 3639, 2254, 5034, 1377, 23020, 14773, 49, 558, 38, 22889, 52, 299, 31, 203, 3639, 2254, 5034, 1377, 6301, 80, 4581, 329, 18411, 31, 203, 3639, 2254, 5034, 1377, 1142, 18411, 9762, 1016, 31, 203, 565, 289, 203, 203, 565, 1958, 14059, 751, 203, 565, 288, 203, 3639, 2254, 5034, 1026, 5147, 31, 203, 3639, 2254, 5034, 1026, 1447, 31, 203, 3639, 2254, 5034, 6205, 2173, 2355, 31, 203, 3639, 2254, 5034, 6205, 382, 1584, 44, 31, 203, 3639, 2254, 5034, 1800, 31, 203, 565, 289, 203, 203, 565, 1958, 17980, 669, 751, 203, 565, 288, 203, 3639, 2254, 5034, 5551, 38, 22889, 31, 203, 3639, 2254, 5034, 6205, 382, 6950, 45, 31, 203, 565, 289, 203, 203, 565, 1958, 453, 26152, 751, 203, 565, 288, 203, 3639, 2254, 5034, 63, 26, 65, 23432, 4473, 31, 203, 3639, 2254, 5034, 565, 709, 81, 13352, 950, 31, 203, 3639, 2254, 5034, 565, 19575, 641, 950, 31, 203, 565, 289, 203, 203, 565, 1958, 399, 303, 556, 751, 203, 565, 288, 203, 3639, 2254, 5034, 13843, 13788, 31, 203, 3639, 2254, 5034, 1652, 3558, 13788, 31, 203, 3639, 2254, 5034, 6205, 43, 1673, 31, 203, 3639, 2254, 2 ]
pragma solidity ^0.4.24; contract FumoEvents { // fired whenever a player registers a name event onNewName ( uint256 indexed playerID, address indexed playerAddress, bytes32 indexed playerName, bool isNewPlayer, uint256 affiliateID, address affiliateAddress, bytes32 affiliateName, uint256 amountPaid, uint256 timeStamp ); // fired at end of buy or reload event onEndTx ( uint256 compressedData, uint256 compressedIDs, bytes32 playerName, address playerAddress, uint256 ethIn, uint256 keysBought, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 P3DAmount, uint256 genAmount, uint256 potAmount, uint256 airDropPot ); // fired whenever theres a withdraw event onWithdraw ( uint256 indexed playerID, address playerAddress, bytes32 playerName, uint256 ethOut, uint256 timeStamp ); // fired whenever a withdraw forces end round to be ran event onWithdrawAndDistribute ( address playerAddress, bytes32 playerName, uint256 ethOut, uint256 compressedData, uint256 compressedIDs, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 P3DAmount, uint256 genAmount ); // fired whenever a player tries a buy after round timer // hit zero, and causes end round to be ran. event onBuyAndDistribute ( address playerAddress, bytes32 playerName, uint256 ethIn, uint256 compressedData, uint256 compressedIDs, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 P3DAmount, uint256 genAmount ); // fired whenever a player tries a reload after round timer // hit zero, and causes end round to be ran. event onReLoadAndDistribute ( address playerAddress, bytes32 playerName, uint256 compressedData, uint256 compressedIDs, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 P3DAmount, uint256 genAmount ); // fired whenever an affiliate is paid event onAffiliatePayout ( uint256 indexed affiliateID, address affiliateAddress, bytes32 affiliateName, uint256 indexed roundID, uint256 indexed buyerID, uint256 amount, uint256 timeStamp ); // received pot swap deposit event onPotSwapDeposit ( uint256 roundID, uint256 amountAddedToPot ); } contract modularShort is FumoEvents {} contract Fumo is modularShort { using SafeMath for *; using NameFilter for string; using FumoKeysCalcLong for uint256; address community_addr = 0x3705B81d42199138E53FB0Ad57613ce309576077; PlayerBookInterface constant private PlayerBook = PlayerBookInterface(0xd085AcFC0FDaA418E03E8570EF9A4E25a0E14eCf); //============================================================================== // _ _ _ |`. _ _ _ |_ | _ _ . // (_(_)| |~|~|(_||_|| (_||_)|(/__\ . (game settings) //=================_|=========================================================== string constant public name = "Fumo token"; string constant public symbol = "FuMo"; uint256 private rndExtra_ = 0; // length of the very first ICO uint256 private rndGap_ = 0; // length of ICO phase, set to 1 year for EOS. uint256 constant private rndInit_ = 30 minutes; // round timer starts at this uint256 constant private rndInc_ = 10 seconds; // every full key purchased adds this much to the timer uint256 constant private rndMax_ = 1 hours; // max length a round timer can be // max length a round timer can be //============================================================================== // _| _ _|_ _ _ _ _|_ _ . // (_|(_| | (_| _\(/_ | |_||_) . (data used to store game info that changes) //=============================|================================================ uint256 public airDropPot_; // person who gets the airdrop wins part of this pot uint256 public airDropTracker_ = 0; // incremented each time a "qualified" tx occurs. used to determine winning air drop uint256 public rID_; // round id number / total rounds that have happened //**************** // PLAYER DATA //**************** mapping (address => uint256) public pIDxAddr_; // (addr => pID) returns player id by address mapping (bytes32 => uint256) public pIDxName_; // (name => pID) returns player id by name mapping (uint256 => Fumodatasets.Player) public plyr_; // (pID => data) player data mapping (uint256 => mapping (uint256 => Fumodatasets.PlayerRounds)) public plyrRnds_; // (pID => rID => data) player round data by player id & round id mapping (uint256 => mapping (bytes32 => bool)) public plyrNames_; // (pID => name => bool) list of names a player owns. (used so you can change your display name amongst any name you own) //**************** // ROUND DATA //**************** mapping (uint256 => Fumodatasets.Round) public round_; // (rID => data) round data mapping (uint256 => mapping(uint256 => uint256)) public rndTmEth_; // (rID => tID => data) eth in per team, by round id and team id //**************** // TEAM FEE DATA //**************** mapping (uint256 => Fumodatasets.TeamFee) public fees_; // (team => fees) fee distribution by team mapping (uint256 => Fumodatasets.PotSplit) public potSplit_; // (team => fees) pot split distribution by team //初始化 constructor() public { // Team allocation structures // 0 = whales // 1 = bears // 2 = sneks // 3 = bulls // Team allocation percentages // (Fumo, 0) + (Pot , Referrals, Community) // Referrals / Community rewards are mathematically designed to come from the winner's share of the pot. fees_[0] = Fumodatasets.TeamFee(30,0); //46% to pot, 20% to aff, 2% to com, 2% to air drop pot fees_[1] = Fumodatasets.TeamFee(43,0); //33% to pot, 20% to aff, 2% to com, 2% to air drop pot fees_[2] = Fumodatasets.TeamFee(56,0); //20% to pot, 20% to aff, 2% to com, 2% to air drop pot fees_[3] = Fumodatasets.TeamFee(43,8); //33% to pot, 20% to aff, 2% to com, 2% to air drop pot // how to split up the final pot based on which team was picked // (Fumo, 0) potSplit_[0] = Fumodatasets.PotSplit(15,0); //48% to winner, 25% to next round, 12% to com potSplit_[1] = Fumodatasets.PotSplit(20,0); //48% to winner, 20% to next round, 12% to com potSplit_[2] = Fumodatasets.PotSplit(25,0); //48% to winner, 15% to next round, 12% to com potSplit_[3] = Fumodatasets.PotSplit(30,0); //48% to winner, 10% to next round, 12% to com } /** * @dev used to make sure no one can interact with contract until it has * been activated. */ modifier isActivated() { require(activated_ == true, "its not ready yet. "); _; } /** * 判断地址是否正确 * @dev prevents contracts from interacting with fomo3d */ modifier isHuman() { address _addr = msg.sender; uint256 _codeLength; assembly {_codeLength := extcodesize(_addr)} require(_codeLength == 0, "sorry humans only"); _; } /** * * @dev sets boundaries for incoming tx */ modifier isWithinLimits(uint256 _eth) { require(_eth >= 1000000000, "pocket lint: not a valid currency"); require(_eth <= 100000000000000000000000, "no vitalik, no"); _; } //============================================================================== // _ |_ |. _ |` _ __|_. _ _ _ . // |_)|_||_)||(_ ~|~|_|| |(_ | |(_)| |_\ . (use these to interact with contract) //====|========================================================================= /** * @dev emergency buy uses last stored affiliate ID and team snek */ function() isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not Fumodatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // buy core buyCore(_pID, plyr_[_pID].laff, 2, _eventData_); } /** * @dev converts all incoming ethereum to keys. * -functionhash- 0x8f38f309 (using ID for affiliate) * -functionhash- 0x98a0871d (using address for affiliate) * -functionhash- 0xa65b37a1 (using name for affiliate) * @param _affCode the ID/address/name of the player who gets the affiliate fee * @param _team what team is the player playing for? */ function buyXid(uint256 _affCode, uint256 _team) isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not Fumodatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals // if no affiliate code was given or player tried to use their own, lolz if (_affCode == 0 || _affCode == _pID) { // use last stored affiliate code _affCode = plyr_[_pID].laff; // if affiliate code was given & its not the same as previously stored } else if (_affCode != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affCode; } // verify a valid team was selected _team = verifyTeam(_team); // buy core buyCore(_pID, _affCode, _team, _eventData_); } function buyXaddr(address _affCode, uint256 _team) isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not Fumodatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == address(0) || _affCode == msg.sender) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxAddr_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // verify a valid team was selected _team = verifyTeam(_team); // buy core buyCore(_pID, _affID, _team, _eventData_); } function buyXname(bytes32 _affCode, uint256 _team) isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not Fumodatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == '' || _affCode == plyr_[_pID].name) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxName_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // verify a valid team was selected _team = verifyTeam(_team); // buy core buyCore(_pID, _affID, _team, _eventData_); } /** * @dev essentially the same as buy, but instead of you sending ether * from your wallet, it uses your unwithdrawn earnings. * -functionhash- 0x349cdcac (using ID for affiliate) * -functionhash- 0x82bfc739 (using address for affiliate) * -functionhash- 0x079ce327 (using name for affiliate) * @param _affCode the ID/address/name of the player who gets the affiliate fee * @param _team what team is the player playing for? * @param _eth amount of earnings to use (remainder returned to gen vault) */ function reLoadXid(uint256 _affCode, uint256 _team, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { // set up our tx event data Fumodatasets.EventReturns memory _eventData_; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals // if no affiliate code was given or player tried to use their own, lolz if (_affCode == 0 || _affCode == _pID) { // use last stored affiliate code _affCode = plyr_[_pID].laff; // if affiliate code was given & its not the same as previously stored } else if (_affCode != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affCode; } // verify a valid team was selected _team = verifyTeam(_team); // reload core reLoadCore(_pID, _affCode, _team, _eth, _eventData_); } function reLoadXaddr(address _affCode, uint256 _team, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { // set up our tx event data Fumodatasets.EventReturns memory _eventData_; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == address(0) || _affCode == msg.sender) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxAddr_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // verify a valid team was selected _team = verifyTeam(_team); // reload core reLoadCore(_pID, _affID, _team, _eth, _eventData_); } function reLoadXname(bytes32 _affCode, uint256 _team, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { // set up our tx event data Fumodatasets.EventReturns memory _eventData_; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == '' || _affCode == plyr_[_pID].name) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxName_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // verify a valid team was selected _team = verifyTeam(_team); // reload core reLoadCore(_pID, _affID, _team, _eth, _eventData_); } /** * 提现 * @dev withdraws all of your earnings. * -functionhash- 0x3ccfd60b */ function withdraw() isActivated() isHuman() public { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // setup temp var for player eth uint256 _eth; // check to see if round has ended and no one has run round end yet if (_now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0) { // set up our tx event data Fumodatasets.EventReturns memory _eventData_; // end the round (distributes pot) round_[_rID].ended = true; _eventData_ = endRound(_eventData_); // get their earnings _eth = withdrawEarnings(_pID); // gib moni if (_eth > 0) plyr_[_pID].addr.transfer(_eth); // build event data _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; // fire withdraw and distribute event emit FumoEvents.onWithdrawAndDistribute ( msg.sender, plyr_[_pID].name, _eth, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.P3DAmount, _eventData_.genAmount ); // in any other situation } else { // get their earnings _eth = withdrawEarnings(_pID); // gib moni if (_eth > 0) plyr_[_pID].addr.transfer(_eth); // fire withdraw event emit FumoEvents.onWithdraw(_pID, msg.sender, plyr_[_pID].name, _eth, _now); } } /** * @dev use these to register names. they are just wrappers that will send the * registration requests to the PlayerBook contract. So registering here is the * same as registering there. UI will always display the last name you registered. * but you will still own all previously registered names to use as affiliate * links. * - must pay a registration fee. * - name must be unique * - names will be converted to lowercase * - name cannot start or end with a space * - cannot have more than 1 space in a row * - cannot be only numbers * - cannot start with 0x * - name must be at least 1 char * - max length of 32 characters long * - allowed characters: a-z, 0-9, and space * -functionhash- 0x921dec21 (using ID for affiliate) * -functionhash- 0x3ddd4698 (using address for affiliate) * -functionhash- 0x685ffd83 (using name for affiliate) * @param _nameString players desired name * @param _affCode affiliate ID, address, or name of who referred you * @param _all set to true if you want this to push your info to all games * (this might cost a lot of gas) */ function registerNameXID(string _nameString, uint256 _affCode, bool _all) isHuman() public payable { bytes32 _name = _nameString.nameFilter(); address _addr = msg.sender; uint256 _paid = msg.value; (bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXIDFromDapp.value(_paid)(_addr, _name, _affCode, _all); uint256 _pID = pIDxAddr_[_addr]; // fire event emit FumoEvents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); } function registerNameXaddr(string _nameString, address _affCode, bool _all) isHuman() public payable { bytes32 _name = _nameString.nameFilter(); address _addr = msg.sender; uint256 _paid = msg.value; (bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXaddrFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all); uint256 _pID = pIDxAddr_[_addr]; // fire event emit FumoEvents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); } function registerNameXname(string _nameString, bytes32 _affCode, bool _all) isHuman() public payable { bytes32 _name = _nameString.nameFilter(); address _addr = msg.sender; uint256 _paid = msg.value; (bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXnameFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all); uint256 _pID = pIDxAddr_[_addr]; // fire event emit FumoEvents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); } /** * 获取购买价格 * @dev return the price buyer will pay for next 1 individual key. * -functionhash- 0x018a25e8 * @return price for next key bought (in wei format) */ function getBuyPrice() public view returns(uint256) { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // are we in a round? if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) return ( (round_[_rID].keys.add(1000000000000000000)).ethRec(1000000000000000000) ); else // rounds over. need price for new round return ( 75000000000000 ); // init } /** * 获取剩余时间 * provider * -functionhash- 0xc7e284b8 * @return time left in seconds */ function getTimeLeft() public view returns(uint256) { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; if (_now < round_[_rID].end) if (_now > round_[_rID].strt + rndGap_) return( (round_[_rID].end).sub(_now) ); else return( (round_[_rID].strt + rndGap_).sub(_now) ); else return(0); } /** * @dev returns player earnings per vaults * -functionhash- 0x63066434 * @return winnings vault * @return general vault * @return affiliate vault */ function getPlayerVaults(uint256 _pID) public view returns(uint256 ,uint256, uint256) { // setup local rID uint256 _rID = rID_; // if round has ended. but round end has not been run (so contract has not distributed winnings) if (now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0) { // if player is winner if (round_[_rID].plyr == _pID) { return ( (plyr_[_pID].win).add( ((round_[_rID].pot).mul(48)) / 100 ), (plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ), plyr_[_pID].aff ); // if player is not the winner } else { return ( plyr_[_pID].win, (plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ), plyr_[_pID].aff ); } // if round is still going on, or round has ended and round end has been ran } else { return ( plyr_[_pID].win, (plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), plyr_[_pID].aff ); } } /** * solidity hates stack limits. this lets us avoid that hate */ function getPlayerVaultsHelper(uint256 _pID, uint256 _rID) private view returns(uint256) { return( ((((round_[_rID].mask).add(((((round_[_rID].pot).mul(potSplit_[round_[_rID].team].gen)) / 100).mul(1000000000000000000)) / (round_[_rID].keys))).mul(plyrRnds_[_pID][_rID].keys)) / 1000000000000000000) ); } /** * @dev returns all current round info needed for front end * -functionhash- 0x747dff42 * @return eth invested during ICO phase * @return round id * @return total keys for round * @return time round ends * @return time round started * @return current pot * @return current team ID & player ID in lead * @return current player in leads address * @return current player in leads name * @return whales eth in for round * @return bears eth in for round * @return sneks eth in for round * @return bulls eth in for round * @return airdrop tracker # & airdrop pot */ function getCurrentRoundInfo() public view returns(uint256, uint256, uint256, uint256, uint256, uint256, uint256, address, bytes32, uint256, uint256, uint256, uint256, uint256) { // setup local rID uint256 _rID = rID_; return ( round_[_rID].ico, //0 _rID, //1 round_[_rID].keys, //2 round_[_rID].end, //3 round_[_rID].strt, //4 round_[_rID].pot, //5 (round_[_rID].team + (round_[_rID].plyr * 10)), //6 plyr_[round_[_rID].plyr].addr, //7 plyr_[round_[_rID].plyr].name, //8 rndTmEth_[_rID][0], //9 rndTmEth_[_rID][1], //10 rndTmEth_[_rID][2], //11 rndTmEth_[_rID][3], //12 airDropTracker_ + (airDropPot_ * 1000) //13 ); } /** * 根据地址获取用户信息 * use msg.sender * -functionhash- 0xee0b5d8b * @param _addr address of the player you want to lookup * @return player ID * @return player name * @return keys owned (current round) * @return winnings vault * @return general vault * @return affiliate vault * @return player round eth */ function getPlayerInfoByAddress(address _addr) public view returns(uint256, bytes32, uint256, uint256, uint256, uint256, uint256) { // setup local rID uint256 _rID = rID_; if (_addr == address(0)) { _addr == msg.sender; } uint256 _pID = pIDxAddr_[_addr]; return ( _pID, //0 plyr_[_pID].name, //1 plyrRnds_[_pID][_rID].keys, //2 plyr_[_pID].win, //3 (plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), //4 plyr_[_pID].aff, //5 plyrRnds_[_pID][_rID].eth //6 ); } /** * 购买合约处理函数 */ function buyCore(uint256 _pID, uint256 _affID, uint256 _team, Fumodatasets.EventReturns memory _eventData_) private { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // if round is active if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) { // call core core(_rID, _pID, msg.value, _affID, _team, _eventData_); // if round is not active } else { // check to see if end round needs to be ran if (_now > round_[_rID].end && round_[_rID].ended == false) { // end the round (distributes pot) & start new round round_[_rID].ended = true; _eventData_ = endRound(_eventData_); // build event data _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; // fire buy and distribute event emit FumoEvents.onBuyAndDistribute ( msg.sender, plyr_[_pID].name, msg.value, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.P3DAmount, _eventData_.genAmount ); } // put eth in players vault plyr_[_pID].gen = plyr_[_pID].gen.add(msg.value); } } /** * @dev logic runs whenever a reload order is executed. determines how to handle * incoming eth depending on if we are in an active round or not */ function reLoadCore(uint256 _pID, uint256 _affID, uint256 _team, uint256 _eth, Fumodatasets.EventReturns memory _eventData_) private { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // if round is active if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) { // get earnings from all vaults and return unused to gen vault // because we use a custom safemath library. this will throw if player // tried to spend more eth than they have. plyr_[_pID].gen = withdrawEarnings(_pID).sub(_eth); // call core core(_rID, _pID, _eth, _affID, _team, _eventData_); // if round is not active and end round needs to be ran } else if (_now > round_[_rID].end && round_[_rID].ended == false) { // end the round (distributes pot) & start new round round_[_rID].ended = true; _eventData_ = endRound(_eventData_); // build event data _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; // fire buy and distribute event emit FumoEvents.onReLoadAndDistribute ( msg.sender, plyr_[_pID].name, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.P3DAmount, _eventData_.genAmount ); } } /** * @dev this is the core logic for any buy/reload that happens while a round * is live. */ function core(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, Fumodatasets.EventReturns memory _eventData_) private { // if player is new to round if (plyrRnds_[_pID][_rID].keys == 0) _eventData_ = managePlayer(_pID, _eventData_); // if eth left is greater than min eth allowed (sorry no pocket lint) if (_eth > 1000000000) { // mint the new keys uint256 _keys = (round_[_rID].eth).keysRec(_eth); // if they bought at least 1 whole key if (_keys >= 1000000000000000000) { updateTimer(_keys, _rID); // set new leaders if (round_[_rID].plyr != _pID) round_[_rID].plyr = _pID; if (round_[_rID].team != _team) round_[_rID].team = _team; // set the new leader bool to true _eventData_.compressedData = _eventData_.compressedData + 100; } // manage airdrops if (_eth >= 100000000000000000) { airDropTracker_++; if (airdrop() == true) { // gib muni uint256 _prize; if (_eth >= 10000000000000000000) { // calculate prize and give it to winner _prize = ((airDropPot_).mul(75)) / 100; plyr_[_pID].win = (plyr_[_pID].win).add(_prize); // adjust airDropPot airDropPot_ = (airDropPot_).sub(_prize); // let event know a tier 3 prize was won _eventData_.compressedData += 300000000000000000000000000000000; } else if (_eth >= 1000000000000000000 && _eth < 10000000000000000000) { // calculate prize and give it to winner _prize = ((airDropPot_).mul(50)) / 100; plyr_[_pID].win = (plyr_[_pID].win).add(_prize); // adjust airDropPot airDropPot_ = (airDropPot_).sub(_prize); // let event know a tier 2 prize was won _eventData_.compressedData += 200000000000000000000000000000000; } else if (_eth >= 100000000000000000 && _eth < 1000000000000000000) { // calculate prize and give it to winner _prize = ((airDropPot_).mul(25)) / 100; plyr_[_pID].win = (plyr_[_pID].win).add(_prize); // adjust airDropPot airDropPot_ = (airDropPot_).sub(_prize); // let event know a tier 3 prize was won _eventData_.compressedData += 300000000000000000000000000000000; } // set airdrop happened bool to true _eventData_.compressedData += 10000000000000000000000000000000; // let event know how much was won _eventData_.compressedData += _prize * 1000000000000000000000000000000000; // reset air drop tracker airDropTracker_ = 0; } } // store the air drop tracker number (number of buys since last airdrop) _eventData_.compressedData = _eventData_.compressedData + (airDropTracker_ * 1000); // update player plyrRnds_[_pID][_rID].keys = _keys.add(plyrRnds_[_pID][_rID].keys); plyrRnds_[_pID][_rID].eth = _eth.add(plyrRnds_[_pID][_rID].eth); // update round round_[_rID].keys = _keys.add(round_[_rID].keys); round_[_rID].eth = _eth.add(round_[_rID].eth); rndTmEth_[_rID][_team] = _eth.add(rndTmEth_[_rID][_team]); // distribute eth _eventData_ = distributeExternal(_rID, _pID, _eth, _affID, _team, _eventData_); _eventData_ = distributeInternal(_rID, _pID, _eth, _team, _keys, _eventData_); // call end tx function to fire end tx event. endTx(_pID, _team, _eth, _keys, _eventData_); } } //============================================================================== // _ _ | _ | _ _|_ _ _ _ . // (_(_||(_|_||(_| | (_)| _\ . //============================================================================== /** * @dev calculates unmasked earnings (just calculates, does not update mask) * @return earnings in wei format */ function calcUnMaskedEarnings(uint256 _pID, uint256 _rIDlast) private view returns(uint256) { return( (((round_[_rIDlast].mask).mul(plyrRnds_[_pID][_rIDlast].keys)) / (1000000000000000000)).sub(plyrRnds_[_pID][_rIDlast].mask) ); } /** * @dev returns the amount of keys you would get given an amount of eth. * -functionhash- 0xce89c80c * @param _rID round ID you want price for * @param _eth amount of eth sent in * @return keys received */ function calcKeysReceived(uint256 _rID, uint256 _eth) public view returns(uint256) { // grab time uint256 _now = now; // are we in a round? if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) return ( (round_[_rID].eth).keysRec(_eth) ); else // rounds over. need keys for new round return ( (_eth).keys() ); } /** * @dev returns current eth price for X keys. * -functionhash- 0xcf808000 * @param _keys number of keys desired (in 18 decimal format) * @return amount of eth needed to send */ function iWantXKeys(uint256 _keys) public view returns(uint256) { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // are we in a round? if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) return ( (round_[_rID].keys.add(_keys)).ethRec(_keys) ); else // rounds over. need price for new round return ( (_keys).eth() ); } //============================================================================== // _|_ _ _ | _ . // | (_)(_)|_\ . //============================================================================== /** * @dev receives name/player info from names contract */ function receivePlayerInfo(uint256 _pID, address _addr, bytes32 _name, uint256 _laff) external { require (msg.sender == address(PlayerBook), "your not playerNames contract... hmmm.."); if (pIDxAddr_[_addr] != _pID) pIDxAddr_[_addr] = _pID; if (pIDxName_[_name] != _pID) pIDxName_[_name] = _pID; if (plyr_[_pID].addr != _addr) plyr_[_pID].addr = _addr; if (plyr_[_pID].name != _name) plyr_[_pID].name = _name; if (plyr_[_pID].laff != _laff) plyr_[_pID].laff = _laff; if (plyrNames_[_pID][_name] == false) plyrNames_[_pID][_name] = true; } /** * @dev receives entire player name list */ function receivePlayerNameList(uint256 _pID, bytes32 _name) external { require (msg.sender == address(PlayerBook), "your not playerNames contract... hmmm.."); if(plyrNames_[_pID][_name] == false) plyrNames_[_pID][_name] = true; } /** * @dev gets existing or registers new pID. use this when a player may be new * @return pID */ function determinePID(Fumodatasets.EventReturns memory _eventData_) private returns (Fumodatasets.EventReturns) { uint256 _pID = pIDxAddr_[msg.sender]; // if player is new to this version of fomo3d if (_pID == 0) { // grab their player ID, name and last aff ID, from player names contract _pID = PlayerBook.getPlayerID(msg.sender); bytes32 _name = PlayerBook.getPlayerName(_pID); uint256 _laff = PlayerBook.getPlayerLAff(_pID); // set up player account pIDxAddr_[msg.sender] = _pID; plyr_[_pID].addr = msg.sender; if (_name != "") { pIDxName_[_name] = _pID; plyr_[_pID].name = _name; plyrNames_[_pID][_name] = true; } if (_laff != 0 && _laff != _pID) plyr_[_pID].laff = _laff; // set the new player bool to true _eventData_.compressedData = _eventData_.compressedData + 1; } return (_eventData_); } /** * @dev checks to make sure user picked a valid team. if not sets team * to default (sneks) */ function verifyTeam(uint256 _team) private pure returns (uint256) { if (_team < 0 || _team > 3) return(2); else return(_team); } /** * @dev decides if round end needs to be run & new round started. and if * player unmasked earnings from previously played rounds need to be moved. */ function managePlayer(uint256 _pID, Fumodatasets.EventReturns memory _eventData_) private returns (Fumodatasets.EventReturns) { // if player has played a previous round, move their unmasked earnings // from that round to gen vault. if (plyr_[_pID].lrnd != 0) updateGenVault(_pID, plyr_[_pID].lrnd); // update player's last round played plyr_[_pID].lrnd = rID_; // set the joined round bool to true _eventData_.compressedData = _eventData_.compressedData + 10; return(_eventData_); } /** * @dev ends the round. manages paying out winner/splitting up pot */ function endRound(Fumodatasets.EventReturns memory _eventData_) private returns (Fumodatasets.EventReturns) { // setup local rID uint256 _rID = rID_; // grab our winning player and team id's uint256 _winPID = round_[_rID].plyr; uint256 _winTID = round_[_rID].team; // grab our pot amount uint256 _pot = round_[_rID].pot; // calculate our winner share, community rewards, gen share, // p3d share, and amount reserved for next pot uint256 _win = (_pot.mul(48)) / 100; uint256 _com = (_pot.mul(6) / 50); uint256 _gen = (_pot.mul(potSplit_[_winTID].gen)) / 100; uint256 _res = (((_pot.sub(_win)).sub(_com)).sub(_gen)); // calculate ppt for round mask uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys); uint256 _dust = _gen.sub((_ppt.mul(round_[_rID].keys)) / 1000000000000000000); if (_dust > 0) { _gen = _gen.sub(_dust); _res = _res.add(_dust); } // pay our winner plyr_[_winPID].win = _win.add(plyr_[_winPID].win); // community rewards community_addr.transfer(_com); // distribute gen portion to key holders round_[_rID].mask = _ppt.add(round_[_rID].mask); // prepare event data _eventData_.compressedData = _eventData_.compressedData + (round_[_rID].end * 1000000); _eventData_.compressedIDs = _eventData_.compressedIDs + (_winPID * 100000000000000000000000000) + (_winTID * 100000000000000000); _eventData_.winnerAddr = plyr_[_winPID].addr; _eventData_.winnerName = plyr_[_winPID].name; _eventData_.amountWon = _win; _eventData_.genAmount = _gen; _eventData_.P3DAmount = 0; _eventData_.newPot = _res; // start next round rID_++; _rID++; round_[_rID].strt = now; round_[_rID].end = now.add(rndInit_).add(rndGap_); round_[_rID].pot = _res; return(_eventData_); } /** * @dev moves any unmasked earnings to gen vault. updates earnings mask */ function updateGenVault(uint256 _pID, uint256 _rIDlast) private { uint256 _earnings = calcUnMaskedEarnings(_pID, _rIDlast); if (_earnings > 0) { // put in gen vault plyr_[_pID].gen = _earnings.add(plyr_[_pID].gen); // zero out their earnings by updating mask plyrRnds_[_pID][_rIDlast].mask = _earnings.add(plyrRnds_[_pID][_rIDlast].mask); } } /** * @dev updates round timer based on number of whole keys bought. */ function updateTimer(uint256 _keys, uint256 _rID) private { // grab time uint256 _now = now; // calculate time based on number of keys bought uint256 _newTime; if (_now > round_[_rID].end && round_[_rID].plyr == 0) _newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(_now); else _newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(round_[_rID].end); // compare to max and set new end time if (_newTime < (rndMax_).add(_now)) round_[_rID].end = _newTime; else round_[_rID].end = rndMax_.add(_now); } /** * @dev generates a random number between 0-99 and checks to see if thats * resulted in an airdrop win * @return do we have a winner? */ function airdrop() private view returns(bool) { uint256 seed = uint256(keccak256(abi.encodePacked( (block.timestamp).add (block.difficulty).add ((uint256(keccak256(abi.encodePacked(block.coinbase)))) / (now)).add (block.gaslimit).add ((uint256(keccak256(abi.encodePacked(msg.sender)))) / (now)).add (block.number) ))); if((seed - ((seed / 1000) * 1000)) < airDropTracker_) return(true); else return(false); } /** * @dev distributes eth based on fees to com, aff, and p3d */ function distributeExternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, Fumodatasets.EventReturns memory _eventData_) private returns(Fumodatasets.EventReturns) { // pay 2% out to community rewards uint256 _com = _eth / 50; // distribute share to affiliate uint256 _aff = _eth / 5; // decide what to do with affiliate share of fees // affiliate must not be self, and must have a name registered if (_affID != _pID && plyr_[_affID].name != '') { plyr_[_affID].aff = _aff.add(plyr_[_affID].aff); emit FumoEvents.onAffiliatePayout(_affID, plyr_[_affID].addr, plyr_[_affID].name, _rID, _pID, _aff, now); } else { _com = _com.add(_aff); } community_addr.transfer(_com); return(_eventData_); } /** * @dev distributes eth based on fees to gen and pot */ function distributeInternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _team, uint256 _keys, Fumodatasets.EventReturns memory _eventData_) private returns(Fumodatasets.EventReturns) { // calculate gen share uint256 _gen = (_eth.mul(fees_[_team].gen)) / 100; // toss 2% into airdrop pot uint256 _air = (_eth / 50); airDropPot_ = airDropPot_.add(_air); // update eth balance (eth = eth - (com share + pot swap share + aff share + p3d share + airdrop pot share)) _eth = _eth.sub(((_eth.mul(24)) / 100)); // calculate pot uint256 _pot = _eth.sub(_gen); // distribute gen share (thats what updateMasks() does) and adjust // balances for dust. uint256 _dust = updateMasks(_rID, _pID, _gen, _keys); if (_dust > 0) _gen = _gen.sub(_dust); // add eth to pot round_[_rID].pot = _pot.add(_dust).add(round_[_rID].pot); // set up event data _eventData_.genAmount = _gen.add(_eventData_.genAmount); _eventData_.potAmount = _pot; return(_eventData_); } /** * @dev updates masks for round and player when keys are bought * @return dust left over */ function updateMasks(uint256 _rID, uint256 _pID, uint256 _gen, uint256 _keys) private returns(uint256) { /* MASKING NOTES earnings masks are a tricky thing for people to wrap their minds around. the basic thing to understand here. is were going to have a global tracker based on profit per share for each round, that increases in relevant proportion to the increase in share supply. the player will have an additional mask that basically says "based on the rounds mask, my shares, and how much i've already withdrawn, how much is still owed to me?" */ // calc profit per key & round mask based on this buy: (dust goes to pot) uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys); round_[_rID].mask = _ppt.add(round_[_rID].mask); // calculate player earning from their own buy (only based on the keys // they just bought). & update player earnings mask uint256 _pearn = (_ppt.mul(_keys)) / (1000000000000000000); plyrRnds_[_pID][_rID].mask = (((round_[_rID].mask.mul(_keys)) / (1000000000000000000)).sub(_pearn)).add(plyrRnds_[_pID][_rID].mask); // calculate & return dust return(_gen.sub((_ppt.mul(round_[_rID].keys)) / (1000000000000000000))); } /** * @dev adds up unmasked earnings, & vault earnings, sets them all to 0 * @return earnings in wei format */ function withdrawEarnings(uint256 _pID) private returns(uint256) { // update gen vault updateGenVault(_pID, plyr_[_pID].lrnd); // from vaults uint256 _earnings = (plyr_[_pID].win).add(plyr_[_pID].gen).add(plyr_[_pID].aff); if (_earnings > 0) { plyr_[_pID].win = 0; plyr_[_pID].gen = 0; plyr_[_pID].aff = 0; } return(_earnings); } /** * @dev prepares compression data and fires event for buy or reload tx's */ function endTx(uint256 _pID, uint256 _team, uint256 _eth, uint256 _keys, Fumodatasets.EventReturns memory _eventData_) private { _eventData_.compressedData = _eventData_.compressedData + (now * 1000000000000000000) + (_team * 100000000000000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID + (rID_ * 10000000000000000000000000000000000000000000000000000); emit FumoEvents.onEndTx ( _eventData_.compressedData, _eventData_.compressedIDs, plyr_[_pID].name, msg.sender, _eth, _keys, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.P3DAmount, _eventData_.genAmount, _eventData_.potAmount, airDropPot_ ); } //激活合约 bool public activated_ = false; function activate() public { // only team just can activate require( msg.sender == community_addr, "only community can activate" ); // can only be ran once require(activated_ == false, "fumo already activated"); // activate the contract activated_ = true; // lets start first round rID_ = 1; round_[1].strt = now + rndExtra_ - rndGap_; round_[1].end = now + rndInit_ + rndExtra_; } } //============================================================================== // __|_ _ __|_ _ . // _\ | | |_|(_ | _\ . //============================================================================== library Fumodatasets { //compressedData key // [76-33][32][31][30][29][28-18][17][16-6][5-3][2][1][0] // 0 - new player (bool) // 1 - joined round (bool) // 2 - new leader (bool) // 3-5 - air drop tracker (uint 0-999) // 6-16 - round end time // 17 - winnerTeam // 18 - 28 timestamp // 29 - team // 30 - 0 = reinvest (round), 1 = buy (round), 2 = buy (ico), 3 = reinvest (ico) // 31 - airdrop happened bool // 32 - airdrop tier // 33 - airdrop amount won //compressedIDs key // [77-52][51-26][25-0] // 0-25 - pID // 26-51 - winPID // 52-77 - rID struct EventReturns { uint256 compressedData; uint256 compressedIDs; address winnerAddr; // winner address bytes32 winnerName; // winner name uint256 amountWon; // amount won uint256 newPot; // amount in new pot uint256 P3DAmount; // amount distributed to p3d uint256 genAmount; // amount distributed to gen uint256 potAmount; // amount added to pot } struct Player { address addr; // player address bytes32 name; // player name uint256 win; // winnings vault uint256 gen; // general vault uint256 aff; // affiliate vault uint256 lrnd; // last round played uint256 laff; // last affiliate id used } struct PlayerRounds { uint256 eth; // eth player has added to round (used for eth limiter) uint256 keys; // keys uint256 mask; // player mask uint256 ico; // ICO phase investment } struct Round { uint256 plyr; // pID of player in lead uint256 team; // tID of team in lead uint256 end; // time ends/ended bool ended; // has round end function been ran uint256 strt; // time round started uint256 keys; // keys uint256 eth; // total eth in uint256 pot; // eth to pot (during round) / final amount paid to winner (after round ends) uint256 mask; // global mask uint256 ico; // total eth sent in during ICO phase uint256 icoGen; // total eth for gen during ICO phase uint256 icoAvg; // average key price for ICO phase } struct TeamFee { uint256 gen; // % of buy in thats paid to key holders of current round uint256 p3d; // % of buy in thats paid to p3d holders } struct PotSplit { uint256 gen; // % of pot thats paid to key holders of current round uint256 p3d; // % of pot thats paid to p3d holders } } //============================================================================== // | _ _ _ | _ . // |<(/_\/ (_(_||(_ . //=======/====================================================================== library FumoKeysCalcLong { using SafeMath for *; /** * @dev calculates number of keys received given X eth * @param _curEth current amount of eth in contract * @param _newEth eth being spent * @return amount of ticket purchased */ function keysRec(uint256 _curEth, uint256 _newEth) internal pure returns (uint256) { return(keys((_curEth).add(_newEth)).sub(keys(_curEth))); } /** * @dev calculates amount of eth received if you sold X keys * @param _curKeys current amount of keys that exist * @param _sellKeys amount of keys you wish to sell * @return amount of eth received */ function ethRec(uint256 _curKeys, uint256 _sellKeys) internal pure returns (uint256) { return((eth(_curKeys)).sub(eth(_curKeys.sub(_sellKeys)))); } /** * @dev calculates how many keys would exist with given an amount of eth * @param _eth eth "in contract" * @return number of keys that would exist */ function keys(uint256 _eth) internal pure returns(uint256) { return ((((((_eth).mul(1000000000000000000)).mul(156250000000000000000000000)).add(1406247070314025878906250000000000000000000000000000000000000000)).sqrt()).sub(37499960937500000000000000000000)) / (78125000); } /** * @dev calculates how much eth would be in contract given a number of keys * @param _keys number of keys "in contract" * @return eth that would exists */ function eth(uint256 _keys) internal pure returns(uint256) { return ((39062500).mul(_keys.sq()).add(((74999921875000).mul(_keys.mul(1000000000000000000))) / (2))) / ((1000000000000000000).sq()); } } //============================================================================== // . _ _|_ _ _ |` _ _ _ _ . // || | | (/_| ~|~(_|(_(/__\ . //============================================================================== interface PlayerBookInterface { function getPlayerID(address _addr) external returns (uint256); function getPlayerName(uint256 _pID) external view returns (bytes32); function getPlayerLAff(uint256 _pID) external view returns (uint256); function getPlayerAddr(uint256 _pID) external view returns (address); function getNameFee() external view returns (uint256); function registerNameXIDFromDapp(address _addr, bytes32 _name, uint256 _affCode, bool _all) external payable returns(bool, uint256); function registerNameXaddrFromDapp(address _addr, bytes32 _name, address _affCode, bool _all) external payable returns(bool, uint256); function registerNameXnameFromDapp(address _addr, bytes32 _name, bytes32 _affCode, bool _all) external payable returns(bool, uint256); } library NameFilter { /** * @dev filters name strings * -converts uppercase to lower case. * -makes sure it does not start/end with a space * -makes sure it does not contain multiple spaces in a row * -cannot be only numbers * -cannot start with 0x * -restricts characters to A-Z, a-z, 0-9, and space. * @return reprocessed string in bytes32 format */ function nameFilter(string _input) internal pure returns(bytes32) { bytes memory _temp = bytes(_input); uint256 _length = _temp.length; //sorry limited to 32 characters require (_length <= 32 && _length > 0, "string must be between 1 and 32 characters"); // make sure it doesnt start with or end with space require(_temp[0] != 0x20 && _temp[_length-1] != 0x20, "string cannot start or end with space"); // make sure first two characters are not 0x if (_temp[0] == 0x30) { require(_temp[1] != 0x78, "string cannot start with 0x"); require(_temp[1] != 0x58, "string cannot start with 0X"); } // create a bool to track if we have a non number character bool _hasNonNumber; // convert & check for (uint256 i = 0; i < _length; i++) { // if its uppercase A-Z if (_temp[i] > 0x40 && _temp[i] < 0x5b) { // convert to lower case a-z _temp[i] = byte(uint(_temp[i]) + 32); // we have a non number if (_hasNonNumber == false) _hasNonNumber = true; } else { require ( // require character is a space _temp[i] == 0x20 || // OR lowercase a-z (_temp[i] > 0x60 && _temp[i] < 0x7b) || // or 0-9 (_temp[i] > 0x2f && _temp[i] < 0x3a), "string contains invalid characters" ); // make sure theres not 2x spaces in a row if (_temp[i] == 0x20) require( _temp[i+1] != 0x20, "string cannot contain consecutive spaces"); // see if we have a character other than a number if (_hasNonNumber == false && (_temp[i] < 0x30 || _temp[i] > 0x39)) _hasNonNumber = true; } } require(_hasNonNumber == true, "string cannot be only numbers"); bytes32 _ret; assembly { _ret := mload(add(_temp, 32)) } return (_ret); } } /** * @title SafeMath v0.1.9 * @dev Math operations with safety checks that throw on error * change notes: original SafeMath library from OpenZeppelin modified by Inventor * - added sqrt * - added sq * - added pwr * - changed asserts to requires with error log outputs * - removed div, its useless */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; require(c / a == b, "SafeMath mul failed"); return c; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath sub failed"); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; require(c >= a, "SafeMath add failed"); return c; } /** * @dev gives square root of given x. */ function sqrt(uint256 x) internal pure returns (uint256 y) { uint256 z = ((add(x,1)) / 2); y = x; while (z < y) { y = z; z = ((add((x / z),z)) / 2); } } /** * @dev gives square. multiplies x by x */ function sq(uint256 x) internal pure returns (uint256) { return (mul(x,x)); } /** * @dev x to the power of y */ function pwr(uint256 x, uint256 y) internal pure returns (uint256) { if (x==0) return (0); else if (y==0) return (1); else { uint256 z = x; for (uint256 i=1; i < y; i++) z = mul(z,x); return (z); } } }
* 购买合约处理函数/ setup local rID grab time if round is active call core if round is not active check to see if end round needs to be ran end the round (distributes pot) & start new round build event data fire buy and distribute event
function buyCore(uint256 _pID, uint256 _affID, uint256 _team, Fumodatasets.EventReturns memory _eventData_) private { uint256 _rID = rID_; uint256 _now = now; if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) { core(_rID, _pID, msg.value, _affID, _team, _eventData_); if (_now > round_[_rID].end && round_[_rID].ended == false) { round_[_rID].ended = true; _eventData_ = endRound(_eventData_); _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; emit FumoEvents.onBuyAndDistribute ( msg.sender, plyr_[_pID].name, msg.value, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.P3DAmount, _eventData_.genAmount ); } } }
13,627,192
[ 1, 169, 117, 260, 165, 122, 113, 166, 243, 235, 168, 123, 104, 166, 102, 231, 168, 243, 233, 166, 234, 126, 167, 248, 113, 19, 3875, 1191, 436, 734, 11086, 813, 309, 3643, 353, 2695, 745, 2922, 309, 3643, 353, 486, 2695, 866, 358, 2621, 309, 679, 3643, 4260, 358, 506, 18892, 679, 326, 3643, 261, 2251, 1141, 5974, 13, 473, 787, 394, 3643, 1361, 871, 501, 4452, 30143, 471, 25722, 871, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 30143, 4670, 12, 11890, 5034, 389, 84, 734, 16, 2254, 5034, 389, 7329, 734, 16, 2254, 5034, 389, 10035, 16, 478, 379, 369, 20637, 2413, 18, 1133, 1356, 3778, 389, 2575, 751, 67, 13, 203, 3639, 3238, 203, 565, 288, 203, 3639, 2254, 5034, 389, 86, 734, 273, 436, 734, 67, 31, 203, 540, 203, 3639, 2254, 5034, 389, 3338, 273, 2037, 31, 203, 540, 203, 3639, 309, 261, 67, 3338, 405, 3643, 67, 63, 67, 86, 734, 8009, 701, 88, 397, 20391, 14001, 67, 597, 261, 67, 3338, 1648, 3643, 67, 63, 67, 86, 734, 8009, 409, 747, 261, 67, 3338, 405, 3643, 67, 63, 67, 86, 734, 8009, 409, 597, 3643, 67, 63, 67, 86, 734, 8009, 1283, 86, 422, 374, 20349, 7010, 3639, 288, 203, 5411, 2922, 24899, 86, 734, 16, 389, 84, 734, 16, 1234, 18, 1132, 16, 389, 7329, 734, 16, 389, 10035, 16, 389, 2575, 751, 67, 1769, 203, 540, 203, 5411, 309, 261, 67, 3338, 405, 3643, 67, 63, 67, 86, 734, 8009, 409, 597, 3643, 67, 63, 67, 86, 734, 8009, 3934, 422, 629, 13, 7010, 5411, 288, 203, 9506, 565, 3643, 67, 63, 67, 86, 734, 8009, 3934, 273, 638, 31, 203, 7734, 389, 2575, 751, 67, 273, 679, 11066, 24899, 2575, 751, 67, 1769, 203, 1171, 203, 7734, 389, 2575, 751, 27799, 15385, 751, 273, 389, 2575, 751, 27799, 15385, 751, 397, 261, 67, 3338, 380, 2130, 12648, 12648, 1769, 203, 7734, 389, 2575, 751, 27799, 15385, 5103, 273, 389, 2575, 751, 2 ]
pragma solidity ^0.4.22; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns(uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns(uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns(uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns(uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title Ownable * @dev The Ownable contract has an owner address and * provides basic authorization control functions */ contract Ownable { // Public properties address public owner; // Log if ownership has been changed event ChangeOwnership(address indexed _owner, address indexed _newOwner); // Checks if address is an owner modifier OnlyOwner() { require(msg.sender == owner); _; } // The Ownable constructor sets the owner address function Ownable() public { owner = msg.sender; } // Transfer current ownership to the new account function transferOwnership(address _newOwner) public OnlyOwner { require(_newOwner != address(0x0)); owner = _newOwner; emit ChangeOwnership(owner, _newOwner); } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { /* * @dev Event to notify listeners about pause. * @param pauseReason string Reason the token was paused for. */ event Pause(string pauseReason); /* * @dev Event to notify listeners about pause. * @param unpauseReason string Reason the token was unpaused for. */ event Unpause(string unpauseReason); bool public isPaused; string public pauseNotice; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier IsNotPaused() { require(!isPaused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier IsPaused() { require(isPaused); _; } /** * @dev called by the owner to pause, triggers stopped state * @param _reason string The reason for the pause. */ function pause(string _reason) OnlyOwner IsNotPaused public { isPaused = true; pauseNotice = _reason; emit Pause(_reason); } /** * @dev called by the owner to unpause, returns to normal state * @param _reason string Reason for the un pause. */ function unpause(string _reason) OnlyOwner IsPaused public { isPaused = false; pauseNotice = _reason; emit Unpause(_reason); } } /** * @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 theBalance); function transfer(address to, uint256 value) public returns(bool success); 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 theAllowance); function transferFrom(address from, address to, uint256 value) public returns(bool success); function approve(address spender, uint256 value) public returns(bool success); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title Basic token * @dev Basic version of StandardToken without allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; // Balances for each account mapping(address => uint256) balances; /** * @dev Get the token balance for account * @param _address The address to query the balance of._address * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _address) public constant returns(uint256 theBalance){ return balances[_address]; } /** * @dev Transfer the balance from owner's account to another account * @param _to The address to transfer to. * @param _value The amount to be transferred. * @return Returns true if transfer has been successful */ function transfer(address _to, uint256 _value) public returns(bool success){ require(_to != address(0x0) && _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; } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 */ contract StandardToken is BasicToken, ERC20 { // Owner of account approves the transfer of an amount to another account mapping (address => mapping (address => uint256)) allowed; /** * @dev Returns the amount of tokens approved by the owner that can be transferred to the spender's account * @param _owner The address which owns the funds. * @param _spender The address which will spend the funds. * @return An uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public constant returns(uint256 theAllowance){ return allowed[_owner][_spender]; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * To change the approve amount you first have to reduce the addresses` * allowance to zero by calling `approve(_spender, 0)` if it is not * already 0 to mitigate the race condition described here: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * @param _spender 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 success){ require(allowed[msg.sender][_spender] == 0 || _value == 0); allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * Transfer from `from` account to `to` account using allowance in `from` account to the sender * * @param _from Origin address * @param _to Destination address * @param _value Amount of CHR tokens to send */ function transferFrom(address _from, address _to, uint256 _value) public returns(bool success) { 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; } } /** * @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]); balances[msg.sender] = balances[msg.sender].sub(_value); totalSupply = totalSupply.sub(_value); emit Burn(msg.sender, _value); } } /** * CHERR.IO is a standard ERC20 token with some additional functionalities: * - Transfers are only enabled after contract owner enables it (after the ICO) * - Contract sets 60% of the total supply as allowance for ICO contract */ contract Cherrio is StandardToken, BurnableToken, Ownable, Pausable { using SafeMath for uint256; // Metadata string public constant name = "CHERR.IO"; string public constant symbol = "CHR"; uint8 public constant decimals = 18; // Token supplies uint256 public constant INITIAL_SUPPLY = 200000000 * (10 ** uint256(decimals)); uint256 public constant ADMIN_ALLOWANCE = 80000000 * (10 ** uint256(decimals)); uint256 public constant CONTRACT_ALLOWANCE = INITIAL_SUPPLY - ADMIN_ALLOWANCE; // Funding cap in ETH. Change to equal $12M at time of token offering uint256 public constant FUNDING_ETH_HARD_CAP = 15000 ether; // Minimum cap in ETH. Change to equal $3M at time of token offering uint256 public constant MINIMUM_ETH_SOFT_CAP = 3750 ether; // Min contribution is 0.1 ether uint256 public constant MINIMUM_CONTRIBUTION = 100 finney; // Price of the tokens as in tokens per ether uint256 public constant RATE = 5333; // Price of the tokens in tier 1 uint256 public constant RATE_TIER1 = 8743; // Price of the tokens in tier 2 uint256 public constant RATE_TIER2 = 7306; // Price of the tokens in tier 3 uint256 public constant RATE_TIER3 = 6584; // Price of the tokens in public sale for limited timeline uint256 public constant RATE_PUBLIC_SALE = 5926; // Maximum cap for tier 1 (60M CHR tokens) uint256 public constant TIER1_CAP = 60000000 * (10 ** uint256(decimals)); // Maximum cap for tier 2 (36M CHR tokens) uint256 public constant TIER2_CAP = 36000000 * (10 ** uint256(decimals)); // Maximum cap for each contributor in tier 1 uint256 public participantCapTier1; // Maximum cap for each contributor in tier 2 uint256 public participantCapTier2; // ETH cap for pool addres only in tier 1 uint256 public poolAddressCapTier1; // ETH cap for pool addres only in tier 2 uint256 public poolAddressCapTier2; // The address of the token admin address public adminAddress; // The address where ETH funds are collected address public beneficiaryAddress; // The address of the contract address public contractAddress; // The address of the pool who can send unlimited ETH to the contract address public poolAddress; // Enable transfers after conclusion of the token offering bool public transferIsEnabled; // Amount of raised in Wei uint256 public weiRaised; // Amount of CHR tokens sent to participant for presale and public sale uint256[4] public tokensSent; // Start of public pre-sale in timestamp uint256 startTimePresale; // Start and end time of public sale in timestamp uint256 startTime; uint256 endTime; // Discount period for public sale uint256 publicSaleDiscountEndTime; // End time limits in timestamp for each tier bonus uint256[3] public tierEndTime; //Check if contract address is already set bool contractAddressIsSet; struct Contributor { bool canContribute; uint8 tier; uint256 contributionInWeiTier1; uint256 contributionInWeiTier2; uint256 contributionInWeiTier3; uint256 contributionInWeiPublicSale; } struct Pool { uint256 contributionInWei; } enum Stages { Pending, PreSale, PublicSale, Ended } // The current stage of the offering Stages public stage; mapping(address => Contributor) public contributors; mapping(address => mapping(uint8 => Pool)) public pool; // Check if transfer is enabled modifier TransferIsEnabled { require(transferIsEnabled || msg.sender == adminAddress || msg.sender == contractAddress); _; } /** * @dev Check if address is a valid destination to transfer tokens to * - must not be zero address * - must not be the token address * - must not be the owner's address * - must not be the admin's address * - must not be the token offering contract address * - must not be the beneficiary address */ modifier ValidDestination(address _to) { require(_to != address(0x0)); require(_to != address(this)); require(_to != owner); require(_to != address(adminAddress)); require(_to != address(contractAddress)); require(_to != address(beneficiaryAddress)); _; } /** * Modifier that requires certain stage before executing the main function body * * @param _expectedStage Value that the current stage is required to match */ modifier AtStage(Stages _expectedStage) { require(stage == _expectedStage); _; } // Check if ICO is live modifier CheckIfICOIsLive() { require(stage != Stages.Pending && stage != Stages.Ended); if(stage == Stages.PreSale) { require( startTimePresale > 0 && now >= startTimePresale && now <= tierEndTime[2] ); } else { require( startTime > 0 && now >= startTime && now <= endTime ); } _; } // Check if participant sent more then miniminum required contribution modifier CheckPurchase() { require(msg.value >= MINIMUM_CONTRIBUTION); _; } /** * Event for token purchase logging * * @param _purchaser Participant who paid for CHR tokens * @param _value Amount in WEI paid for token * @param _tokens Amount of tokens purchased */ event TokenPurchase(address indexed _purchaser, uint256 _value, uint256 _tokens); /** * Event when token offering started * * @param _msg Message * @param _startTime Start time in timestamp * @param _endTime End time in timestamp */ event OfferingOpens(string _msg, uint256 _startTime, uint256 _endTime); /** * Event when token offering ended and how much has been raised in wei * * @param _endTime End time in timestamp * @param _totalWeiRaised Total raised funds in wei */ event OfferingCloses(uint256 _endTime, uint256 _totalWeiRaised); /** * Cherrio constructor */ function Cherrio() public { totalSupply = INITIAL_SUPPLY; // Mint tokens balances[msg.sender] = totalSupply; emit Transfer(address(0x0), msg.sender, totalSupply); // Aprove an allowance for admin account adminAddress = 0xe0509bB3921aacc433108D403f020a7c2f92e936; approve(adminAddress, ADMIN_ALLOWANCE); participantCapTier1 = 100 ether; participantCapTier2 = 100 ether; poolAddressCapTier1 = 2000 ether; poolAddressCapTier2 = 2000 ether; weiRaised = 0; startTimePresale = 0; startTime = 0; endTime = 0; publicSaleDiscountEndTime = 0; transferIsEnabled = false; contractAddressIsSet = false; } /** * Add approved addresses * * @param _addresses Array of approved addresses * @param _tier Tier */ function addApprovedAddresses(address[] _addresses, uint8 _tier) external OnlyOwner { uint256 length = _addresses.length; for(uint256 i = 0; i < length; i++) { if(!contributors[_addresses[i]].canContribute) { contributors[_addresses[i]].canContribute = true; contributors[_addresses[i]].tier = _tier; contributors[_addresses[i]].contributionInWeiTier1 = 0; contributors[_addresses[i]].contributionInWeiTier2 = 0; contributors[_addresses[i]].contributionInWeiTier3 = 0; contributors[_addresses[i]].contributionInWeiPublicSale = 0; } } } /** * Add approved address * * @param _address Approved address * @param _tier Tier */ function addSingleApprovedAddress(address _address, uint8 _tier) external OnlyOwner { if(!contributors[_address].canContribute) { contributors[_address].canContribute = true; contributors[_address].tier = _tier; contributors[_address].contributionInWeiTier1 = 0; contributors[_address].contributionInWeiTier2 = 0; contributors[_address].contributionInWeiTier3 = 0; contributors[_address].contributionInWeiPublicSale = 0; } } /** * Set token offering address to approve allowance for offering contract to distribute tokens */ function setTokenOffering() external OnlyOwner{ require(!contractAddressIsSet); require(!transferIsEnabled); contractAddress = address(this); approve(contractAddress, CONTRACT_ALLOWANCE); beneficiaryAddress = 0xAec8c4242c8c2E532c6D6478A7de380263234845; poolAddress = 0x1A2C916B640520E1e93A78fEa04A49D8345a5aa9; pool[poolAddress][0].contributionInWei = 0; pool[poolAddress][1].contributionInWei = 0; pool[poolAddress][2].contributionInWei = 0; pool[poolAddress][3].contributionInWei = 0; tokensSent[0] = 0; tokensSent[1] = 0; tokensSent[2] = 0; tokensSent[3] = 0; stage = Stages.Pending; contractAddressIsSet = true; } /** * Set when presale starts * * @param _startTimePresale Start time of presale in timestamp */ function startPresale(uint256 _startTimePresale) external OnlyOwner AtStage(Stages.Pending) { if(_startTimePresale == 0) { startTimePresale = now; } else { startTimePresale = _startTimePresale; } setTierEndTime(); stage = Stages.PreSale; } /** * Set when public sale starts * * @param _startTime Start time of public sale in timestamp */ function startPublicSale(uint256 _startTime) external OnlyOwner AtStage(Stages.PreSale) { if(_startTime == 0) { startTime = now; } else { startTime = _startTime; } endTime = startTime + 15 days; publicSaleDiscountEndTime = startTime + 3 days; stage = Stages.PublicSale; } // Fallback function can be used to buy CHR tokens function () public payable { buy(); } function buy() public payable IsNotPaused CheckIfICOIsLive returns(bool _success) { uint8 currentTier = getCurrentTier(); if(currentTier > 3) { revert(); } if(!buyTokens(currentTier)) { revert(); } return true; } /** * @param _tier Current Token Sale tier */ function buyTokens(uint8 _tier) internal ValidDestination(msg.sender) CheckPurchase returns(bool _success) { if(weiRaised.add(msg.value) > FUNDING_ETH_HARD_CAP) { revert(); } uint256 contributionInWei = msg.value; if(!checkTierCap(_tier, contributionInWei)) { revert(); } uint256 rate = getTierTokens(_tier); uint256 tokens = contributionInWei.mul(rate); if(msg.sender != poolAddress) { if(stage == Stages.PreSale) { if(!checkAllowedTier(msg.sender, _tier)) { revert(); } } if(!checkAllowedContribution(msg.sender, contributionInWei, _tier)) { revert(); } if(!this.transferFrom(owner, msg.sender, tokens)) { revert(); } if(stage == Stages.PreSale) { if(_tier == 0) { contributors[msg.sender].contributionInWeiTier1 = contributors[msg.sender].contributionInWeiTier1.add(contributionInWei); } else if(_tier == 1) { contributors[msg.sender].contributionInWeiTier2 = contributors[msg.sender].contributionInWeiTier2.add(contributionInWei); } else if(_tier == 2) { contributors[msg.sender].contributionInWeiTier3 = contributors[msg.sender].contributionInWeiTier3.add(contributionInWei); } } else { contributors[msg.sender].contributionInWeiPublicSale = contributors[msg.sender].contributionInWeiPublicSale.add(contributionInWei); } } else { if(!checkPoolAddressTierCap(_tier, contributionInWei)) { revert(); } if(!this.transferFrom(owner, msg.sender, tokens)) { revert(); } pool[poolAddress][_tier].contributionInWei = pool[poolAddress][_tier].contributionInWei.add(contributionInWei); } weiRaised = weiRaised.add(contributionInWei); tokensSent[_tier] = tokensSent[_tier].add(tokens); if(weiRaised >= FUNDING_ETH_HARD_CAP) { offeringEnded(); } beneficiaryAddress.transfer(address(this).balance); emit TokenPurchase(msg.sender, contributionInWei, tokens); return true; } /** * Manually withdraw tokens to private investors * * @param _to Address of private investor * @param _value The number of tokens to send to private investor */ function withdrawCrowdsaleTokens(address _to, uint256 _value) external OnlyOwner ValidDestination(_to) returns (bool _success) { if(!this.transferFrom(owner, _to, _value)) { revert(); } return true; } /** * Transfer from sender to another account * * @param _to Destination address * @param _value Amount of CHR tokens to send */ function transfer(address _to, uint256 _value) public ValidDestination(_to) TransferIsEnabled IsNotPaused returns(bool _success){ return super.transfer(_to, _value); } /** * Transfer from `from` account to `to` account using allowance in `from` account to the sender * * @param _from Origin address * @param _to Destination address * @param _value Amount of CHR tokens to send */ function transferFrom(address _from, address _to, uint256 _value) public ValidDestination(_to) TransferIsEnabled IsNotPaused returns(bool _success){ return super.transferFrom(_from, _to, _value); } /** * Check if participant is allowed to contribute in current tier * * @param _address Participant address * @param _tier Current tier */ function checkAllowedTier(address _address, uint8 _tier) internal view returns (bool _allowed) { if(contributors[_address].tier <= _tier) { return true; } else{ return false; } } /** * Check contribution cap for only tier 1 and 2 * * @param _tier Current tier * @param _value Participant contribution */ function checkTierCap(uint8 _tier, uint256 _value) internal view returns (bool _success) { uint256 currentlyTokensSent = tokensSent[_tier]; bool status = true; if(_tier == 0) { if(TIER1_CAP < currentlyTokensSent.add(_value)) { status = false; } } else if(_tier == 1) { if(TIER2_CAP < currentlyTokensSent.add(_value)) { status = false; } } return status; } /** * Check cap for pool address in tier 1 and 2 * * @param _tier Current tier * @param _value Pool contribution */ function checkPoolAddressTierCap(uint8 _tier, uint256 _value) internal view returns (bool _success) { uint256 currentContribution = pool[poolAddress][_tier].contributionInWei; if((_tier == 0 && (poolAddressCapTier1 < currentContribution.add(_value))) || (_tier == 1 && (poolAddressCapTier2 < currentContribution.add(_value)))) { return false; } return true; } /** * Check cap for pool address in tier 1 and 2 * * @param _address Participant address * @param _value Participant contribution * @param _tier Current tier */ function checkAllowedContribution(address _address, uint256 _value, uint8 _tier) internal view returns (bool _success) { bool status = false; if(contributors[_address].canContribute) { if(_tier == 0) { if(participantCapTier1 >= contributors[_address].contributionInWeiTier1.add(_value)) { status = true; } } else if(_tier == 1) { if(participantCapTier2 >= contributors[_address].contributionInWeiTier2.add(_value)) { status = true; } } else if(_tier == 2) { status = true; } else { status = true; } } return status; } /** * Get current tier tokens rate * * @param _tier Current tier */ function getTierTokens(uint8 _tier) internal view returns(uint256 _tokens) { uint256 tokens = RATE_TIER1; if(_tier == 1) { tokens = RATE_TIER2; } else if(_tier == 2) { tokens = RATE_TIER3; } else if(_tier == 3) { if(now <= publicSaleDiscountEndTime) { tokens = RATE_PUBLIC_SALE; } else { tokens = RATE; } } return tokens; } // Get current tier function getCurrentTier() public view returns(uint8 _tier) { uint8 currentTier = 3; // 3 is public sale if(stage == Stages.PreSale) { if(now <= tierEndTime[0]) { currentTier = 0; } else if(now <= tierEndTime[1]) { currentTier = 1; } else if(now <= tierEndTime[2]) { currentTier = 2; } } else { if(now > endTime) { currentTier = 4; // Token offering ended } } return currentTier; } // Set end time for each tier function setTierEndTime() internal AtStage(Stages.Pending) { tierEndTime[0] = startTimePresale + 1 days; tierEndTime[1] = tierEndTime[0] + 2 days; tierEndTime[2] = tierEndTime[1] + 6 days; } // End the token offering function endOffering() public OnlyOwner { offeringEnded(); } // Token offering is ended function offeringEnded() internal { endTime = now; stage = Stages.Ended; emit OfferingCloses(endTime, weiRaised); } // Enable transfers, burn unsold tokens & set tokenOfferingAddress to 0 function enableTransfer() public OnlyOwner returns(bool _success){ transferIsEnabled = true; uint256 tokensToBurn = allowed[msg.sender][contractAddress]; if(tokensToBurn != 0){ burn(tokensToBurn); approve(contractAddress, 0); } return true; } /** * Extend end time * * @param _addedTime Addtional time in secods */ function extendEndTime(uint256 _addedTime) external OnlyOwner { endTime = endTime + _addedTime; } /** * Extend public sale discount time * * @param _addedPublicSaleDiscountEndTime Addtional time in secods */ function extendPublicSaleDiscountEndTime(uint256 _addedPublicSaleDiscountEndTime) external OnlyOwner { publicSaleDiscountEndTime = publicSaleDiscountEndTime + _addedPublicSaleDiscountEndTime; } /** * Update pool cap for tier 1 * * @param _poolAddressCapTier1 Tier cap */ function updatePoolAddressCapTier1(uint256 _poolAddressCapTier1) external OnlyOwner { poolAddressCapTier1 = _poolAddressCapTier1; } /** * Update pool cap for tier 2 * * @param _poolAddressCapTier2 Tier cap */ function updatePoolAddressCapTier2(uint256 _poolAddressCapTier2) external OnlyOwner { poolAddressCapTier2 = _poolAddressCapTier2; } // /** * Update participant cap for tier 1 * * @param _participantCapTier1 Tier cap */ function updateParticipantCapTier1(uint256 _participantCapTier1) external OnlyOwner { participantCapTier1 = _participantCapTier1; } /** * Update participant cap for tier 2 * * @param _participantCapTier2 Tier cap */ function updateParticipantCapTier2(uint256 _participantCapTier2) external OnlyOwner { participantCapTier2 = _participantCapTier2; } }
* @title Burnable Token @dev Token that can be irreversibly burned (destroyed)./
contract BurnableToken is BasicToken { event Burn(address indexed burner, uint256 value); function burn(uint256 _value) public { require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); totalSupply = totalSupply.sub(_value); emit Burn(msg.sender, _value); } }
5,504,624
[ 1, 38, 321, 429, 3155, 225, 3155, 716, 848, 506, 9482, 266, 2496, 24755, 18305, 329, 261, 11662, 329, 2934, 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, 16351, 605, 321, 429, 1345, 353, 7651, 1345, 288, 203, 565, 871, 605, 321, 12, 2867, 8808, 18305, 264, 16, 2254, 5034, 460, 1769, 203, 203, 565, 445, 18305, 12, 11890, 5034, 389, 1132, 13, 1071, 288, 203, 3639, 2583, 24899, 1132, 1648, 324, 26488, 63, 3576, 18, 15330, 19226, 203, 203, 3639, 324, 26488, 63, 3576, 18, 15330, 65, 273, 324, 26488, 63, 3576, 18, 15330, 8009, 1717, 24899, 1132, 1769, 203, 3639, 2078, 3088, 1283, 273, 2078, 3088, 1283, 18, 1717, 24899, 1132, 1769, 203, 203, 3639, 3626, 605, 321, 12, 3576, 18, 15330, 16, 389, 1132, 1769, 203, 565, 289, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol"; import "./ArmyEnhancer.sol"; /** * @notice ENS registry to get chainlink resolver */ interface ENS { function resolver(bytes32) external view returns (Resolver); } /** * @notice Chainlink resolver to get price feed proxy */ interface Resolver { function addr(bytes32) external view returns (address); } /** * @title Army contract with basic command * @author Justa Liang */ abstract contract ArmyBase is ERC721Enumerable { /// @notice Corresponding Enhancer contract ENHR public enhancerContract; /// @notice Serial number of minions, imply how many minions have been created uint public serialNumber; /// @notice Inital minion's power int public initPower; /// @notice ENS interface (fixed address) ENS public ens; /// @dev Minion data structure struct Minion { address branchAddr; // branch address (which proxy of Chainlink price feed) bool armed; // armed or not int envFactor; // environment factor (latest updated price from Chainlink) int power; // power of the minion } /// @dev Minion profile to view struct MinionProfile { address branch; bool armed; int price; int power; string uri; } /// @dev Minion data storage mapping(uint => Minion) public minions; /// @notice Emit when minion's state changes event MinionState( uint indexed minionID, address indexed branchAddress, bool indexed armed, int environmentFactor, int power ); /** * @dev Set name, symbol, and addresses of interactive contracts * @param ensRegistryAddr Address of ENS Registry */ constructor(address ensRegistryAddr) { serialNumber = 0; initPower = 1000; ens = ENS(ensRegistryAddr); } /** * @notice Get if minion exists * @param minionID ID of the minion * @return Exists or not */ function minionExists(uint minionID) external view returns (bool) { return _exists(minionID); } /** * @notice Get minion's on-chain information * @param minionID ID of the minion * @return On-chain information of the minion */ function getMinionInfo(uint minionID) public view returns (address, bool, int, int) { require( _exists(minionID), "ARMY: commander query for nonexistent minion"); Minion storage m = minions[minionID]; return (m.branchAddr, m.armed, m.envFactor, m.power); } /** * @notice Get minion IDs, like (2,6,9), given commander * @param commander Commander of these minions * @return minionIDs IDs of these minions */ function getMinionIDs(address commander) public view returns(uint[] memory minionIDs) { uint minionCount = balanceOf(commander); minionIDs = new uint[](minionCount); for (uint i = 0; i < minionCount; i++) { minionIDs[i] = tokenOfOwnerByIndex(commander, i); } } /** * @notice Recruit a minion * @param branchHash ENS-namehash of given pair (ex: eth-usd.data.eth) * @return ID of the newly recruited minion */ function recruit(bytes32 branchHash) external returns (uint) { address branchAddr = _resolve(branchHash); require( branchAddr != address(0), "ARMY: invalid branch"); // get current price AggregatorV3Interface pricefeed = AggregatorV3Interface(branchAddr); (,int currPrice,,,) = pricefeed.latestRoundData(); // mint minion and store its data on chain uint newID = serialNumber; _safeMint(msg.sender, newID); minions[newID] = Minion(branchAddr, false, currPrice, initPower); emit MinionState(newID, branchAddr, false, currPrice, initPower); serialNumber++; return newID; } /** * @dev Check if commander can command the minion * @param minionID ID of the minion */ modifier checkCommander(uint minionID) { require( _isApprovedOrOwner(msg.sender, minionID), "ARMY: commander can't command the minion"); _; } /** * @dev Resolve ENS-namehash to Chainlink price feed proxy * @param node ENS-namehash of given pair * @return Chainlink price feed proxy */ function _resolve(bytes32 node) internal view returns (address) { Resolver resolver = ens.resolver(node); return resolver.addr(node); } }
* @dev Check if commander can command the minion @param minionID ID of the minion/
modifier checkCommander(uint minionID) { require( _isApprovedOrOwner(msg.sender, minionID), "ARMY: commander can't command the minion"); _; }
12,714,750
[ 1, 1564, 309, 1296, 264, 848, 1296, 326, 13524, 225, 13524, 734, 1599, 434, 326, 13524, 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, 9606, 866, 2189, 264, 12, 11890, 13524, 734, 13, 288, 203, 3639, 2583, 12, 203, 5411, 389, 291, 31639, 1162, 5541, 12, 3576, 18, 15330, 16, 13524, 734, 3631, 203, 5411, 315, 985, 22114, 30, 1296, 264, 848, 1404, 1296, 326, 13524, 8863, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.23; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { 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 ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @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 ); } contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } /** * @dev Allows the current owner to relinquish control of the contract. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } } /** * @title Crowdsale * @dev Crowdsale is a base contract for managing a token crowdsale, * allowing investors to purchase tokens with ether. This contract implements * such functionality in its most fundamental form and can be extended to provide additional * functionality and/or custom behavior. * The external interface represents the basic interface for purchasing tokens, and conform * the base architecture for crowdsales. They are *not* intended to be modified / overriden. * The internal interface conforms the extensible and modifiable surface of crowdsales. Override * the methods to add functionality. Consider using 'super' where appropiate to concatenate * behavior. */ contract XDMCCrowdsale is Ownable { using SafeMath for uint256; event Log(string _a, uint256 _b); // The token being sold ERC20 public token; address wallet; //address for contribution receiving uint256 public icoRate = 0; // will be set manually when ico starts uint256 public icoOver1 = 0; // will be set manually when ico starts uint256 public icoBonus1 = 0; // will be set manually when ico starts uint256 public icoOver2 = 0; // will be set manually when ico starts uint256 public icoBonus2 = 0; // will be set manually when ico starts uint256 public icoOver3 = 0; // will be set manually when ico starts uint256 public icoBonus3 = 0; // will be set manually when ico starts uint256 public icoOver4 = 0; // will be set manually when ico starts uint256 public icoBonus4 = 0; // will be set manually when ico starts uint256 public icoOver5 = 0; // will be set manually when ico starts uint256 public icoBonus5 = 0; // will be set manually when ico starts uint256 public ico1cap = uint256(224502081).mul(1 ether); uint256 public ico2cap = uint256(190996929).mul(1 ether); uint256 public ico3cap = uint256(127331286).mul(1 ether); enum Stages {Pause, Ico1, Ico1End, Ico2, Ico2End, Ico3, Ico3End} Stages currentStage; address public teamAddress = 0x4B58EBeEb96b7551Bb752Ea9512771615C554De3; uint256 public vestingStartTime = 0; uint256 public vestingPeriod = 15552000; // 180 days uint256 public teamTokens = uint256(198639670).mul(1 ether); uint256 public teamTokensPerPeriod = uint256(33768743).mul(1 ether); uint256 public teamTokensReleased = 0; uint256 public devTokensIco1 = uint256(52060948).mul(1 ether); uint256 public devTokensIco2 = uint256(52060948).mul(1 ether); uint256 public devTokensIco3 = uint256(53638554).mul(1 ether); uint256 public ico1endTime = 0; uint256 public ico2endTime = 0; uint256 public ico3endTime = 0; uint256 public getUnsoldPeriod = 8640000; // 100 days uint256 public ico1total = 0; uint256 public ico2total = 0; uint256 public ico3total = 0; uint256 public ico1receivedTotal = 0; uint256 public ico2receivedTotal = 0; uint256 public ico3receivedTotal = 0; mapping(address => uint256) ico1amount; mapping(address => uint256) ico2amount; mapping(address => uint256) ico3amount; mapping(address => uint256) ico1received; mapping(address => uint256) ico2received; mapping(address => uint256) ico3received; // Amount of wei raised uint256 public weiRaised; /** * Event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokenPurchase( address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount ); event TokenPriceDescription( uint256 basePrice, uint256 bonus, uint256 tokens ); /** * * @param _owner Address where collected funds will be forwarded to * @param _token Address of the token being sold */ constructor(address _owner, address _wallet, ERC20 _token) public { require(_owner != address(0)); require(_wallet != address(0)); require(_token != address(0)); currentStage = Stages.Pause; vestingStartTime = now; owner = _owner; token = _token; wallet = _wallet; teamTokensReleased = teamTokensReleased.add(teamTokensPerPeriod); } // ----------------------------------------- // Crowdsale external interface // ----------------------------------------- /** * @dev fallback function ***DO NOT OVERRIDE*** */ function () external payable { buyTokens(msg.sender); } function startIco1( uint256 _rate, uint256 _over1, uint256 _bonus1, uint256 _over2, uint256 _bonus2, uint256 _over3, uint256 _bonus3, uint256 _over4, uint256 _bonus4, uint256 _over5, uint256 _bonus5 ) public onlyOwner returns (bool) { require(currentStage == Stages.Pause); require(token.balanceOf(address(this)) >= uint256(865461673).mul(1 ether)); require(_rate > 0); currentStage = Stages.Ico1; icoRate = _rate; icoOver1 = _over1.mul(1 ether); icoBonus1 = _bonus1; icoOver2 = _over2.mul(1 ether); icoBonus2 = _bonus2; icoOver3 = _over3.mul(1 ether); icoBonus3 = _bonus3; icoOver4 = _over4.mul(1 ether); icoBonus4 = _bonus4; icoOver5 = _over5.mul(1 ether); icoBonus5 = _bonus5; require(token.transfer(owner, devTokensIco1)); return true; } function endIco1() public onlyOwner returns (bool) { require(currentStage == Stages.Ico1); currentStage = Stages.Ico1End; ico1endTime = now; return true; } function startIco2( uint256 _rate, uint256 _over1, uint256 _bonus1, uint256 _over2, uint256 _bonus2, uint256 _over3, uint256 _bonus3, uint256 _over4, uint256 _bonus4, uint256 _over5, uint256 _bonus5 ) public onlyOwner returns (bool) { require(currentStage == Stages.Ico1End); currentStage = Stages.Ico2; if (_rate > 0) icoRate = _rate; icoOver1 = _over1.mul(1 ether); icoBonus1 = _bonus1; icoOver2 = _over2.mul(1 ether); icoBonus2 = _bonus2; icoOver3 = _over3.mul(1 ether); icoBonus3 = _bonus3; icoOver4 = _over4.mul(1 ether); icoBonus4 = _bonus4; icoOver5 = _over5.mul(1 ether); icoBonus5 = _bonus5; require(token.transfer(owner, devTokensIco2)); return true; } function endIco2() public onlyOwner returns (bool) { require(currentStage == Stages.Ico2); currentStage = Stages.Ico2End; ico2endTime = now; return true; } function startIco3( uint256 _rate, uint256 _over1, uint256 _bonus1, uint256 _over2, uint256 _bonus2, uint256 _over3, uint256 _bonus3, uint256 _over4, uint256 _bonus4, uint256 _over5, uint256 _bonus5 ) public onlyOwner returns (bool) { require(currentStage == Stages.Ico2End); currentStage = Stages.Ico3; if (_rate > 0) icoRate = _rate; icoOver1 = _over1.mul(1 ether); icoBonus1 = _bonus1; icoOver2 = _over2.mul(1 ether); icoBonus2 = _bonus2; icoOver3 = _over3.mul(1 ether); icoBonus3 = _bonus3; icoOver4 = _over4.mul(1 ether); icoBonus4 = _bonus4; icoOver5 = _over5.mul(1 ether); icoBonus5 = _bonus5; require(token.transfer(owner, devTokensIco3)); return true; } function endIco3() public onlyOwner returns (bool) { require(currentStage == Stages.Ico3); currentStage = Stages.Ico3End; ico3endTime = now; return true; } function getUnsoldReceived(uint256 _stage, address _address) public view returns (uint256) { if (_stage == 1) return ico1received[_address]; else if (_stage == 2) return ico2received[_address]; else if (_stage == 3) return ico3received[_address]; else return 0; } function getStageAmount(uint256 _stage, address _address) public view returns (uint256) { if (_stage == 1) return ico1amount[_address]; else if (_stage == 2) return ico2amount[_address]; else if (_stage == 3) return ico3amount[_address]; else return 0; } function getStageName() public view returns (string) { if (currentStage == Stages.Pause) return 'ICO is not started yet'; else if (currentStage == Stages.Ico1) return 'ICO 1'; else if (currentStage == Stages.Ico1End) return 'ICO 1 end'; else if (currentStage == Stages.Ico2) return 'ICO 2'; else if (currentStage == Stages.Ico2End) return 'ICO 2 end'; else if (currentStage == Stages.Ico3) return 'ICO 3'; else if (currentStage == Stages.Ico3End) return 'ICO 3 end'; return 'Undefined'; } function getPrice() public view returns (uint256) { if (currentStage == Stages.Ico1) return icoRate; else if (currentStage == Stages.Ico2) return icoRate; else if (currentStage == Stages.Ico3) return icoRate; return 0; } function getBonus(uint256 _ether) public view returns (uint256) { return _getBonus(_ether.mul(1 ether)); } function _getBonus(uint256 _wei) internal view returns (uint256) { if ( currentStage == Stages.Ico1 || currentStage == Stages.Ico2 || currentStage == Stages.Ico3 ) { if (_wei >= icoOver1) return icoBonus1; else if (_wei >= icoOver2) return icoBonus2; else if (_wei >= icoOver3) return icoBonus3; else if (_wei >= icoOver4) return icoBonus4; else if (_wei >= icoOver5) return icoBonus5; return 0; } return 0; } function getVestingPeriodNumber() public view returns (uint256) { if (vestingStartTime == 0) return 0; return now.sub(vestingStartTime).div(vestingPeriod).add(1); } function getTeamToken() public { uint256 vestingPeriodNumber = getVestingPeriodNumber(); require(vestingPeriodNumber > 1); require(teamTokensReleased < teamTokens); uint256 toRelease; if (vestingPeriodNumber >= 6) toRelease = teamTokens; else toRelease = vestingPeriodNumber.mul(teamTokensPerPeriod); if (toRelease > teamTokens) toRelease = teamTokens; toRelease = toRelease.sub(teamTokensReleased); require(toRelease > 0); teamTokensReleased = teamTokensReleased.add(toRelease); require(token.transfer(teamAddress, toRelease)); } /** * @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); _validateTokensAmount(tokens); if (currentStage == Stages.Ico1) { ico1amount[msg.sender] = ico1amount[msg.sender].add(tokens); ico1total = ico1total.add(tokens); } else if (currentStage == Stages.Ico2) { ico2amount[msg.sender] = ico2amount[msg.sender].add(tokens); ico2total = ico2total.add(tokens); } else if (currentStage == Stages.Ico3) { ico3amount[msg.sender] = ico3amount[msg.sender].add(tokens); ico3total = ico3total.add(tokens); } weiRaised = weiRaised.add(weiAmount); _processPurchase(_beneficiary, tokens); emit TokenPurchase(msg.sender, _beneficiary, weiAmount, tokens); _forwardFunds(weiAmount); } /** * @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. Use super to concatenate validations. * @param _beneficiary Address performing the token purchase * @param _weiAmount Value in wei involved in the purchase */ function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal view { require(_beneficiary != address(0)); require(_weiAmount >= 100 finney); if (currentStage == Stages.Ico1) require(_weiAmount <= 1000 ether); else if (currentStage == Stages.Ico2) require(_weiAmount <= 500 ether); else if (currentStage == Stages.Ico3) require(_weiAmount <= 500 ether); else revert(); } function _validateTokensAmount(uint256 _tokens) internal view { require(_tokens > 0); if (currentStage == Stages.Ico1) require(_tokens <= ico1cap); else if (currentStage == Stages.Ico2) require(_tokens <= ico2cap); else if (currentStage == Stages.Ico3) require(_tokens <= ico3cap); } /** * @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 { require(token.transfer(_beneficiary, _tokenAmount)); } /** * @dev Executed when a purchase has been validated and is ready to be executed. Not necessarily emits/sends tokens. * @param _beneficiary Address receiving the tokens * @param _tokenAmount Number of tokens to be purchased */ function _processPurchase(address _beneficiary, uint256 _tokenAmount) internal { _deliverTokens(_beneficiary, _tokenAmount); } /** * @dev Override to extend the way in which ether is converted to tokens. * @param _weiAmount Value in wei to be converted into tokens * @return Number of tokens that can be purchased with the specified _weiAmount */ function _getTokenAmount(uint256 _weiAmount) internal returns (uint256) { uint256 basePrice = icoRate; uint256 tokens = _weiAmount.mul(basePrice); uint256 bonuses = _getBonus(_weiAmount); if (bonuses > 0) { uint256 bonusTokens = tokens.mul(bonuses).div(100); tokens = tokens.add(bonusTokens); } emit TokenPriceDescription(basePrice, bonuses, tokens); return tokens; } /** * @dev Determines how ETH is stored/forwarded on purchases. */ function _forwardFunds(uint256 _weiAmount) internal { require(wallet != address(0)); wallet.transfer(_weiAmount); } function getUnsoldOwner() public onlyOwner returns (bool) { uint256 unsoldTokensRemains = 0; uint256 stageRemains; if ( ico1endTime > 0 && now.sub(ico1endTime) > getUnsoldPeriod && ico1receivedTotal < ico1cap.sub(ico1total) ) { stageRemains = ico1cap.sub(ico1total).sub(ico1receivedTotal); unsoldTokensRemains = unsoldTokensRemains.add(stageRemains); ico1receivedTotal = ico1cap.sub(ico1total); } if ( ico2endTime > 0 && now.sub(ico2endTime) > getUnsoldPeriod && ico2receivedTotal < ico2cap.sub(ico1total) ) { stageRemains = ico2cap.sub(ico2total).sub(ico2receivedTotal); unsoldTokensRemains = unsoldTokensRemains.add(stageRemains); ico2receivedTotal = ico2cap.sub(ico2total); } if ( ico3endTime > 0 && now.sub(ico3endTime) > getUnsoldPeriod && ico3receivedTotal < ico3cap.sub(ico3total) ) { stageRemains = ico3cap.sub(ico3total).sub(ico3receivedTotal); unsoldTokensRemains = unsoldTokensRemains.add(stageRemains); ico3receivedTotal = ico3cap.sub(ico3total); } require(unsoldTokensRemains > 0); require(token.transfer(owner, unsoldTokensRemains)); return true; } function getUnsold() public returns (bool) { uint256 unsoldTokensShare = 0; uint256 tokenBalance = token.balanceOf(msg.sender); uint256 stageShare; uint256 stageRemains; if ( ico1endTime > 0 && now.sub(ico1endTime) < getUnsoldPeriod && ico1received[msg.sender] == 0 && tokenBalance >= ico1amount[msg.sender] ) { tokenBalance = tokenBalance.sub(ico1amount[msg.sender]); stageRemains = ico1cap.sub(ico1total); stageShare = stageRemains.mul(ico1amount[msg.sender]).div(ico1total); unsoldTokensShare = unsoldTokensShare.add(stageShare); ico1received[msg.sender] = stageShare; ico1receivedTotal = ico1receivedTotal.add(stageShare); require(ico1receivedTotal <= ico1cap.sub(ico1total)); } if ( ico2endTime > 0 && now.sub(ico2endTime) < getUnsoldPeriod && ico2received[msg.sender] == 0 && tokenBalance >= ico2amount[msg.sender] ) { tokenBalance = tokenBalance.sub(ico2amount[msg.sender]); stageRemains = ico2cap.sub(ico2total); stageShare = stageRemains.mul(ico2amount[msg.sender]).div(ico2total); unsoldTokensShare = unsoldTokensShare.add(stageShare); ico2received[msg.sender] = stageShare; ico2receivedTotal = ico2receivedTotal.add(stageShare); require(ico2receivedTotal <= ico2cap.sub(ico2total)); } if ( ico3endTime > 0 && now.sub(ico3endTime) < getUnsoldPeriod && ico3received[msg.sender] == 0 && tokenBalance >= ico3amount[msg.sender] ) { stageRemains = ico3cap.sub(ico3total); stageShare = stageRemains.mul(ico3amount[msg.sender]).div(ico3total); unsoldTokensShare = unsoldTokensShare.add(stageShare); ico3received[msg.sender] = stageShare; ico3receivedTotal = ico3receivedTotal.add(stageShare); require(ico3receivedTotal <= ico3cap.sub(ico3total)); } require(unsoldTokensShare > 0); require(token.transfer(msg.sender, unsoldTokensShare)); return true; } }
will be set manually when ico starts
uint256 public icoBonus3 = 0;
14,385,945
[ 1, 20194, 506, 444, 10036, 1347, 277, 2894, 2542, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 225, 2254, 5034, 1071, 277, 2894, 38, 22889, 23, 273, 374, 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 ]
// (C) block.one all rights reserved pragma solidity ^0.4.24; import "../math/SafeMath.sol"; import "../ERC20/IERC20.sol"; import "../presale/IPresale.sol"; import "./ICrowdsale.sol"; import "../access/roles/ManagerRole.sol"; import "../access/roles/RecoverRole.sol"; contract TBNCrowdSale is ICrowdsale, ManagerRole, RecoverRole, FundkeeperRole { using SafeMath for uint256; uint256 private _numberOfIntervals; // number of intervals in the sale (188) bytes32 private _hiddenCap; // a hash of <the hidden hard cap(in WEI)>+<a secret number> to be revealed if/when the hard cap is reached - does not rebase so choose wisely IERC20 private _erc20; // the TBN ERC20 token deployment IPresale private _presale; // the presale contract deployment // Note: 18 decimal precision accomodates ETH prices up to 10**5 uint256 private _ETHPrice; // ETH price in USD with 18 decimal precision for calculating reserve pricing uint256 private _reserveFloor; // the minimum possible reserve price in USD @ 18 decimal precision (set @ 0.0975 USD) uint256 private _reserveCeiling; // the maximum possible reserve price in USD @ 18 decimal precision (set @ 0.15 USD) uint256 private _reserveStep; // the base amount to step down the price if reserve is not met @ 18 decimals of precision (0.15-.0975/188 = .0000279255) uint256 private _crowdsaleAllocation; // total amount of TBN allocated to the crowdsale contract for distribution uint256 private _presaleDistribution; // total amount of TBN distributed to accounts in the presale contract uint256 private WEI_FACTOR = 10**18; // ETH base in WEI uint256 private INTERVAL_BLOCKS = 5520; // number of block per interval - 23 hours @ 15 sec per block uint256 private _rebaseNewPrice; // holds the rebase ETH price until rebasing in the next active interval @ decimal 18 uint256 private _rebased; // the interval the last rebase was set in, 0 if no rebasing has been done uint256 private _startBlock; // block number of the start of interval 0 uint256 private _tokensPerInterval; // number of tokens available for distribution each interval uint256 private _lastAdjustedInterval; // the most recent reserve adjusted interval mapping (uint256 => uint256) public intervalTotals; // total ETH contributed per interval struct Interval { uint256 reservePrice; // the reservePrice for this interval @ 18 decimals of precision uint256 ETHReserveAmount; } mapping (uint256 => Interval) public intervals; struct PresaleData { uint256 balance; uint256 remaining; bool setup; } mapping (address => PresaleData) public presaleData; mapping (uint256 => mapping (address => uint256)) public participationAmount; mapping (uint256 => mapping (address => bool)) public claimed; Stages public stages; /* * Enums */ enum Stages { CrowdsaleDeployed, Crowdsale, CrowdsaleEnded } /* * Modifiers */ modifier atStage(Stages _stage) { require(stages == _stage, "functionality not allowed at current stage"); _; } // update reserve adjustment and execute rebasing if ETH price was rebased last interval modifier update() { uint256 interval = getInterval(block.number); if(_lastAdjustedInterval != interval){ // check that the current interval was reserve adjusted for (uint i = _lastAdjustedInterval.add(1); i <= interval; i++) { // if not catch up adjustment until current interval _adjustReserve(i); } _lastAdjustedInterval = interval; } // we can rebase only if reserve ETH ajdustment is current (done above) if(_rebased == interval.sub(1)){ // check if the ETH price was rebased last interval _rebase(_rebaseNewPrice); _; } else { _; } } constructor( IERC20 token, IPresale presale, uint256 numberOfIntervals, bytes32 hiddenCap ) public { require(address(token) != 0x0, "token address cannot be 0x0"); require(address(presale) != 0x0, "presale address cannot be 0x0"); require(presale.getERC20() == address(token), "Presale contract must be assigned to the same ERC20 instance as this contract"); require(numberOfIntervals > 0, "numberOfIntervals must be larger than zero"); _numberOfIntervals = numberOfIntervals; _hiddenCap = hiddenCap; _erc20 = token; _presale = presale; stages = Stages.CrowdsaleDeployed; } /** * @dev Fallback participates with any ETH payment */ function () public payable { participate(0); } function getInterval(uint256 blockNumber) public view returns (uint256) { return _intervalFor(blockNumber); } function getERC20() public view returns (address) { return address(_erc20); } function getPresale() public view returns (address) { return address(_presale); } // rebase ETH participation depending on ETH and reserve pricing function getMin() public view atStage(Stages.Crowdsale) returns (uint256) { uint256 interval = getInterval(block.number); uint256 minETH; if (_ETHPrice < intervals[interval].reservePrice) { minETH = 10 ether; } else if (_ETHPrice < intervals[interval].reservePrice.mul(10)) { minETH = 1 ether; } else if (_ETHPrice < intervals[interval].reservePrice.mul(100)) { minETH = .1 ether; } else if (_ETHPrice < intervals[interval].reservePrice.mul(1000)) { minETH = .01 ether; } else { minETH = .001 ether; } return minETH; } // This method provides the participant some protections regarding the maximum price prior to // applying this payment that will be allowed. (price is in TBN per ETH) function participate(uint256 limit) public payable reChecks atStage(Stages.Crowdsale) returns (bool) { uint256 interval = getInterval(block.number); require(interval <= _numberOfIntervals, "interval of current block number must be less than or equal to the number of intervals"); require(msg.value >= getMin(), "minimum participation amount, enforced to prevent rounding errors in "); participationAmount[interval][msg.sender] = participationAmount[interval][msg.sender].add(msg.value); intervalTotals[interval] = intervalTotals[interval].add(msg.value); if (limit != 0) { require(_tokensPerInterval.div(intervalTotals[interval]) <= limit, ""); } emit Participated(interval, msg.sender, msg.value); return true; } function claim(uint256 interval) public reChecks atStage(Stages.Crowdsale) { require(stages == Stages.Crowdsale || stages == Stages.CrowdsaleEnded, "must be in the last two stages to call"); require(getInterval(block.number) > interval, "the given interval must be less than the current interval"); uint256 intervalClaim; if (_presale.presaleBalanceOf(account) == 0){ if (claimed[interval][msg.sender] || intervalTotals[interval] == 0) { return; } } uint256 contributorProportion = participationAmount[interval][msg.sender].mul(WEI_FACTOR).div(intervalTotals[interval]); uint256 reserveMultiplier; if (intervalTotals[interval] >= intervals[interval].ETHReserveAmount){ reserveMultiplier = WEI_FACTOR; } else { reserveMultiplier = intervalTotals[interval].mul(WEI_FACTOR).div(intervals[interval].ETHReserveAmount); } intervalClaim = _tokensPerInterval.mul(contributorProportion).mul(reserveMultiplier).div(WEI_FACTOR.mul(3)); // presale vesting intervalClaim = intervalClaim.add(_presaleVesting(msg.sender)); claimed[interval][msg.sender] = true; _erc20.transfer(msg.sender, intervalClaim); emit Claimed(interval, msg.sender, intervalClaim); } function _presaleVesting(address account) internal returns (uint256) { if(!presaleData[account].setup){ // intial assignment of an account's presale data uint256 totalPresaleAmount = _presale.presaleBalanceOf(account); presaleData[account].balance = totalPresaleAmount; presaleData[account].remaining = totalPresaleAmount; presaleData[account].setup = true; } uint256 vestRate; if(presaleData[account].balance <= _numberOfIntervals.mul(10**20)){ vestRate = 10**20; // this is 100 TBN (100 TBN is the minimum vesting amount per interval - except on last vest for account, vesting all remaining could be smaller) } else { vestRate = presaleData[account].balance.div(_numberOfIntervals); } assert(vestRate >= 10**20); // the above guarantees this if (presaleData[account].remaining > 0){ // check if there is any remaining balance to vest if (vestRate <= presaleData[account].remaining) { // check if set vest rate is <= remaining presaleData[account].remaining = presaleData[account].remaining.sub(vestRate); emit PresaleVest(account, vestRate); return vestRate; } else { vestRate = presaleData[account].remaining; // vest all remaining, as it is less than this accounts interval vest amount presaleData[account].remaining = presaleData[account].remaining.sub(vestRate); emit PresaleVest(account, vestRate); return vestRate; } } else { // no remaining balance to vest return 0; } } function claimAll() public atStage(Stages.Crowdsale) { for (uint i = 0; i < getInterval(block.number); i++) { claim(i); } } function initialize( uint256 ETHPrice, uint256 reserveFloor, uint256 reserveCeiling, uint256 crowdsaleAllocation ) external onlyManager atStage(Stages.CrowdsaleDeployed) returns (bool) { require(ETHPrice > 0, "ETH basis price must be greater than 0"); require(reserveFloor > 0, "the reserve floor must be greater than 0"); require(reserveCeiling > reserveFloor.add(_numberOfIntervals), "the reserve ceiling must be _numberOfIntervals WEI greater than the reserve floor"); require(crowdsaleAllocation > 0, "crowdsale allocation must be assigned a number greater than 0"); address fundkeeper = _erc20.fundkeeper(); require(_erc20.allowance(address(fundkeeper), address(this)) == crowdsaleAllocation, "crowdsale allocation must be equal to the amount of tokens approved for this contract"); require(_presale.getCrowdsale() == address(this), " crowdsale contract address has not been set in the presale contract yet"); _ETHPrice = ETHPrice; _crowdsaleAllocation = crowdsaleAllocation; _reserveFloor = reserveFloor; _reserveCeiling = reserveCeiling; _reserveStep = (_reserveCeiling.sub(_reserveFloor)).div(_numberOfIntervals); // calc initial intervalReserve uint256 interval = getInterval(block.number); intervals[interval].reservePrice = (_reserveCeiling.mul(WEI_FACTOR)).div(_ETHPrice); intervals[interval].ETHReserveAmount = _tokensPerInterval.mul(intervals[interval].reservePrice); // place crowdsale allocation in this contract _erc20.transferFrom(fundkeeper, address(this), crowdsaleAllocation); // end the Presale Stage of the presale contract (therby locking any presale account updates and transferring the distributed presale tokens to this contract for vested claiming) _presale.presaleEnd(); uint256 presaleDistribution = _presale.getPresaleDistribution(); // this can no longer change and is the amount sent to this contract form the presale contract _presaleDistribution = presaleDistribution; //create variables _startBlock = block.number; _tokensPerInterval = crowdsaleAllocation.div(_numberOfIntervals); stages = Stages.Crowdsale; return true; } /** * @dev Safety function for recovering missent ERC20 tokens * @param token address of the ERC20 contract */ function recoverToken(IERC20 token) external onlyRecoverer atStage(Stages.CrowdsaleEnded) returns (bool) { token.transfer(msg.sender, token.balanceOf(address(this))); return true; } // crowdsale manager can rebase the ETH price (rebase will be applied to the next interval) function setRebase(uint256 newETHPrice) external onlyManager atStage(Stages.Crowdsale) returns (bool) { uint256 interval = getInterval(block.number); require(interval > 0, "cannot rebase in the initial interval"); _rebaseNewPrice = newETHPrice; _rebased = interval; return true; } // reveal hidden cap (and end sale early) function revealCap(uint256 cap, uint256 secret) external onlyManager atStage(Stages.Crowdsale) returns (bool) { bytes32 hashed = keccak256(abi.encode(cap, secret)); if (hashed == _hiddenCap) { stages = Stages.CrowdsaleEnded; return true; } return false; } // Fundkeeper can collect ETH any number of times function collect() external onlyFundkeeper returns (bool) { msg.sender.transfer(address(this).balance); emit Collected(msg.sender, address(this).balance); } function _rebase(uint256 newETHPrice) internal onlyManager atStage(Stages.Crowdsale) { uint256 interval = getInterval(block.number); // new ETH base price _ETHPrice = newETHPrice; // recalc ETH reserve Price intervals[interval].reservePrice = (_reserveCeiling.mul(WEI_FACTOR)).div(_ETHPrice); // recalc ETH reserve amount intervals[interval].ETHReserveAmount = _tokensPerInterval.mul(intervals[interval].reservePrice); // reset _rebaseNewPrice to 0 _rebaseNewPrice = 0; emit Rebased( _ETHPrice, intervals[interval].ETHReserveAmount ); } // Each window is 23 hours long so that end-of-window rotates // around the clock for all timezones. function _intervalFor(uint256 blockNumber) internal view returns (uint256) { return blockNumber < _startBlock ? 0 : blockNumber.sub(_startBlock).div(INTERVAL_BLOCKS); } function _adjustReserve(uint256 interval) internal { require(interval > 0, "cannot adjust the intial interval reserve"); // get last reserve info uint256 lastReserveAmount = intervals[interval.sub(1)].ETHReserveAmount; uint256 lastIntervalPrice = intervals[interval.sub(1)].reservePrice; // check if last reserve was met uint256 adjustment; // adjust reservePrice accordingly if (intervalTotals[interval.sub(1)] >= lastReserveAmount){ // reserve ETH was met last interval uint ceiling = (_reserveCeiling.mul(WEI_FACTOR)).div(_ETHPrice); if(lastReserveAmount == _tokensPerInterval.mul(ceiling)){ // lastReserveAmount was equal to the max reserve ETH intervals[interval].reservePrice = ceiling; // reserve price cannot go above ceiling } else { // reserve met but lastReserveAmount was less than max reserve intervals[interval].reservePrice = intervalTotals[interval.sub(1)].mul(_ETHPrice).div(_tokensPerInterval); intervals[interval].ETHReserveAmount = _tokensPerInterval.mul(intervals[interval].reservePrice); } } else { uint256 offset = WEI_FACTOR.sub(intervalTotals[_lastAdjustedInterval].mul(WEI_FACTOR).div(intervals[_lastAdjustedInterval].ETHReserveAmount)); if (offset < 10**17) { adjustment = 1; } else if(offset != WEI_FACTOR) { adjustment = (offset.div(10**17)).add(1); } else { adjustment = 10; } uint256 newReservePrice = intervals[interval].reservePrice.sub(_reserveStep.mul(adjustment)); if(newReservePrice <= _reserveFloor){ intervals[interval].reservePrice = _reserveFloor; } else { intervals[interval].reservePrice = newReservePrice; } } // calculate reserveAmount intervals[interval].ETHReserveAmount = _tokensPerInterval.mul(intervals[interval].reservePrice.mul(WEI_FACTOR).div(_ETHPrice)); } }
Fundkeeper can collect ETH any number of times
function collect() external onlyFundkeeper returns (bool) { msg.sender.transfer(address(this).balance); emit Collected(msg.sender, address(this).balance); }
13,111,089
[ 1, 42, 1074, 79, 9868, 848, 3274, 512, 2455, 1281, 1300, 434, 4124, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 3274, 1435, 3903, 1338, 42, 1074, 79, 9868, 1135, 261, 6430, 13, 288, 203, 3639, 1234, 18, 15330, 18, 13866, 12, 2867, 12, 2211, 2934, 12296, 1769, 203, 3639, 3626, 9302, 329, 12, 3576, 18, 15330, 16, 1758, 12, 2211, 2934, 12296, 1769, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/295/0x0000000000000000000000000000000000233233/sources/HederaResponseCodes.sol
Any of the token Ids in customFees is invalid
int32 internal constant INVALID_TOKEN_ID_IN_CUSTOM_FEES = 234;
4,664,334
[ 1, 2961, 434, 326, 1147, 29085, 316, 1679, 2954, 281, 353, 2057, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 509, 1578, 2713, 5381, 10071, 67, 8412, 67, 734, 67, 706, 67, 15136, 67, 8090, 3991, 273, 576, 5026, 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 ]
./full_match/1/0x3eE100d5559c3D058D1eC5936084D37D360ED008/sources/browser/HEXMONEY.sol
///HEXMONEY TOKEN CONTRACT//uniswap setuphex contract setuptransform roommint / freezetokenomicsmultisigadminteamminters
contract HEXMONEY is IERC20, TokenEvents { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; address internal uniFactory = 0xc0a47dFe034B400B47bDaD5FecDa2621de6c4d95; address internal uniETHHEX = 0x05cDe89cCfa0adA8C88D5A23caaa79Ef129E7883; address public uniETHHXY = address(0); UniswapExchangeInterface internal uniHEXInterface = UniswapExchangeInterface(uniETHHEX); UniswapExchangeInterface internal uniHXYInterface; UniswapFactoryInterface internal uniFactoryInterface = UniswapFactoryInterface(uniFactory); uint uniswapLiquidityTokens = 0; address internal hexAddress = 0x2b591e99afE9f32eAA6214f7B7629768c40Eeb39; HEX internal hexInterface = HEX(hexAddress); uint public ethForLiquidity = 0; bool public roomActive; uint public roundCap = 0; uint public roundTransformed = 0; uint public totalHeartsTransformed = 0; uint public totalHXYTransformed = 0; uint public distributable = 0; uint public liquidityReserve = 0; uint public unlockLvl = 0; uint public lockStartTimestamp = 0; uint public lockedTokens = 0; uint public totalFrozen = 0; uint256 internal _totalSupply; string public constant name = "HEX Money"; string public constant symbol = "HXY"; uint public constant decimals = 8; address payable internal MULTISIG = 0x35C7a87EbC3E9fBfd2a31579c70f0A2A8D4De4c5; address payable internal FOUNDER = 0xc61f905832aE9FB6Ef5BaD8CF6e5b8B5aE1DF026; address payable internal KYLE = 0xD30BC4859A79852157211E6db19dE159673a67E2; address payable internal MICHAEL = 0xe551072153c02fa33d4903CAb0435Fb86F1a80cb; address payable internal SWIFT = 0x7251FFB72C77221D16e6e04c9CD309EfFd0F940D; address payable internal MARCO = 0xbf1984B12878c6A25f0921535c76C05a60bdEf39; address payable internal MARK = 0x35e9034f47cc00b8A9b555fC1FDB9598b2c245fD; address payable internal JARED = 0x5eCb4D3B4b451b838242c3CF8404ef18f5C486aB; address payable internal LOUIS = 0x454f203260a74C0A8B5c0a78fbA5B4e8B31dCC63; address payable internal LOTTO = 0x1EF0Bab01329a6CE39e92eA6B88828430B1Cd91f; address payable internal DONATOR = 0x723e82Eb1A1b419Fb36e9bD65E50A979cd13d341; address payable internal KEVIN = 0x3487b398546C9b757921df6dE78EC308203f5830; address payable internal AMIRIS = 0x406D1fC98D231aD69807Cd41d4D6F8273401354f; mapping(address => bool) admins; mapping(address => bool) minters; mapping (address => Frozen) public frozen; struct Frozen{ uint freezeStartTimestamp; uint freezeLength; uint daysPast; } modifier onlyMultisig(){ require(msg.sender == MULTISIG, "not authorized"); _; } modifier onlyAdmins(){ require(admins[msg.sender], "not an admin"); _; } modifier onlyMinters(){ require(minters[msg.sender], "not a minter"); _; } constructor() public { admins[FOUNDER] = true; admins[KYLE] = true; admins[MARCO] = true; admins[SWIFT] = true; admins[MICHAEL] = true; admins[msg.sender] = true; uniETHHXY = uniFactoryInterface.createExchange(address(this)); uniHXYInterface = UniswapExchangeInterface(uniETHHXY); } receive() external payable{ donate(); } function _initialLiquidity() onlyAdmins payable public { require(msg.value >= 0.001 ether, "eth value too low"); uint hxy = heartsForEth / mintRatio; } function _addLiquidity() onlyAdmins payable public { require(roomActive); require(ethForLiquidity > 0 || msg.value > 0, "no eth available"); if(msg.value > 0){ ethForLiquidity += msg.value; } _approve(address(this), uniETHHXY, balanceOf(address(this))); ethForLiquidity = 0; } function _addLiquidity() onlyAdmins payable public { require(roomActive); require(ethForLiquidity > 0 || msg.value > 0, "no eth available"); if(msg.value > 0){ ethForLiquidity += msg.value; } _approve(address(this), uniETHHXY, balanceOf(address(this))); ethForLiquidity = 0; } function swapToEth() public { require(liquidityReserve > 0); hexInterface.approve(uniETHHEX, liquidityReserve); liquidityReserve = 0; } function totalSupply() public view override returns (uint256) { return _totalSupply; } function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(msg.sender, 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(msg.sender, spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } 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); } function _mint(address account, uint256 amount) internal { uint256 amt = amount; require(account != address(0), "ERC20: mint to the zero address"); if(!mintBlock){ if(_totalSupply < _maxSupply){ if(_totalSupply.add(amt) > _maxSupply){ amt = _maxSupply.sub(_totalSupply); _totalSupply = _maxSupply; mintBlock = true; } else{ _totalSupply = _totalSupply.add(amt); } _balances[account] = _balances[account].add(amt); emit Transfer(address(0), account, amt); } } } function _mint(address account, uint256 amount) internal { uint256 amt = amount; require(account != address(0), "ERC20: mint to the zero address"); if(!mintBlock){ if(_totalSupply < _maxSupply){ if(_totalSupply.add(amt) > _maxSupply){ amt = _maxSupply.sub(_totalSupply); _totalSupply = _maxSupply; mintBlock = true; } else{ _totalSupply = _totalSupply.add(amt); } _balances[account] = _balances[account].add(amt); emit Transfer(address(0), account, amt); } } } function _mint(address account, uint256 amount) internal { uint256 amt = amount; require(account != address(0), "ERC20: mint to the zero address"); if(!mintBlock){ if(_totalSupply < _maxSupply){ if(_totalSupply.add(amt) > _maxSupply){ amt = _maxSupply.sub(_totalSupply); _totalSupply = _maxSupply; mintBlock = true; } else{ _totalSupply = _totalSupply.add(amt); } _balances[account] = _balances[account].add(amt); emit Transfer(address(0), account, amt); } } } function _mint(address account, uint256 amount) internal { uint256 amt = amount; require(account != address(0), "ERC20: mint to the zero address"); if(!mintBlock){ if(_totalSupply < _maxSupply){ if(_totalSupply.add(amt) > _maxSupply){ amt = _maxSupply.sub(_totalSupply); _totalSupply = _maxSupply; mintBlock = true; } else{ _totalSupply = _totalSupply.add(amt); } _balances[account] = _balances[account].add(amt); emit Transfer(address(0), account, amt); } } } function _mint(address account, uint256 amount) internal { uint256 amt = amount; require(account != address(0), "ERC20: mint to the zero address"); if(!mintBlock){ if(_totalSupply < _maxSupply){ if(_totalSupply.add(amt) > _maxSupply){ amt = _maxSupply.sub(_totalSupply); _totalSupply = _maxSupply; mintBlock = true; } else{ _totalSupply = _totalSupply.add(amt); } _balances[account] = _balances[account].add(amt); emit Transfer(address(0), account, amt); } } } 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); } 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); } function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve(account, msg.sender, _allowances[account][msg.sender].sub(amount, "ERC20: burn amount exceeds allowance")); } event Approval(address indexed owner, address indexed spender, uint256 value); function mintFounderTokens(uint tokens) internal returns(bool) { require(tokens <= _maxSupply.mul(20).div(100), "founder tokens cannot be over 20%"); address minter = FOUNDER; lock(tokens/2); return true; } function lock(uint tokens) internal { lockStartTimestamp = now; lockedTokens = tokens; } function unlock() public onlyAdmins { uint sixMonths = lockDayLength/10; require(unlockLvl < 10, "token unlock complete"); uint value = lockedTokens/10; if(lockStartTimestamp.add((sixMonths).mul(daySeconds)) <= now && unlockLvl == 0){ transfer(FOUNDER, value); unlockLvl++; } else if(lockStartTimestamp.add((sixMonths * 2).mul(daySeconds)) <= now && unlockLvl == 1){ transfer(FOUNDER, value); unlockLvl++; } else if(lockStartTimestamp.add((sixMonths * 3).mul(daySeconds)) <= now && unlockLvl == 2){ transfer(FOUNDER, value); unlockLvl++; } else if(lockStartTimestamp.add((sixMonths * 4).mul(daySeconds)) <= now && unlockLvl == 3){ transfer(FOUNDER, value); unlockLvl++; } else if(lockStartTimestamp.add((sixMonths * 5).mul(daySeconds)) <= now && unlockLvl == 4){ transfer(FOUNDER, value); unlockLvl++; } else if(lockStartTimestamp.add((sixMonths * 6).mul(daySeconds)) <= now && unlockLvl == 5){ transfer(FOUNDER, value); unlockLvl++; } else if(lockStartTimestamp.add((sixMonths * 7).mul(daySeconds)) <= now && unlockLvl == 6){ transfer(FOUNDER, value); unlockLvl++; } else if(lockStartTimestamp.add((sixMonths * 8).mul(daySeconds)) <= now && unlockLvl == 7) { transfer(FOUNDER, value); unlockLvl++; } else if(lockStartTimestamp.add((sixMonths * 9).mul(daySeconds)) <= now && unlockLvl == 8){ transfer(FOUNDER, value); unlockLvl++; } else if(lockStartTimestamp.add((sixMonths * 10).mul(daySeconds)) <= now && unlockLvl == 9){ transfer(FOUNDER, value); unlockLvl++; } else{ revert(); } } function unlock() public onlyAdmins { uint sixMonths = lockDayLength/10; require(unlockLvl < 10, "token unlock complete"); uint value = lockedTokens/10; if(lockStartTimestamp.add((sixMonths).mul(daySeconds)) <= now && unlockLvl == 0){ transfer(FOUNDER, value); unlockLvl++; } else if(lockStartTimestamp.add((sixMonths * 2).mul(daySeconds)) <= now && unlockLvl == 1){ transfer(FOUNDER, value); unlockLvl++; } else if(lockStartTimestamp.add((sixMonths * 3).mul(daySeconds)) <= now && unlockLvl == 2){ transfer(FOUNDER, value); unlockLvl++; } else if(lockStartTimestamp.add((sixMonths * 4).mul(daySeconds)) <= now && unlockLvl == 3){ transfer(FOUNDER, value); unlockLvl++; } else if(lockStartTimestamp.add((sixMonths * 5).mul(daySeconds)) <= now && unlockLvl == 4){ transfer(FOUNDER, value); unlockLvl++; } else if(lockStartTimestamp.add((sixMonths * 6).mul(daySeconds)) <= now && unlockLvl == 5){ transfer(FOUNDER, value); unlockLvl++; } else if(lockStartTimestamp.add((sixMonths * 7).mul(daySeconds)) <= now && unlockLvl == 6){ transfer(FOUNDER, value); unlockLvl++; } else if(lockStartTimestamp.add((sixMonths * 8).mul(daySeconds)) <= now && unlockLvl == 7) { transfer(FOUNDER, value); unlockLvl++; } else if(lockStartTimestamp.add((sixMonths * 9).mul(daySeconds)) <= now && unlockLvl == 8){ transfer(FOUNDER, value); unlockLvl++; } else if(lockStartTimestamp.add((sixMonths * 10).mul(daySeconds)) <= now && unlockLvl == 9){ transfer(FOUNDER, value); unlockLvl++; } else{ revert(); } } function unlock() public onlyAdmins { uint sixMonths = lockDayLength/10; require(unlockLvl < 10, "token unlock complete"); uint value = lockedTokens/10; if(lockStartTimestamp.add((sixMonths).mul(daySeconds)) <= now && unlockLvl == 0){ transfer(FOUNDER, value); unlockLvl++; } else if(lockStartTimestamp.add((sixMonths * 2).mul(daySeconds)) <= now && unlockLvl == 1){ transfer(FOUNDER, value); unlockLvl++; } else if(lockStartTimestamp.add((sixMonths * 3).mul(daySeconds)) <= now && unlockLvl == 2){ transfer(FOUNDER, value); unlockLvl++; } else if(lockStartTimestamp.add((sixMonths * 4).mul(daySeconds)) <= now && unlockLvl == 3){ transfer(FOUNDER, value); unlockLvl++; } else if(lockStartTimestamp.add((sixMonths * 5).mul(daySeconds)) <= now && unlockLvl == 4){ transfer(FOUNDER, value); unlockLvl++; } else if(lockStartTimestamp.add((sixMonths * 6).mul(daySeconds)) <= now && unlockLvl == 5){ transfer(FOUNDER, value); unlockLvl++; } else if(lockStartTimestamp.add((sixMonths * 7).mul(daySeconds)) <= now && unlockLvl == 6){ transfer(FOUNDER, value); unlockLvl++; } else if(lockStartTimestamp.add((sixMonths * 8).mul(daySeconds)) <= now && unlockLvl == 7) { transfer(FOUNDER, value); unlockLvl++; } else if(lockStartTimestamp.add((sixMonths * 9).mul(daySeconds)) <= now && unlockLvl == 8){ transfer(FOUNDER, value); unlockLvl++; } else if(lockStartTimestamp.add((sixMonths * 10).mul(daySeconds)) <= now && unlockLvl == 9){ transfer(FOUNDER, value); unlockLvl++; } else{ revert(); } } function unlock() public onlyAdmins { uint sixMonths = lockDayLength/10; require(unlockLvl < 10, "token unlock complete"); uint value = lockedTokens/10; if(lockStartTimestamp.add((sixMonths).mul(daySeconds)) <= now && unlockLvl == 0){ transfer(FOUNDER, value); unlockLvl++; } else if(lockStartTimestamp.add((sixMonths * 2).mul(daySeconds)) <= now && unlockLvl == 1){ transfer(FOUNDER, value); unlockLvl++; } else if(lockStartTimestamp.add((sixMonths * 3).mul(daySeconds)) <= now && unlockLvl == 2){ transfer(FOUNDER, value); unlockLvl++; } else if(lockStartTimestamp.add((sixMonths * 4).mul(daySeconds)) <= now && unlockLvl == 3){ transfer(FOUNDER, value); unlockLvl++; } else if(lockStartTimestamp.add((sixMonths * 5).mul(daySeconds)) <= now && unlockLvl == 4){ transfer(FOUNDER, value); unlockLvl++; } else if(lockStartTimestamp.add((sixMonths * 6).mul(daySeconds)) <= now && unlockLvl == 5){ transfer(FOUNDER, value); unlockLvl++; } else if(lockStartTimestamp.add((sixMonths * 7).mul(daySeconds)) <= now && unlockLvl == 6){ transfer(FOUNDER, value); unlockLvl++; } else if(lockStartTimestamp.add((sixMonths * 8).mul(daySeconds)) <= now && unlockLvl == 7) { transfer(FOUNDER, value); unlockLvl++; } else if(lockStartTimestamp.add((sixMonths * 9).mul(daySeconds)) <= now && unlockLvl == 8){ transfer(FOUNDER, value); unlockLvl++; } else if(lockStartTimestamp.add((sixMonths * 10).mul(daySeconds)) <= now && unlockLvl == 9){ transfer(FOUNDER, value); unlockLvl++; } else{ revert(); } } function unlock() public onlyAdmins { uint sixMonths = lockDayLength/10; require(unlockLvl < 10, "token unlock complete"); uint value = lockedTokens/10; if(lockStartTimestamp.add((sixMonths).mul(daySeconds)) <= now && unlockLvl == 0){ transfer(FOUNDER, value); unlockLvl++; } else if(lockStartTimestamp.add((sixMonths * 2).mul(daySeconds)) <= now && unlockLvl == 1){ transfer(FOUNDER, value); unlockLvl++; } else if(lockStartTimestamp.add((sixMonths * 3).mul(daySeconds)) <= now && unlockLvl == 2){ transfer(FOUNDER, value); unlockLvl++; } else if(lockStartTimestamp.add((sixMonths * 4).mul(daySeconds)) <= now && unlockLvl == 3){ transfer(FOUNDER, value); unlockLvl++; } else if(lockStartTimestamp.add((sixMonths * 5).mul(daySeconds)) <= now && unlockLvl == 4){ transfer(FOUNDER, value); unlockLvl++; } else if(lockStartTimestamp.add((sixMonths * 6).mul(daySeconds)) <= now && unlockLvl == 5){ transfer(FOUNDER, value); unlockLvl++; } else if(lockStartTimestamp.add((sixMonths * 7).mul(daySeconds)) <= now && unlockLvl == 6){ transfer(FOUNDER, value); unlockLvl++; } else if(lockStartTimestamp.add((sixMonths * 8).mul(daySeconds)) <= now && unlockLvl == 7) { transfer(FOUNDER, value); unlockLvl++; } else if(lockStartTimestamp.add((sixMonths * 9).mul(daySeconds)) <= now && unlockLvl == 8){ transfer(FOUNDER, value); unlockLvl++; } else if(lockStartTimestamp.add((sixMonths * 10).mul(daySeconds)) <= now && unlockLvl == 9){ transfer(FOUNDER, value); unlockLvl++; } else{ revert(); } } function unlock() public onlyAdmins { uint sixMonths = lockDayLength/10; require(unlockLvl < 10, "token unlock complete"); uint value = lockedTokens/10; if(lockStartTimestamp.add((sixMonths).mul(daySeconds)) <= now && unlockLvl == 0){ transfer(FOUNDER, value); unlockLvl++; } else if(lockStartTimestamp.add((sixMonths * 2).mul(daySeconds)) <= now && unlockLvl == 1){ transfer(FOUNDER, value); unlockLvl++; } else if(lockStartTimestamp.add((sixMonths * 3).mul(daySeconds)) <= now && unlockLvl == 2){ transfer(FOUNDER, value); unlockLvl++; } else if(lockStartTimestamp.add((sixMonths * 4).mul(daySeconds)) <= now && unlockLvl == 3){ transfer(FOUNDER, value); unlockLvl++; } else if(lockStartTimestamp.add((sixMonths * 5).mul(daySeconds)) <= now && unlockLvl == 4){ transfer(FOUNDER, value); unlockLvl++; } else if(lockStartTimestamp.add((sixMonths * 6).mul(daySeconds)) <= now && unlockLvl == 5){ transfer(FOUNDER, value); unlockLvl++; } else if(lockStartTimestamp.add((sixMonths * 7).mul(daySeconds)) <= now && unlockLvl == 6){ transfer(FOUNDER, value); unlockLvl++; } else if(lockStartTimestamp.add((sixMonths * 8).mul(daySeconds)) <= now && unlockLvl == 7) { transfer(FOUNDER, value); unlockLvl++; } else if(lockStartTimestamp.add((sixMonths * 9).mul(daySeconds)) <= now && unlockLvl == 8){ transfer(FOUNDER, value); unlockLvl++; } else if(lockStartTimestamp.add((sixMonths * 10).mul(daySeconds)) <= now && unlockLvl == 9){ transfer(FOUNDER, value); unlockLvl++; } else{ revert(); } } function unlock() public onlyAdmins { uint sixMonths = lockDayLength/10; require(unlockLvl < 10, "token unlock complete"); uint value = lockedTokens/10; if(lockStartTimestamp.add((sixMonths).mul(daySeconds)) <= now && unlockLvl == 0){ transfer(FOUNDER, value); unlockLvl++; } else if(lockStartTimestamp.add((sixMonths * 2).mul(daySeconds)) <= now && unlockLvl == 1){ transfer(FOUNDER, value); unlockLvl++; } else if(lockStartTimestamp.add((sixMonths * 3).mul(daySeconds)) <= now && unlockLvl == 2){ transfer(FOUNDER, value); unlockLvl++; } else if(lockStartTimestamp.add((sixMonths * 4).mul(daySeconds)) <= now && unlockLvl == 3){ transfer(FOUNDER, value); unlockLvl++; } else if(lockStartTimestamp.add((sixMonths * 5).mul(daySeconds)) <= now && unlockLvl == 4){ transfer(FOUNDER, value); unlockLvl++; } else if(lockStartTimestamp.add((sixMonths * 6).mul(daySeconds)) <= now && unlockLvl == 5){ transfer(FOUNDER, value); unlockLvl++; } else if(lockStartTimestamp.add((sixMonths * 7).mul(daySeconds)) <= now && unlockLvl == 6){ transfer(FOUNDER, value); unlockLvl++; } else if(lockStartTimestamp.add((sixMonths * 8).mul(daySeconds)) <= now && unlockLvl == 7) { transfer(FOUNDER, value); unlockLvl++; } else if(lockStartTimestamp.add((sixMonths * 9).mul(daySeconds)) <= now && unlockLvl == 8){ transfer(FOUNDER, value); unlockLvl++; } else if(lockStartTimestamp.add((sixMonths * 10).mul(daySeconds)) <= now && unlockLvl == 9){ transfer(FOUNDER, value); unlockLvl++; } else{ revert(); } } function unlock() public onlyAdmins { uint sixMonths = lockDayLength/10; require(unlockLvl < 10, "token unlock complete"); uint value = lockedTokens/10; if(lockStartTimestamp.add((sixMonths).mul(daySeconds)) <= now && unlockLvl == 0){ transfer(FOUNDER, value); unlockLvl++; } else if(lockStartTimestamp.add((sixMonths * 2).mul(daySeconds)) <= now && unlockLvl == 1){ transfer(FOUNDER, value); unlockLvl++; } else if(lockStartTimestamp.add((sixMonths * 3).mul(daySeconds)) <= now && unlockLvl == 2){ transfer(FOUNDER, value); unlockLvl++; } else if(lockStartTimestamp.add((sixMonths * 4).mul(daySeconds)) <= now && unlockLvl == 3){ transfer(FOUNDER, value); unlockLvl++; } else if(lockStartTimestamp.add((sixMonths * 5).mul(daySeconds)) <= now && unlockLvl == 4){ transfer(FOUNDER, value); unlockLvl++; } else if(lockStartTimestamp.add((sixMonths * 6).mul(daySeconds)) <= now && unlockLvl == 5){ transfer(FOUNDER, value); unlockLvl++; } else if(lockStartTimestamp.add((sixMonths * 7).mul(daySeconds)) <= now && unlockLvl == 6){ transfer(FOUNDER, value); unlockLvl++; } else if(lockStartTimestamp.add((sixMonths * 8).mul(daySeconds)) <= now && unlockLvl == 7) { transfer(FOUNDER, value); unlockLvl++; } else if(lockStartTimestamp.add((sixMonths * 9).mul(daySeconds)) <= now && unlockLvl == 8){ transfer(FOUNDER, value); unlockLvl++; } else if(lockStartTimestamp.add((sixMonths * 10).mul(daySeconds)) <= now && unlockLvl == 9){ transfer(FOUNDER, value); unlockLvl++; } else{ revert(); } } function unlock() public onlyAdmins { uint sixMonths = lockDayLength/10; require(unlockLvl < 10, "token unlock complete"); uint value = lockedTokens/10; if(lockStartTimestamp.add((sixMonths).mul(daySeconds)) <= now && unlockLvl == 0){ transfer(FOUNDER, value); unlockLvl++; } else if(lockStartTimestamp.add((sixMonths * 2).mul(daySeconds)) <= now && unlockLvl == 1){ transfer(FOUNDER, value); unlockLvl++; } else if(lockStartTimestamp.add((sixMonths * 3).mul(daySeconds)) <= now && unlockLvl == 2){ transfer(FOUNDER, value); unlockLvl++; } else if(lockStartTimestamp.add((sixMonths * 4).mul(daySeconds)) <= now && unlockLvl == 3){ transfer(FOUNDER, value); unlockLvl++; } else if(lockStartTimestamp.add((sixMonths * 5).mul(daySeconds)) <= now && unlockLvl == 4){ transfer(FOUNDER, value); unlockLvl++; } else if(lockStartTimestamp.add((sixMonths * 6).mul(daySeconds)) <= now && unlockLvl == 5){ transfer(FOUNDER, value); unlockLvl++; } else if(lockStartTimestamp.add((sixMonths * 7).mul(daySeconds)) <= now && unlockLvl == 6){ transfer(FOUNDER, value); unlockLvl++; } else if(lockStartTimestamp.add((sixMonths * 8).mul(daySeconds)) <= now && unlockLvl == 7) { transfer(FOUNDER, value); unlockLvl++; } else if(lockStartTimestamp.add((sixMonths * 9).mul(daySeconds)) <= now && unlockLvl == 8){ transfer(FOUNDER, value); unlockLvl++; } else if(lockStartTimestamp.add((sixMonths * 10).mul(daySeconds)) <= now && unlockLvl == 9){ transfer(FOUNDER, value); unlockLvl++; } else{ revert(); } } function unlock() public onlyAdmins { uint sixMonths = lockDayLength/10; require(unlockLvl < 10, "token unlock complete"); uint value = lockedTokens/10; if(lockStartTimestamp.add((sixMonths).mul(daySeconds)) <= now && unlockLvl == 0){ transfer(FOUNDER, value); unlockLvl++; } else if(lockStartTimestamp.add((sixMonths * 2).mul(daySeconds)) <= now && unlockLvl == 1){ transfer(FOUNDER, value); unlockLvl++; } else if(lockStartTimestamp.add((sixMonths * 3).mul(daySeconds)) <= now && unlockLvl == 2){ transfer(FOUNDER, value); unlockLvl++; } else if(lockStartTimestamp.add((sixMonths * 4).mul(daySeconds)) <= now && unlockLvl == 3){ transfer(FOUNDER, value); unlockLvl++; } else if(lockStartTimestamp.add((sixMonths * 5).mul(daySeconds)) <= now && unlockLvl == 4){ transfer(FOUNDER, value); unlockLvl++; } else if(lockStartTimestamp.add((sixMonths * 6).mul(daySeconds)) <= now && unlockLvl == 5){ transfer(FOUNDER, value); unlockLvl++; } else if(lockStartTimestamp.add((sixMonths * 7).mul(daySeconds)) <= now && unlockLvl == 6){ transfer(FOUNDER, value); unlockLvl++; } else if(lockStartTimestamp.add((sixMonths * 8).mul(daySeconds)) <= now && unlockLvl == 7) { transfer(FOUNDER, value); unlockLvl++; } else if(lockStartTimestamp.add((sixMonths * 9).mul(daySeconds)) <= now && unlockLvl == 8){ transfer(FOUNDER, value); unlockLvl++; } else if(lockStartTimestamp.add((sixMonths * 10).mul(daySeconds)) <= now && unlockLvl == 9){ transfer(FOUNDER, value); unlockLvl++; } else{ revert(); } } function unlock() public onlyAdmins { uint sixMonths = lockDayLength/10; require(unlockLvl < 10, "token unlock complete"); uint value = lockedTokens/10; if(lockStartTimestamp.add((sixMonths).mul(daySeconds)) <= now && unlockLvl == 0){ transfer(FOUNDER, value); unlockLvl++; } else if(lockStartTimestamp.add((sixMonths * 2).mul(daySeconds)) <= now && unlockLvl == 1){ transfer(FOUNDER, value); unlockLvl++; } else if(lockStartTimestamp.add((sixMonths * 3).mul(daySeconds)) <= now && unlockLvl == 2){ transfer(FOUNDER, value); unlockLvl++; } else if(lockStartTimestamp.add((sixMonths * 4).mul(daySeconds)) <= now && unlockLvl == 3){ transfer(FOUNDER, value); unlockLvl++; } else if(lockStartTimestamp.add((sixMonths * 5).mul(daySeconds)) <= now && unlockLvl == 4){ transfer(FOUNDER, value); unlockLvl++; } else if(lockStartTimestamp.add((sixMonths * 6).mul(daySeconds)) <= now && unlockLvl == 5){ transfer(FOUNDER, value); unlockLvl++; } else if(lockStartTimestamp.add((sixMonths * 7).mul(daySeconds)) <= now && unlockLvl == 6){ transfer(FOUNDER, value); unlockLvl++; } else if(lockStartTimestamp.add((sixMonths * 8).mul(daySeconds)) <= now && unlockLvl == 7) { transfer(FOUNDER, value); unlockLvl++; } else if(lockStartTimestamp.add((sixMonths * 9).mul(daySeconds)) <= now && unlockLvl == 8){ transfer(FOUNDER, value); unlockLvl++; } else if(lockStartTimestamp.add((sixMonths * 10).mul(daySeconds)) <= now && unlockLvl == 9){ transfer(FOUNDER, value); unlockLvl++; } else{ revert(); } } function unlock() public onlyAdmins { uint sixMonths = lockDayLength/10; require(unlockLvl < 10, "token unlock complete"); uint value = lockedTokens/10; if(lockStartTimestamp.add((sixMonths).mul(daySeconds)) <= now && unlockLvl == 0){ transfer(FOUNDER, value); unlockLvl++; } else if(lockStartTimestamp.add((sixMonths * 2).mul(daySeconds)) <= now && unlockLvl == 1){ transfer(FOUNDER, value); unlockLvl++; } else if(lockStartTimestamp.add((sixMonths * 3).mul(daySeconds)) <= now && unlockLvl == 2){ transfer(FOUNDER, value); unlockLvl++; } else if(lockStartTimestamp.add((sixMonths * 4).mul(daySeconds)) <= now && unlockLvl == 3){ transfer(FOUNDER, value); unlockLvl++; } else if(lockStartTimestamp.add((sixMonths * 5).mul(daySeconds)) <= now && unlockLvl == 4){ transfer(FOUNDER, value); unlockLvl++; } else if(lockStartTimestamp.add((sixMonths * 6).mul(daySeconds)) <= now && unlockLvl == 5){ transfer(FOUNDER, value); unlockLvl++; } else if(lockStartTimestamp.add((sixMonths * 7).mul(daySeconds)) <= now && unlockLvl == 6){ transfer(FOUNDER, value); unlockLvl++; } else if(lockStartTimestamp.add((sixMonths * 8).mul(daySeconds)) <= now && unlockLvl == 7) { transfer(FOUNDER, value); unlockLvl++; } else if(lockStartTimestamp.add((sixMonths * 9).mul(daySeconds)) <= now && unlockLvl == 8){ transfer(FOUNDER, value); unlockLvl++; } else if(lockStartTimestamp.add((sixMonths * 10).mul(daySeconds)) <= now && unlockLvl == 9){ transfer(FOUNDER, value); unlockLvl++; } else{ revert(); } } function FreezeTokens(uint amt) public { require(amt > 0, "zero input"); if(isFreezeFinished()){ } totalFrozen = totalFrozen.add(amt); frozen[msg.sender].freezeStartTimestamp = now; frozen[msg.sender].freezeLength = minFreezeDayLength; emit TokenFreeze(msg.sender, amt); } function FreezeTokens(uint amt) public { require(amt > 0, "zero input"); if(isFreezeFinished()){ } totalFrozen = totalFrozen.add(amt); frozen[msg.sender].freezeStartTimestamp = now; frozen[msg.sender].freezeLength = minFreezeDayLength; emit TokenFreeze(msg.sender, amt); } tokenFrozenBalances[msg.sender] = tokenFrozenBalances[msg.sender].add(amt); function UnfreezeTokens(uint amt) public { require(amt > 0, "zero input"); require(isFreezeFinished(), "tokens cannot be unlocked yet. min 7 day freeze"); totalFrozen = totalFrozen.sub(amt); emit TokenUnfreeze(msg.sender, amt); } function daysPastFreezeLength() internal returns(uint) { frozen[msg.sender].daysPast = now.sub(frozen[msg.sender].freezeStartTimestamp).div(daySeconds); if(frozen[msg.sender].daysPast > frozen[msg.sender].freezeLength){ } else{ return 0; } } function daysPastFreezeLength() internal returns(uint) { frozen[msg.sender].daysPast = now.sub(frozen[msg.sender].freezeStartTimestamp).div(daySeconds); if(frozen[msg.sender].daysPast > frozen[msg.sender].freezeLength){ } else{ return 0; } } function daysPastFreezeLength() internal returns(uint) { frozen[msg.sender].daysPast = now.sub(frozen[msg.sender].freezeStartTimestamp).div(daySeconds); if(frozen[msg.sender].daysPast > frozen[msg.sender].freezeLength){ } else{ return 0; } } function calcFreezingRewards() internal returns(uint) { return (tokenFrozenBalances[msg.sender].div(mintRatio) * frozen[msg.sender].freezeLength + daysPastFreezeLength()); } public { require(roomActive, "transform room not active"); { require(roundCap >= roundTransformed.add(HXY.add(HXY.div(10))), "round supply cap reached"); require(roundCap < _maxSupply.sub(totalSupply()), "round cap exeeds remaining maxSupply, reduce roundCap"); roundTransformed += HXY.add(HXY.div(10)); totalHXYTransformed += HXY.add(HXY.div(10)); totalHeartsTransformed += hearts; _mint(ref, HXY.div(10)); } require(roundCap >= roundTransformed.add(HXY), "round supply cap reached"); require(roundCap < _maxSupply.sub(totalSupply()), "round cap exeeds remaining maxSupply, reduce roundCap"); roundTransformed += HXY; totalHXYTransformed += HXY; totalHeartsTransformed += hearts; } liquidityReserve += lr; distributable += hearts.sub(lr); emit Transform(hearts, HXY, msg.sender); { require(roomActive, "transform room not active"); { require(roundCap >= roundTransformed.add(HXY.add(HXY.div(10))), "round supply cap reached"); require(roundCap < _maxSupply.sub(totalSupply()), "round cap exeeds remaining maxSupply, reduce roundCap"); roundTransformed += HXY.add(HXY.div(10)); totalHXYTransformed += HXY.add(HXY.div(10)); totalHeartsTransformed += hearts; _mint(ref, HXY.div(10)); } require(roundCap >= roundTransformed.add(HXY), "round supply cap reached"); require(roundCap < _maxSupply.sub(totalSupply()), "round cap exeeds remaining maxSupply, reduce roundCap"); roundTransformed += HXY; totalHXYTransformed += HXY; totalHeartsTransformed += hearts; } liquidityReserve += lr; distributable += hearts.sub(lr); emit Transform(hearts, HXY, msg.sender); uint lr = hearts.div(100); }
9,642,924
[ 1, 28111, 20661, 17667, 2602, 14275, 8020, 2849, 1268, 759, 318, 291, 91, 438, 3875, 7118, 6835, 3875, 6547, 7725, 81, 474, 342, 4843, 94, 278, 969, 362, 2102, 23978, 360, 20864, 474, 3820, 1154, 5432, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 16351, 23971, 17667, 2602, 353, 467, 654, 39, 3462, 16, 3155, 3783, 288, 203, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 203, 565, 2874, 261, 2867, 516, 2254, 5034, 13, 3238, 389, 70, 26488, 31, 203, 203, 565, 2874, 261, 2867, 516, 2874, 261, 2867, 516, 2254, 5034, 3719, 3238, 389, 5965, 6872, 31, 203, 203, 565, 1758, 2713, 7738, 1733, 273, 374, 6511, 20, 69, 9462, 72, 2954, 4630, 24, 38, 16010, 38, 9462, 70, 40, 69, 40, 25, 42, 557, 40, 69, 5558, 5340, 323, 26, 71, 24, 72, 8778, 31, 203, 565, 1758, 2713, 7738, 1584, 17500, 2294, 273, 374, 92, 6260, 71, 758, 6675, 71, 39, 507, 20, 361, 37, 28, 39, 5482, 40, 25, 37, 4366, 5353, 7598, 7235, 41, 74, 24886, 41, 27, 5482, 23, 31, 203, 565, 1758, 1071, 7738, 1584, 17500, 8546, 273, 1758, 12, 20, 1769, 203, 565, 1351, 291, 91, 438, 11688, 1358, 2713, 7738, 20661, 1358, 273, 1351, 291, 91, 438, 11688, 1358, 12, 318, 77, 1584, 17500, 2294, 1769, 203, 565, 1351, 291, 91, 438, 11688, 1358, 2713, 7738, 44, 8546, 1358, 31, 203, 565, 1351, 291, 91, 438, 1733, 1358, 2713, 7738, 1733, 1358, 273, 1351, 291, 91, 438, 1733, 1358, 12, 318, 77, 1733, 1769, 203, 565, 2254, 640, 291, 91, 438, 48, 18988, 24237, 5157, 273, 374, 31, 203, 565, 1758, 2713, 3827, 1887, 273, 374, 92, 22, 70, 6162, 21, 73, 2733, 1727, 41, 29, 74, 1578, 73, 5284, 8898, 3461, 74, 27, 38, 6669, 2 ]
pragma solidity ^0.4.21; interface Sale { function buy(uint256) external payable; function sell(uint256) external; } contract TokenSaleAttack { Sale public target; address public owner; modifier onlyOwner { require(msg.sender == owner); _; } function TokenSaleAttack(address _target) public payable { require(msg.value == 1 ether); target = Sale(_target); owner = msg.sender; } function attack() public onlyOwner { uint256 numTokens; uint256 pricePerToken = 1 ether; // https://medium.com/wicketh/mathemagic-512-bit-division-in-solidity-afa55870a65 // This divides 2^256 - 1 by 10^18 assembly { numTokens := add(div(sub(0, pricePerToken), pricePerToken), 1) } // Add 1 to overflow numTokens += 1; // Check that it actually overflows assert(numTokens * pricePerToken < numTokens); // Get the wei value to send uint256 val = numTokens * pricePerToken; // Call the buy function to overflow the balance target.buy.value(val)(numTokens); // Retrieve some of the ether from the challenge target.sell(1); } function clean() public { selfdestruct(owner); } function() external payable {} }
Check that it actually overflows
assert(numTokens * pricePerToken < numTokens);
12,547,873
[ 1, 1564, 716, 518, 6013, 9391, 87, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1815, 12, 2107, 5157, 380, 6205, 2173, 1345, 411, 818, 5157, 1769, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/4/0x9701565fFf4daE5d12696Cc402D73D51391733f2/sources/contracts/Marketplace.sol
* @dev Creates a new order @param nftAddress - Non fungible registry address @param assetId - ID of the published NFT @param priceInWei - Price in Wei for the supported coin @param expiresAt - Duration of the order (in hours)/
function _createOrder( address nftAddress, uint256 assetId, uint256 priceInWei, uint256 expiresAt ) internal { _requireERC721(nftAddress); address sender = _msgSender(); ERC721Interface nftRegistry = ERC721Interface(nftAddress); address assetOwner = nftRegistry.ownerOf(assetId); require(sender == assetOwner, "Only the owner can create orders"); require( nftRegistry.getApproved(assetId) == address(this) || nftRegistry.isApprovedForAll(assetOwner, address(this)), "The contract is not authorized to manage the asset" ); require(priceInWei > 0, "Price should be bigger than 0"); bytes32 orderId = keccak256( abi.encodePacked( block.timestamp, assetOwner, assetId, nftAddress, priceInWei ) ); orderByAssetId[nftAddress][assetId] = Order({ id: orderId, seller: assetOwner, nftAddress: nftAddress, price: priceInWei, expiresAt: expiresAt }); emit OrderCreated( orderId, assetId, assetOwner, nftAddress, priceInWei, expiresAt ); }
12,426,370
[ 1, 2729, 279, 394, 1353, 225, 290, 1222, 1887, 300, 3858, 9831, 75, 1523, 4023, 1758, 225, 3310, 548, 300, 1599, 434, 326, 9487, 423, 4464, 225, 6205, 382, 3218, 77, 300, 20137, 316, 1660, 77, 364, 326, 3260, 13170, 225, 7368, 861, 300, 4822, 434, 326, 1353, 261, 267, 7507, 13176, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 2640, 2448, 12, 203, 3639, 1758, 290, 1222, 1887, 16, 203, 3639, 2254, 5034, 3310, 548, 16, 203, 3639, 2254, 5034, 6205, 382, 3218, 77, 16, 203, 3639, 2254, 5034, 7368, 861, 203, 565, 262, 2713, 288, 203, 3639, 389, 6528, 654, 39, 27, 5340, 12, 82, 1222, 1887, 1769, 203, 203, 3639, 1758, 5793, 273, 389, 3576, 12021, 5621, 203, 203, 3639, 4232, 39, 27, 5340, 1358, 290, 1222, 4243, 273, 4232, 39, 27, 5340, 1358, 12, 82, 1222, 1887, 1769, 203, 3639, 1758, 3310, 5541, 273, 290, 1222, 4243, 18, 8443, 951, 12, 9406, 548, 1769, 203, 203, 3639, 2583, 12, 15330, 422, 3310, 5541, 16, 315, 3386, 326, 3410, 848, 752, 11077, 8863, 203, 3639, 2583, 12, 203, 5411, 290, 1222, 4243, 18, 588, 31639, 12, 9406, 548, 13, 422, 1758, 12, 2211, 13, 747, 203, 7734, 290, 1222, 4243, 18, 291, 31639, 1290, 1595, 12, 9406, 5541, 16, 1758, 12, 2211, 13, 3631, 203, 5411, 315, 1986, 6835, 353, 486, 10799, 358, 10680, 326, 3310, 6, 203, 3639, 11272, 203, 3639, 2583, 12, 8694, 382, 3218, 77, 405, 374, 16, 315, 5147, 1410, 506, 18983, 2353, 374, 8863, 203, 3639, 203, 203, 3639, 1731, 1578, 20944, 273, 203, 5411, 417, 24410, 581, 5034, 12, 203, 7734, 24126, 18, 3015, 4420, 329, 12, 203, 10792, 1203, 18, 5508, 16, 203, 10792, 3310, 5541, 16, 203, 10792, 3310, 548, 16, 203, 10792, 290, 1222, 1887, 16, 203, 10792, 6205, 382, 3218, 77, 203, 7734, 262, 203, 5411, 11272, 203, 2 ]
./full_match/3/0xc1631D25d9cbB914d8E5e3F53b97918d018906b0/sources/contracts/Operations.sol
NOTE: there is no check that variable sizes are same as constants (i.e. TOKEN_BYTES), fix if possible.
function readPartialExitPubdata(bytes memory _data, uint256 _offset) internal pure returns (PartialExit memory parsed) { }
14,159,842
[ 1, 17857, 30, 1915, 353, 1158, 866, 716, 2190, 8453, 854, 1967, 487, 6810, 261, 77, 18, 73, 18, 14275, 67, 13718, 3631, 2917, 309, 3323, 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 ]
[ 1, 1, 1, 1, 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, 855, 9447, 6767, 9581, 892, 12, 3890, 3778, 389, 892, 16, 2254, 5034, 389, 3348, 13, 203, 3639, 2713, 203, 3639, 16618, 203, 3639, 1135, 261, 9447, 6767, 3778, 2707, 13, 203, 565, 288, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/4/0x4172f25D3f3dD274Ac24E0C36de496B935732E63/sources/contracts/UniswapPairPriceAdapter.sol
Dependency file: contracts/interfaces/ICKValuer.sol/ pragma solidity 0.6.10; import { ICKToken } from "contracts/interfaces/ICKToken.sol";
interface ICKValuer { function calculateCKTokenValuation(ICKToken _ckToken, address _quoteAsset) external view returns (uint256); }
12,520,192
[ 1, 7787, 585, 30, 20092, 19, 15898, 19, 16656, 58, 700, 264, 18, 18281, 19, 10878, 18035, 560, 374, 18, 26, 18, 2163, 31, 1930, 288, 467, 3507, 1345, 289, 628, 315, 16351, 87, 19, 15898, 19, 16656, 1345, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 5831, 467, 3507, 58, 700, 264, 288, 203, 565, 445, 4604, 3507, 1345, 58, 700, 367, 12, 16656, 1345, 389, 363, 1345, 16, 1758, 389, 6889, 6672, 13, 3903, 1476, 1135, 261, 11890, 5034, 1769, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.8.4; //SPDX-License-Identifier: MIT import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; import "./HorseUtilityContract.sol"; import "base64-sol/base64.sol"; // // ____ _ _ _ _ _ _ _ _____ _____ // / ___| |__ __ _(_)_ __ ___ __| | | | | | ___ _ __ ___ ___ | \ | | ___|_ _| // | | | '_ \ / _` | | '_ \ / _ \/ _` | | |_| |/ _ \| '__/ __|/ _ \ | \| | |_ | | // | |___| | | | (_| | | | | | __/ (_| | | _ | (_) | | \__ \ __/ | |\ | _| | | // \____|_| |_|\__,_|_|_| |_|\___|\__,_| |_| |_|\___/|_| |___/\___| |_| \_|_| |_| // // // // ,, // // .//,,,,,,,,, // .//,,,,@@,,,,,,, // /////,,,,,,,,,,,,, // /////,,,,,, // /////,,,,,, // ///////,,,,,, // ///////////,,,,,, // /////,,,,,,,,,,,,,,,,,,,,,,,,,, // /////,,,,,,,,,,,,,,,,,,,,,,,,,,,, // /////,,,,,,,,,,,,,,,,,,,,,,,,,,,, // /////,,,,,,,,,,,,,,,,,,,,,,,,,,,, // //// ,, // ,, // // //// ,, // ,, // // //// ,, // ,, // // // ,, // ,, // // @@ @@ @@ @@ // // ** ChainedHorseNFT: ChainedHorseTokenContract.sol ** // Written and developed by: Moonfarm // Twitter: @spacesh1pdev // Discord: Moonfarm#1138 // contract ChainedHorseTokenContract is ERC721Enumerable, Ownable { using SafeMath for uint256; // attribute rarities uint256[] private maneColorRarities = [ 4000, 1000, 1000, 1000, 800, 800, 500, 300, 300, 200, 100 ]; uint256[] private patternColorRarities = [ 3000, 1700, 1350, 900, 800, 800, 500, 300, 200, 200, 150, 100 ]; uint256[] private hoofColorRarities = [ 3500, 1500, 1100, 1000, 1000, 500, 500, 400, 200, 200, 100 ]; uint256[] private bodyColorRarities = [ 2900, 1500, 1500, 1500, 700, 600, 500, 500, 200, 100 ]; uint256[] private backgroundRarities = [ 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000 ]; uint256[] private tailRarities = [ 3000, 2000, 1500, 1200, 1000, 750, 350, 200 ]; uint256[] private maneRarities = [ 3000, 1800, 1600, 900, 800, 700, 600, 400, 200 ]; uint256[] private patternRarities = [ 2000, 1500, 1500, 1100, 1000, 800, 800, 500, 500, 300 ]; uint256[] private headAccessoryRarities = [ 3100, 1500, 1000, 800, 700, 700, 500, 550, 250, 300, 300, 150, 100, 50 ]; uint256[] private bodyAccessoryRarities = [ 2500, 2300, 1400, 1000, 800, 800, 600, 400, 200 ]; uint256[] private utilityRarities = [ 3700, 1000, 900, 500, 400, 500, 200, 600, 900, 500, 300, 250, 100, 100, 50 ]; // amount of attributes uint8 constant maneColorCount = 11; uint8 constant patternColorCount = 12; uint8 constant hoofColorCount = 11; uint8 constant bodyColorCount = 10; uint8 constant backgroundCount = 10; uint8 constant tailCount = 8; uint8 constant maneCount = 9; uint8 constant patternCount = 10; uint8 constant headAccessoryCount = 14; uint8 constant bodyAccessoryCount = 9; uint8 constant utilityCount = 15; /** * Define the utility contract address so we know where to fetch svgs from */ address public utilityContract = 0x0000000000000000000000000000000000000001; /** * Pretty standard NFT contract variables */ uint256 public maxTokens = 10000; uint256 public mintedTokens = 0; uint256 public burnedTokens = 0; uint256 public rebirthedTokens = 0; uint256 public mintPrice = 0.02 ether; uint256 public rebirthPrice = 0.01 ether; uint8 public claimableTokensPerAddress = 20; uint8 public maxTokensPerTxn = 5; bool public saleActive = false; /** * Whitelist info */ uint256 public whitelistTokensUnlocksAtBlockNumber = 0; uint256 public whitelistAddressCount = 0; /** * Burned horse base64-image */ string ashes = "data:image/svg+xml;base64,PHN2ZyB4bWxucz0naHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmcnIHZpZXdCb3g9JzAgMCAzMiAzMic+PHBhdGggZmlsbD0nI2QxZDNkNCcgZD0nTTAgMGgzMnYzMkgweicvPjxwYXRoIGZpbGw9JyM1ODU5NWInIGQ9J00xMCAyN0g5di0xaDF6bTEwIDBoLTF2LTFoMXptMiAwaC0xdi0xaDF6Jy8+PHBhdGggZmlsbD0nIzIzMWYyMCcgZD0nTTIzIDI3aC0xdi0xaDF6Jy8+PHBhdGggZmlsbD0nIzU4NTk1YicgZD0nTTI0IDI3aC0xdi0xaDF6bTEgMGgtMXYtMWgxem0tMTQgMGgtMXYtMWgxem0xIDBoLTF2LTFoMXptMSAwaC0xdi0xaDF6bTEgMGgtMXYtMWgxem0xIDBoLTF2LTFoMXptMSAwaC0xdi0xaDF6bTEgMGgtMXYtMWgxeicvPjxwYXRoIGZpbGw9JyM4MDgyODUnIGQ9J00xOCAyN2gtMXYtMWgxeicvPjxwYXRoIGZpbGw9JyM1ODU5NWInIGQ9J00xOSAyN2gtMXYtMWgxem0yIDBoLTF2LTFoMXptMC0xaC0xdi0xaDF6bS0xIDBoLTF2LTFoMXptLTEgMGgtMXYtMWgxem0tMSAwaC0xdi0xaDF6bS0xIDBoLTF2LTFoMXonLz48cGF0aCBmaWxsPScjMjMxZjIwJyBkPSdNMTYgMjZoLTF2LTFoMXonLz48cGF0aCBmaWxsPScjNTg1OTViJyBkPSdNMTUgMjZoLTF2LTFoMXptMS0xaC0xdi0xaDF6bTEgMGgtMXYtMWgxeicvPjxwYXRoIGZpbGw9JyMyMzFmMjAnIGQ9J00xOCAyNWgtMXYtMWgxeicvPjxwYXRoIGZpbGw9JyM1ODU5NWInIGQ9J00xOSAyNWgtMXYtMWgxem0xIDBoLTF2LTFoMXptLTEtMWgtMXYtMWgxeicvPjxwYXRoIGZpbGw9JyM4MDgyODUnIGQ9J00xNyAyNGgtMXYtMWgxeicvPjxwYXRoIGZpbGw9JyM1ODU5NWInIGQ9J00xOCAyNGgtMXYtMWgxem0tNCAyaC0xdi0xaDF6Jy8+PHBhdGggZmlsbD0nIzgwODI4NScgZD0nTTEzIDI2aC0xdi0xaDF6Jy8+PHBhdGggZmlsbD0nIzU4NTk1YicgZD0nTTEyIDI2aC0xdi0xaDF6Jy8+PC9zdmc+"; /** * Amount of tokens a specific whitelist address has left to mint * * Always starts at 20 for each address added */ mapping(address => uint256) public whitelistedAddressMintsLeft; /** * Save seed for traits for each token */ mapping(uint256 => uint256) public tokenSeed; mapping(uint256 => bool) public tokenBurned; /** * Pretty standard constructor variables, nothing wierd here * * Mints #0 to the creator */ constructor( string memory tokenName, string memory tokenSymbol, uint256 _maxTokens, address _utilityContract, address mintedByOnOldContract ) ERC721(tokenName, tokenSymbol) { maxTokens = _maxTokens; utilityContract = _utilityContract; migrateMintedTokensFromOldContract(mintedByOnOldContract); } /** * Mint tokens that have been minted on the old contract and send to minters * Set the same seed as the old contract generated for the minted tokens so they get the same properties */ function migrateMintedTokensFromOldContract(address mintedByOnOldContract) private { _safeMint(msg.sender, 0); _safeMint(mintedByOnOldContract, 1); _safeMint(mintedByOnOldContract, 2); _safeMint(mintedByOnOldContract, 3); _safeMint(mintedByOnOldContract, 4); _safeMint(mintedByOnOldContract, 5); tokenSeed[0] = 5544338833776644337733999; tokenSeed[1] = 7788333333735555114477799; tokenSeed[2] = 1111772266993344221133999; tokenSeed[3] = 1155775566117788663333999; tokenSeed[4] = 1144222200001111889999799; tokenSeed[5] = 5588447788664477885544999; mintedTokens += 6; } /** * 1) Sets whitelisted tokens to be available for public mint in * 40320 blocks from the block this function was called (approximately a week) * 2) Starts the sale */ function startSale() public onlyOwner { whitelistTokensUnlocksAtBlockNumber = block.number + 40320; // approximately a week saleActive = true; } /** * Standard withdraw function */ function withdraw() public onlyOwner { uint256 balance = payable(address(this)).balance; payable(msg.sender).transfer(balance); } /** * Private function so it can be called cheaper from tokenURI and tokenSVG */ function _tokenSVG(uint256 seed) private view returns (string memory) { (string memory svg, string memory properties) = getRandomAttributes( seed ); return svg; } /** * Get the svg for a token in base64 format * * Comment: * Uses the UtilityContract to get svg-information for each attribute */ function tokenSVG(uint256 tokenId) public view returns (string memory) { bool lessThanMinted = tokenId < mintedTokens; bool lessThanMintedRebirthOrMoreThanStartOfRebirth = tokenId < (maxTokens + burnedTokens) && tokenId > maxTokens; if ( !_exists(tokenId) && (lessThanMinted || lessThanMintedRebirthOrMoreThanStartOfRebirth) ) { return ashes; } require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); return string( abi.encodePacked( "data:image/svg+xml;base64,", _tokenSVG(tokenSeed[tokenId]) ) ); } /** * Get the metadata for a token in base64 format * * Comment: * Uses the UtilityContract to get svg-information for each attribute */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { if ( !_exists(tokenId) && (tokenId < mintedTokens || (tokenId < (maxTokens + burnedTokens) && tokenId > maxTokens)) ) { return string( abi.encodePacked( "data:application/json;base64,", Base64.encode( abi.encodePacked( '{"name":"Burned Chained Horse #', uint2str(tokenId), '", "description": "A horse that lives on the ethereum blockchain.", "attributes": [', packMetaData("status", "burned", 1), '], "image":"', ashes, '"}' ) ) ) ); } require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); (string memory svg, string memory properties) = getRandomAttributes( tokenSeed[tokenId] ); return string( abi.encodePacked( "data:application/json;base64,", Base64.encode( abi.encodePacked( '{"name":"Chained Horse #', uint2str(tokenId), '", "description": "A horse that lives on the ethereum blockchain.", "attributes": [', properties, '], "image":"data:image/svg+xml;base64,', svg, '"}' ) ) ) ); } /** * A claim function for whitelisted addresses until claim-period is over */ function claim(uint256 amount) public { require( whitelistedAddressMintsLeft[msg.sender] >= amount, "Exceeded amount of claims left on address" ); require( whitelistTokensUnlocksAtBlockNumber > block.number, "Claim period is over" ); mint(amount); whitelistedAddressMintsLeft[msg.sender] -= amount; } /** * A mint function for anyone */ function publicMint(uint256 amount) public payable { require( amount.add(mintedTokens) <= maxTokens - (whitelistAddressCount * claimableTokensPerAddress) || block.number > whitelistTokensUnlocksAtBlockNumber, "Tokens left are for whitelist" ); require(mintPrice.mul(amount) <= msg.value, "Not enough ether to mint"); require(saleActive, "Sale has not started"); mint(amount); } /** * Mint with requirements that both claim and publicMint needs to follow */ function mint(uint256 amount) private { require( amount <= maxTokensPerTxn, "Trying to mint more than allowed tokens" ); require( amount.add(mintedTokens) <= maxTokens, "Amount exceeded max tokens" ); for (uint256 i = 0; i < amount; i++) { tokenSeed[mintedTokens + i] = uint256( keccak256( abi.encodePacked( block.difficulty, block.timestamp, mintedTokens + i ) ) ); _safeMint(msg.sender, mintedTokens + i); } mintedTokens += amount; } /** * Rebirth a horse by burning two horses owned by the caller */ function rebirth(uint256 tokenId1, uint256 tokenId2) public payable { require(tokenId1 != tokenId2, "Not different tokens"); require(ownerOf(tokenId1) == msg.sender, "Not owner of token"); require(ownerOf(tokenId2) == msg.sender, "Not owner of token"); require(!tokenBurned[tokenId1], "Already burned"); require(!tokenBurned[tokenId2], "Already burned"); require(msg.value == rebirthPrice, "Not enough ether to rebirth"); tokenBurned[tokenId1] = true; tokenBurned[tokenId2] = true; _burn(tokenId1); _burn(tokenId2); burnedTokens += 2; uint256 rebirthTokenId = maxTokens.add(rebirthedTokens); tokenSeed[rebirthTokenId] = uint256( keccak256( abi.encodePacked( block.difficulty, block.timestamp, rebirthTokenId ) ) ); _safeMint(msg.sender, rebirthTokenId); rebirthedTokens++; } /** * Add an address to the whitelist */ function addWhitelistAddresses(address[] memory newWhitelistMembers) public onlyOwner { for (uint256 i = 0; i < newWhitelistMembers.length; i++) { whitelistedAddressMintsLeft[ newWhitelistMembers[i] ] = claimableTokensPerAddress; whitelistAddressCount++; } } /** * Small function to convert uint to string */ function uint2str(uint256 _i) internal pure returns (string memory _uintAsString) { if (_i == 0) { return "0"; } uint256 j = _i; uint256 len; while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint256 k = len; while (_i != 0) { k = k - 1; uint8 temp = (48 + uint8(_i - (_i / 10) * 10)); bytes1 b1 = bytes1(temp); bstr[k] = b1; _i /= 10; } return string(bstr); } /** * Use: * Get random attributes for each different property of the token * * Comment: * Can only be used by the TokenContract defined by address tokenContract */ function getRandomAttributes(uint256 randomNumber) public view returns (string memory svg, string memory properties) { uint8[] memory attributes = new uint8[](11); attributes[0] = getRandomIndex( maneColorRarities, maneColorCount, randomNumber ); randomNumber = randomNumber / 100; attributes[1] = getRandomIndex( patternColorRarities, patternColorCount, randomNumber ); randomNumber = randomNumber / 100; attributes[2] = getRandomIndex( hoofColorRarities, hoofColorCount, randomNumber ); randomNumber = randomNumber / 100; attributes[3] = getRandomIndex( bodyColorRarities, bodyColorCount, randomNumber ); randomNumber = randomNumber / 100; attributes[4] = getRandomIndex( backgroundRarities, backgroundCount, randomNumber ); randomNumber = randomNumber / 100; attributes[5] = getRandomIndex(tailRarities, tailCount, randomNumber); randomNumber = randomNumber / 100; attributes[6] = getRandomIndex(maneRarities, maneCount, randomNumber); randomNumber = randomNumber / 100; attributes[7] = getRandomIndex( patternRarities, patternCount, randomNumber ); randomNumber = randomNumber / 100; attributes[8] = getRandomIndex( headAccessoryRarities, headAccessoryCount, randomNumber ); randomNumber = randomNumber / 100; attributes[9] = getRandomIndex( bodyAccessoryRarities, bodyAccessoryCount, randomNumber ); randomNumber = randomNumber / 100; attributes[10] = getRandomIndex( utilityRarities, utilityCount, randomNumber ); // render svg bytes memory _svg = HorseUtilityContract(utilityContract).renderHorse( HorseUtilityContract(utilityContract).renderColors( attributes[0], attributes[1], attributes[2], attributes[3] ), attributes[4], attributes[5], attributes[6], attributes[7], attributes[8], attributes[9], attributes[10] ); svg = Base64.encode(_svg); // pack properties bytes memory _properties = abi.encodePacked( packMetaData( "background", HorseUtilityContract(utilityContract).getBackground( attributes[4] ), 0 ), packMetaData( "tail", HorseUtilityContract(utilityContract).getTail(attributes[5]), 0 ), packMetaData( "mane", HorseUtilityContract(utilityContract).getMane(attributes[6]), 0 ), packMetaData( "pattern", HorseUtilityContract(utilityContract).getPattern(attributes[7]), 0 ), packMetaData( "head accessory", HorseUtilityContract(utilityContract).getHeadAccessory( attributes[8] ), 0 ), packMetaData( "body accessory", HorseUtilityContract(utilityContract).getBodyAccessory( attributes[9] ), 0 ), packMetaData( "utility", HorseUtilityContract(utilityContract).getUtility( attributes[10] ), 0 ) ); string[] memory colorNames = new string[](4); colorNames[0] = HorseUtilityContract(utilityContract).getManeColor( attributes[0] ); colorNames[1] = HorseUtilityContract(utilityContract).getPatternColor( attributes[1] ); colorNames[2] = HorseUtilityContract(utilityContract).getHoofColor( attributes[2] ); colorNames[3] = HorseUtilityContract(utilityContract).getBodyColor( attributes[3] ); properties = string( abi.encodePacked( _properties, packMetaData("mane color", colorNames[0], 0), packMetaData("pattern color", colorNames[1], 0), packMetaData("hoof color", colorNames[2], 0), packMetaData("body color", colorNames[3], 1) ) ); return (svg, properties); } /** * Bundle metadata so it follows the standard */ function packMetaData( string memory name, string memory svg, uint256 last ) private pure returns (bytes memory) { string memory comma = ","; if (last > 0) comma = ""; return abi.encodePacked( '{"trait_type": "', name, '", "value": "', svg, '"}', comma ); } /** * Use: * Get a random attribute using the rarities defined */ function getRandomIndex( uint256[] memory attributeRarities, uint8 attributeCount, uint256 randomNumber ) private pure returns (uint8 index) { uint256 random10k = randomNumber % 10000; uint256 steps = 0; for (uint8 i = 0; i < attributeCount; i++) { uint256 currentRarity = attributeRarities[i] + steps; if (random10k < currentRarity) { return i; } steps = currentRarity; } return 0; } } // 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; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./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 "../ERC721.sol"; import "./IERC721Enumerable.sol"; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library Counters { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } pragma solidity ^0.8.4; //SPDX-License-Identifier: MIT // // ____ _ _ _ _ _ _ _ _____ _____ // / ___| |__ __ _(_)_ __ ___ __| | | | | | ___ _ __ ___ ___ | \ | | ___|_ _| // | | | '_ \ / _` | | '_ \ / _ \/ _` | | |_| |/ _ \| '__/ __|/ _ \ | \| | |_ | | // | |___| | | | (_| | | | | | __/ (_| | | _ | (_) | | \__ \ __/ | |\ | _| | | // \____|_| |_|\__,_|_|_| |_|\___|\__,_| |_| |_|\___/|_| |___/\___| |_| \_|_| |_| // // // // ,, // // .//,,,,,,,,, // .//,,,,@@,,,,,,, // /////,,,,,,,,,,,,, // /////,,,,,, // /////,,,,,, // ///////,,,,,, // ///////////,,,,,, // /////,,,,,,,,,,,,,,,,,,,,,,,,,, // /////,,,,,,,,,,,,,,,,,,,,,,,,,,,, // /////,,,,,,,,,,,,,,,,,,,,,,,,,,,, // /////,,,,,,,,,,,,,,,,,,,,,,,,,,,, // //// ,, // ,, // // //// ,, // ,, // // //// ,, // ,, // // // ,, // ,, // // @@ @@ @@ @@ // // ** ChainedHorseNFT: HorseUtilityContract.sol ** // Written and developed by: Moonfarm // Twitter: @spacesh1pdev // Discord: Moonfarm#1138 // contract HorseUtilityContract { //SVG-parts string constant svgStart = "<svg xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' viewBox='0 0 32 32'>"; string constant svgEnd = "</svg>"; string constant base = "<path fill='url(#body-color)' d='M19 7h1v1h-1zm2 0h1v1h-1zm-2 1h1v1h-1zm0 1h1v1h-1zm0 1h1v1h-1zm0 1h1v1h-1zm0 1h1v1h-1zm0 1h1v1h-1zm0 1h1v1h-1zm0 1h1v1h-1zm0 1h1v1h-1zm-1 0h1v1h-1zm-1 0h1v1h-1zm-1 0h1v1h-1zm-1 0h1v1h-1zm-1 0h1v1h-1zm-1 0h1v1h-1zm-1 0h1v1h-1zm-1 0h1v1h-1zm-1 0h1v1h-1zm0 1h1v1h-1zm-1 0h1v1H9zm0 1h1v1H9zm1 0h1v1h-1zm1 0h1v1h-1zm0-1h1v1h-1zm1 0h1v1h-1zm1 0h1v1h-1zm1 0h1v1h-1zm1 0h1v1h-1zm1 0h1v1h-1zm1 0h1v1h-1zm1 0h1v1h-1zm1 0h1v1h-1zm1 0h1v1h-1zm0-1h1v1h-1zm0-1h1v1h-1zm0-1h1v1h-1zm0-1h1v1h-1zm0-1h1v1h-1zm0-1h1v1h-1zm0-1h1v1h-1zm0-1h1v1h-1zm1 0h1v1h-1zm1 0h1v1h-1zm0 1h1v1h-1zm1 0h1v1h-1zm1 0h1v1h-1zm0 1h1v1h-1zm-1 0h1v1h-1zm-1 0h1v1h-1zm-1 0h1v1h-1zm0 1h1v1h-1zm0 1h1v1h-1zm0 1h1v1h-1zm0 1h1v1h-1zm0 1h1v1h-1zm0 1h1v1h-1zm0 1h1v1h-1zm0 1h1v1h-1zm0 1h1v1h-1zm-1 0h1v1h-1zm-1 0h1v1h-1zm-1 0h1v1h-1zm-1 0h1v1h-1zm-1 0h1v1h-1zm-1 0h1v1h-1zm-1 0h1v1h-1zm-1 0h1v1h-1zm-1 0h1v1h-1zm-1 0h1v1h-1zm-1 0h1v1h-1zm-1 0h1v1H9zm0-1h1v1H9zm1 0h1v1h-1zm1 0h1v1h-1zm1 0h1v1h-1zm1 0h1v1h-1zm1 0h1v1h-1zm1 0h1v1h-1zm1 0h1v1h-1zm1 0h1v1h-1zm1 0h1v1h-1zm1 0h1v1h-1zm1 0h1v1h-1zm0-1h1v1h-1zm-1 0h1v1h-1zm-1 0h1v1h-1zm-1 0h1v1h-1zm-1 0h1v1h-1zm-1 0h1v1h-1zm-1 0h1v1h-1zm-1 0h1v1h-1zm-1 0h1v1h-1zm-3 3h1v1H9zm0 1h1v1H9zm0 1h1v1H9zm0 1h1v1H9zm2 0h1v1h-1zm0-1h1v1h-1zm0-1h1v1h-1zm0-1h1v1h-1zm8 0h1v1h-1zm0 1h1v1h-1zm0 1h1v1h-1zm0 1h1v1h-1zm2 0h1v1h-1zm0-1h1v1h-1zm0-1h1v1h-1zm0-1h1v1h-1z' /><path fill='#000' opacity='.35' d='M21 7h1v1h-1zm0 14h1v1h-1zm0 1h1v1h-1zm0 1h1v1h-1zm0 1h1v1h-1zm-10 0h1v1h-1zm0-1h1v1h-1zm0-1h1v1h-1zm0-1h1v1h-1z' /><path fill='url(#hoof-color)' d='M9 25h1v1H9zm2 0h1v1h-1zm8 0h1v1h-1zm2 0h1v1h-1z' /><path fill='#000' d='M21 10h1v1h-1z' />"; // attribute svgs string[] private maneColorSvgs = [ "#000", "#da5d97", "#806bd5", "#b05ecd", "#f25a5f", "#ff8c2f", "#fff", "#00b7e6", "#3fa966", "#3d6ccd", "#ebbd54" ]; string[] private patternColorSvgs = [ "#643323", "#333", "#72d2ff", "#f1c5d1", "#dad4f7", "#6ecb63", "#da3832", "#fffac8", "#df6436", "#50b7e6", "#ff0075", "#fff" ]; string[] private hoofColorSvgs = [ "#000", "#544116", "#22577a", "#7e5b24", "#004927", "#008762", "#d53832", "#b0c7e6", "#76267b", "#e6adb0", "#ebbd54" ]; string[] private bodyColorSvgs = [ "#dfc969", "#685991", "#6d6e71", "#845f36", "#fff", "#6ecb63", "#b4255b", "#418151", "#007791", "#ebbd54" ]; string[] private headAccessorySvgs = [ "", "<path fill='#912b61' d='M19 8h1v1h-1zM19 7h1v1h-1zM20 7h1v1h-1zM21 7h1v1h-1zM21 8h1v1h-1zM20 8h1v1h-1zM22 8h1v1h-1zM23 8h1v1h-1zM24 8h1v1h-1zM22 7h1v1h-1z' />", "<path fill='#da3832' d='M19 8h1v1h-1zM19 7h1v1h-1zM20 7h1v1h-1z' /><path fill='#fae84b' d='M20 8h1v1h-1zM21 8h1v1h-1zM21 7h1v1h-1z' /><path fill='#4a549f' d='M22 7h1v1h-1zM22 8h1v1h-1z' /><path fill='#119b55' d='M23 8h1v1h-1zM24 8h1v1h-1z' /><path fill='#3e4e9c' d='M21 6h1v1h-1zM21 5h1v1h-1zM20 5h1v1h-1zM22 5h1v1h-1z' />", "<path fill='#ebbd54' d='M18 15h1v1h-1zM18 16h1v1h-1zM19 17h1v1h-1zM20 18h1v1h-1zM21 18h1v1h-1zM22 18h1v1h-1zM22 19h1v1h-1zM21 19h1v1h-1z' />", "<path fill='#1fafff' d='M22 9h1v1h-1zM22 8h1v1h-1zM23 8h1v1h-1zM23 7h1v1h-1zM24 7h1v1h-1zM24 6h1v1h-1zM24 5h1v1h-1z' />", "<path fill='#ebbc53' d='M26 10h1v1h-1zM25 11h1v1h-1zM27 10h1v1h-1zM27 12h1v1h-1zM28 12h1v1h-1zM28 11h1v1h-1zM29 12h1v1h-1zM29 11h1v1h-1zM30 11h1v1h-1z' /><path fill='#d53931' d='M27 11h1v1h-1zM26 11h1v1h-1z' /><path fill='#ebbc53' d='M28 10h1v1h-1z' />", "<path fill='#000' d='M18 8h1v1h-1zM19 8h1v1h-1zM19 7h1v1h-1zM19 6h1v1h-1zM20 6h1v1h-1zM20 7h1v1h-1zM19 5h1v1h-1zM20 5h1v1h-1zM21 5h1v1h-1zM22 5h1v1h-1zM20 8h1v1h-1zM21 8h1v1h-1zM21 7h1v1h-1zM21 6h1v1h-1zM22 8h1v1h-1zM22 7h1v1h-1zM22 6h1v1h-1zM23 8h1v1h-1z' />", "<path fill='#af3034' d='M19 9h1v1h-1zM19 8h1v1h-1zM19 7h1v1h-1zM19 6h1v1h-1z' /><path fill='#7c231f' d='M21 8h1v1h-1zM21 7h1v1h-1zM21 6h1v1h-1z' />", "<path fill='#2d388b' d='M17 9h1v1h-1zM17 8h1v1h-1zM18 9h1v1h-1z' /><path fill='#ebbd54' d='M19 7h1v1h-1z' /><path fill='#2d388b' d='M19 6h1v1h-1zM19 5h1v1h-1zM19 4h1v1h-1zM18 4h1v1h-1zM17 4h1v1h-1zM17 5h1v1h-1zM20 5h1v1h-1zM21 6h1v1h-1zM20 6h1v1h-1zM20 7h1v1h-1zM21 7h1v1h-1z' /><path fill='#ebbd54' d='M21 8h1v1h-1z' /><path fill='#2d388b' d='M22 8h1v1h-1zM22 7h1v1h-1zM24 7h1v1h-1zM23 8h1v1h-1zM20 8h1v1h-1zM19 9h1v1h-1zM19 8h1v1h-1z' />", "<path fill='#e65157' d='M21 10h1v1h-1zM22 10h1v1h-1zM23 10h1v1h-1zM24 10h1v1h-1zM25 10h1v1h-1zM26 10h1v1h-1zM27 10h1v1h-1zM28 10h1v1h-1zM29 10h1v1h-1zM30 10h1v1h-1zM31 10h1v1h-1z' />", "<path fill='#7f5748' d='M19 9h1v1h-1zM19 8h1v1h-1zM20 7h1v1h-1z' /><path fill='#b2b6ba' d='M20 8h1v1h-1z' /><path fill='#7f5748' d='M20 9h1v1h-1zM21 9h1v1h-1zM21 8h1v1h-1z' /><path fill='#b2b6ba' d='M19 7h1v1h-1zM19 6h1v1h-1zM19 5h1v1h-1z' /><path fill='#8e959c' d='M22 6h1v1h-1zM22 5h1v1h-1z' /><path fill='#7f5748' d='M21 7h1v1h-1zM22 7h1v1h-1zM22 8h1v1h-1zM22 9h1v1h-1zM23 8h1v1h-1zM23 9h1v1h-1z' />", "<path fill='#ebbd54' d='M18 4h1v1h-1zM19 5h1v1h-1zM20 5h1v1h-1zM21 5h1v1h-1zM22 5h1v1h-1zM23 4h1v1h-1zM22 3h1v1h-1zM21 3h1v1h-1zM20 3h1v1h-1zM19 3h1v1h-1z' />", "<path fill='#86c661' d='M25 14h1v1h-1zm0 1h1v1h-1z' /><path fill='#04b3e9' d='M25 16h1v1h-1z' /><path fill='#86c661' d='M25 19h1v1h-1zm0-1h1v1h-1z' /><path fill='#04b3e9' d='M25 21h1v1h-1z' /><path fill='#fbee41' d='M24 12h1v1h-1zm0 2h1v1h-1z' /><path fill='#f58220' d='M24 13h1v1h-1z' /><path fill='#fbee41' d='M24 16h1v1h-1zm0 2h1v1h-1zm0-3h1v1h-1z' /><path fill='#ef4354' d='M23 12h1v1h-1z' /><path fill='#f58220' d='M23 16h1v1h-1z' /><path fill='#ef4354' d='M23 15h1v1h-1zm0 2h1v1h-1zm0 2h1v1h-1zm0-6h1v1h-1z' />", "<path fill='#ebbd54' d='M19 9h1v1h-1zM19 8h1v1h-1zM19 7h1v1h-1zM19 6h1v1h-1zM20 7h1v1h-1zM20 8h1v1h-1zM20 9h1v1h-1zM21 9h1v1h-1zM21 8h1v1h-1zM21 7h1v1h-1zM21 6h1v1h-1zM22 7h1v1h-1zM22 8h1v1h-1zM22 9h1v1h-1zM23 6h1v1h-1zM23 7h1v1h-1zM23 8h1v1h-1zM23 9h1v1h-1z' />" ]; string[] private bodyAccessorySvgs = [ "", "<path fill='#898989' d='M12 16h1v1h-1zM12 17h1v1h-1zM12 18h1v1h-1zM12 19h1v1h-1zM12 20h1v1h-1zM17 20h1v1h-1zM17 19h1v1h-1zM17 18h1v1h-1zM17 17h1v1h-1z' /><path fill='#221f20' d='M14 17h1v1h-1z' /><path fill='#fff' d='M14 16h1v1h-1zM15 16h1v1h-1zM16 16h1v1h-1zM16 17h1v1h-1zM16 18h1v1h-1zM16 19h1v1h-1zM16 20h1v1h-1zM14 20h1v1h-1zM14 19h1v1h-1zM14 18h1v1h-1zM13 18h1v1h-1zM13 17h1v1h-1zM13 16h1v1h-1zM13 19h1v1h-1zM13 20h1v1h-1z' /><path fill='#221f20' d='M15 17h1v1h-1zM15 18h1v1h-1zM15 19h1v1h-1zM15 20h1v1h-1z' /><path fill='#898989' d='M17 16h1v1h-1z' />", "<path fill='#af7139' d='M9 23h1v1H9zM9 24h1v1H9zM9 25h1v1H9zM10 25h1v1h-1z' /><path fill='#643323' d='M11 23h1v1h-1zM11 24h1v1h-1zM11 25h1v1h-1zM12 25h1v1h-1z' /><path fill='#af7139' d='M19 23h1v1h-1zM19 24h1v1h-1zM19 25h1v1h-1zM20 25h1v1h-1z' /><path fill='#643323' d='M21 23h1v1h-1zM21 24h1v1h-1zM21 25h1v1h-1zM22 25h1v1h-1z' />", "<path fill='#ff8c2f' d='M15 16h1v1h-1z' /><path fill='#e65157' d='M15 15h1v1h-1z' /><path fill='#ff8c2f' d='M14 15h1v1h-1z' /><path fill='#fff560' d='M14 16h1v1h-1z' /><path fill='#94ce6e' d='M13 16h1v1h-1z' /><path fill='#fff560' d='M13 15h1v1h-1z' /><path fill='#94ce6e' d='M12 15h1v1h-1z' /><path fill='#1db1e3' d='M12 16h1v1h-1zM11 15h1v1h-1z' /><path fill='#e65157' d='M14 14h1v1h-1z' /><path fill='#ff8c2f' d='M13 14h1v1h-1z' /><path fill='#fff560' d='M12 14h1v1h-1z' /><path fill='#94ce6e' d='M11 14h1v1h-1z' /><path fill='#1db1e3' d='M10 14h1v1h-1z' /><path fill='#e65157' d='M12 13h1v1h-1z' /><path fill='#ff8c2f' d='M11 13h1v1h-1z' /><path fill='#fff560' d='M10 13h1v1h-1z' /><path fill='#94ce6e' d='M9 13h1v1H9z' /><path fill='#1db1e3' d='M8 13h1v1H8z' /><path fill='#e65157' d='M10 12h1v1h-1z' /><path fill='#ff8c2f' d='M9 12h1v1H9z' /><path fill='#fff560' d='M8 12h1v1H8z' /><path fill='#94ce6e' d='M7 12h1v1H7z' /><path fill='#1db1e3' d='M6 12h1v1H6z' /><path fill='#e65157' d='M8 11h1v1H8z' /><path fill='#ff8c2f' d='M7 11h1v1H7z' /><path fill='#fff560' d='M6 11h1v1H6z' /><path fill='#94ce6e' d='M5 11h1v1H5z' /><path fill='#1db1e3' d='M4 11h1v1H4z' /><path fill='#e65157' d='M5 10h1v1H5z' /><path fill='#ff8c2f' d='M4 10h1v1H4z' /><path fill='#fff560' d='M3 10h1v1H3z' /><path fill='#94ce6e' d='M2 10h1v1H2z' /><path fill='#1db1e3' d='M1 10h1v1H1z' /><path fill='#e65157' d='M2 9h1v1H2z' /><path fill='#ff8c2f' d='M1 9h1v1H1z' /><path fill='#fff560' d='M0 9h1v1H0z' />", "<path fill='#fdef38' d='M14 12h1v1h-1zM13 12h1v1h-1zM12 11h1v1h-1zM9 13h1v1H9zM9 14h1v1H9zM10 15h1v1h-1zM13 17h1v1h-1zM13 18h1v1h-1zM14 19h1v1h-1zM14 20h1v1h-1zM15 21h1v1h-1zM23 18h1v1h-1zM23 17h1v1h-1zM22 16h1v1h-1zM23 24h1v1h-1zM24 24h1v1h-1zM25 23h1v1h-1zM26 23h1v1h-1zM25 14h1v1h-1zM24 13h1v1h-1zM13 23h1v1h-1zM14 24h1v1h-1zM15 24h1v1h-1zM19 17h1v1h-1zM19 16h1v1h-1zM19 15h1v1h-1zM18 14h1v1h-1zM18 13h1v1h-1z' />", "<path fill='#4487ab' d='M15 16h1v1h-1z' /><path fill='#addbfb' d='M14 16h1v1h-1zM14 14h1v1h-1z' /><path fill='#4487ab' d='M15 14h1v1h-1zM15 13h1v1h-1zM14 13h1v1h-1zM13 14h1v1h-1z' /><path fill='#addbfb' d='M13 13h1v1h-1z' /><path fill='#4487ab' d='M12 13h1v1h-1z' /><path fill='#addbfb' d='M12 14h1v1h-1zM11 13h1v1h-1zM11 12h1v1h-1zM10 13h1v1h-1zM9 12h1v1H9zM8 11h1v1H8z' /><path fill='#4487ab' d='M8 10h1v1H8zM9 13h1v1H9z' /><path fill='#addbfb' d='M9 11h1v1H9zM10 12h1v1h-1z' /><path fill='#4487ab' d='M14 12h1v1h-1zM13 12h1v1h-1z' /><path fill='#addbfb' d='M12 12h1v1h-1z' /><path fill='#4487ab' d='M12 11h1v1h-1zM11 11h1v1h-1zM10 11h1v1h-1z' /><path fill='#addbfb' d='M11 14h1v1h-1zM10 14h1v1h-1z' /><path fill='#4487ab' d='M15 15h1v1h-1z' /><path fill='#addbfb' d='M14 15h1v1h-1zM13 15h1v1h-1zM12 15h1v1h-1z' /><path fill='#4487ab' d='M9 10h1v1H9z' />", "<path fill='#afadb0' d='M14 15h1v1h-1zM15 15h1v1h-1zM15 14h1v1h-1zM14 14h1v1h-1zM14 13h1v1h-1zM15 13h1v1h-1zM16 13h1v1h-1zM16 14h1v1h-1zM14 12h1v1h-1zM13 12h1v1h-1zM13 13h1v1h-1zM13 14h1v1h-1zM12 14h1v1h-1zM12 13h1v1h-1zM12 12h1v1h-1zM11 12h1v1h-1zM11 13h1v1h-1zM11 14h1v1h-1z' /><path fill='#f25a5f' d='M10 13h1v1h-1z' /><path fill='#f3cb4e' d='M10 12h1v1h-1zM9 12h1v1H9z' /><path fill='#f25a5f' d='M9 13h1v1H9z' /><path fill='#f3cb4e' d='M8 13h1v1H8zM8 12h1v1H8zM7 12h1v1H7zM7 13h1v1H7zM6 13h1v1H6zM10 14h1v1h-1zM9 14h1v1H9zM8 14h1v1H8z' />", "<path d='M14 15h1v1h-1zM14 14h1v1h-1zM13 14h1v1h-1zM13 15h1v1h-1zM12 15h1v1h-1zM12 14h1v1h-1zM11 14h1v1h-1zM11 15h1v1h-1zM11 16h1v1h-1zM11 17h1v1h-1zM11 18h1v1h-1zM14 13h1v1h-1zM14 12h1v1h-1zM13 12h1v1h-1zM13 13h1v1h-1zM12 13h1v1h-1zM13 11h1v1h-1zM13 10h1v1h-1zM14 10h1v1h-1zM14 11h1v1h-1zM13 9h1v1h-1zM15 11h1v1h-1zM15 10h1v1h-1z' /><path fill='#f8e100' d='M14 10h1v1h-1z' />", "<path fill='#221f20' d='M15 16h1v1h-1z' /><path fill='#5d5e60' d='M14 16h1v1h-1zM14 14h1v1h-1z' /><path fill='#221f20' d='M15 14h1v1h-1zM15 13h1v1h-1zM14 13h1v1h-1zM13 14h1v1h-1z' /><path fill='#5d5e60' d='M13 13h1v1h-1z' /><path fill='#221f20' d='M12 13h1v1h-1z' /><path fill='#5d5e60' d='M12 14h1v1h-1zM11 13h1v1h-1zM11 12h1v1h-1zM10 13h1v1h-1zM9 12h1v1H9zM8 11h1v1H8z' /><path fill='#221f20' d='M8 10h1v1H8zM9 13h1v1H9z' /><path fill='#5d5e60' d='M9 11h1v1H9zM10 12h1v1h-1z' /><path fill='#221f20' d='M14 12h1v1h-1zM13 12h1v1h-1z' /><path fill='#5d5e60' d='M12 12h1v1h-1z' /><path fill='#221f20' d='M12 11h1v1h-1zM11 11h1v1h-1zM10 11h1v1h-1z' /><path fill='#5d5e60' d='M11 14h1v1h-1zM10 14h1v1h-1z' /><path fill='#221f20' d='M15 15h1v1h-1z' /><path fill='#5d5e60' d='M14 15h1v1h-1zM13 15h1v1h-1zM12 15h1v1h-1z' /><path fill='#221f20' d='M9 10h1v1H9z' />" ]; string[] private patternSvgs = [ "<path fill='url(#pattern-color)' d='M19 7h1v1h-1zM21 7h1v1h-1zM23 10h1v1h-1zM24 10h1v1h-1zM19 12h1v1h-1zM19 13h1v1h-1zM21 14h1v1h-1zM21 15h1v1h-1zM19 17h1v1h-1zM20 18h1v1h-1zM16 18h1v1h-1zM16 17h1v1h-1zM14 16h1v1h-1zM13 17h1v1h-1zM14 20h1v1h-1zM13 20h1v1h-1zM18 20h1v1h-1zM19 21h1v1h-1zM21 24h1v1h-1zM21 23h1v1h-1zM9 20h1v1H9zM9 21h1v1H9zM11 16h1v1h-1zM11 17h1v1h-1z' />", "<path fill='url(#pattern-color)' d='M19 14h1v1h-1zM21 17h1v1h-1zM18 19h1v1h-1zM20 20h1v1h-1zM14 16h1v1h-1zM12 19h1v1h-1zM11 17h1v1h-1zM16 20h1v1h-1zM9 23h1v1H9z' />", "<path fill='url(#pattern-color)' d='M16 16h1v1h-1zM15 17h1v1h-1zM16 17h1v1h-1zM16 18h1v1h-1zM16 19h1v1h-1zM17 19h1v1h-1zM17 20h1v1h-1zM15 18h1v1h-1zM15 19h1v1h-1zM16 20h1v1h-1zM15 20h1v1h-1zM14 20h1v1h-1zM13 20h1v1h-1zM12 20h1v1h-1zM11 20h1v1h-1zM11 21h1v1h-1zM11 22h1v1h-1zM11 23h1v1h-1zM11 24h1v1h-1zM9 24h1v1H9zM9 23h1v1H9zM9 22h1v1H9zM9 21h1v1H9zM9 20h1v1H9zM10 20h1v1h-1zM10 19h1v1h-1zM9 19h1v1H9zM9 18h1v1H9zM9 17h1v1H9zM10 17h1v1h-1zM10 16h1v1h-1zM11 16h1v1h-1zM12 16h1v1h-1zM13 16h1v1h-1zM14 16h1v1h-1zM15 16h1v1h-1zM14 17h1v1h-1zM14 18h1v1h-1zM14 19h1v1h-1zM13 19h1v1h-1zM13 18h1v1h-1zM13 17h1v1h-1zM12 17h1v1h-1zM12 18h1v1h-1zM12 19h1v1h-1zM11 19h1v1h-1zM11 18h1v1h-1zM11 17h1v1h-1zM10 18h1v1h-1z' />", "<path fill='url(#pattern-color)' d='M24 10h1v1h-1zM19 7h1v1h-1zM21 7h1v1h-1z' />", "<path fill='url(#pattern-color)' d='M9 19h1v1H9zM10 19h1v1h-1zM11 18h1v1h-1zM12 18h1v1h-1zM13 17h1v1h-1zM14 17h1v1h-1zM15 17h1v1h-1zM16 18h1v1h-1zM17 18h1v1h-1zM18 18h1v1h-1zM19 19h1v1h-1zM20 19h1v1h-1zM21 18h1v1h-1zM19 12h1v1h-1zM20 13h1v1h-1zM21 14h1v1h-1zM21 15h1v1h-1zM17 20h1v1h-1zM16 20h1v1h-1zM15 20h1v1h-1zM9 22h1v1H9zM9 23h1v1H9zM9 24h1v1H9z' />", "<path fill='url(#pattern-color)' d='M12 16h1v1h-1zM11 17h1v1h-1zM10 18h1v1h-1zM9 19h1v1H9zM9 23h1v1H9zM12 20h1v1h-1zM13 19h1v1h-1zM14 18h1v1h-1zM15 17h1v1h-1zM15 16h1v1h-1zM18 16h1v1h-1zM18 17h1v1h-1zM18 18h1v1h-1zM18 19h1v1h-1zM17 20h1v1h-1zM21 17h1v1h-1zM20 16h1v1h-1zM20 15h1v1h-1zM19 14h1v1h-1zM19 11h1v1h-1zM20 12h1v1h-1zM21 13h1v1h-1zM19 22h1v1h-1zM21 24h1v1h-1zM11 22h1v1h-1z'/>", "<path fill='url(#pattern-color)' d='M9 18h1v1H9zM10 17h1v1h-1zM11 18h1v1h-1zM12 17h1v1h-1zM13 18h1v1h-1zM14 17h1v1h-1zM15 18h1v1h-1zM16 17h1v1h-1zM17 18h1v1h-1zM18 17h1v1h-1zM19 18h1v1h-1zM20 17h1v1h-1zM21 18h1v1h-1zM10 19h1v1h-1zM9 20h1v1H9zM11 20h1v1h-1zM12 19h1v1h-1zM13 20h1v1h-1zM14 19h1v1h-1zM15 20h1v1h-1zM16 19h1v1h-1zM17 20h1v1h-1zM18 19h1v1h-1zM19 20h1v1h-1zM20 19h1v1h-1zM21 20h1v1h-1zM21 16h1v1h-1zM19 16h1v1h-1zM20 15h1v1h-1zM19 14h1v1h-1zM20 13h1v1h-1zM19 12h1v1h-1zM19 22h1v1h-1zM19 24h1v1h-1zM9 22h1v1H9zM9 24h1v1H9zM11 24h1v1h-1zM11 22h1v1h-1zM21 22h1v1h-1zM21 24h1v1h-1z' />", "<path fill='url(#pattern-color)' d='M12 17h1v1h-1zM12 18h1v1h-1zM11 18h1v1h-1zM11 19h1v1h-1zM12 19h1v1h-1zM12 20h1v1h-1zM13 20h1v1h-1zM13 19h1v1h-1zM14 19h1v1h-1zM15 19h1v1h-1zM15 18h1v1h-1zM14 18h1v1h-1zM13 18h1v1h-1zM13 17h1v1h-1zM16 16h1v1h-1zM17 16h1v1h-1zM18 16h1v1h-1zM18 17h1v1h-1zM17 17h1v1h-1zM19 17h1v1h-1zM21 12h1v1h-1zM21 13h1v1h-1zM21 14h1v1h-1zM20 14h1v1h-1zM20 13h1v1h-1zM21 19h1v1h-1zM20 19h1v1h-1zM20 20h1v1h-1zM21 20h1v1h-1zM19 21h1v1h-1zM19 22h1v1h-1zM19 20h1v1h-1z'/>", "", "<path fill='url(#pattern-color)' d='M21 9h1v1h-1zM20 9h1v1h-1zM20 10h1v1h-1zM20 11h1v1h-1zM21 11h1v1h-1z' /><path fill='#fff' d='M21 10h1v1h-1z' /><path fill='url(#pattern-color)' d='M22 11h1v1h-1zM22 10h1v1h-1zM22 9h1v1h-1zM23 10h1v1h-1zM23 11h1v1h-1zM24 10h1v1h-1zM24 11h1v1h-1zM20 13h1v1h-1zM20 14h1v1h-1zM20 15h1v1h-1zM20 16h1v1h-1zM19 16h1v1h-1zM18 16h1v1h-1zM17 16h1v1h-1zM16 16h1v1h-1zM15 16h1v1h-1zM14 16h1v1h-1zM13 16h1v1h-1zM12 16h1v1h-1zM11 16h1v1h-1zM10 16h1v1h-1zM11 17h1v1h-1zM10 18h1v1h-1zM10 19h1v1h-1zM14 17h1v1h-1zM13 18h1v1h-1zM13 19h1v1h-1zM17 17h1v1h-1zM16 18h1v1h-1zM16 19h1v1h-1zM19 17h1v1h-1zM19 18h1v1h-1zM19 19h1v1h-1z' />" ]; string[] private tailSvgs = [ "<path fill='url(#mane-color)' d='M10 17H9v-1h1zM9 17H8v-1h1zM8 18H7v-1h1zM9 18H8v-1h1zM9 19H8v-1h1zM8 19H7v-1h1zM8 20H7v-1h1zM9 20H8v-1h1zM9 21H8v-1h1zM8 21H7v-1h1zM8 22H7v-1h1zM7 22H6v-1h1zM8 23H7v-1h1zM7 23H6v-1h1zM7 24H6v-1h1zM8 24H7v-1h1zM7 25H6v-1h1z' />", "<path fill='url(#mane-color)' d='M10 17H9v-1h1zM9 17H8v-1h1zM9 18H8v-1h1zM8 18H7v-1h1zM8 19H7v-1h1zM8 20H7v-1h1zM8 21H7v-1h1zM9 21H8v-1h1zM9 20H8v-1h1zM9 19H8v-1h1zM8 22H7v-1h1zM7 22H6v-1h1zM7 21H6v-1h1zM6 21H5v-1h1zM6 20H5v-1h1z' />", "<path fill='url(#mane-color)' d='M10 17H9v-1h1zM10 16H9v-1h1zM10 15H9v-1h1z'/>", "<path fill='url(#mane-color)' d='M10 17H9v-1h1zM9 17H8v-1h1zM8 18H7v-1h1zM9 18H8v-1h1zM9 19H8v-1h1zM8 19H7v-1h1zM8 20H7v-1h1zM9 20H8v-1h1zM9 21H8v-1h1zM8 21H7v-1h1zM8 22H7v-1h1zM7 22H6v-1h1zM8 23H7v-1h1zM7 23H6v-1h1zM7 24H6v-1h1zM8 24H7v-1h1zM7 25H6v-1h1zM7 26H6v-1h1zM6 26H5v-1h1zM5 26H4v-1h1zM4 26H3v-1h1zM3 26H2v-1h1zM6 25H5v-1h1zM6 24H5v-1h1zM5 25H4v-1h1zM2 26H1v-1h1zM1 26H0v-1h1zM4 25H3v-1h1z' />", "<path fill='url(#mane-color)' d='M10 17H9v-1h1z' />", "<path fill='url(#mane-color)' d='M10 17H9v-1h1zM9 17H8v-1h1zM9 18H8v-1h1zM9 20H8v-1h1zM9 21H8v-1h1z' />", "<path fill='url(#mane-color)' d='M10 17H9v-1h1zM9 17H8v-1h1zM9 18H8v-1h1zM9 20H8v-1h1zM9 21H8v-1h1z' />", "<path fill='url(#mane-color)' d='M10 17H9v-1h1zM9 18H8v-1h1zM9 17H8v-1h1zM8 18H7v-1h1zM9 19H8v-1h1zM9 20H8v-1h1zM9 21H8v-1h1zM9 22H8v-1h1zM8 20H7v-1h1zM8 22H7v-1h1zM9 23H8v-1h1zM9 24H8v-1h1z'/>" ]; string[] private maneSvgs = [ "<path fill='url(#mane-color)' d='M21 9h-1V8h1zm-2 1h-1V9h1zm0 1h-1v-1h1zm0 1h-1v-1h1zm0 1h-1v-1h1zm0 1h-1v-1h1zm0 1h-1v-1h1zm0 1h-1v-1h1zm-1 0h-1v-1h1zm-1 0h-1v-1h1zm-1 0h-1v-1h1zm-1 0h-1v-1h1zm2-1h-1v-1h1zm1 0h-1v-1h1zm0-1h-1v-1h1zm0-1h-1v-1h1zm0-1h-1v-1h1zm4-3h-1V8h1z' />", "<path fill='url(#mane-color)' d='M21 9h-1V8h1zM21 10h-1V9h1zM19 10h-1V9h1zM19 11h-1v-1h1zM19 12h-1v-1h1zM19 13h-1v-1h1zM19 14h-1v-1h1zM19 15h-1v-1h1zM19 16h-1v-1h1zM18 16h-1v-1h1zM17 16h-1v-1h1zM16 16h-1v-1h1zM16 17h-1v-1h1zM15 17h-1v-1h1zM14 17h-1v-1h1zM14 18h-1v-1h1zM15 18h-1v-1h1zM15 19h-1v-1h1zM14 19h-1v-1h1zM14 20h-1v-1h1zM14 21h-1v-1h1zM13 20h-1v-1h1zM13 21h-1v-1h1zM13 22h-1v-1h1zM13 23h-1v-1h1zM15 16h-1v-1h1zM17 15h-1v-1h1zM18 15h-1v-1h1zM18 14h-1v-1h1zM18 13h-1v-1h1zM18 12h-1v-1h1zM22 9h-1V8h1z' />", "<path fill='url(#mane-color)' d='M21 9h-1V8h1zM19 10h-1V9h1zM19 11h-1v-1h1zM19 12h-1v-1h1zM19 13h-1v-1h1zM19 14h-1v-1h1zM19 15h-1v-1h1zM19 16h-1v-1h1zM18 16h-1v-1h1zM22 9h-1V8h1z' />", "<path fill='url(#mane-color)' d='M21 9h-1V8h1zM19 10h-1V9h1zM19 11h-1v-1h1zM19 12h-1v-1h1zM19 13h-1v-1h1zM19 14h-1v-1h1zM19 15h-1v-1h1zM19 16h-1v-1h1zM18 16h-1v-1h1zM17 16h-1v-1h1zM17 17h-1v-1h1zM16 17h-1v-1h1zM16 18h-1v-1h1zM16 19h-1v-1h1zM15 18h-1v-1h1zM15 19h-1v-1h1zM15 20h-1v-1h1zM15 21h-1v-1h1zM15 22h-1v-1h1zM15 23h-1v-1h1zM15 24h-1v-1h1zM16 16h-1v-1h1zM15 16h-1v-1h1zM15 17h-1v-1h1zM14 17h-1v-1h1zM14 18h-1v-1h1zM14 19h-1v-1h1zM14 20h-1v-1h1zM14 21h-1v-1h1zM14 22h-1v-1h1zM14 23h-1v-1h1zM17 15h-1v-1h1zM18 15h-1v-1h1zM18 14h-1v-1h1zM18 13h-1v-1h1zM18 12h-1v-1h1zM22 9h-1V8h1z' />", "<path fill='url(#mane-color)' d='M21 9h-1V8h1zM19 10h-1V9h1zM19 11h-1v-1h1zM19 12h-1v-1h1zM19 13h-1v-1h1zM19 14h-1v-1h1zM22 9h-1V8h1z' />", "<path fill='url(#mane-color)' d='M21 9h-1V8h1zM19 10h-1V9h1zM19 11h-1v-1h1zM19 12h-1v-1h1zM19 13h-1v-1h1zM19 14h-1v-1h1zM19 15h-1v-1h1zM19 16h-1v-1h1zM18 16h-1v-1h1zM17 16h-1v-1h1zM16 16h-1v-1h1zM17 15h-1v-1h1zM18 15h-1v-1h1zM18 14h-1v-1h1zM18 13h-1v-1h1zM18 12h-1v-1h1zM15 16h-1v-1h1zM24 13h-1v-1h1zM24 14h-1v-1h1zM24 15h-1v-1h1zM25 13h-1v-1h1zM22 9h-1V8h1z' />", "<path fill='url(#mane-color)' d='M21 9h-1V8h1zM19 10h-1V9h1zM18 10h-1V9h1zM18 12h-1v-1h1zM19 11h-1v-1h1zM19 12h-1v-1h1zM19 13h-1v-1h1zM19 14h-1v-1h1zM19 15h-1v-1h1zM18 14h-1v-1h1zM22 9h-1V8h1z' />", "<path fill='url(#mane-color)' d='M21 9h-1V8h1zM19 10h-1V9h1zM19 11h-1v-1h1zM19 13h-1v-1h1zM19 14h-1v-1h1zM19 16h-1v-1h1zM18 16h-1v-1h1zM22 9h-1V8h1z' />", "<path fill='url(#mane-color)' d='M21 9h-1V8h1zm-2 1h-1V9h1zm-1 0h-1V9h1zm0 2h-1v-1h1zm1-1h-1v-1h1zm0 1h-1v-1h1zm0 1h-1v-1h1zm0 1h-1v-1h1zm0 1h-1v-1h1zm0 1h-1v-1h1zm-1 0h-1v-1h1zm-1 0h-1v-1h1zm-1 0h-1v-1h1zm-1 0h-1v-1h1zm-1 0h-1v-1h1zm-1 0h-1v-1h1zm-1 0h-1v-1h1zm4-1h-1v-1h1zm-2 0h-1v-1h1zm10-2h-1v-1h1zm1 0h-1v-1h1zm-1 1h-1v-1h1zm0 1h-1v-1h1zm-6-1h-1v-1h1zm4-5h-1V8h1z' />" ]; string[] private backgroundSvgs = [ "<rect width='32' height='32' fill='#fff9d0' />", "<rect width='32' height='32' fill='#dfefff' />", "<rect width='32' height='32' fill='#aaffcf' />", "<rect width='32' height='32' fill='#efefcf' />", "<rect width='32' height='32' fill='#dadee9' />", "<rect width='32' height='32' fill='#ddadaf' />", "<rect width='32' height='32' fill='#ffefcf' />", "<rect width='32' height='32' fill='#bbe4ea' />", "<rect width='32' height='32' fill='#ffefbf' />", "<rect width='32' height='32' fill='#ffdfff' />" ]; string[] private utilitySvgs = [ "", "<path fill='#7f5748' d='M28 3h1v1h-1zM28 4h1v1h-1zM27 2h1v1h-1zM29 2h1v1h-1z' /><path fill='#ffda69' d='M29 3h1v1h-1zM29 5h1v1h-1zM27 3h1v1h-1zM27 5h1v1h-1z' />", "<path fill='#93d0f3' d='M27 23h1v1h-1zM27 24h1v1h-1zM28 22h1v1h-1z' /><path fill='#a4d18a' d='M28 21h1v1h-1z' /><path fill='#ffea84' d='M27 22h1v1h-1z' /><path fill='#93d0f3' d='M27 25h1v1h-1zM26 25h1v1h-1zM28 25h1v1h-1zM26 22h1v1h-1z' />", "<path fill='#ffda69' d='M27 20h1v1h-1zM26 21h1v1h-1z' /><path fill='#7f5748' d='M27 21h1v1h-1z' /><path fill='#ffda69' d='M28 21h1v1h-1zM28 22h1v1h-1zM27 22h1v1h-1zM26 22h1v1h-1zM27 23h1v1h-1zM27 24h1v1h-1zM26 25h1v1h-1zM27 25h1v1h-1zM28 25h1v1h-1z' />", "<path fill='#ffda69' d='M27 18h1v1h-1zM28 20h1v1h-1zM27 22h1v1h-1zM27 23h1v1h-1zM26 23h1v1h-1zM26 24h1v1h-1z' /><path fill='#d9554d' d='M27 24h1v1h-1z' /><path fill='#ffda69' d='M28 24h1v1h-1z' /><path fill='#a85f44' d='M28 25h1v1h-1zM27 25h1v1h-1zM26 25h1v1h-1zM25 25h1v1h-1zM29 25h1v1h-1z' />", "<path fill='#4dc7f6' d='M26 16h1v1h-1z' /><path fill='#555' d='M27 24h1v1h-1zm1-1h1v1h-1zm1-1h1v1h-1zm1-1h1v1h-1zm1-1h1v1h-1zm0-1h1v1h-1zm0-1h1v1h-1zm-1-1h1v1h-1zm-1-1h1v1h-1zm-1-1h1v1h-1zm-1 0h1v1h-1zm0 8h1v1h-1zm0 2h1v1h-1zm-1 0h1v1h-1zm-1 0h1v1h-1zm3 0h1v1h-1zm1 0h1v1h-1z' /><path fill='#4dc7f6' d='M25 17h1v1h-1z' /><path fill='#56b746' d='M24 18h1v1h-1zm0 1h1v1h-1z' /><path fill='#4dc7f6' d='M24 20h1v1h-1zm1 1h1v1h-1zm1 1h1v1h-1z' /><path fill='#56b746' d='M27 22h1v1h-1z' /><path fill='#4dc7f6' d='M28 22h1v1h-1zm1-1h1v1h-1z' /><path fill='#56b746' d='M30 20h1v1h-1z' /><path fill='#4dc7f6' d='M30 19h1v1h-1z' /><path fill='#56b746' d='M30 18h1v1h-1z' /><path fill='#4dc7f6' d='M29 17h1v1h-1zm-1-1h1v1h-1z' /><path fill='#56b746' d='M27 16h1v1h-1z' /><path fill='#4dc7f6' d='M26 17h1v1h-1z' /><path fill='#56b746' d='M26 18h1v1h-1zm-1 0h1v1h-1zm0 1h1v1h-1zm1 1h1v1h-1z' /><path fill='#4dc7f6' d='M26 19h1v1h-1zm-1 1h1v1h-1zm1 1h1v1h-1z' /><path fill='#56b746' d='M27 21h1v1h-1zm1 0h1v1h-1zm0-1h1v1h-1zm0-1h1v1h-1zm-1 0h1v1h-1zm0 1h1v1h-1z' /><path fill='#4dc7f6' d='M29 20h1v1h-1z' /><path fill='#56b746' d='M29 19h1v1h-1zm0-1h1v1h-1z' /><path fill='#4dc7f6' d='M28 18h1v1h-1z' /><path fill='#56b746' d='M27 18h1v1h-1zm0-1h1v1h-1zm1 0h1v1h-1z' />", "<path fill='#000' d='M27 8h1v1h-1zM26 7h1v1h-1zM28 7h1v1h-1zM22 4h1v1h-1zM21 3h1v1h-1zM23 3h1v1h-1zM28 3h1v1h-1zM27 2h1v1h-1zM29 2h1v1h-1z' />", "<path fill='#555' d='M27 25h1v1h-1zM27 24h1v1h-1zM27 23h1v1h-1zM27 22h1v1h-1zM26 25h1v1h-1zM26 22h1v1h-1zM28 22h1v1h-1zM28 25h1v1h-1z' /><path fill='#27aae1' d='M26 18h1v1h-1zM25 19h1v1h-1zM25 20h1v1h-1zM26 21h1v1h-1zM27 21h1v1h-1zM28 21h1v1h-1zM29 20h1v1h-1zM29 19h1v1h-1zM29 18h1v1h-1zM28 17h1v1h-1zM27 17h1v1h-1zM26 17h1v1h-1zM25 18h1v1h-1zM26 19h1v1h-1zM26 20h1v1h-1zM27 20h1v1h-1zM28 20h1v1h-1zM28 19h1v1h-1z' /><path fill='#fff' d='M28 18h1v1h-1z' /><path fill='#27aae1' d='M27 18h1v1h-1zM27 19h1v1h-1z' />", "<path fill='#75c164' d='M27 25h1v1h-1zM27 24h1v1h-1zM27 23h1v1h-1z' /><path fill='#ffda6a' d='M27 22h1v1h-1z' /><path fill='#ee2636' d='M27 21h1v1h-1z' /><path fill='#ffda6a' d='M27 20h1v1h-1z' /><path fill='#fff' d='M26 20h1v1h-1z' /><path fill='#ffda6a' d='M26 21h1v1h-1z' /><path fill='#fff' d='M26 22h1v1h-1zM28 22h1v1h-1z' /><path fill='#ffda6a' d='M28 21h1v1h-1z' /><path fill='#fff' d='M28 20h1v1h-1z' /><path fill='#75c164' d='M28 24h1v1h-1z' />", "<path fill='#1c75bc' d='M27 22h1v1h-1zm-1 1h1v1h-1zm0 1h1v1h-1zm1 1h1v1h-1zm1 0h1v1h-1zm1 0h1v1h-1zm1-1h1v1h-1zm0-1h1v1h-1zm-1-1h1v1h-1z' /><path fill='#00aeef' d='M27 23h1v1h-1zm1 0h1v1h-1z' /><path fill='#fbb040' d='M29 23h1v1h-1z' /><path fill='#00aeef' d='M29 24h1v1h-1zm-1 0h1v1h-1zm-1 0h1v1h-1z' />", "<path fill='#754c29' d='M26 24h1v1h-1zm1 0h1v1h-1zm1 0h1v1h-1zm1 0h1v1h-1zm-1 1h1v1h-1zm-1 0h1v1h-1z' /><path fill='#a97c50' d='M28 23h1v1h-1zm-1-1h1v1h-1zm1-1h1v1h-1zm1 0h1v1h-1zm1-1h1v1h-1z' /><path fill='#75c164' d='M30 19h1v1h-1zm0-1h1v1h-1zm-1 0h1v1h-1zm0-1h1v1h-1zm-1 0h1v1h-1zm-1 0h1v1h-1zm-1 0h1v1h-1zm0 1h1v1h-1zm-1 0h1v1h-1zm0 1h1v1h-1zm1 0h1v1h-1zm0 1h1v1h-1zm1 0h1v1h-1zm1 0h1v1h-1zm1 0h1v1h-1zm0-1h1v1h-1zm-1 0h1v1h-1zm-1 0h1v1h-1zm0-1h1v1h-1zm1 0h1v1h-1z' />", "<path fill='#8b5e3c' d='M26 25h1v1h-1zm1 0h1v1h-1zm1 0h1v1h-1zm1 0h1v1h-1zm0-1h1v1h-1zm0-1h1v1h-1zm-2 0h1v1h-1zm-1 0h1v1h-1z' /><path fill='#ffda6a' d='M27 22h1v1h-1zm1 0h1v1h-1zm1 0h1v1h-1zm-3 0h1v1h-1zm1-1h1v1h-1zm1 0h1v1h-1z' /><path fill='#8b5e3c' d='M26 24h1v1h-1z' /><path fill='#414042' d='M27 24h1v1h-1zm1 0h1v1h-1z' /><path fill='#8b5e3c' d='M28 23h1v1h-1zm2-1h1v1h-1zm0-1h1v1h-1zm0-1h1v1h-1zm0-1h1v1h-1zm1 1h1v1h-1zm0 1h1v1h-1z' />", "<path fill='#a97c50' d='M29 25h1v1h-1zm-2 0h1v1h-1z' /><path fill='#4eb74a' d='M24 23h1v1h-1zm1 0h1v1h-1zm0 1h1v1h-1zm-1 0h1v1h-1zm2 0h1v1h-1z' /><path fill='#408251' d='M27 24h1v1h-1zm0-1h1v1h-1zm1-1h1v1h-1zm1 0h1v1h-1zm1 2h1v1h-1zm-1 0h1v1h-1zm-1 0h1v1h-1zm0-1h1v1h-1zm1 0h1v1h-1zm1 0h1v1h-1z' /><path fill='#4eb74a' d='M31 24h1v1h-1z' />", "<path fill='#f57f20' d='M26 25h1v1h-1zM28 25h1v1h-1z' /><path fill='#fff' d='M29 23h1v1h-1zM29 22h1v1h-1zM29 24h1v1h-1zM28 24h1v1h-1zM27 24h1v1h-1zM26 24h1v1h-1zM26 23h1v1h-1zM25 23h1v1h-1zM25 22h1v1h-1zM25 21h1v1h-1zM25 20h1v1h-1zM26 20h1v1h-1zM26 21h1v1h-1zM26 22h1v1h-1zM27 23h1v1h-1zM28 23h1v1h-1z' /><path fill='#ebbd54' d='M24 21h1v1h-1z' />", "<path fill='#939598' opacity='.5' d='M26 23h1v1h-1zm0-1h1v1h-1zm0-1h1v1h-1zm0-1h1v1h-1zm0-1h1v1h-1zm0-1h1v1h-1zm1 0h1v1h-1zm0-1h1v1h-1zm1 0h1v1h-1zm1 0h1v1h-1zm0 1h1v1h-1zm1 0h1v1h-1zm0 2h1v1h-1zm0 1h1v1h-1zm0 1h1v1h-1zm0 1h1v1h-1zm-1-1h1v1h-1zm-1 1h1v1h-1zm-1-1h1v1h-1zm1 0h1v1h-1zm0-1h1v1h-1zm1 0h1v1h-1zm0-1h1v1h-1zm0-1h1v1h-1zm-1-1h1v1h-1zm-1 1h1v1h-1zm0 1h1v1h-1zm0 1h1v1h-1zm1-1h1v1h-1z' /><path fill='#fff200' d='M30 19h1v1h-1zm-2 0h1v1h-1z' />" ]; // attribute names string[] private patternNames = [ "giraffe", "small spots", "two tone", "tips", "curves", "stripes", "racing", "big spots", "butt naked", "death" ]; string[] private headAccessoryNames = [ "none", "purple cap", "propeller cap", "golden necklace", "unicorn horn", "flame breath", "top hat", "devil horns", "wizard hat", "laser", "viking helmet", "golden halo", "rainbow puke", "crown" ]; string[] private bodyAccessoryNames = [ "none", "winner", "bravery boots", "rainbow", "charged", "wings", "speed booster", "black cat", "hell wings" ]; string[] private maneColorNames = [ "black", "strawberry", "blackberry", "juneberry", "cranberry", "cloudberry", "snowberry", "blueberry", "caperberry", "dewberry", "gold" ]; string[] private patternColorNames = [ "brown", "dark", "light blue", "pink", "purple", "green", "red", "cream", "orange", "blue", "deep pink", "white" ]; string[] private hoofColorNames = [ "black", "dark brown", "dark blue", "brown", "dark green", "light green", "red", "light purple", "purple", "pink", "gold" ]; string[] private bodyColorNames = [ "giraffe", "butterfly", "elephant", "bear", "polar bear", "frog", "lobster", "turtle", "whale", "gold" ]; string[] private tailNames = [ "normal", "pointy", "dog", "long", "bun", "baked", "pile", "dragon" ]; string[] private maneNames = [ "normal", "messy", "tidy", "overwhelming", "short", "bearded", "dragon", "baked", "mother of dragons" ]; string[] private backgroundNames = [ "curd", "starlight", "seafoam", "ghost green", "fog", "chestnut", "sand", "ice", "banana", "grape" ]; string[] private utilityNames = [ "none", "butterfly of fortune", "martini with alcohol", "grail of gold", "bonfire from hell", "globe of nastyness", "bats of mayhem", "orb of future", "flower of goodwill", "bowl of gold fish", "bonsai of life", "chest with bling", "turtle of speed", "duck of doom", "ghost of death" ]; // attribute rarities uint256[] private maneColorRarities = [ 4000, 1000, 1000, 1000, 800, 800, 500, 300, 300, 200, 100 ]; uint256[] private patternColorRarities = [ 3000, 1700, 1350, 900, 800, 800, 500, 300, 200, 200, 150, 100 ]; uint256[] private hoofColorRarities = [ 3500, 1500, 1100, 1000, 1000, 500, 500, 400, 200, 200, 100 ]; uint256[] private bodyColorRarities = [ 2900, 1500, 1500, 1500, 700, 600, 500, 500, 200, 100 ]; uint256[] private backgroundRarities = [ 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000 ]; uint256[] private tailRarities = [ 3000, 2000, 1500, 1200, 1000, 750, 350, 200 ]; uint256[] private maneRarities = [ 3000, 1800, 1600, 900, 800, 700, 600, 400, 200 ]; uint256[] private patternRarities = [ 2000, 1500, 1500, 1100, 1000, 800, 800, 500, 500, 300 ]; uint256[] private headAccessoryRarities = [ 3100, 1500, 1000, 800, 700, 700, 500, 550, 250, 300, 300, 150, 100, 50 ]; uint256[] private bodyAccessoryRarities = [ 2500, 2300, 1400, 1000, 800, 800, 600, 400, 200 ]; uint256[] private utilityRarities = [ 3700, 1000, 900, 500, 400, 500, 200, 600, 900, 500, 300, 250, 100, 100, 50 ]; // amount of attributes uint8 constant maneColorCount = 11; uint8 constant patternColorCount = 12; uint8 constant hoofColorCount = 11; uint8 constant bodyColorCount = 10; uint8 constant backgroundCount = 10; uint8 constant tailCount = 8; uint8 constant maneCount = 9; uint8 constant patternCount = 10; uint8 constant headAccessoryCount = 14; uint8 constant bodyAccessoryCount = 9; uint8 constant utilityCount = 15; /** * Use: * Get a random attribute using the rarities defined */ function getRandomIndex( uint256[] memory attributeRarities, uint8 attributeCount, uint256 randomNumber ) private pure returns (uint8 index) { uint256 random10k = randomNumber % 10000; uint256 steps = 0; for (uint8 i = 0; i < attributeCount; i++) { uint256 currentRarity = attributeRarities[i] + steps; if (random10k < currentRarity) { return i; } steps = currentRarity; } return 0; } /** * Use: * Get random attributes for each different property of the token * * Comment: * Can only be used by the TokenContract defined by address tokenContract */ function getRandomAttributes(uint256 randomNumber) public view returns ( uint8 maneColor, uint8 patternColor, uint8 hoofColor, uint8 bodyColor, uint8 background, uint8 tail, uint8 mane, uint8 pattern, uint8 headAccessory, uint8 bodyAccessory, uint8 utility ) { maneColor = getRandomManeColor(randomNumber); randomNumber = randomNumber / 10; patternColor = getRandomPatternColor(randomNumber); randomNumber = randomNumber / 10; hoofColor = getRandomHoofColor(randomNumber); randomNumber = randomNumber / 10; bodyColor = getRandomBodyColor(randomNumber); randomNumber = randomNumber / 10; background = getRandomBackground(randomNumber); randomNumber = randomNumber / 10; tail = getRandomTail(randomNumber); randomNumber = randomNumber / 10; mane = getRandomMane(randomNumber); randomNumber = randomNumber / 10; pattern = getRandomPattern(randomNumber); randomNumber = randomNumber / 10; headAccessory = getRandomHeadAccessory(randomNumber); randomNumber = randomNumber / 10; bodyAccessory = getRandomBodyAccessory(randomNumber); randomNumber = randomNumber / 10; utility = getRandomUtility(randomNumber); return ( maneColor, patternColor, hoofColor, bodyColor, background, tail, mane, pattern, headAccessory, bodyAccessory, utility ); } function getRandomManeColor(uint256 randomNumber) private view returns (uint8) { return getRandomIndex(maneColorRarities, maneColorCount, randomNumber); } function getRandomPatternColor(uint256 randomNumber) private view returns (uint8) { return getRandomIndex( patternColorRarities, patternColorCount, randomNumber ); } function getRandomHoofColor(uint256 randomNumber) private view returns (uint8) { return getRandomIndex(hoofColorRarities, hoofColorCount, randomNumber); } function getRandomBodyColor(uint256 randomNumber) private view returns (uint8) { return getRandomIndex(bodyColorRarities, bodyColorCount, randomNumber); } function getRandomBackground(uint256 randomNumber) private view returns (uint8) { return getRandomIndex(backgroundRarities, backgroundCount, randomNumber); } function getRandomTail(uint256 randomNumber) private view returns (uint8) { return getRandomIndex(tailRarities, tailCount, randomNumber); } function getRandomMane(uint256 randomNumber) private view returns (uint8) { return getRandomIndex(maneRarities, maneCount, randomNumber); } function getRandomPattern(uint256 randomNumber) private view returns (uint8) { return getRandomIndex(patternRarities, patternCount, randomNumber); } function getRandomHeadAccessory(uint256 randomNumber) private view returns (uint8) { return getRandomIndex( headAccessoryRarities, headAccessoryCount, randomNumber ); } function getRandomBodyAccessory(uint256 randomNumber) private view returns (uint8) { return getRandomIndex( bodyAccessoryRarities, bodyAccessoryCount, randomNumber ); } function getRandomUtility(uint256 randomNumber) private view returns (uint8) { return getRandomIndex(utilityRarities, utilityCount, randomNumber); } /** * Use: * Get the attribute name for the properties of the token * * Comment: * Can only be used by the TokenContract defined by address tokenContract */ function getManeColor(uint8 index) public view returns (string memory) { return maneColorNames[index]; } function getPatternColor(uint8 index) public view returns (string memory) { return patternColorNames[index]; } function getHoofColor(uint8 index) public view returns (string memory) { return hoofColorNames[index]; } function getBodyColor(uint8 index) public view returns (string memory) { return bodyColorNames[index]; } function getBackground(uint8 index) public view returns (string memory) { return backgroundNames[index]; } function getTail(uint8 index) public view returns (string memory) { return tailNames[index]; } function getMane(uint8 index) public view returns (string memory) { return maneNames[index]; } function getPattern(uint8 index) public view returns (string memory) { return patternNames[index]; } function getHeadAccessory(uint8 index) public view returns (string memory) { return headAccessoryNames[index]; } function getBodyAccessory(uint8 index) public view returns (string memory) { return bodyAccessoryNames[index]; } function getUtility(uint8 index) public view returns (string memory) { return utilityNames[index]; } /** * Use: * Get the attribute svg for a different property of the token * * Comment: * Can only be used by the TokenContract defined by address tokenContract */ function renderHorse( bytes memory colors, uint8 background, uint8 tail, uint8 mane, uint8 pattern, uint8 headAccessory, uint8 bodyAccessory, uint8 utility ) public view returns (bytes memory) { bytes memory start = abi.encodePacked( svgStart, colors, backgroundSvgs[background], base, patternSvgs[pattern] ); return abi.encodePacked( start, tailSvgs[tail], maneSvgs[mane], headAccessorySvgs[headAccessory], bodyAccessorySvgs[bodyAccessory], utilitySvgs[utility], svgEnd ); } /** * Use: * Create color definitions for the svg */ function packColor(string memory colorName, string memory colorSvg) private pure returns (bytes memory) { return abi.encodePacked( "<linearGradient id='", colorName, "'><stop stop-color='", colorSvg, "'/></linearGradient>" ); } /** * Use: * Pack all colors together */ function renderColors( uint8 maneColor, uint8 patternColor, uint8 hoofColor, uint8 bodyColor ) public view returns (bytes memory) { return abi.encodePacked( "<defs>", packColor("mane-color", maneColorSvgs[maneColor]), packColor("pattern-color", patternColorSvgs[patternColor]), packColor("hoof-color", hoofColorSvgs[hoofColor]), packColor("body-color", bodyColorSvgs[bodyColor]), "</defs>" ); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.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 Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @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 "../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); }
* Use: Get random attributes for each different property of the token Comment: Can only be used by the TokenContract defined by address tokenContract/ render svg pack properties
function getRandomAttributes(uint256 randomNumber) public view returns (string memory svg, string memory properties) { uint8[] memory attributes = new uint8[](11); attributes[0] = getRandomIndex( maneColorRarities, maneColorCount, randomNumber ); randomNumber = randomNumber / 100; attributes[1] = getRandomIndex( patternColorRarities, patternColorCount, randomNumber ); randomNumber = randomNumber / 100; attributes[2] = getRandomIndex( hoofColorRarities, hoofColorCount, randomNumber ); randomNumber = randomNumber / 100; attributes[3] = getRandomIndex( bodyColorRarities, bodyColorCount, randomNumber ); randomNumber = randomNumber / 100; attributes[4] = getRandomIndex( backgroundRarities, backgroundCount, randomNumber ); randomNumber = randomNumber / 100; attributes[5] = getRandomIndex(tailRarities, tailCount, randomNumber); randomNumber = randomNumber / 100; attributes[6] = getRandomIndex(maneRarities, maneCount, randomNumber); randomNumber = randomNumber / 100; attributes[7] = getRandomIndex( patternRarities, patternCount, randomNumber ); randomNumber = randomNumber / 100; attributes[8] = getRandomIndex( headAccessoryRarities, headAccessoryCount, randomNumber ); randomNumber = randomNumber / 100; attributes[9] = getRandomIndex( bodyAccessoryRarities, bodyAccessoryCount, randomNumber ); randomNumber = randomNumber / 100; attributes[10] = getRandomIndex( utilityRarities, utilityCount, randomNumber ); bytes memory _svg = HorseUtilityContract(utilityContract).renderHorse( HorseUtilityContract(utilityContract).renderColors( attributes[0], attributes[1], attributes[2], attributes[3] ), attributes[4], attributes[5], attributes[6], attributes[7], attributes[8], attributes[9], attributes[10] ); svg = Base64.encode(_svg); bytes memory _properties = abi.encodePacked( packMetaData( "background", HorseUtilityContract(utilityContract).getBackground( attributes[4] ), 0 ), packMetaData( "tail", HorseUtilityContract(utilityContract).getTail(attributes[5]), 0 ), packMetaData( "mane", HorseUtilityContract(utilityContract).getMane(attributes[6]), 0 ), packMetaData( "pattern", HorseUtilityContract(utilityContract).getPattern(attributes[7]), 0 ), packMetaData( "head accessory", HorseUtilityContract(utilityContract).getHeadAccessory( attributes[8] ), 0 ), packMetaData( "body accessory", HorseUtilityContract(utilityContract).getBodyAccessory( attributes[9] ), 0 ), packMetaData( "utility", HorseUtilityContract(utilityContract).getUtility( attributes[10] ), 0 ) ); string[] memory colorNames = new string[](4); colorNames[0] = HorseUtilityContract(utilityContract).getManeColor( attributes[0] ); colorNames[1] = HorseUtilityContract(utilityContract).getPatternColor( attributes[1] ); colorNames[2] = HorseUtilityContract(utilityContract).getHoofColor( attributes[2] ); colorNames[3] = HorseUtilityContract(utilityContract).getBodyColor( attributes[3] ); properties = string( abi.encodePacked( _properties, packMetaData("mane color", colorNames[0], 0), packMetaData("pattern color", colorNames[1], 0), packMetaData("hoof color", colorNames[2], 0), packMetaData("body color", colorNames[3], 1) ) ); return (svg, properties); }
1,425,389
[ 1, 3727, 30, 968, 2744, 1677, 364, 1517, 3775, 1272, 434, 326, 1147, 9821, 30, 4480, 1338, 506, 1399, 635, 326, 3155, 8924, 2553, 635, 1758, 1147, 8924, 19, 1743, 9804, 2298, 1790, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 20581, 2498, 12, 11890, 5034, 2744, 1854, 13, 203, 3639, 1071, 203, 3639, 1476, 203, 3639, 1135, 261, 1080, 3778, 9804, 16, 533, 3778, 1790, 13, 203, 565, 288, 203, 3639, 2254, 28, 8526, 3778, 1677, 273, 394, 2254, 28, 8526, 12, 2499, 1769, 203, 3639, 1677, 63, 20, 65, 273, 20581, 1016, 12, 203, 5411, 3161, 73, 2957, 54, 297, 1961, 16, 203, 5411, 3161, 73, 2957, 1380, 16, 203, 5411, 2744, 1854, 203, 3639, 11272, 203, 3639, 2744, 1854, 273, 2744, 1854, 342, 2130, 31, 203, 3639, 1677, 63, 21, 65, 273, 20581, 1016, 12, 203, 5411, 1936, 2957, 54, 297, 1961, 16, 203, 5411, 1936, 2957, 1380, 16, 203, 5411, 2744, 1854, 203, 3639, 11272, 203, 3639, 2744, 1854, 273, 2744, 1854, 342, 2130, 31, 203, 3639, 1677, 63, 22, 65, 273, 20581, 1016, 12, 203, 5411, 26025, 792, 2957, 54, 297, 1961, 16, 203, 5411, 26025, 792, 2957, 1380, 16, 203, 5411, 2744, 1854, 203, 3639, 11272, 203, 3639, 2744, 1854, 273, 2744, 1854, 342, 2130, 31, 203, 3639, 1677, 63, 23, 65, 273, 20581, 1016, 12, 203, 5411, 1417, 2957, 54, 297, 1961, 16, 203, 5411, 1417, 2957, 1380, 16, 203, 5411, 2744, 1854, 203, 3639, 11272, 203, 3639, 2744, 1854, 273, 2744, 1854, 342, 2130, 31, 203, 3639, 1677, 63, 24, 65, 273, 20581, 1016, 12, 203, 5411, 5412, 54, 297, 1961, 16, 203, 5411, 5412, 1380, 16, 203, 5411, 2744, 1854, 203, 3639, 11272, 203, 3639, 2744, 1854, 273, 2744, 1854, 342, 2130, 31, 203, 2 ]
//SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/utils/Base64.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; import "./TLTBase.sol"; contract Web3Bnb is TLTBase, ERC721URIStorage { constructor() ERC721("Web3Bnb", "W3BNB") {} using SafeMath for uint256; using Counters for Counters.Counter; Counters.Counter private _tokenIds; mapping(uint256 => string) public assets; // mapping(uint256 => address) private _owners; event AssetCreated(address indexed _from, string _tokenURI); function getAssets(uint256 _tokenId) public view returns (string memory) { return assets[_tokenId]; } function ownerOf(uint256 tokenId) public view virtual override(TLTBase, ERC721) returns (address) { return super.ownerOf(tokenId); } function mintAsset( string memory _name, string memory _description, string memory _image ) external payable { _tokenIds.increment(); uint256 newItemId = _tokenIds.current(); string memory json = Base64.encode( bytes( string( abi.encodePacked( '{"name": "', // We set the title of our NFT as the generated word. _name, '", "description": "', _description, '", "image": "', _image, '"}' ) ) ) ); string memory finalTokenUri = string( abi.encodePacked("data:application/json;base64,", json) ); _safeMint(msg.sender, newItemId); _setTokenURI(newItemId, finalTokenUri); assets[newItemId] = finalTokenUri; emit AssetCreated(msg.sender, finalTokenUri); } }
mapping(uint256 => address) private _owners;
contract Web3Bnb is TLTBase, ERC721URIStorage { using SafeMath for uint256; using Counters for Counters.Counter; Counters.Counter private _tokenIds; mapping(uint256 => string) public assets; event AssetCreated(address indexed _from, string _tokenURI); constructor() ERC721("Web3Bnb", "W3BNB") {} function getAssets(uint256 _tokenId) public view returns (string memory) { return assets[_tokenId]; } function ownerOf(uint256 tokenId) public view virtual override(TLTBase, ERC721) returns (address) { return super.ownerOf(tokenId); } function mintAsset( string memory _name, string memory _description, string memory _image ) external payable { _tokenIds.increment(); uint256 newItemId = _tokenIds.current(); string memory json = Base64.encode( bytes( string( abi.encodePacked( '{"name": "', _name, '", "description": "', _description, '", "image": "', _image, '"}' ) ) ) ); string memory finalTokenUri = string( abi.encodePacked("data:application/json;base64,", json) ); _safeMint(msg.sender, newItemId); _setTokenURI(newItemId, finalTokenUri); assets[newItemId] = finalTokenUri; emit AssetCreated(msg.sender, finalTokenUri); } function mintAsset( string memory _name, string memory _description, string memory _image ) external payable { _tokenIds.increment(); uint256 newItemId = _tokenIds.current(); string memory json = Base64.encode( bytes( string( abi.encodePacked( '{"name": "', _name, '", "description": "', _description, '", "image": "', _image, '"}' ) ) ) ); string memory finalTokenUri = string( abi.encodePacked("data:application/json;base64,", json) ); _safeMint(msg.sender, newItemId); _setTokenURI(newItemId, finalTokenUri); assets[newItemId] = finalTokenUri; emit AssetCreated(msg.sender, finalTokenUri); } }
5,428,254
[ 1, 6770, 12, 11890, 5034, 516, 1758, 13, 3238, 389, 995, 414, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 2999, 23, 38, 6423, 353, 399, 12050, 2171, 16, 4232, 39, 27, 5340, 3098, 3245, 288, 203, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 565, 1450, 9354, 87, 364, 9354, 87, 18, 4789, 31, 203, 565, 9354, 87, 18, 4789, 3238, 389, 2316, 2673, 31, 203, 203, 565, 2874, 12, 11890, 5034, 516, 533, 13, 1071, 7176, 31, 203, 203, 565, 871, 10494, 6119, 12, 2867, 8808, 389, 2080, 16, 533, 389, 2316, 3098, 1769, 203, 203, 203, 565, 3885, 1435, 4232, 39, 27, 5340, 2932, 4079, 23, 38, 6423, 3113, 315, 59, 23, 15388, 38, 7923, 2618, 203, 565, 445, 336, 10726, 12, 11890, 5034, 389, 2316, 548, 13, 1071, 1476, 1135, 261, 1080, 3778, 13, 288, 203, 3639, 327, 7176, 63, 67, 2316, 548, 15533, 203, 565, 289, 203, 203, 565, 445, 3410, 951, 12, 11890, 5034, 1147, 548, 13, 203, 3639, 1071, 203, 3639, 1476, 203, 3639, 5024, 203, 3639, 3849, 12, 5967, 56, 2171, 16, 4232, 39, 27, 5340, 13, 203, 3639, 1135, 261, 2867, 13, 203, 565, 288, 203, 3639, 327, 2240, 18, 8443, 951, 12, 2316, 548, 1769, 203, 565, 289, 203, 203, 565, 445, 312, 474, 6672, 12, 203, 3639, 533, 3778, 389, 529, 16, 203, 3639, 533, 3778, 389, 3384, 16, 203, 3639, 533, 3778, 389, 2730, 203, 565, 262, 3903, 8843, 429, 288, 203, 3639, 389, 2316, 2673, 18, 15016, 5621, 203, 3639, 2254, 5034, 394, 17673, 273, 389, 2316, 2673, 18, 2972, 5621, 203, 203, 3639, 533, 3778, 1163, 273, 2 ]
// SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.6.11; // File: @openzeppelin/contracts/token/ERC20/IERC20.sol /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint value); } // File: @openzeppelin/contracts/math/SafeMath.sol /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint a, uint b) internal pure returns (bool, uint) { uint c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint a, uint b) internal pure returns (bool, uint) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint a, uint b) internal pure returns (bool, uint) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint a, uint b) internal pure returns (bool, uint) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint a, uint b) internal pure returns (bool, uint) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint a, uint b) internal pure returns (uint) { uint c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint a, uint b) internal pure returns (uint) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint a, uint b) internal pure returns (uint) { if (a == 0) return 0; uint c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint a, uint b) internal pure returns (uint) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint a, uint b) internal pure returns (uint) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint a, uint b, string memory errorMessage ) internal pure returns (uint) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint a, uint b, string memory errorMessage ) internal pure returns (uint) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint a, uint b, string memory errorMessage ) internal pure returns (uint) { require(b > 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/utils/Address.sol /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint value ) internal returns (bytes memory) { return functionCallWithValue( target, data, value, "Address: low-level call with value failed" ); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint value, string memory errorMessage ) internal returns (bytes memory) { require( address(this).balance >= value, "Address: insufficient balance for call" ); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{value: value}(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall( target, data, "Address: low-level delegate call failed" ); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) private pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint; using Address for address; function safeTransfer( IERC20 token, address to, uint value ) internal { _callOptionalReturn( token, abi.encodeWithSelector(token.transfer.selector, to, value) ); } function safeTransferFrom( IERC20 token, address from, address to, uint value ) internal { _callOptionalReturn( token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value) ); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn( token, abi.encodeWithSelector(token.approve.selector, spender, value) ); } function safeIncreaseAllowance( IERC20 token, address spender, uint value ) internal { uint newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn( token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance) ); } function safeDecreaseAllowance( IERC20 token, address spender, uint value ) internal { uint newAllowance = token.allowance(address(this), spender).sub( value, "SafeERC20: decreased allowance below zero" ); _callOptionalReturn( token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance) ); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require( abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed" ); } } } // File: contracts/protocol/IStrategy.sol /* version 1.2.0 Changes Changes listed here do not affect interaction with other contracts (Vault and Controller) - removed function assets(address _token) external view returns (bool); - remove function deposit(uint), declared in IStrategyERC20 - add function setSlippage(uint _slippage); - add function setDelta(uint _delta); */ interface IStrategy { function admin() external view returns (address); function controller() external view returns (address); function vault() external view returns (address); /* @notice Returns address of underlying asset (ETH or ERC20) @dev Must return 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE for ETH strategy */ function underlying() external view returns (address); /* @notice Returns total amount of underlying transferred from vault */ function totalDebt() external view returns (uint); function performanceFee() external view returns (uint); function slippage() external view returns (uint); /* @notice Multiplier used to check total underlying <= total debt * delta / DELTA_MIN */ function delta() external view returns (uint); /* @dev Flag to force exit in case normal exit fails */ function forceExit() external view returns (bool); function setAdmin(address _admin) external; function setController(address _controller) external; function setPerformanceFee(uint _fee) external; function setSlippage(uint _slippage) external; function setDelta(uint _delta) external; function setForceExit(bool _forceExit) external; /* @notice Returns amount of underlying asset locked in this contract @dev Output may vary depending on price of liquidity provider token where the underlying asset is invested */ function totalAssets() external view returns (uint); /* @notice Withdraw `_amount` underlying asset @param amount Amount of underlying asset to withdraw */ function withdraw(uint _amount) external; /* @notice Withdraw all underlying asset from strategy */ function withdrawAll() external; /* @notice Sell any staking rewards for underlying and then deposit undelying */ function harvest() external; /* @notice Increase total debt if profit > 0 and total assets <= max, otherwise transfers profit to vault. @dev Guard against manipulation of external price feed by checking that total assets is below factor of total debt */ function skim() external; /* @notice Exit from strategy @dev Must transfer all underlying tokens back to vault */ function exit() external; /* @notice Transfer token accidentally sent here to admin @param _token Address of token to transfer @dev _token must not be equal to underlying token */ function sweep(address _token) external; } // File: contracts/protocol/IStrategyERC20.sol interface IStrategyERC20 is IStrategy { /* @notice Deposit `amount` underlying ERC20 token @param amount Amount of underlying ERC20 token to deposit */ function deposit(uint _amount) external; } // File: contracts/protocol/IController.sol interface IController { function ADMIN_ROLE() external view returns (bytes32); function HARVESTER_ROLE() external view returns (bytes32); function admin() external view returns (address); function treasury() external view returns (address); function setAdmin(address _admin) external; function setTreasury(address _treasury) external; function grantRole(bytes32 _role, address _addr) external; function revokeRole(bytes32 _role, address _addr) external; /* @notice Set strategy for vault @param _vault Address of vault @param _strategy Address of strategy @param _min Minimum undelying token current strategy must return. Prevents slippage */ function setStrategy( address _vault, address _strategy, uint _min ) external; // calls to strategy /* @notice Invest token in vault into strategy @param _vault Address of vault */ function invest(address _vault) external; function harvest(address _strategy) external; function skim(address _strategy) external; /* @notice Withdraw from strategy to vault @param _strategy Address of strategy @param _amount Amount of underlying token to withdraw @param _min Minimum amount of underlying token to withdraw */ function withdraw( address _strategy, uint _amount, uint _min ) external; /* @notice Withdraw all from strategy to vault @param _strategy Address of strategy @param _min Minimum amount of underlying token to withdraw */ function withdrawAll(address _strategy, uint _min) external; /* @notice Exit from strategy @param _strategy Address of strategy @param _min Minimum amount of underlying token to withdraw */ function exit(address _strategy, uint _min) external; } // File: contracts/StrategyERC20.sol /* version 1.2.0 Changes from StrategyBase - performance fee capped at 20% - add slippage gaurd - update skim(), increments total debt withoud withdrawing if total assets is near total debt - sweep - delete mapping "assets" and use require to explicitly check protected tokens - add immutable to vault - add immutable to underlying - add force exit */ // used inside harvest abstract contract StrategyERC20 is IStrategyERC20 { using SafeERC20 for IERC20; using SafeMath for uint; address public override admin; address public override controller; address public immutable override vault; address public immutable override underlying; // total amount of underlying transferred from vault uint public override totalDebt; // performance fee sent to treasury when harvest() generates profit uint public override performanceFee = 500; uint private constant PERFORMANCE_FEE_CAP = 2000; // upper limit to performance fee uint internal constant PERFORMANCE_FEE_MAX = 10000; // prevent slippage from deposit / withdraw uint public override slippage = 100; uint internal constant SLIPPAGE_MAX = 10000; /* Multiplier used to check totalAssets() is <= total debt * delta / DELTA_MIN */ uint public override delta = 10050; uint private constant DELTA_MIN = 10000; // Force exit, in case normal exit fails bool public override forceExit; constructor( address _controller, address _vault, address _underlying ) public { require(_controller != address(0), "controller = zero address"); require(_vault != address(0), "vault = zero address"); require(_underlying != address(0), "underlying = zero address"); admin = msg.sender; controller = _controller; vault = _vault; underlying = _underlying; } modifier onlyAdmin() { require(msg.sender == admin, "!admin"); _; } modifier onlyAuthorized() { require( msg.sender == admin || msg.sender == controller || msg.sender == vault, "!authorized" ); _; } function setAdmin(address _admin) external override onlyAdmin { require(_admin != address(0), "admin = zero address"); admin = _admin; } function setController(address _controller) external override onlyAdmin { require(_controller != address(0), "controller = zero address"); controller = _controller; } function setPerformanceFee(uint _fee) external override onlyAdmin { require(_fee <= PERFORMANCE_FEE_CAP, "performance fee > cap"); performanceFee = _fee; } function setSlippage(uint _slippage) external override onlyAdmin { require(_slippage <= SLIPPAGE_MAX, "slippage > max"); slippage = _slippage; } function setDelta(uint _delta) external override onlyAdmin { require(_delta >= DELTA_MIN, "delta < min"); delta = _delta; } function setForceExit(bool _forceExit) external override onlyAdmin { forceExit = _forceExit; } function _increaseDebt(uint _underlyingAmount) private { uint balBefore = IERC20(underlying).balanceOf(address(this)); IERC20(underlying).safeTransferFrom(vault, address(this), _underlyingAmount); uint balAfter = IERC20(underlying).balanceOf(address(this)); totalDebt = totalDebt.add(balAfter.sub(balBefore)); } function _decreaseDebt(uint _underlyingAmount) private { uint balBefore = IERC20(underlying).balanceOf(address(this)); IERC20(underlying).safeTransfer(vault, _underlyingAmount); uint balAfter = IERC20(underlying).balanceOf(address(this)); uint diff = balBefore.sub(balAfter); if (diff >= totalDebt) { totalDebt = 0; } else { totalDebt -= diff; } } function _totalAssets() internal view virtual returns (uint); /* @notice Returns amount of underlying tokens locked in this contract */ function totalAssets() external view override returns (uint) { return _totalAssets(); } function _deposit() internal virtual; /* @notice Deposit underlying token into this strategy @param _underlyingAmount Amount of underlying token to deposit */ function deposit(uint _underlyingAmount) external override onlyAuthorized { require(_underlyingAmount > 0, "deposit = 0"); _increaseDebt(_underlyingAmount); _deposit(); } /* @notice Returns total shares owned by this contract for depositing underlying into external Defi */ function _getTotalShares() internal view virtual returns (uint); function _getShares(uint _underlyingAmount, uint _totalUnderlying) internal view returns (uint) { /* calculate shares to withdraw w = amount of underlying to withdraw U = total redeemable underlying s = shares to withdraw P = total shares deposited into external liquidity pool w / U = s / P s = w / U * P */ if (_totalUnderlying > 0) { uint totalShares = _getTotalShares(); return _underlyingAmount.mul(totalShares) / _totalUnderlying; } return 0; } function _withdraw(uint _shares) internal virtual; /* @notice Withdraw undelying token to vault @param _underlyingAmount Amount of underlying token to withdraw @dev Caller should implement guard against slippage */ function withdraw(uint _underlyingAmount) external override onlyAuthorized { require(_underlyingAmount > 0, "withdraw = 0"); uint totalUnderlying = _totalAssets(); require(_underlyingAmount <= totalUnderlying, "withdraw > total"); uint shares = _getShares(_underlyingAmount, totalUnderlying); if (shares > 0) { _withdraw(shares); } // transfer underlying token to vault /* WARNING: Here we are transferring all funds in this contract. This operation is safe under 2 conditions: 1. This contract does not hold any funds at rest. 2. Vault does not allow user to withdraw excess > _underlyingAmount */ uint underlyingBal = IERC20(underlying).balanceOf(address(this)); if (underlyingBal > 0) { _decreaseDebt(underlyingBal); } } function _withdrawAll() internal { uint totalShares = _getTotalShares(); if (totalShares > 0) { _withdraw(totalShares); } uint underlyingBal = IERC20(underlying).balanceOf(address(this)); if (underlyingBal > 0) { IERC20(underlying).safeTransfer(vault, underlyingBal); totalDebt = 0; } } /* @notice Withdraw all underlying to vault @dev Caller should implement guard agains slippage */ function withdrawAll() external override onlyAuthorized { _withdrawAll(); } /* @notice Sell any staking rewards for underlying and then deposit undelying */ function harvest() external virtual override; /* @notice Increase total debt if profit > 0 and total assets <= max, otherwise transfers profit to vault. @dev Guard against manipulation of external price feed by checking that total assets is below factor of total debt */ function skim() external override onlyAuthorized { uint totalUnderlying = _totalAssets(); require(totalUnderlying > totalDebt, "total underlying < debt"); uint profit = totalUnderlying - totalDebt; // protect against price manipulation uint max = totalDebt.mul(delta) / DELTA_MIN; if (totalUnderlying <= max) { /* total underlying is within reasonable bounds, probaly no price manipulation occured. */ /* If we were to withdraw profit followed by deposit, this would increase the total debt roughly by the profit. Withdrawing consumes high gas, so here we omit it and directly increase debt, as if withdraw and deposit were called. */ totalDebt = totalDebt.add(profit); } else { /* Possible reasons for total underlying > max 1. total debt = 0 2. total underlying really did increase over max 3. price was manipulated */ uint shares = _getShares(profit, totalUnderlying); if (shares > 0) { uint balBefore = IERC20(underlying).balanceOf(address(this)); _withdraw(shares); uint balAfter = IERC20(underlying).balanceOf(address(this)); uint diff = balAfter.sub(balBefore); if (diff > 0) { IERC20(underlying).safeTransfer(vault, diff); } } } } function exit() external virtual override; function sweep(address) external virtual override; } // File: contracts/interfaces/uniswap/Uniswap.sol interface Uniswap { function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactTokensForETH( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); } // File: contracts/interfaces/curve/LiquidityGauge.sol // https://github.com/curvefi/curve-contract/blob/master/contracts/gauges/LiquidityGauge.vy interface LiquidityGauge { function deposit(uint) external; function balanceOf(address) external view returns (uint); function withdraw(uint) external; } // File: contracts/interfaces/curve/Minter.sol // https://github.com/curvefi/curve-dao-contracts/blob/master/contracts/Minter.vy interface Minter { function mint(address) external; } // File: contracts/interfaces/curve/StableSwapGusd.sol interface StableSwapGusd { function get_virtual_price() external view returns (uint); /* 0 GUSD 1 3CRV */ function balances(uint index) external view returns (uint); } // File: contracts/interfaces/curve/StableSwap3Pool.sol interface StableSwap3Pool { function get_virtual_price() external view returns (uint); function add_liquidity(uint[3] calldata amounts, uint min_mint_amount) external; function remove_liquidity_one_coin( uint token_amount, int128 i, uint min_uamount ) external; function balances(uint index) external view returns (uint); } // File: contracts/interfaces/curve/DepositGusd.sol interface DepositGusd { /* 0 GUSD 1 DAI 2 USDC 3 USDT */ function add_liquidity(uint[4] memory amounts, uint min) external returns (uint); function remove_liquidity_one_coin( uint amount, int128 index, uint min ) external returns (uint); } // File: contracts/strategies/StrategyGusdV2.sol contract StrategyGusdV2 is StrategyERC20 { // Uniswap // address private constant UNISWAP = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; address private constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address internal constant GUSD = 0x056Fd409E1d7A124BD7017459dFEa2F387b6d5Cd; address internal constant DAI = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address internal constant USDC = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48; address internal constant USDT = 0xdAC17F958D2ee523a2206206994597C13D831ec7; // GUSD = 0 | DAI = 1 | USDC = 2 | USDT = 3 uint private immutable UNDERLYING_INDEX; // precision to convert 10 ** 18 to underlying decimals uint[4] private PRECISION_DIV = [1e16, 1, 1e12, 1e12]; // precision div of underlying token (used to save gas) uint private immutable PRECISION_DIV_UNDERLYING; // Curve // // StableSwap3Pool address private constant BASE_POOL = 0xbEbc44782C7dB0a1A60Cb6fe97d0b483032FF1C7; // StableSwapGusd address private constant SWAP = 0x4f062658EaAF2C1ccf8C8e36D6824CDf41167956; // liquidity provider token (GUSD / 3CRV) address private constant LP = 0xD2967f45c4f384DEEa880F807Be904762a3DeA07; // DepositGusd address private constant DEPOSIT = 0x64448B78561690B70E17CBE8029a3e5c1bB7136e; // LiquidityGauge address private constant GAUGE = 0xC5cfaDA84E902aD92DD40194f0883ad49639b023; // Minter address private constant MINTER = 0xd061D61a4d941c39E5453435B6345Dc261C2fcE0; // CRV address private constant CRV = 0xD533a949740bb3306d119CC777fa900bA034cd52; constructor( address _controller, address _vault, address _underlying, uint _underlyingIndex ) public StrategyERC20(_controller, _vault, _underlying) { UNDERLYING_INDEX = _underlyingIndex; PRECISION_DIV_UNDERLYING = PRECISION_DIV[_underlyingIndex]; // These tokens are never held by this contract // so the risk of them getting stolen is minimal IERC20(CRV).safeApprove(UNISWAP, uint(-1)); } function _totalAssets() internal view override returns (uint) { uint lpBal = LiquidityGauge(GAUGE).balanceOf(address(this)); uint pricePerShare = StableSwapGusd(SWAP).get_virtual_price(); return lpBal.mul(pricePerShare) / (PRECISION_DIV_UNDERLYING * 1e18); } /* @notice deposit token into curve */ function _depositIntoCurve(address _token, uint _index) private { // token to LP uint bal = IERC20(_token).balanceOf(address(this)); if (bal > 0) { IERC20(_token).safeApprove(DEPOSIT, 0); IERC20(_token).safeApprove(DEPOSIT, bal); // mint LP uint[4] memory amounts; amounts[_index] = bal; /* shares = underlying amount * precision div * 1e18 / price per share */ uint pricePerShare = StableSwapGusd(SWAP).get_virtual_price(); uint shares = bal.mul(PRECISION_DIV[_index]).mul(1e18).div(pricePerShare); uint min = shares.mul(SLIPPAGE_MAX - slippage) / SLIPPAGE_MAX; DepositGusd(DEPOSIT).add_liquidity(amounts, min); } // stake into LiquidityGauge uint lpBal = IERC20(LP).balanceOf(address(this)); if (lpBal > 0) { IERC20(LP).safeApprove(GAUGE, 0); IERC20(LP).safeApprove(GAUGE, lpBal); LiquidityGauge(GAUGE).deposit(lpBal); } } /* @notice Deposits underlying to LiquidityGauge */ function _deposit() internal override { _depositIntoCurve(underlying, UNDERLYING_INDEX); } function _getTotalShares() internal view override returns (uint) { return LiquidityGauge(GAUGE).balanceOf(address(this)); } function _withdraw(uint _lpAmount) internal override { // withdraw LP from LiquidityGauge LiquidityGauge(GAUGE).withdraw(_lpAmount); // withdraw underlying // uint lpBal = IERC20(LP).balanceOf(address(this)); // remove liquidity IERC20(LP).safeApprove(DEPOSIT, 0); IERC20(LP).safeApprove(DEPOSIT, lpBal); /* underlying amount = (shares * price per shares) / (1e18 * precision div) */ uint pricePerShare = StableSwapGusd(SWAP).get_virtual_price(); uint underlyingAmount = lpBal.mul(pricePerShare) / (PRECISION_DIV_UNDERLYING * 1e18); uint min = underlyingAmount.mul(SLIPPAGE_MAX - slippage) / SLIPPAGE_MAX; // withdraw creates LP dust DepositGusd(DEPOSIT).remove_liquidity_one_coin( lpBal, int128(UNDERLYING_INDEX), min ); // Now we have underlying } /* @notice Returns address and index of token with lowest balance in Curve StableSwap */ function _getMostPremiumToken() internal view returns (address, uint) { // meta pool balances uint[2] memory balances; balances[0] = StableSwapGusd(SWAP).balances(0).mul(1e16); // GUSD balances[1] = StableSwapGusd(SWAP).balances(1); // 3CRV if (balances[0] <= balances[1]) { return (GUSD, 0); } else { // base pool balances uint[3] memory baseBalances; baseBalances[0] = StableSwap3Pool(BASE_POOL).balances(0); // DAI baseBalances[1] = StableSwap3Pool(BASE_POOL).balances(1).mul(1e12); // USDC baseBalances[2] = StableSwap3Pool(BASE_POOL).balances(2).mul(1e12); // USDT /* DAI 1 USDC 2 USDT 3 */ // DAI if ( baseBalances[0] <= baseBalances[1] && baseBalances[0] <= baseBalances[2] ) { return (DAI, 1); } // USDC if ( baseBalances[1] <= baseBalances[0] && baseBalances[1] <= baseBalances[2] ) { return (USDC, 2); } return (USDT, 3); } } /* @dev Uniswap fails with zero address so no check is necessary here */ function _swap( address _from, address _to, uint _amount ) private { // create dynamic array with 3 elements address[] memory path = new address[](3); path[0] = _from; path[1] = WETH; path[2] = _to; Uniswap(UNISWAP).swapExactTokensForTokens( _amount, 1, path, address(this), block.timestamp ); } function _claimRewards(address _token) private { // claim CRV Minter(MINTER).mint(GAUGE); uint crvBal = IERC20(CRV).balanceOf(address(this)); // Swap only if CRV >= 1, otherwise swap may fail for small amount of GUSD if (crvBal >= 1e18) { _swap(CRV, _token, crvBal); // Now this contract has token } } /* @notice Claim CRV and deposit most premium token into Curve */ function harvest() external override onlyAuthorized { (address token, uint index) = _getMostPremiumToken(); _claimRewards(token); uint bal = IERC20(token).balanceOf(address(this)); if (bal > 0) { // transfer fee to treasury uint fee = bal.mul(performanceFee) / PERFORMANCE_FEE_MAX; if (fee > 0) { address treasury = IController(controller).treasury(); require(treasury != address(0), "treasury = zero address"); IERC20(token).safeTransfer(treasury, fee); } _depositIntoCurve(token, index); } } /* @notice Exit strategy by harvesting CRV to underlying token and then withdrawing all underlying to vault @dev Must return all underlying token to vault @dev Caller should implement guard agains slippage */ function exit() external override onlyAuthorized { if (forceExit) { return; } _claimRewards(underlying); _withdrawAll(); } function sweep(address _token) external override onlyAdmin { require(_token != underlying, "protected token"); IERC20(_token).safeTransfer(admin, IERC20(_token).balanceOf(address(this))); } } // File: contracts/strategies/StrategyGusdDaiV2.sol contract StrategyGusdDaiV2 is StrategyGusdV2 { constructor(address _controller, address _vault) public StrategyGusdV2(_controller, _vault, DAI, 1) {} }
claim CRV Swap only if CRV >= 1, otherwise swap may fail for small amount of GUSD Now this contract has token
function _claimRewards(address _token) private { Minter(MINTER).mint(GAUGE); uint crvBal = IERC20(CRV).balanceOf(address(this)); if (crvBal >= 1e18) { _swap(CRV, _token, crvBal); } }
54,498
[ 1, 14784, 6732, 58, 12738, 1338, 309, 6732, 58, 1545, 404, 16, 3541, 7720, 2026, 2321, 364, 5264, 3844, 434, 611, 3378, 40, 4494, 333, 6835, 711, 1147, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 14784, 17631, 14727, 12, 2867, 389, 2316, 13, 3238, 288, 203, 3639, 490, 2761, 12, 6236, 2560, 2934, 81, 474, 12, 43, 27738, 1769, 203, 203, 3639, 2254, 4422, 90, 38, 287, 273, 467, 654, 39, 3462, 12, 5093, 58, 2934, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 3639, 309, 261, 3353, 90, 38, 287, 1545, 404, 73, 2643, 13, 288, 203, 5411, 389, 22270, 12, 5093, 58, 16, 389, 2316, 16, 4422, 90, 38, 287, 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 ]
//Contract based on https://docs.openzeppelin.com/contracts/4.x/erc721 // SPDX-License-Identifier: MIT pragma solidity ^0.8.8 < 0.9.0; //OpenZeppelin contract/token imports import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol"; import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; //Contract instantiation contract LegionsOfLoud is ERC721Enumerable, Ownable, ReentrancyGuard { using ECDSA for bytes32; mapping(string => bool) private _usedNonces; address private _signerAddress = 0xF5FF2CC2Ee8b4eA2C03F0cf0c93fd3a867Da9E8A; // Contract wallet uint public constant lolBadges = 7200; // Total number of token ID's uint256 private _priceOfToken = 69000000000000000; // Total cost per token minted is 0.069 ETH string private _tokenURIBaseURL = "https://api.legionsofloud.com/meta/"; //Base URL of token metadata bool public tokenSale = true; // True means sale is active, false means sale is not active. constructor() ERC721("Legions of Loud", "LOL") {} function hashTransaction(address sender, uint256 qty, string memory nonce) private pure returns(bytes32) { bytes32 hash = keccak256(abi.encodePacked( "\x19Ethereum Signed Message:\n32", keccak256(abi.encodePacked(sender, qty, nonce))) ); return hash; } function matchAddresSigner(bytes32 hash, bytes memory signature) private view returns(bool) { return _signerAddress == hash.recover(signature); } function setSignerAddress(address addr) external onlyOwner { _signerAddress = addr; } function reUp(bytes memory signature, string memory nonce, uint256 token_quantity) external payable nonReentrant { require(matchAddresSigner(hashTransaction(msg.sender, token_quantity, nonce), signature), "DIRECT MINT IS NOT ALLOWED please visit www.legionsofloud.com"); require(!_usedNonces[nonce], "HASH USED"); _usedNonces[nonce] = true; require(token_quantity + totalSupply() <= lolBadges, "The max amount of tokens has been reached, per contract."); require(tokenSale, "Tokens are not for sale."); require(token_quantity <= 20, "The token amount entered is above the allowable limit of 20 per transaction. Please enter a lesser amount."); require(msg.value >= tokenPrice(token_quantity), "You have insufficient funds."); for (uint i = 0; i < token_quantity; i++) { _safeMint(msg.sender, totalSupply() + 1); } } function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal override { super._beforeTokenTransfer(from, to, tokenId); } function walletOfOwner(address _owner) external view returns(uint256[] memory) { uint tokenCount = balanceOf(_owner); uint256[] memory tokensId = new uint256[](tokenCount); for(uint i = 0; i < tokenCount; i++){ tokensId[i] = tokenOfOwnerByIndex(_owner, i); } return tokensId; } function tokenOnSale(bool _isTokenSale) public onlyOwner { tokenSale = _isTokenSale; } function _baseURI() internal view virtual override returns (string memory) { return _tokenURIBaseURL; } function setBaseURI(string memory baseURI) public onlyOwner { _tokenURIBaseURL = baseURI; } function tokenPrice(uint token_quantity) public view returns (uint256) { return _priceOfToken * token_quantity; } // Just in case ETH does some crazy stuff function setPrice(uint256 _newPrice) public onlyOwner() { _priceOfToken = _newPrice; } function getPrice() public view returns (uint256){ return _priceOfToken; } // Contract Payout Structure address constant dev1Address = 0x9F90601582eD28922a81156a60aad0cf0fd69203; // Dev 1 address address constant dev2Address = 0xC7067F6Ed87F0fd8D5Cc47AD0F0C0b512a3CC275; // Dev 2 address address constant owner2Address = 0x70716Bd3E3E46e93E220E92045af42F2907Bbb9B; // Owner 2 address address constant artAddress = 0x80528F38843d19eCf558df2655354c99F05731a3; // Artist address uint constant dev1Fee = 13; uint constant dev2Fee = 12; uint constant artFee = 10; uint constant owner2Fee = 32; uint private constant sumShare = 100; function withdraw() public payable onlyOwner { uint256 balance = address(this).balance; uint dev1Transfer = (balance * dev1Fee)/sumShare; uint dev2Transfer = (balance * dev2Fee)/sumShare; uint artTransfer = (balance * artFee)/sumShare; uint owner2Transfer = (balance * owner2Fee)/sumShare; uint partnerTransfer = balance - (dev1Transfer + dev2Transfer + artTransfer + owner2Transfer); payable(dev1Address).transfer(dev1Transfer); payable(dev2Address).transfer(dev2Transfer); payable(artAddress).transfer(artTransfer); payable(owner2Address).transfer(owner2Transfer); payable(msg.sender).transfer(partnerTransfer); require(address(this).balance == 0); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC721.sol"; import "./IERC721Enumerable.sol"; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../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 "../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 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; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @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); }
True means sale is active, false means sale is not active.
bool public tokenSale = true;
13,707,254
[ 1, 5510, 4696, 272, 5349, 353, 2695, 16, 629, 4696, 272, 5349, 353, 486, 2695, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 1426, 1071, 1147, 30746, 273, 638, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
//sub contract for claim managers list pragma solidity ^0.5.0; contract ClaimManagersList { enum ClaimStatus {Accepted, Rejected, InProgress} struct ClaimManager { //bool status; //active or suspended uint256 claimsPassed; //numbers of settled and rejected claims uint256 claimsSettled; //number of settled claims //uint256 numberOfReports; //number of reports for reopen claims address personAddress; //bytes32 personAddressHash; } struct ProposedClaimManager { string personURL; uint256 votesPro; uint256 votesContra; address personAddress; } /* event NewManagerProposed(); event NewManagerPromoted(address _add); */ uint claimDeposit; //sum of deposit to start process claim - in order avoid claims spam uint adminFee; //lists of contracts managers and etc ClaimManager[] claimManagers; //list of managers ProposedClaimManager[] proposedClaimManagers; //list of proposed managers constructor (uint _deposit) public { require(_deposit > 0); claimDeposit = _deposit * (1 finney); //temp nominated in finney //make sender as first manager claimManagers.push(ClaimManager ({ //status: true, claimsPassed: 0, claimsSettled: 0, //numberOfReports: 0, //personAddressHash: keccak256(msg.sender), personAddress: msg.sender })); } //check if _add is a manager function checkClaimManager (address _add) private view returns (bool _isClaimManager) { _isClaimManager = false; for (uint256 i = 0; i < claimManagers.length; i++) { if (claimManagers[i].personAddress == _add) { _isClaimManager = true; break; } } } //check if _add is a proposed manager function checkProposedClaimManager (address _add) private view returns (bool _isClaimManager) { _isClaimManager = false; for (uint256 i = 0; i < proposedClaimManagers.length; i++) { if (proposedClaimManagers[i].personAddress == _add) { _isClaimManager = true; break; } } } function returnFirstProposedManagerUrl () public view returns (string memory) { require(proposedClaimManagers.length > 0); //require(checkClaimManager(msg.sender)); //commented for unit test but may be it's ok? return proposedClaimManagers[0].personURL; } function proposeNewManager (string memory _url, address _add) public payable { require(msg.value >= claimDeposit); //require(checkClaimManager(msg.sender)); //commented for unit test but may be it's ok? require(!checkClaimManager(_add)); require(!checkProposedClaimManager(_add)); adminFee += msg.value; proposedClaimManagers.push(ProposedClaimManager ({personURL: _url, votesPro: 0, votesContra: 0, personAddress: _add})); } function voteForProposedManager (string memory _url, bool _vote) public { require(checkClaimManager(msg.sender)); require(keccak256(bytes(_url)) == keccak256(bytes(returnFirstProposedManagerUrl()))); if (_vote) proposedClaimManagers[0].votesPro++; //always votes for first promoted manager else proposedClaimManagers[0].votesContra++; //check if 1/2 of total votes already pro or contra this manager if (proposedClaimManagers[0].votesPro * 2 >= claimManagers.length) { //more or equal of half pro promoteProposedManager(); } if (proposedClaimManagers.length>0) { if (proposedClaimManagers[0].votesContra * 2 > claimManagers.length) { //more then half contra rejectProposedManager(); } } //get some payment from admin fee for activity? } function rejectProposedManager () private { for (uint256 i = 1; i < proposedClaimManagers.length; i++) proposedClaimManagers[0] = proposedClaimManagers[i]; delete proposedClaimManagers[proposedClaimManagers.length-1]; proposedClaimManagers.length--; } function promoteProposedManager () private { claimManagers.push(ClaimManager ({ //status: true, claimsPassed: 0, claimsSettled: 0, //numberOfReports: 0, //personAddressHash: keccak256(proposedClaimManagers[0].personAddress), personAddress: proposedClaimManagers[0].personAddress })); rejectProposedManager(); //remove him from list after promotion } /* //_addhash is not good also function updateCountOfPassedClaimsByManager (bytes32 _addhash, uint _cstatus) public { for (uint256 i =0; i < claimManagers.length; i++) { if (claimManagers[i].personAddressHash == _addhash) { claimManagers[i].claimsPassed++; if (_cstatus == uint(ClaimStatus.Accepted)) claimManagers[i].claimsSettled++; break; } } } */ //test help functions function returnLengthOfList () public view returns (uint256) { return claimManagers.length; } function returnLengthOfProposedList () public view returns (uint256) { return proposedClaimManagers.length; } function returnManagerAddress (uint256 _num) public view returns (address) { require(_num<claimManagers.length); return claimManagers[_num].personAddress; } function returnProposedManagerAddress (uint256 _num) public view returns (address) { require(_num<proposedClaimManagers.length); return proposedClaimManagers[_num].personAddress; } function returnClaimDepositValue () public view returns (uint256) { return claimDeposit; } //functions to retrive payment for claims adjustement from admeen fee? }
numbers of settled and rejected claims
uint256 claimsPassed;
15,781,117
[ 1, 13851, 434, 26319, 1259, 471, 11876, 11955, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 2254, 5034, 11955, 22530, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity >=0.6.12; import "./interfaces/IERC20.sol"; import './interfaces/IRewardToken.sol'; import './libraries/SafeMath.sol'; import './modules/Configable.sol'; import "./modules/ReentrancyGuard.sol"; import './modules/Pausable.sol'; import './modules/Initializable.sol'; // Have fun reading it. Hopefully it's bug-free. God bless. contract SwitchPool is Pausable, Configable, ReentrancyGuard, Initializable { using SafeMath for uint; // Info of each user. struct UserInfo { uint amount; // How many tokens the user has provided. uint rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of RewardTokens // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accRewardPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws tokens to a pool. Here's what happens: // 1. The pool's `accRewardPerShare` (and `lastBlock`) 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 { address depositToken; // Address of LP token contract. uint allocPoint; // How many allocation points assigned to this pool. RewardTokens to distribute per block. uint lastBlock; // Last block number that RewardTokens distribution occurs. uint accRewardPerShare; // Accumulated RewardTokens per share, times 1e18. See below. uint depositTokenSupply; uint16 depositFeeBP; // Deposit fee in basis points uint16 tokenType; bool paused; } uint public constant version = 1; // The reward TOKEN! address public rewardToken; // Dev address. address public team; // reward tokens created per block. uint public mintPerBlock; // Bonus muliplier for early rewardToken makers. uint public constant BONUS_MULTIPLIER = 1; // Deposit Fee address address public feeAddress; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes tokens. mapping(uint => mapping(address => UserInfo)) public userInfo; // Total allocation points. Must be the sum of all allocation points in all pools. uint public totalAllocPoint; // The block number when reward token mining starts. uint public startBlock; event Deposit(address indexed user, address indexed to, uint indexed pid, uint amount, uint fee); event Withdraw(address indexed user, address indexed to, uint indexed pid, uint amount); event EmergencyWithdraw(address indexed user, address indexed to, uint indexed pid, uint amount); event SetFeeAddress(address indexed user, address indexed newAddress); event SetDevAddress(address indexed user, address indexed newAddress); event UpdateEmissionRate(address indexed user, uint mintPerBlock); function initialize( address _rewardToken, address _team, address _feeAddress, uint _mintPerBlock, uint _startBlock ) external initializer { owner = msg.sender; rewardToken = _rewardToken; team = _team; feeAddress = _feeAddress; mintPerBlock = _mintPerBlock; startBlock = _startBlock; } function poolLength() external view returns (uint) { return poolInfo.length; } mapping(address => bool) public poolExistence; modifier nonDuplicated(address _depositToken) { require(poolExistence[_depositToken] == false, "nonDuplicated: duplicated"); _; } modifier validatePoolByPid(uint _pid) { require (_pid < poolInfo.length , "Pool does not exist"); _; } function pause() public onlyManager whenNotPaused { _pause(); } function unpause() public onlyManager whenPaused { _unpause(); } // Add a new lp to the pool. Can only be called by the owner. function add(bool _withUpdate, uint _allocPoint, address _depositToken, uint16 _depositFeeBP, uint16 _tokenType) public onlyDev nonDuplicated(_depositToken) { require(_depositFeeBP <= 10000, "add: invalid deposit fee basis points"); if (_withUpdate) { massUpdatePools(); } uint lastBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolExistence[_depositToken] = true; poolInfo.push(PoolInfo({ depositToken : _depositToken, allocPoint : _allocPoint, lastBlock : lastBlock, accRewardPerShare : 0, depositTokenSupply: 0, depositFeeBP : _depositFeeBP, tokenType: _tokenType, paused: false })); } function batchAdd(bool _withUpdate, uint[] memory _allocPoints, address[] memory _depositTokens, uint16[] memory _depositFeeBPs, uint16[] memory _tokenTypes) external onlyDev { require(_allocPoints.length == _depositTokens.length && _depositTokens.length == _depositFeeBPs.length, 'invalid params'); if (_withUpdate) { massUpdatePools(); } for(uint i; i<_allocPoints.length; i++) { add(false, _allocPoints[i], _depositTokens[i], _depositFeeBPs[i], _tokenTypes[i]); } } function set(bool _withUpdate, uint _pid, uint _allocPoint, uint16 _depositFeeBP, uint16 _tokenType, bool _paused) external validatePoolByPid(_pid) onlyManager { require(_depositFeeBP <= 10000, "depositFeeBP should be <=10000!"); if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; poolInfo[_pid].depositFeeBP = _depositFeeBP; poolInfo[_pid].tokenType = _tokenType; poolInfo[_pid].paused = _paused; } function batchSetAllocPoint(uint[] memory _pids, uint[] memory _allocPoints) external onlyManager { require(_pids.length == _allocPoints.length, 'invalid params'); massUpdatePools(); for (uint i; i<_pids.length; i++) { totalAllocPoint = totalAllocPoint.sub(poolInfo[_pids[i]].allocPoint).add(_allocPoints[i]); poolInfo[_pids[i]].allocPoint = _allocPoints[i]; } } function batchSetDepositFeeBP(uint[] memory _pids, uint16[] memory _depositFeeBPs) external onlyManager { require(_pids.length == _depositFeeBPs.length, 'invalid params'); for (uint i; i<_pids.length; i++) { require(_depositFeeBPs[i] <= 10000, 'depositFeeBP should be <=10000!'); poolInfo[_pids[i]].depositFeeBP = _depositFeeBPs[i]; } } function batchSetPaused(uint[] memory _pids, bool[] memory _pauseds) external onlyManager { require(_pids.length == _pauseds.length, 'invalid params'); for (uint i; i<_pids.length; i++) { poolInfo[_pids[i]].paused = _pauseds[i]; } } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint _from, uint _to) public view returns (uint) { return _to.sub(_from).mul(BONUS_MULTIPLIER); } function getToBlock() public view returns (uint) { return block.number; } function pendingRewardInfo(uint _pid) public view validatePoolByPid(_pid) returns (uint, uint) { PoolInfo storage pool = poolInfo[_pid]; if (rewardToken != address(0) && getToBlock() > pool.lastBlock && totalAllocPoint > 0) { uint multiplier = getMultiplier(pool.lastBlock, getToBlock()); uint reward = multiplier.mul(mintPerBlock).mul(pool.allocPoint).div(totalAllocPoint); return (reward, block.number); } return (0, block.number); } // View function to see pending RewardTokens on frontend. function pendingReward(uint _pid, address _user) external view validatePoolByPid(_pid) returns (uint) { PoolInfo memory pool = poolInfo[_pid]; UserInfo memory user = userInfo[_pid][_user]; uint accRewardPerShare = pool.accRewardPerShare; if (block.number > pool.lastBlock && pool.depositTokenSupply != 0) { uint multiplier = getMultiplier(pool.lastBlock, block.number); uint reward = multiplier.mul(mintPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accRewardPerShare = accRewardPerShare.add(reward.mul(1e18).div(pool.depositTokenSupply)); } return user.amount.mul(accRewardPerShare).div(1e18).sub(user.rewardDebt); } function _mintRewardToken(uint _pid) internal view returns (uint, uint) { if(rewardToken == address(0)) { return (0, block.number); } (uint reward,) = pendingRewardInfo(_pid); return (reward, block.number); } // Update reward variables for all pools. Be careful of gas spending! function massUpdatePools() public { uint length = poolInfo.length; for (uint pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint _pid) internal { PoolInfo storage pool = poolInfo[_pid]; uint toBlock = getToBlock(); if (toBlock <= pool.lastBlock) { return; } if (pool.depositTokenSupply == 0 || pool.allocPoint == 0) { pool.lastBlock = toBlock; return; } (uint reward,) = _mintRewardToken(_pid); pool.accRewardPerShare = pool.accRewardPerShare.add(reward.mul(1e18).div(pool.depositTokenSupply)); pool.lastBlock = toBlock; } // Deposit tokens to SwitchFarm for reward allocation. function deposit(uint _pid, uint _amount, address _to) external validatePoolByPid(_pid) whenNotPaused nonReentrant returns(uint, uint) { PoolInfo storage pool = poolInfo[_pid]; require(pool.paused == false, "pool is paused"); UserInfo storage user = userInfo[_pid][_to]; updatePool(_pid); uint depositFee; if (_amount > 0) { IERC20(pool.depositToken).transferFrom(address(msg.sender), address(this), _amount); if (pool.depositFeeBP > 0) { depositFee = _amount.mul(pool.depositFeeBP).div(10000); safeTransfer(pool.depositToken, feeAddress, depositFee); _amount = _amount.sub(depositFee); user.amount = user.amount.add(_amount); } else { user.amount = user.amount.add(_amount); } } pool.depositTokenSupply = pool.depositTokenSupply.add(_amount); user.rewardDebt = user.amount.mul(pool.accRewardPerShare).div(1e18); emit Deposit(msg.sender, _to, _pid, _amount, depositFee); return (_amount, depositFee); } // Withdraw tokens from SwitchFarm. function withdraw(uint _pid, uint _amount, address _to) external validatePoolByPid(_pid) whenNotPaused nonReentrant returns(uint) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(pool.paused == false, "pool is paused"); require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); _harvestRewardToken(_pid, _to); if (_amount > 0) { user.amount = user.amount.sub(_amount); pool.depositTokenSupply = pool.depositTokenSupply.sub(_amount); safeTransfer(pool.depositToken, _to, _amount); } user.rewardDebt = user.amount.mul(pool.accRewardPerShare).div(1e18); emit Withdraw(msg.sender, _to, _pid, _amount); return _amount; } function _harvestRewardToken(uint _pid, address _to) internal returns(uint amount) { if(rewardToken == address(0)) { return 0; } PoolInfo memory pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; amount = user.amount.mul(pool.accRewardPerShare).div(1e18).sub(user.rewardDebt); uint take = IRewardToken(rewardToken).take(); if(amount > take) { amount = take; } IRewardToken(rewardToken).mint(_to, amount); user.rewardDebt = user.amount.mul(pool.accRewardPerShare).div(1e18); return amount; } function harvest(uint _pid, address _to) external validatePoolByPid(_pid) whenNotPaused nonReentrant returns (uint reward) { PoolInfo memory pool = poolInfo[_pid]; require(pool.paused == false, "pool is paused"); updatePool(_pid); reward = _harvestRewardToken(_pid, _to); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint _pid, address _to) external validatePoolByPid(_pid) nonReentrant returns(uint) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; uint amount = user.amount; require(amount > 0, 'no balance'); user.amount = 0; user.rewardDebt = 0; pool.depositTokenSupply = pool.depositTokenSupply.sub(amount); safeTransfer(pool.depositToken, _to, amount); emit EmergencyWithdraw(msg.sender, _to, _pid, amount); return amount; } // Safe Token transfer function, just in case if rounding error causes pool to not have enough tokens. function safeTokenTransfer(address _token, address _to, uint _amount) internal returns(uint) { uint tokenBal = IERC20(_token).balanceOf(address(this)); if(_amount >0) { if(tokenBal == 0) { return 0; } if (_amount > tokenBal) { _amount = tokenBal; } safeTransfer(_token, _to, _amount); } return _amount; } function safeTransfer(address _token, address _to, uint _amount) internal returns(uint) { (bool success, bytes memory data) = _token.call(abi.encodeWithSelector(0xa9059cbb, _to, _amount)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'safeTransfer: TRANSFER_FAILED'); return _amount; } function setTeamAddress(address _team) external onlyDev { require(_team != address(0), 'zero address'); team = _team; emit SetDevAddress(msg.sender, _team); } function setFeeAddress(address _feeAddress) external onlyDev { feeAddress = _feeAddress; emit SetFeeAddress(msg.sender, _feeAddress); } //reward has to add hidden dummy pools inorder to alter the emission, here we make it simple and transparent to all. function updateEmissionRate(uint _mintPerBlock) external onlyDev { massUpdatePools(); mintPerBlock = _mintPerBlock; emit UpdateEmissionRate(msg.sender, _mintPerBlock); } } // SPDX-License-Identifier: MIT pragma solidity >=0.5.0; interface IERC20 { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.12; interface IRewardToken { function balanceOf(address owner) external view returns (uint); function take() external view returns (uint); function funds(address user) external view returns (uint); function mint(address to, uint value) external returns (bool); } // 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; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.6; interface IConfig { function dev() external view returns (address); function admin() external view returns (address); } contract Configable { address public config; address public owner; event ConfigChanged(address indexed _user, address indexed _old, address indexed _new); event OwnerChanged(address indexed _user, address indexed _old, address indexed _new); function setupConfig(address _config) external onlyOwner { emit ConfigChanged(msg.sender, config, _config); config = _config; } modifier onlyOwner() { require(msg.sender == owner, 'OWNER FORBIDDEN'); _; } function admin() public view returns(address) { if(config != address(0)) { return IConfig(config).admin(); } return owner; } function dev() public view returns(address) { if(config != address(0)) { return IConfig(config).dev(); } return owner; } function changeOwner(address _user) external onlyOwner { require(owner != _user, 'Owner: NO CHANGE'); emit OwnerChanged(msg.sender, owner, _user); owner = _user; } modifier onlyDev() { require(msg.sender == dev() || msg.sender == owner, 'dev FORBIDDEN'); _; } modifier onlyAdmin() { require(msg.sender == admin(), 'admin FORBIDDEN'); _; } modifier onlyManager() { require(msg.sender == dev() || msg.sender == admin() || msg.sender == owner, 'manager FORBIDDEN'); _; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 0; uint256 private constant _ENTERED = 1; uint256 private _status; /** * @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.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. */ abstract contract Pausable { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(); bool private _paused; /** * @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() virtual { 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(); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0; /** * @title Initializable * * @dev Helper contract to support initializer functions. To use it, replace * the constructor with a function that has the `initializer` modifier. * WARNING: Unlike constructors, initializer functions must be manually * invoked. This applies both to deploying an Initializable contract, as well * as extending an Initializable contract via inheritance. * WARNING: When used with inheritance, manual care must be taken to not invoke * a parent initializer twice, or ensure that all initializers are idempotent, * because this is not dealt with automatically as with constructors. */ contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private initializing; /** * @dev Modifier to use in the initializer function of a contract. */ modifier initializer() { require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized"); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = true; } _; if (isTopLevelCall) { initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. 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; }
Update reward variables of the given pool to be up-to-date.
function updatePool(uint _pid) internal { PoolInfo storage pool = poolInfo[_pid]; uint toBlock = getToBlock(); if (toBlock <= pool.lastBlock) { return; } if (pool.depositTokenSupply == 0 || pool.allocPoint == 0) { pool.lastBlock = toBlock; return; } (uint reward,) = _mintRewardToken(_pid); pool.accRewardPerShare = pool.accRewardPerShare.add(reward.mul(1e18).div(pool.depositTokenSupply)); pool.lastBlock = toBlock; }
1,184,227
[ 1, 1891, 19890, 3152, 434, 326, 864, 2845, 358, 506, 731, 17, 869, 17, 712, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1089, 2864, 12, 11890, 389, 6610, 13, 2713, 288, 203, 3639, 8828, 966, 2502, 2845, 273, 2845, 966, 63, 67, 6610, 15533, 203, 3639, 2254, 358, 1768, 273, 19478, 1768, 5621, 203, 3639, 309, 261, 869, 1768, 1648, 2845, 18, 2722, 1768, 13, 288, 203, 5411, 327, 31, 203, 3639, 289, 203, 3639, 309, 261, 6011, 18, 323, 1724, 1345, 3088, 1283, 422, 374, 747, 2845, 18, 9853, 2148, 422, 374, 13, 288, 203, 5411, 2845, 18, 2722, 1768, 273, 358, 1768, 31, 203, 5411, 327, 31, 203, 3639, 289, 203, 540, 203, 3639, 261, 11890, 19890, 16, 13, 273, 389, 81, 474, 17631, 1060, 1345, 24899, 6610, 1769, 203, 3639, 2845, 18, 8981, 17631, 1060, 2173, 9535, 273, 2845, 18, 8981, 17631, 1060, 2173, 9535, 18, 1289, 12, 266, 2913, 18, 16411, 12, 21, 73, 2643, 2934, 2892, 12, 6011, 18, 323, 1724, 1345, 3088, 1283, 10019, 203, 203, 3639, 2845, 18, 2722, 1768, 273, 358, 1768, 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 ]
pragma solidity ^0.4.23; // File: contracts/ERC20Interface.sol // https://github.com/ethereum/EIPs/issues/20 interface ERC20 { function totalSupply() external view returns (uint supply); function balanceOf(address _owner) external view returns (uint balance); function transfer(address _to, uint _value) external returns (bool success); function transferFrom(address _from, address _to, uint _value) external returns (bool success); function approve(address _spender, uint _value) external returns (bool success); function allowance(address _owner, address _spender) external view returns (uint remaining); function decimals() external view returns(uint digits); event Approval(address indexed _owner, address indexed _spender, uint _value); } // File: contracts/PermissionGroups.sol contract PermissionGroups { address public admin; address public pendingAdmin; mapping(address=>bool) internal operators; mapping(address=>bool) internal alerters; address[] internal operatorsGroup; address[] internal alertersGroup; uint constant internal MAX_GROUP_SIZE = 50; constructor(address _admin) public { admin = _admin; } modifier onlyAdmin() { require(msg.sender == admin); _; } modifier onlyOperator() { require(operators[msg.sender]); _; } modifier onlyAlerter() { require(alerters[msg.sender]); _; } function getOperators () external view returns(address[]) { return operatorsGroup; } function getAlerters () external view returns(address[]) { return alertersGroup; } event TransferAdminPending(address pendingAdmin); /** * @dev Allows the current admin to set the pendingAdmin address. * @param newAdmin The address to transfer ownership to. */ function transferAdmin(address newAdmin) public onlyAdmin { require(newAdmin != address(0)); emit TransferAdminPending(pendingAdmin); pendingAdmin = newAdmin; } /** * @dev Allows the current admin to set the admin in one tx. Useful initial deployment. * @param newAdmin The address to transfer ownership to. */ function transferAdminQuickly(address newAdmin) public onlyAdmin { require(newAdmin != address(0)); emit TransferAdminPending(newAdmin); emit AdminClaimed(newAdmin, admin); admin = newAdmin; } event AdminClaimed( address newAdmin, address previousAdmin); /** * @dev Allows the pendingAdmin address to finalize the change admin process. */ function claimAdmin() public { require(pendingAdmin == msg.sender); emit AdminClaimed(pendingAdmin, admin); admin = pendingAdmin; pendingAdmin = address(0); } event AlerterAdded (address newAlerter, bool isAdd); function addAlerter(address newAlerter) public onlyAdmin { require(!alerters[newAlerter]); // prevent duplicates. require(alertersGroup.length < MAX_GROUP_SIZE); emit AlerterAdded(newAlerter, true); alerters[newAlerter] = true; alertersGroup.push(newAlerter); } function removeAlerter (address alerter) public onlyAdmin { require(alerters[alerter]); alerters[alerter] = false; for (uint i = 0; i < alertersGroup.length; ++i) { if (alertersGroup[i] == alerter) { alertersGroup[i] = alertersGroup[alertersGroup.length - 1]; alertersGroup.length--; emit AlerterAdded(alerter, false); break; } } } event OperatorAdded(address newOperator, bool isAdd); function addOperator(address newOperator) public onlyAdmin { require(!operators[newOperator]); // prevent duplicates. require(operatorsGroup.length < MAX_GROUP_SIZE); emit OperatorAdded(newOperator, true); operators[newOperator] = true; operatorsGroup.push(newOperator); } function removeOperator (address operator) public onlyAdmin { require(operators[operator]); operators[operator] = false; for (uint i = 0; i < operatorsGroup.length; ++i) { if (operatorsGroup[i] == operator) { operatorsGroup[i] = operatorsGroup[operatorsGroup.length - 1]; operatorsGroup.length -= 1; emit OperatorAdded(operator, false); break; } } } } // File: contracts/Withdrawable.sol /** * @title Contracts that should be able to recover tokens or ethers can inherit this contract. * @author Ilan Doron * @dev Allows to recover any tokens or Ethers received in a contract. * Should prevent any accidental loss of tokens. */ contract Withdrawable is PermissionGroups { constructor(address _admin) PermissionGroups (_admin) public {} event TokenWithdraw(ERC20 token, uint amount, address sendTo); /** * @dev Withdraw all ERC20 compatible tokens * @param token ERC20 The address of the token contract */ function withdrawToken(ERC20 token, uint amount, address sendTo) external onlyAdmin { require(token.transfer(sendTo, amount)); emit TokenWithdraw(token, amount, sendTo); } event EtherWithdraw(uint amount, address sendTo); /** * @dev Withdraw Ethers */ function withdrawEther(uint amount, address sendTo) external onlyAdmin { sendTo.transfer(amount); emit EtherWithdraw(amount, sendTo); } } // File: contracts/zeppelin/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&#39;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/IEORate.sol contract IEORate is Withdrawable { uint public ethToTokenNumerator; uint public ethToTokenDenominator; constructor(address admin) Withdrawable(admin) public {} event RateSet (uint rateNumerator, uint rateDenominator, address sender); function setRateEthToToken(uint rateNumerator, uint rateDenominator) public onlyOperator { require(rateNumerator > 0); require(rateDenominator > 0); ethToTokenNumerator = rateNumerator; ethToTokenDenominator = rateDenominator; emit RateSet(rateNumerator, rateDenominator, msg.sender); } function getRate () public view returns(uint rateNumerator, uint rateDenominator) { rateNumerator = ethToTokenNumerator; rateDenominator = ethToTokenDenominator; } } // File: contracts/CapManager.sol //@Title Cap manager handles contribution cap per contributor. //@dev IEO will have 2 phases: // First phase is capped IEO where each contributor can contribute up to capped amount. // Second phase will be open for unlimited contributions that are blocked only by amount of tokens. contract CapManager is Withdrawable { mapping(uint=>uint) public participatedWei; uint public contributorCapWei; uint internal IEOId; //uinque ID will be part of hash uint constant public MAX_PURCHASE_WEI = uint(-1); uint public cappedIEOStartTime; uint public openIEOStartTime; //open IEO means no cap on purchase amount of KYC addresses. uint public endIEOTime; using SafeMath for uint; constructor(uint _cappedIEOTime, uint _openIEOTime, uint _endIEOTime, uint _contributorCapWei, uint _IEOId, address _admin) Withdrawable(_admin) public { require(_cappedIEOTime >= now); // solium-disable-line security/no-block-members require(_cappedIEOTime <= _openIEOTime); require(_openIEOTime <= _endIEOTime); require(_IEOId != 0); contributorCapWei = _contributorCapWei; IEOId = _IEOId; cappedIEOStartTime = _cappedIEOTime; openIEOStartTime = _openIEOTime; endIEOTime = _endIEOTime; } //@dev getContributorRemainingCap returns remaining cap for a contributor // Assuming that contributor has passed KYC process = is allowed to participate. // If contributor hasn"t participated - it will return full cap according to IEO stage (capped / open / close). // If contributor already participated. when IEO in capped stage, will return contributor cap less previous // participation. if open contribute stage will return max cap. // notice the participation amount will still be blocked by token balance of this contract. function getContributorRemainingCap(uint userId) public view returns(uint capWei) { if (!IEOStarted()) return 0; if (IEOEnded()) return 0; if (openIEOStarted()) { capWei = MAX_PURCHASE_WEI; } else { if (participatedWei[userId] >= contributorCapWei) capWei = 0; else capWei = contributorCapWei.sub(participatedWei[userId]); } } function eligible(uint userID, uint amountWei) public view returns(uint) { uint remainingCap = getContributorRemainingCap(userID); if (amountWei > remainingCap) return remainingCap; return amountWei; } event ContributorCapSet(uint capWei, address sender); function setContributorCap(uint capWei) public onlyAdmin { contributorCapWei = capWei; emit ContributorCapSet(capWei, msg.sender); } function IEOStarted() public view returns(bool) { return (now >= cappedIEOStartTime); // solium-disable-line security/no-block-members } function openIEOStarted() public view returns(bool) { return (now >= openIEOStartTime); // solium-disable-line security/no-block-members } function IEOEnded() public view returns(bool) { return (now >= endIEOTime); // solium-disable-line security/no-block-members } function validateContributor(address contributor, uint userId, uint8 v, bytes32 r, bytes32 s) public view returns(bool) { require(verifySignature(keccak256(contributor, userId, IEOId), v, r, s)); return true; } function getIEOId() external view returns(uint) { return IEOId; } function eligibleCheckAndIncrement(uint userId, uint amountInWei) internal returns(uint) { uint result = eligible(userId, amountInWei); participatedWei[userId] = participatedWei[userId].add(result); return result; } function verifySignature(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal view returns(bool) { address signer = ecrecover(hash, v, r, s); return operators[signer]; } } // File: contracts/KyberIEOInterface.sol interface KyberIEOInterface { function contribute(address contributor, uint userId, uint8 v, bytes32 r, bytes32 s) external payable returns(bool); function getContributorRemainingCap(uint userId) external view returns(uint capWei); function getIEOId() external view returns(uint); } // File: contracts/KyberIEO.sol contract KyberIEO is KyberIEOInterface, CapManager { mapping(address=>bool) public whiteListedAddresses; ERC20 public token; uint public raisedWei; uint public distributedTokensTwei; bool public haltedIEO = false; IEORate public IEORateContract; address public contributionWallet; constructor ( address _admin, address _contributionWallet, ERC20 _token, uint _contributorCapWei, uint _IEOId, uint _cappedIEOStart, uint _openIEOStart, uint _publicIEOEnd) CapManager(_cappedIEOStart, _openIEOStart, _publicIEOEnd, _contributorCapWei, _IEOId, _admin) public { require(_token != address(0)); require(_contributionWallet != address(0)); IEORateContract = new IEORate(_admin); contributionWallet = _contributionWallet; token = _token; } event IEOHalted(address sender); function haltIEO() public onlyAlerter { haltedIEO = true; emit IEOHalted(msg.sender); } event IEOResumed(address sender); function resumeIEO() public onlyAdmin { haltedIEO = false; emit IEOResumed(msg.sender); } event Contribution(address msgSender, address contributor, uint userId, uint distributedTokensTwei, uint payedWei); function contribute(address contributor, uint userId, uint8 v, bytes32 r, bytes32 s) external payable returns(bool) { require(!haltedIEO); require(IEOStarted()); require(!IEOEnded()); require((contributor == msg.sender) || whiteListedAddresses[msg.sender]); uint rateNumerator; uint rateDenominator; (rateNumerator, rateDenominator) = IEORateContract.getRate(); require(rateNumerator > 0); require(rateDenominator > 0); require(validateContributor(contributor, userId, v, r, s)); uint weiPayment = eligibleCheckAndIncrement(userId, msg.value); require(weiPayment > 0); uint tokenQty = weiPayment.mul(rateNumerator).div(rateDenominator); require(tokenQty > 0); // send remaining wei to msg.sender, not to contributor if(msg.value > weiPayment) { msg.sender.transfer(msg.value.sub(weiPayment)); } // send payment to wallet sendETHToContributionWallet(weiPayment); raisedWei = raisedWei.add(weiPayment); //send exchanged tokens to contributor require(token.transfer(contributor, tokenQty)); distributedTokensTwei = distributedTokensTwei.add(tokenQty); emit Contribution(msg.sender, contributor, userId, tokenQty, weiPayment); return true; } event addressWhiteListed(address _address, bool whiteListed); function whiteListAddress(address addr, bool whiteListed) public onlyAdmin { whiteListedAddresses[addr] = whiteListed; emit addressWhiteListed(addr, whiteListed); } function getRate () public view returns(uint rateNumerator, uint rateDenominator) { (rateNumerator, rateDenominator) = IEORateContract.getRate(); } // just to check that funds goes to the right place // tokens are not given in return function debugBuy() public payable { require(msg.value == 123); sendETHToContributionWallet(msg.value); } function sendETHToContributionWallet(uint valueWei) internal { contributionWallet.transfer(valueWei); } } // File: contracts/KyberIEOGetter.sol contract ERC20Plus is ERC20 { function symbol() external view returns(string); function totalSupply() external view returns(uint); } contract KyberIEOGetter { function getIEOInfo(KyberIEO IEO) public view returns ( uint[3] IEOTimes, bool[4] IEOStates, uint[2] rate, uint[5] amounts, uint tokenDecimals, address tokenAddress, string symbol ) { IEOTimes = [IEO.cappedIEOStartTime(), IEO.openIEOStartTime(), IEO.endIEOTime()]; IEOStates = [IEO.IEOStarted(), IEO.openIEOStarted(), IEO.IEOEnded(), IEO.haltedIEO()]; rate = [IEORate(IEO.IEORateContract()).ethToTokenNumerator(), IEORate(IEO.IEORateContract()).ethToTokenDenominator()]; amounts = [IEO.distributedTokensTwei(), IEO.raisedWei(), IEO.contributorCapWei(), 0, IEO.token().totalSupply()]; amounts[3] = IEO.token().balanceOf(address(IEO)); return(IEOTimes, IEOStates, rate, amounts, IEO.token().decimals(), IEO.token(), ERC20Plus(IEO.token()).symbol()); } function getIEOsInfo(KyberIEO[] IEOs) public view returns( uint[] distributedTweiPerIEO, uint[] tokenBalancePerIEO, address[] tokenAddressPerIEO, bytes32[] tokenSymbolPerIEO, uint[] tokenDecimalsPerIEO, uint[] totalSupplyPerIEO ) { distributedTweiPerIEO = new uint[](IEOs.length); tokenBalancePerIEO = new uint[](IEOs.length); tokenAddressPerIEO = new address[](IEOs.length); tokenSymbolPerIEO = new bytes32[](IEOs.length); tokenDecimalsPerIEO = new uint[](IEOs.length); totalSupplyPerIEO = new uint[](IEOs.length); for(uint i = 0; i < IEOs.length; i++) { distributedTweiPerIEO[i] = IEOs[i].distributedTokensTwei(); tokenBalancePerIEO[i] = IEOs[i].token().balanceOf(address(IEOs[i])); tokenAddressPerIEO[i] = IEOs[i].token(); tokenSymbolPerIEO[i] = stringToBytes32(ERC20Plus(IEOs[i].token()).symbol()); tokenDecimalsPerIEO[i] = IEOs[i].token().decimals(); totalSupplyPerIEO[i] = IEOs[i].token().totalSupply(); } } function stringToBytes32(string memory source) public pure returns (bytes32 result) { bytes memory tempEmptyStringTest = bytes(source); if (tempEmptyStringTest.length == 0) { return 0x0; } assembly { result := mload(add(source, 32)) } } }
* @title Contracts that should be able to recover tokens or ethers can inherit this contract. @author Ilan Doron @dev Allows to recover any tokens or Ethers received in a contract. Should prevent any accidental loss of tokens./
contract Withdrawable is PermissionGroups { event TokenWithdraw(ERC20 token, uint amount, address sendTo); constructor(address _admin) PermissionGroups (_admin) public {} function withdrawToken(ERC20 token, uint amount, address sendTo) external onlyAdmin { require(token.transfer(sendTo, amount)); emit TokenWithdraw(token, amount, sendTo); } event EtherWithdraw(uint amount, address sendTo); function withdrawEther(uint amount, address sendTo) external onlyAdmin { sendTo.transfer(amount); emit EtherWithdraw(amount, sendTo); } }
6,653,558
[ 1, 20723, 716, 1410, 506, 7752, 358, 5910, 2430, 578, 13750, 414, 848, 6811, 333, 6835, 18, 225, 467, 6115, 463, 280, 265, 225, 25619, 358, 5910, 1281, 2430, 578, 512, 29540, 5079, 316, 279, 6835, 18, 9363, 5309, 1281, 25961, 287, 8324, 434, 2430, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 3423, 9446, 429, 353, 8509, 3621, 288, 203, 203, 203, 565, 871, 3155, 1190, 9446, 12, 654, 39, 3462, 1147, 16, 2254, 3844, 16, 1758, 29091, 1769, 203, 203, 203, 565, 3885, 12, 2867, 389, 3666, 13, 8509, 3621, 261, 67, 3666, 13, 1071, 2618, 203, 565, 445, 598, 9446, 1345, 12, 654, 39, 3462, 1147, 16, 2254, 3844, 16, 1758, 29091, 13, 3903, 1338, 4446, 288, 203, 3639, 2583, 12, 2316, 18, 13866, 12, 4661, 774, 16, 3844, 10019, 203, 3639, 3626, 3155, 1190, 9446, 12, 2316, 16, 3844, 16, 29091, 1769, 203, 565, 289, 203, 203, 565, 871, 512, 1136, 1190, 9446, 12, 11890, 3844, 16, 1758, 29091, 1769, 203, 203, 565, 445, 598, 9446, 41, 1136, 12, 11890, 3844, 16, 1758, 29091, 13, 3903, 1338, 4446, 288, 203, 3639, 29091, 18, 13866, 12, 8949, 1769, 203, 3639, 3626, 512, 1136, 1190, 9446, 12, 8949, 16, 29091, 1769, 203, 565, 289, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT // File: @openzeppelin/contracts/token/ERC20/IERC20.sol pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); function decimals() external view returns (uint8); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts/math/SafeMath.sol pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/utils/Address.sol 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"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol pragma solidity ^0.6.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File: @openzeppelin/contracts/GSN/Context.sol pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts/access/Ownable.sol pragma solidity ^0.6.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _governance; event GovernanceTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _governance = msgSender; emit GovernanceTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function governance() public view returns (address) { return _governance; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyGovernance() { require(_governance == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferGovernance(address newOwner) internal virtual onlyGovernance { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit GovernanceTransferred(_governance, newOwner); _governance = newOwner; } } // Tornado interfaces interface TornadoContract { function denomination() external view returns (uint256); function deposit(bytes32 _commitment) external; function withdraw(bytes calldata _proof, bytes32 _root, bytes32 _nullifierHash, address payable _recipient, address payable _relayer, uint256 _fee, uint256 _refund) external payable; } // File: contracts/StabilizeTornadoProxy.sol pragma solidity ^0.6.6; // The Stabilize Tornado Proxy is a contract that is a front for the Tornado protocol // It will collect all the relay fees and distribute some to sender and some to the treasury // The only fee check this contract does is for 10 stablecoins going to the sender of the message contract StabilizeTornadoProxy is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; using Address for address; address public treasuryAddress; // Address of the treasury uint256 constant minStablecoinFee = 10; // Absolute minimum amount that goes to msg.sender // Info of each Tornado mixer struct MixerInfo { IERC20 token; // Reference of Stablecoin uint256 denomination; // The units to deposit and withdraw TornadoContract mixer; // Reference to the mixer uint256 totalDeposits; // The current pool size uint256 depositSinceWithdraw; // The number of deposits since the last withdraw uint256 lastDeposit; // Time of last deposit uint256 decimals; // Decimals of token } // Each coin type is in a separate mixer field MixerInfo[] private daiMixers; MixerInfo[] private usdcMixers; MixerInfo[] private usdtMixers; constructor( address _treasury ) public { treasuryAddress = _treasury; setupTornadoProxies(); // Setup the tornado proxies } // Initialization functions function setupTornadoProxies() internal { // Setup mixer info // Start with DAI IERC20 _token = IERC20(address(0x6B175474E89094C44Da98b954EedeAC495271d0F)); TornadoContract _tor = TornadoContract(address(0xD4B88Df4D29F5CedD6857912842cff3b20C8Cfa3)); // DAI 100 daiMixers.push( MixerInfo({ token: _token, mixer: _tor, denomination: _tor.denomination(), decimals: _token.decimals(), totalDeposits: 0, depositSinceWithdraw: 0, lastDeposit: 0 }) ); _tor = TornadoContract(address(0xFD8610d20aA15b7B2E3Be39B396a1bC3516c7144)); // DAI 1000 daiMixers.push( MixerInfo({ token: _token, mixer: _tor, denomination: _tor.denomination(), decimals: _token.decimals(), totalDeposits: 0, depositSinceWithdraw: 0, lastDeposit: 0 }) ); // USDC _token = IERC20(address(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48)); _tor = TornadoContract(address(0xd96f2B1c14Db8458374d9Aca76E26c3D18364307)); // USDC 100 usdcMixers.push( MixerInfo({ token: _token, mixer: _tor, denomination: _tor.denomination(), decimals: _token.decimals(), totalDeposits: 0, depositSinceWithdraw: 0, lastDeposit: 0 }) ); _tor = TornadoContract(address(0x4736dCf1b7A3d580672CcE6E7c65cd5cc9cFBa9D)); // USDC 1000 usdcMixers.push( MixerInfo({ token: _token, mixer: _tor, denomination: _tor.denomination(), decimals: _token.decimals(), totalDeposits: 0, depositSinceWithdraw: 0, lastDeposit: 0 }) ); // USDT _token = IERC20(address(0xdAC17F958D2ee523a2206206994597C13D831ec7)); _tor = TornadoContract(address(0x169AD27A470D064DEDE56a2D3ff727986b15D52B)); // USDT 100 usdtMixers.push( MixerInfo({ token: _token, mixer: _tor, denomination: _tor.denomination(), decimals: _token.decimals(), totalDeposits: 0, depositSinceWithdraw: 0, lastDeposit: 0 }) ); _tor = TornadoContract(address(0x0836222F2B2B24A3F36f98668Ed8F0B38D1a872f)); // USDT 1000 usdtMixers.push( MixerInfo({ token: _token, mixer: _tor, denomination: _tor.denomination(), decimals: _token.decimals(), totalDeposits: 0, depositSinceWithdraw: 0, lastDeposit: 0 }) ); } function getPoolsInfo(uint256 _type) public view returns (uint256, uint256, uint256, uint256, uint256) { // Returns everything about the pool in one call require(_type < 3,"Type out of range"); if(_type == 0){ // We want DAI info return( daiMixers[0].totalDeposits.add(daiMixers[1].totalDeposits), // Total balance in both DAI pools daiMixers[0].depositSinceWithdraw, // Pool 0 number of deposits daiMixers[1].depositSinceWithdraw, // Pool 1 daiMixers[0].lastDeposit, // Pool 0 last withdraw time daiMixers[1].lastDeposit ); }else if(_type == 1){ // USDC return( usdcMixers[0].totalDeposits.add(usdcMixers[1].totalDeposits), // Total balance in both USDC pools usdcMixers[0].depositSinceWithdraw, // Pool 0 number of deposits usdcMixers[1].depositSinceWithdraw, // Pool 1 usdcMixers[0].lastDeposit, // Pool 0 last withdraw time usdcMixers[1].lastDeposit ); }else{ return( usdtMixers[0].totalDeposits.add(usdtMixers[1].totalDeposits), // Total balance in both USDT pools usdtMixers[0].depositSinceWithdraw, // Pool 0 number of deposits usdtMixers[1].depositSinceWithdraw, // Pool 1 usdtMixers[0].lastDeposit, // Pool 0 last withdraw time usdtMixers[1].lastDeposit ); } } // Deposit methods function depositDAI(bytes32 _commitment, uint256 amount) external { require(amount == daiMixers[0].denomination || amount == daiMixers[1].denomination, "Can only deposit either 100 or 1000 DAI"); uint256 _ind = 0; // 100 Pool if(amount == daiMixers[1].denomination){ _ind = 1; // Set to 1000 Pool } daiMixers[_ind].token.safeTransferFrom(_msgSender(), address(this), amount); // Pull from the user daiMixers[_ind].token.safeApprove(address(daiMixers[_ind].mixer), amount); // Approve the DAI here to send to Tornado daiMixers[_ind].mixer.deposit(_commitment); // Now deposit the DAI daiMixers[_ind].lastDeposit = now; // Metrics, last deposit time daiMixers[_ind].totalDeposits = daiMixers[_ind].totalDeposits.add(amount); // Add to the deposit amount daiMixers[_ind].depositSinceWithdraw = daiMixers[_ind].depositSinceWithdraw.add(1); // Total deposits since withdraw } function depositUSDC(bytes32 _commitment, uint256 amount) external { require(amount == usdcMixers[0].denomination || amount == usdcMixers[1].denomination, "Can only deposit either 100 or 1000 USDC"); uint256 _ind = 0; // 100 Pool if(amount == usdcMixers[1].denomination){ _ind = 1; // Set to 1000 Pool } usdcMixers[_ind].token.safeTransferFrom(_msgSender(), address(this), amount); // Pull from the user usdcMixers[_ind].token.safeApprove(address(usdcMixers[_ind].mixer), amount); // Approve the USDC here to send to Tornado usdcMixers[_ind].mixer.deposit(_commitment); // Now deposit the USDC usdcMixers[_ind].lastDeposit = now; // Metrics, last deposit time usdcMixers[_ind].totalDeposits = usdcMixers[_ind].totalDeposits.add(amount); // Add to the deposit amount usdcMixers[_ind].depositSinceWithdraw = usdcMixers[_ind].depositSinceWithdraw.add(1); // Total deposits since withdraw } function depositUSDT(bytes32 _commitment, uint256 amount) external { require(amount == usdtMixers[0].denomination || amount == usdtMixers[1].denomination, "Can only deposit either 100 or 1000 USDT"); uint256 _ind = 0; // 100 Pool if(amount == usdtMixers[1].denomination){ _ind = 1; // Set to 1000 Pool } usdtMixers[_ind].token.safeTransferFrom(_msgSender(), address(this), amount); // Pull from the user usdtMixers[_ind].token.safeApprove(address(usdtMixers[_ind].mixer), amount); // Approve the USDT here to send to Tornado usdtMixers[_ind].mixer.deposit(_commitment); // Now deposit the USDT usdtMixers[_ind].lastDeposit = now; // Metrics, last deposit time usdtMixers[_ind].totalDeposits = usdtMixers[_ind].totalDeposits.add(amount); // Add to the deposit amount usdtMixers[_ind].depositSinceWithdraw = usdtMixers[_ind].depositSinceWithdraw.add(1); // Total deposits since withdraw } // Withdraw functions function withdrawDAI(bytes calldata _proof, uint256 amount, bytes32 _root, bytes32 _nullifierHash, address payable _recipient, address payable _relayer, uint256 _fee, uint256 _refund) external payable { // The user can send ETH to the recipient require(amount == daiMixers[0].denomination || amount == daiMixers[1].denomination, "Can only withdraw either 100 or 1000 DAI"); require(_relayer == address(this), "The relayer must be this contract"); uint256 _ind = 0; // 100 Pool if(amount == daiMixers[1].denomination){ _ind = 1; // Set to 1000 Pool } // This address should now have the fee uint256 gasCharge = minStablecoinFee.mul(10**daiMixers[_ind].decimals); // Get gas fee in base units require(_fee >= gasCharge, "Fee not enough to pay for minimum fee of 10 tokens"); daiMixers[_ind].mixer.withdraw{value: msg.value}(_proof, _root, _nullifierHash, _recipient, _relayer, _fee, _refund); // Now withdraw the DAI _fee = _fee.sub(gasCharge); // The gas charge goes directly to the message sender uint256 treasuryFee = _fee.div(2); // Treasury takes half the withdraw fee _fee = _fee.sub(treasuryFee); daiMixers[_ind].token.safeTransfer(_msgSender(), _fee.add(gasCharge)); // The message sender gets half the fee plus gas charge daiMixers[_ind].token.safeTransfer(treasuryAddress,treasuryFee); daiMixers[_ind].totalDeposits = daiMixers[_ind].totalDeposits.sub(amount); // Take away from deposits daiMixers[_ind].depositSinceWithdraw = 0; // Reset withdraws } function withdrawUSDC(bytes calldata _proof, uint256 amount, bytes32 _root, bytes32 _nullifierHash, address payable _recipient, address payable _relayer, uint256 _fee, uint256 _refund) external payable { // The user can send ETH to the recipient require(amount == usdcMixers[0].denomination || amount == usdcMixers[1].denomination, "Can only withdraw either 100 or 1000 USDC"); require(_relayer == address(this), "The relayer must be this contract"); uint256 _ind = 0; // 100 Pool if(amount == usdcMixers[1].denomination){ _ind = 1; // Set to 1000 Pool } // This address should now have the fee uint256 gasCharge = minStablecoinFee.mul(10**usdcMixers[_ind].decimals); // Get gas fee in base units require(_fee >= gasCharge, "Fee not enough to pay for minimum fee of 10 tokens"); usdcMixers[_ind].mixer.withdraw{value: msg.value}(_proof, _root, _nullifierHash, _recipient, _relayer, _fee, _refund); // Now withdraw the USDC _fee = _fee.sub(gasCharge); // The gas charge goes directly to the message sender uint256 treasuryFee = _fee.div(2); // Treasury takes half the withdraw fee _fee = _fee.sub(treasuryFee); usdcMixers[_ind].token.safeTransfer(_msgSender(), _fee.add(gasCharge)); // The message sender gets half the fee plus gas charge usdcMixers[_ind].token.safeTransfer(treasuryAddress,treasuryFee); usdcMixers[_ind].totalDeposits = usdcMixers[_ind].totalDeposits.sub(amount); // Take away from deposits usdcMixers[_ind].depositSinceWithdraw = 0; // Reset withdraws } function withdrawUSDT(bytes calldata _proof, uint256 amount, bytes32 _root, bytes32 _nullifierHash, address payable _recipient, address payable _relayer, uint256 _fee, uint256 _refund) external payable { // The user can send ETH to the recipient require(amount == usdtMixers[0].denomination || amount == usdtMixers[1].denomination, "Can only withdraw either 100 or 1000 USDT"); require(_relayer == address(this), "The relayer must be this contract"); uint256 _ind = 0; // 100 Pool if(amount == usdtMixers[1].denomination){ _ind = 1; // Set to 1000 Pool } // This address should now have the fee uint256 gasCharge = minStablecoinFee.mul(10**usdtMixers[_ind].decimals); // Get gas fee in base units require(_fee >= gasCharge, "Fee not enough to pay for minimum fee of 10 tokens"); usdtMixers[_ind].mixer.withdraw{value: msg.value}(_proof, _root, _nullifierHash, _recipient, _relayer, _fee, _refund); // Now withdraw the USDT _fee = _fee.sub(gasCharge); // The gas charge directly to the message sender uint256 treasuryFee = _fee.div(2); // Treasury takes half the withdraw fee _fee = _fee.sub(treasuryFee); usdtMixers[_ind].token.safeTransfer(_msgSender(), _fee.add(gasCharge)); // The message sender gets half the fee plus gas charge usdtMixers[_ind].token.safeTransfer(treasuryAddress,treasuryFee); usdtMixers[_ind].totalDeposits = usdtMixers[_ind].totalDeposits.sub(amount); // Take away from deposits usdtMixers[_ind].depositSinceWithdraw = 0; // Reset withdraws } // Governance functions // Timelock variables uint256 private _timelockStart; // The start of the timelock to change governance variables uint256 private _timelockType; // The function that needs to be changed uint256 constant _timelockDuration = 86400; // Timelock is 24 hours // Reusable timelock variables address private _timelock_address; modifier timelockConditionsMet(uint256 _type) { require(_timelockType == _type, "Timelock not acquired for this function"); _timelockType = 0; // Reset the type once the timelock is used require(now >= _timelockStart + _timelockDuration, "Timelock time not met"); _; } // Change the owner of the token contract // -------------------- function startGovernanceChange(address _address) external onlyGovernance { _timelockStart = now; _timelockType = 1; _timelock_address = _address; } function finishGovernanceChange() external onlyGovernance timelockConditionsMet(1) { transferGovernance(_timelock_address); } // -------------------- // Change the treasury address // -------------------- function startChangeTreasury(address _address) external onlyGovernance { _timelockStart = now; _timelockType = 2; _timelock_address = _address; } function finishChangeTreasury() external onlyGovernance timelockConditionsMet(2) { treasuryAddress = _timelock_address; } // -------------------- }
Now withdraw the USDC
usdcMixers[_ind].mixer.withdraw{value: msg.value}(_proof, _root, _nullifierHash, _recipient, _relayer, _fee, _refund);
484,291
[ 1, 8674, 598, 9446, 326, 11836, 5528, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 18701, 584, 7201, 21294, 414, 63, 67, 728, 8009, 14860, 264, 18, 1918, 9446, 95, 1132, 30, 1234, 18, 1132, 97, 24899, 24207, 16, 389, 3085, 16, 389, 2011, 1251, 2310, 16, 389, 20367, 16, 389, 2878, 1773, 16, 389, 21386, 16, 389, 1734, 1074, 1769, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.4.24; library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) return 0; c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } contract TESTToken { using SafeMath for uint256; /*** State Variables ***/ //TODO use this as a constant when LIVE so that the source code signature includes it and is unique //TODO Set this to the Neureal multisig wallet that will take the ETH from the sale // address private constant NEUREAL_ETH_WALLET = 0x0000000000000000000000000000000000000000; address public NEUREAL_ETH_WALLET; //TODO use this as a constant when LIVE so that the source code signature includes it and is unique //TODO Set this to the address of the wallet that has authority to send the whitelisted Ethereum addresses // address private constant WHITELIST_PROVIDER = 0x0000000000000000000000000000000000000000; address public WHITELIST_PROVIDER; //TODO Set this to the opening rate of token per ETH here based on https://www.coinbase.com/charts //ex: $448 (per ETH) / $0.07 (opening price) = 6400 (works for wei as long as token decimals=18 because ETH=10^18 wei) uint256 public constant OPENING_RATE = 6400; //TODO change these values to the real values when going LIVE uint256 public constant MAX_SALE = 700 * 10**18; //Maximum token that can be purchased in the sale (70000000) uint256 public constant MIN_PURCHASE = 7 * 10**18; //Minumum token that can be purchased (150000) uint256 public constant MAX_ALLOCATION = 50 * 10**18; //Maximum token that can be allocated by the owner (5000000) uint256 public constant MAX_SUPPLY = MAX_SALE + MAX_ALLOCATION; //Maximum token that can be created //Maximum value of ETH (in Wei) in the contract that can be withdrawn immediately after its sold. The rest can only be withdrawn after the sale has ended. uint256 public constant MAX_WEI_WITHDRAWAL = (70 * 10**18) / OPENING_RATE; //Maximum ETH that can be withdrawn during the sale (7000000) address private owner_; //Contract creator function owner() external view returns (address) { return owner_; } mapping(address => bool) private whitelist_; //List of addresses that can purchase token function whitelisted(address _who) external view returns (bool) { return whitelist_[_who]; } uint256 private totalSale_ = 0; //Current total token sold (only for viewing) function totalSale() external view returns (uint256) { return totalSale_; } uint256 private totalSaleWei_ = 0; //Current total Wei recieved from sale (only for viewing) function totalSaleWei() external view returns (uint256) { return totalSaleWei_; } uint256 private totalAllocated_ = 0; //Current total token allocated (only for viewing) function totalAllocated() external view returns (uint256) { return totalAllocated_; } //TODO Make private when going LIVE ?? uint256 public weiWithdrawn_ = 0; //Current total Wei withdrawn to NEUREAL_ETH_WALLET uint256 public totalRefunds_ = 0; //Current Wei locked up in refunds mapping(address => uint256) public pendingRefunds_; enum Phase { BeforeSale, Sale, Finalized } Phase private phase_ = Phase.BeforeSale; //Current sale state function phase() external view returns (Phase) { return phase_; } /*** Events ***/ event Transfer(address indexed _from, address indexed _to, uint256 _value); event TokenPurchase(uint256 _totalTokenSold, uint256 _totalWei); event Refund(address indexed _who, uint256 _weiValue); event SaleStarted(); event SaleFinalized(); /*** ERC20 token standard ***/ string public constant name = "Neureal TGE Test"; string public constant symbol = "TEST"; uint8 public constant decimals = 18; uint256 private totalSupply_ = 0; function totalSupply() external view returns (uint256) { return totalSupply_; } mapping(address => uint256) private balances_; function balanceOf(address _who) external view returns (uint256) { return balances_[_who]; } function transfer(address _to, uint256 _value) external returns (bool) { // Non transferable, revert so people don't loose as much ether revert(); //uses some gas, around 23000, only like 3 instructions // require(false); //uses some gas, around 23000, medium number of instructions // assert(false); //uses full gas limit // revert("NOT SUPPORTED"); //uses some gas, around 23000, lots of instructions return false; //not needed? } /*** Non ERC20 Functions ***/ /* Initializes contract */ //TODO take parameters out when LIVE constructor(address _NEUREAL_ETH_WALLET, address _WHITELIST_PROVIDER) public { owner_ = msg.sender; NEUREAL_ETH_WALLET = _NEUREAL_ETH_WALLET; //TODO take out when LIVE WHITELIST_PROVIDER = _WHITELIST_PROVIDER; //TODO take out when LIVE } /** Purchase **/ /* KYC/AML/accredited auth whitelisting */ function whitelist(address _who) external { require(phase_ != Phase.Finalized); //Only works before and during sale require(msg.sender == WHITELIST_PROVIDER); //Only whitelist provider whitelist_[_who] = true; //DONT check blacklist (coinbase, exchange, etc) here, check in auth website } //TODO do we really need this? function whitelistMany(address[] _who) external { require(phase_ != Phase.Finalized); //Only works before and during sale require(msg.sender == WHITELIST_PROVIDER); //Only whitelist provider for (uint256 i = 0; i < _who.length; i++) { whitelist_[_who[i]] = true; } } //TODO do we really need this? function whitelistRemove(address _who) external { require(phase_ != Phase.Finalized); //Only works before and during sale require(msg.sender == WHITELIST_PROVIDER); //Only whitelist provider whitelist_[_who] = false; } /* Token purchase (called whenever someone tries to send ether to this contract) */ function() external payable { require(phase_ == Phase.Sale); //Only sell during sale require(msg.value != 0); //Stop spamming, contract only calls, etc require(msg.sender != address(0)); //Prevent transfer to 0x0 address require(msg.sender != address(this)); //Prevent calls from this.transfer(this) require(whitelist_[msg.sender]); //Only whitelisted // assert(address(this).balance >= msg.value); //this.balance gets updated with msg.value before this function starts uint256 tokens = msg.value.mul(OPENING_RATE); require(tokens >= MIN_PURCHASE); //must be above minimum uint256 newTotalSale = totalSale_.add(tokens); require(newTotalSale <= MAX_SALE); //Check if there is enough available in sale uint256 newTotalSupply = totalSupply_.add(tokens); require(newTotalSupply <= MAX_SUPPLY); //Check if there is enough available (should not happen) balances_[msg.sender] = balances_[msg.sender].add(tokens); totalSupply_ = newTotalSupply; totalSale_ = newTotalSale; totalSaleWei_ = totalSaleWei_.add(msg.value); // NEUREAL_ETH_WALLET.transfer(msg.value); //This is not safe, use withdraw and revert methods emit Transfer(address(0), msg.sender, tokens); emit TokenPurchase(totalSale_, totalSaleWei_); } /* Withdraw current available ETH in contract */ function withdraw() external { require(msg.sender == owner_); //Only owner uint256 withdrawalValue = address(this).balance.sub(totalRefunds_); if (phase_ != Phase.Finalized) { uint256 newWeiWithdrawn = weiWithdrawn_.add(withdrawalValue); if (newWeiWithdrawn > MAX_WEI_WITHDRAWAL) { withdrawalValue = MAX_WEI_WITHDRAWAL.sub(weiWithdrawn_); //Withdraw up to the full amount left require(withdrawalValue != 0); //Bail if already depleted newWeiWithdrawn = MAX_WEI_WITHDRAWAL; } weiWithdrawn_ = newWeiWithdrawn; } NEUREAL_ETH_WALLET.transfer(withdrawalValue); //This works with our multisig (using 2300 gas stipend) // require(NEUREAL_ETH_WALLET.call.value(withdrawalValue)()); //alternative to be able to send more gas } /** Revert **/ /* Revert token purchase, lock all ETH for refund, put all allocated token back in allocation pool */ function revertPurchase(address _who) external payable { require(phase_ == Phase.Sale); //Only revert during sale, afterwords can revert using NEUREAL TGE require(msg.sender == owner_); //Only owner require(_who != address(0)); //Prevent refund to 0x0 address require(balances_[_who] != 0); //Prevent if never purchased require(pendingRefunds_[_who] == 0); //Prevent if already reverted uint256 tokenValue = balances_[_who]; uint256 weiValue = tokenValue.div(OPENING_RATE); assert(weiValue != 0); //We don't allow transfers, but if we did this might happen from rounding require(address(this).balance >= weiValue); //Must have enough wei in contract after payable to lock up totalRefunds_ = totalRefunds_.add(weiValue); pendingRefunds_[_who] = weiValue; totalSaleWei_ = totalSaleWei_.sub(weiValue); totalSupply_ = totalSupply_.sub(tokenValue); totalSale_ = totalSale_.sub(tokenValue); balances_[_who] = 0; emit Transfer(_who, address(0), tokenValue); } /* send allocated refund, anyone can call anytime */ function sendRefund(address _who) external { require(pendingRefunds_[_who] != 0); //Limit reentrancy and execution if not needed uint256 weiValue = pendingRefunds_[_who]; pendingRefunds_[_who] = 0; totalRefunds_ = totalRefunds_.sub(weiValue); emit Refund(_who, weiValue); _who.transfer(weiValue); // require(_who.call.value(weiValue)()); //TODO I think I need to use this alternative to send more gas than 2300 to be able to refund to contracts } /** Allocate **/ /* Owner allocation, create new token (under conditions) without costing ETH */ function allocate(address _to, uint256 _value) external { require(phase_ != Phase.Finalized); //Only works before and during sale require(msg.sender == owner_); //Only owner require(_value != 0); //Allocate is not a transfer call from a wallet app, so this is ok require(_to != address(0)); //Prevent transfer to 0x0 address require(_to != address(this)); //Prevent transfer to this contract address uint256 newTotalAllocated = totalAllocated_.add(_value); require(newTotalAllocated <= MAX_ALLOCATION); //Check if there is enough available to allocate uint256 newTotalSupply = totalSupply_.add(_value); require(newTotalSupply <= MAX_SUPPLY); //Check if there is enough available (should not happen) balances_[_to] = balances_[_to].add(_value); totalSupply_ = newTotalSupply; totalAllocated_ = newTotalAllocated; emit Transfer(address(0), _to, _value); } /** Contract State **/ /* state transition */ function transition() external { require(phase_ != Phase.Finalized); //Only works before and during sale require(msg.sender == owner_); //Only owner if (phase_ == Phase.BeforeSale) { phase_ = Phase.Sale; emit SaleStarted(); } else if (phase_ == Phase.Sale) { phase_ = Phase.Finalized; emit SaleFinalized(); } } } /* 0x0000000000000000000000000000000000000000 TEST 18 JSON Interface: [ ] */
Maximum token that can be purchased in the sale (70000000)
uint256 public constant MAX_SALE = 700 * 10**18;
12,770,472
[ 1, 13528, 1147, 716, 848, 506, 5405, 343, 8905, 316, 326, 272, 5349, 261, 27, 17877, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 5034, 1071, 5381, 4552, 67, 5233, 900, 273, 2371, 713, 380, 1728, 636, 2643, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.16; import "./CErc20.sol"; /** * @title Compound's CErc20Immutable Contract * @notice CTokens which wrap an EIP-20 underlying and are immutable * @author Compound */ contract CErc20Immutable is CErc20 { /** * @notice Construct a new money market * @param underlying_ The address of the underlying asset * @param comptroller_ The address of the Comptroller * @param interestRateModel_ The address of the interest rate model * @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18 * @param name_ ERC-20 name of this token * @param symbol_ ERC-20 symbol of this token * @param decimals_ ERC-20 decimal precision of this token * @param admin_ Address of the administrator of this token */ constructor(address underlying_, ComptrollerInterface comptroller_, InterestRateModel interestRateModel_, uint initialExchangeRateMantissa_, string memory name_, string memory symbol_, uint8 decimals_, address payable admin_) public { // Creator of the contract is admin during initialization admin = msg.sender; // Initialize the market initialize(underlying_, comptroller_, interestRateModel_, initialExchangeRateMantissa_, name_, symbol_, decimals_); // Set the proper admin now that initialization is done admin = admin_; } } pragma solidity ^0.5.16; import "./CToken.sol"; /** * @title Compound's CErc20 Contract * @notice CTokens which wrap an EIP-20 underlying * @author Compound */ contract CErc20 is CToken, CErc20Interface { /** * @notice Initialize the new money market * @param underlying_ The address of the underlying asset * @param comptroller_ The address of the Comptroller * @param interestRateModel_ The address of the interest rate model * @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18 * @param name_ ERC-20 name of this token * @param symbol_ ERC-20 symbol of this token * @param decimals_ ERC-20 decimal precision of this token */ function initialize(address underlying_, ComptrollerInterface comptroller_, InterestRateModel interestRateModel_, uint initialExchangeRateMantissa_, string memory name_, string memory symbol_, uint8 decimals_) public { // CToken initialize does the bulk of the work super.initialize(comptroller_, interestRateModel_, initialExchangeRateMantissa_, name_, symbol_, decimals_); // Set underlying and sanity check it underlying = underlying_; EIP20Interface(underlying).totalSupply(); } /*** User Interface ***/ /** * @notice Sender supplies assets into the market and receives cTokens in exchange * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param mintAmount The amount of the underlying asset to supply * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function mint(uint mintAmount) external returns (uint) { (uint err,) = mintInternal(mintAmount); return err; } /** * @notice Sender redeems cTokens in exchange for the underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemTokens The number of cTokens to redeem into underlying * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeem(uint redeemTokens) external returns (uint) { return redeemInternal(redeemTokens); } /** * @notice Sender redeems cTokens in exchange for a specified amount of underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemAmount The amount of underlying to redeem * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemUnderlying(uint redeemAmount) external returns (uint) { return redeemUnderlyingInternal(redeemAmount); } /** * @notice Sender borrows assets from the protocol to their own address * @param borrowAmount The amount of the underlying asset to borrow * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function borrow(uint borrowAmount) external returns (uint) { return borrowInternal(borrowAmount); } /** * @notice Sender repays their own borrow * @param repayAmount The amount to repay * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function repayBorrow(uint repayAmount) external returns (uint) { (uint err,) = repayBorrowInternal(repayAmount); return err; } /** * @notice Sender repays a borrow belonging to borrower * @param borrower the account with the debt being payed off * @param repayAmount The amount to repay * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function repayBorrowBehalf(address borrower, uint repayAmount) external returns (uint) { (uint err,) = repayBorrowBehalfInternal(borrower, repayAmount); return err; } /** * @notice The sender liquidates the borrowers collateral. * The collateral seized is transferred to the liquidator. * @param borrower The borrower of this cToken to be liquidated * @param repayAmount The amount of the underlying borrowed asset to repay * @param cTokenCollateral The market in which to seize collateral from the borrower * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function liquidateBorrow(address borrower, uint repayAmount, CTokenInterface cTokenCollateral) external returns (uint) { (uint err,) = liquidateBorrowInternal(borrower, repayAmount, cTokenCollateral); return err; } /** * @notice The sender adds to reserves. * @param addAmount The amount fo underlying token to add as reserves * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _addReserves(uint addAmount) external returns (uint) { return _addReservesInternal(addAmount); } /*** Safe Token ***/ /** * @notice Gets balance of this contract in terms of the underlying * @dev This excludes the value of the current message, if any * @return The quantity of underlying tokens owned by this contract */ function getCashPrior() internal view returns (uint) { EIP20Interface token = EIP20Interface(underlying); return token.balanceOf(address(this)); } /** * @dev Similar to EIP20 transfer, except it handles a False result from `transferFrom` and reverts in that case. * This will revert due to insufficient balance or insufficient allowance. * This function returns the actual amount received, * which may be less than `amount` if there is a fee attached to the transfer. * * Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value. * See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca */ function doTransferIn(address from, uint amount) internal returns (uint) { EIP20NonStandardInterface token = EIP20NonStandardInterface(underlying); uint balanceBefore = EIP20Interface(underlying).balanceOf(address(this)); token.transferFrom(from, address(this), amount); bool success; assembly { switch returndatasize() case 0 { // This is a non-standard ERC-20 success := not(0) // set success to true } case 32 { // This is a compliant ERC-20 returndatacopy(0, 0, 32) success := mload(0) // Set `success = returndata` of external call } default { // This is an excessively non-compliant ERC-20, revert. revert(0, 0) } } require(success, "TOKEN_TRANSFER_IN_FAILED"); // Calculate the amount that was *actually* transferred uint balanceAfter = EIP20Interface(underlying).balanceOf(address(this)); require(balanceAfter >= balanceBefore, "TOKEN_TRANSFER_IN_OVERFLOW"); return balanceAfter - balanceBefore; // underflow already checked above, just subtract } /** * @dev Similar to EIP20 transfer, except it handles a False success from `transfer` and returns an explanatory * error code rather than reverting. If caller has not called checked protocol's balance, this may revert due to * insufficient cash held in this contract. If caller has checked protocol's balance prior to this call, and verified * it is >= amount, this should not revert in normal conditions. * * Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value. * See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca */ function doTransferOut(address payable to, uint amount) internal { EIP20NonStandardInterface token = EIP20NonStandardInterface(underlying); token.transfer(to, amount); bool success; assembly { switch returndatasize() case 0 { // This is a non-standard ERC-20 success := not(0) // set success to true } case 32 { // This is a complaint ERC-20 returndatacopy(0, 0, 32) success := mload(0) // Set `success = returndata` of external call } default { // This is an excessively non-compliant ERC-20, revert. revert(0, 0) } } require(success, "TOKEN_TRANSFER_OUT_FAILED"); } } pragma solidity ^0.5.16; import "./ComptrollerInterface.sol"; import "./CTokenInterfaces.sol"; import "./ErrorReporter.sol"; import "./Exponential.sol"; import "./EIP20Interface.sol"; import "./EIP20NonStandardInterface.sol"; import "./InterestRateModel.sol"; /** * @title Compound's CToken Contract * @notice Abstract base for CTokens * @author Compound */ contract CToken is CTokenInterface, Exponential, TokenErrorReporter { /** * @notice Initialize the money market * @param comptroller_ The address of the Comptroller * @param interestRateModel_ The address of the interest rate model * @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18 * @param name_ EIP-20 name of this token * @param symbol_ EIP-20 symbol of this token * @param decimals_ EIP-20 decimal precision of this token */ function initialize(ComptrollerInterface comptroller_, InterestRateModel interestRateModel_, uint initialExchangeRateMantissa_, string memory name_, string memory symbol_, uint8 decimals_) public { require(msg.sender == admin, "only admin may initialize the market"); require(accrualBlockNumber == 0 && borrowIndex == 0, "market may only be initialized once"); // Set initial exchange rate initialExchangeRateMantissa = initialExchangeRateMantissa_; require(initialExchangeRateMantissa > 0, "initial exchange rate must be greater than zero."); // Set the comptroller uint err = _setComptroller(comptroller_); require(err == uint(Error.NO_ERROR), "setting comptroller failed"); // Initialize block number and borrow index (block number mocks depend on comptroller being set) accrualBlockNumber = getBlockNumber(); borrowIndex = mantissaOne; // Set the interest rate model (depends on block number / borrow index) err = _setInterestRateModelFresh(interestRateModel_); require(err == uint(Error.NO_ERROR), "setting interest rate model failed"); name = name_; symbol = symbol_; decimals = decimals_; // The counter starts true to prevent changing it from zero to non-zero (i.e. smaller cost/refund) _notEntered = true; } /** * @notice Transfer `tokens` tokens from `src` to `dst` by `spender` * @dev Called by both `transfer` and `transferFrom` internally * @param spender The address of the account performing the transfer * @param src The address of the source account * @param dst The address of the destination account * @param tokens The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferTokens(address spender, address src, address dst, uint tokens) internal returns (uint) { /* Fail if transfer not allowed */ uint allowed = comptroller.transferAllowed(address(this), src, dst, tokens); if (allowed != 0) { return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.TRANSFER_COMPTROLLER_REJECTION, allowed); } /* Do not allow self-transfers */ if (src == dst) { return fail(Error.BAD_INPUT, FailureInfo.TRANSFER_NOT_ALLOWED); } /* Get the allowance, infinite for the account owner */ uint startingAllowance = 0; if (spender == src) { startingAllowance = uint(-1); } else { startingAllowance = transferAllowances[src][spender]; } /* Do the calculations, checking for {under,over}flow */ MathError mathErr; uint allowanceNew; uint srcTokensNew; uint dstTokensNew; (mathErr, allowanceNew) = subUInt(startingAllowance, tokens); if (mathErr != MathError.NO_ERROR) { return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_NOT_ALLOWED); } (mathErr, srcTokensNew) = subUInt(accountTokens[src], tokens); if (mathErr != MathError.NO_ERROR) { return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_NOT_ENOUGH); } (mathErr, dstTokensNew) = addUInt(accountTokens[dst], tokens); if (mathErr != MathError.NO_ERROR) { return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_TOO_MUCH); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) accountTokens[src] = srcTokensNew; accountTokens[dst] = dstTokensNew; /* Eat some of the allowance (if necessary) */ if (startingAllowance != uint(-1)) { transferAllowances[src][spender] = allowanceNew; } /* We emit a Transfer event */ emit Transfer(src, dst, tokens); comptroller.transferVerify(address(this), src, dst, tokens); return uint(Error.NO_ERROR); } /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address dst, uint256 amount) external nonReentrant returns (bool) { return transferTokens(msg.sender, msg.sender, dst, amount) == uint(Error.NO_ERROR); } /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom(address src, address dst, uint256 amount) external nonReentrant returns (bool) { return transferTokens(msg.sender, src, dst, amount) == uint(Error.NO_ERROR); } /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param amount The number of tokens that are approved (-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint256 amount) external returns (bool) { address src = msg.sender; transferAllowances[src][spender] = amount; emit Approval(src, spender, amount); return true; } /** * @notice Get the current allowance from `owner` for `spender` * @param owner The address of the account which owns the tokens to be spent * @param spender The address of the account which may transfer tokens * @return The number of tokens allowed to be spent (-1 means infinite) */ function allowance(address owner, address spender) external view returns (uint256) { return transferAllowances[owner][spender]; } /** * @notice Get the token balance of the `owner` * @param owner The address of the account to query * @return The number of tokens owned by `owner` */ function balanceOf(address owner) external view returns (uint256) { return accountTokens[owner]; } /** * @notice Get the underlying balance of the `owner` * @dev This also accrues interest in a transaction * @param owner The address of the account to query * @return The amount of underlying owned by `owner` */ function balanceOfUnderlying(address owner) external returns (uint) { Exp memory exchangeRate = Exp({mantissa: exchangeRateCurrent()}); (MathError mErr, uint balance) = mulScalarTruncate(exchangeRate, accountTokens[owner]); require(mErr == MathError.NO_ERROR, "balance could not be calculated"); return balance; } /** * @notice Get a snapshot of the account's balances, and the cached exchange rate * @dev This is used by comptroller to more efficiently perform liquidity checks. * @param account Address of the account to snapshot * @return (possible error, token balance, borrow balance, exchange rate mantissa) */ function getAccountSnapshot(address account) external view returns (uint, uint, uint, uint) { uint cTokenBalance = accountTokens[account]; uint borrowBalance; uint exchangeRateMantissa; MathError mErr; (mErr, borrowBalance) = borrowBalanceStoredInternal(account); if (mErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0, 0, 0); } (mErr, exchangeRateMantissa) = exchangeRateStoredInternal(); if (mErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0, 0, 0); } return (uint(Error.NO_ERROR), cTokenBalance, borrowBalance, exchangeRateMantissa); } /** * @dev Function to simply retrieve block number * This exists mainly for inheriting test contracts to stub this result. */ function getBlockNumber() internal view returns (uint) { return block.number; } /** * @notice Returns the current per-block borrow interest rate for this cToken * @return The borrow interest rate per block, scaled by 1e18 */ function borrowRatePerBlock() external view returns (uint) { return interestRateModel.getBorrowRate(getCashPrior(), totalBorrows, totalReserves); } /** * @notice Returns the current per-block supply interest rate for this cToken * @return The supply interest rate per block, scaled by 1e18 */ function supplyRatePerBlock() external view returns (uint) { return interestRateModel.getSupplyRate(getCashPrior(), totalBorrows, totalReserves, reserveFactorMantissa); } /** * @notice Returns the current total borrows plus accrued interest * @return The total borrows with interest */ function totalBorrowsCurrent() external nonReentrant returns (uint) { require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed"); return totalBorrows; } /** * @notice Accrue interest to updated borrowIndex and then calculate account's borrow balance using the updated borrowIndex * @param account The address whose balance should be calculated after updating borrowIndex * @return The calculated balance */ function borrowBalanceCurrent(address account) external nonReentrant returns (uint) { require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed"); return borrowBalanceStored(account); } /** * @notice Return the borrow balance of account based on stored data * @param account The address whose balance should be calculated * @return The calculated balance */ function borrowBalanceStored(address account) public view returns (uint) { (MathError err, uint result) = borrowBalanceStoredInternal(account); require(err == MathError.NO_ERROR, "borrowBalanceStored: borrowBalanceStoredInternal failed"); return result; } /** * @notice Return the borrow balance of account based on stored data * @param account The address whose balance should be calculated * @return (error code, the calculated balance or 0 if error code is non-zero) */ function borrowBalanceStoredInternal(address account) internal view returns (MathError, uint) { /* Note: we do not assert that the market is up to date */ MathError mathErr; uint principalTimesIndex; uint result; /* Get borrowBalance and borrowIndex */ BorrowSnapshot storage borrowSnapshot = accountBorrows[account]; /* If borrowBalance = 0 then borrowIndex is likely also 0. * Rather than failing the calculation with a division by 0, we immediately return 0 in this case. */ if (borrowSnapshot.principal == 0) { return (MathError.NO_ERROR, 0); } /* Calculate new borrow balance using the interest index: * recentBorrowBalance = borrower.borrowBalance * market.borrowIndex / borrower.borrowIndex */ (mathErr, principalTimesIndex) = mulUInt(borrowSnapshot.principal, borrowIndex); if (mathErr != MathError.NO_ERROR) { return (mathErr, 0); } (mathErr, result) = divUInt(principalTimesIndex, borrowSnapshot.interestIndex); if (mathErr != MathError.NO_ERROR) { return (mathErr, 0); } return (MathError.NO_ERROR, result); } /** * @notice Accrue interest then return the up-to-date exchange rate * @return Calculated exchange rate scaled by 1e18 */ function exchangeRateCurrent() public nonReentrant returns (uint) { require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed"); return exchangeRateStored(); } /** * @notice Calculates the exchange rate from the underlying to the CToken * @dev This function does not accrue interest before calculating the exchange rate * @return Calculated exchange rate scaled by 1e18 */ function exchangeRateStored() public view returns (uint) { (MathError err, uint result) = exchangeRateStoredInternal(); require(err == MathError.NO_ERROR, "exchangeRateStored: exchangeRateStoredInternal failed"); return result; } /** * @notice Calculates the exchange rate from the underlying to the CToken * @dev This function does not accrue interest before calculating the exchange rate * @return (error code, calculated exchange rate scaled by 1e18) */ function exchangeRateStoredInternal() internal view returns (MathError, uint) { uint _totalSupply = totalSupply; if (_totalSupply == 0) { /* * If there are no tokens minted: * exchangeRate = initialExchangeRate */ return (MathError.NO_ERROR, initialExchangeRateMantissa); } else { /* * Otherwise: * exchangeRate = (totalCash + totalBorrows - totalReserves) / totalSupply */ uint totalCash = getCashPrior(); uint cashPlusBorrowsMinusReserves; Exp memory exchangeRate; MathError mathErr; (mathErr, cashPlusBorrowsMinusReserves) = addThenSubUInt(totalCash, totalBorrows, totalReserves); if (mathErr != MathError.NO_ERROR) { return (mathErr, 0); } (mathErr, exchangeRate) = getExp(cashPlusBorrowsMinusReserves, _totalSupply); if (mathErr != MathError.NO_ERROR) { return (mathErr, 0); } return (MathError.NO_ERROR, exchangeRate.mantissa); } } /** * @notice Get cash balance of this cToken in the underlying asset * @return The quantity of underlying asset owned by this contract */ function getCash() external view returns (uint) { return getCashPrior(); } /** * @notice Applies accrued interest to total borrows and reserves * @dev This calculates interest accrued from the last checkpointed block * up to the current block and writes new checkpoint to storage. */ function accrueInterest() public returns (uint) { /* Remember the initial block number */ uint currentBlockNumber = getBlockNumber(); uint accrualBlockNumberPrior = accrualBlockNumber; /* Short-circuit accumulating 0 interest */ if (accrualBlockNumberPrior == currentBlockNumber) { return uint(Error.NO_ERROR); } /* Read the previous values out of storage */ uint cashPrior = getCashPrior(); uint borrowsPrior = totalBorrows; uint reservesPrior = totalReserves; uint borrowIndexPrior = borrowIndex; /* Calculate the current borrow interest rate */ uint borrowRateMantissa = interestRateModel.getBorrowRate(cashPrior, borrowsPrior, reservesPrior); require(borrowRateMantissa <= borrowRateMaxMantissa, "borrow rate is absurdly high"); /* Calculate the number of blocks elapsed since the last accrual */ (MathError mathErr, uint blockDelta) = subUInt(currentBlockNumber, accrualBlockNumberPrior); require(mathErr == MathError.NO_ERROR, "could not calculate block delta"); /* * Calculate the interest accumulated into borrows and reserves and the new index: * simpleInterestFactor = borrowRate * blockDelta * interestAccumulated = simpleInterestFactor * totalBorrows * totalBorrowsNew = interestAccumulated + totalBorrows * totalReservesNew = interestAccumulated * reserveFactor + totalReserves * borrowIndexNew = simpleInterestFactor * borrowIndex + borrowIndex */ Exp memory simpleInterestFactor; uint interestAccumulated; uint totalBorrowsNew; uint totalReservesNew; uint borrowIndexNew; (mathErr, simpleInterestFactor) = mulScalar(Exp({mantissa: borrowRateMantissa}), blockDelta); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_SIMPLE_INTEREST_FACTOR_CALCULATION_FAILED, uint(mathErr)); } (mathErr, interestAccumulated) = mulScalarTruncate(simpleInterestFactor, borrowsPrior); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_ACCUMULATED_INTEREST_CALCULATION_FAILED, uint(mathErr)); } (mathErr, totalBorrowsNew) = addUInt(interestAccumulated, borrowsPrior); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_BORROWS_CALCULATION_FAILED, uint(mathErr)); } (mathErr, totalReservesNew) = mulScalarTruncateAddUInt(Exp({mantissa: reserveFactorMantissa}), interestAccumulated, reservesPrior); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED, uint(mathErr)); } (mathErr, borrowIndexNew) = mulScalarTruncateAddUInt(simpleInterestFactor, borrowIndexPrior, borrowIndexPrior); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_BORROW_INDEX_CALCULATION_FAILED, uint(mathErr)); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* We write the previously calculated values into storage */ accrualBlockNumber = currentBlockNumber; borrowIndex = borrowIndexNew; totalBorrows = totalBorrowsNew; totalReserves = totalReservesNew; /* We emit an AccrueInterest event */ emit AccrueInterest(cashPrior, interestAccumulated, borrowIndexNew, totalBorrowsNew); return uint(Error.NO_ERROR); } /** * @notice Sender supplies assets into the market and receives cTokens in exchange * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param mintAmount The amount of the underlying asset to supply * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount. */ function mintInternal(uint mintAmount) internal nonReentrant returns (uint, uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed return (fail(Error(error), FailureInfo.MINT_ACCRUE_INTEREST_FAILED), 0); } // mintFresh emits the actual Mint event if successful and logs on errors, so we don't need to return mintFresh(msg.sender, mintAmount); } struct MintLocalVars { Error err; MathError mathErr; uint exchangeRateMantissa; uint mintTokens; uint totalSupplyNew; uint accountTokensNew; uint actualMintAmount; } /** * @notice User supplies assets into the market and receives cTokens in exchange * @dev Assumes interest has already been accrued up to the current block * @param minter The address of the account which is supplying the assets * @param mintAmount The amount of the underlying asset to supply * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount. */ function mintFresh(address minter, uint mintAmount) internal returns (uint, uint) { /* Fail if mint not allowed */ uint allowed = comptroller.mintAllowed(address(this), minter, mintAmount); if (allowed != 0) { return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.MINT_COMPTROLLER_REJECTION, allowed), 0); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.MINT_FRESHNESS_CHECK), 0); } MintLocalVars memory vars; (vars.mathErr, vars.exchangeRateMantissa) = exchangeRateStoredInternal(); if (vars.mathErr != MathError.NO_ERROR) { return (failOpaque(Error.MATH_ERROR, FailureInfo.MINT_EXCHANGE_RATE_READ_FAILED, uint(vars.mathErr)), 0); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We call `doTransferIn` for the minter and the mintAmount. * Note: The cToken must handle variations between ERC-20 and ETH underlying. * `doTransferIn` reverts if anything goes wrong, since we can't be sure if * side-effects occurred. The function returns the amount actually transferred, * in case of a fee. On success, the cToken holds an additional `actualMintAmount` * of cash. */ vars.actualMintAmount = doTransferIn(minter, mintAmount); /* * We get the current exchange rate and calculate the number of cTokens to be minted: * mintTokens = actualMintAmount / exchangeRate */ (vars.mathErr, vars.mintTokens) = divScalarByExpTruncate(vars.actualMintAmount, Exp({mantissa: vars.exchangeRateMantissa})); require(vars.mathErr == MathError.NO_ERROR, "MINT_EXCHANGE_CALCULATION_FAILED"); /* * We calculate the new total supply of cTokens and minter token balance, checking for overflow: * totalSupplyNew = totalSupply + mintTokens * accountTokensNew = accountTokens[minter] + mintTokens */ (vars.mathErr, vars.totalSupplyNew) = addUInt(totalSupply, vars.mintTokens); require(vars.mathErr == MathError.NO_ERROR, "MINT_NEW_TOTAL_SUPPLY_CALCULATION_FAILED"); (vars.mathErr, vars.accountTokensNew) = addUInt(accountTokens[minter], vars.mintTokens); require(vars.mathErr == MathError.NO_ERROR, "MINT_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED"); /* We write previously calculated values into storage */ totalSupply = vars.totalSupplyNew; accountTokens[minter] = vars.accountTokensNew; /* We emit a Mint event, and a Transfer event */ emit Mint(minter, vars.actualMintAmount, vars.mintTokens); emit Transfer(address(this), minter, vars.mintTokens); /* We call the defense hook */ comptroller.mintVerify(address(this), minter, vars.actualMintAmount, vars.mintTokens); return (uint(Error.NO_ERROR), vars.actualMintAmount); } /** * @notice Sender redeems cTokens in exchange for the underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemTokens The number of cTokens to redeem into underlying * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemInternal(uint redeemTokens) internal nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED); } // redeemFresh emits redeem-specific logs on errors, so we don't need to return redeemFresh(msg.sender, redeemTokens, 0); } /** * @notice Sender redeems cTokens in exchange for a specified amount of underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemAmount The amount of underlying to receive from redeeming cTokens * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemUnderlyingInternal(uint redeemAmount) internal nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED); } // redeemFresh emits redeem-specific logs on errors, so we don't need to return redeemFresh(msg.sender, 0, redeemAmount); } struct RedeemLocalVars { Error err; MathError mathErr; uint exchangeRateMantissa; uint redeemTokens; uint redeemAmount; uint totalSupplyNew; uint accountTokensNew; } /** * @notice User redeems cTokens in exchange for the underlying asset * @dev Assumes interest has already been accrued up to the current block * @param redeemer The address of the account which is redeeming the tokens * @param redeemTokensIn The number of cTokens to redeem into underlying (only one of redeemTokensIn or redeemAmountIn may be non-zero) * @param redeemAmountIn The number of underlying tokens to receive from redeeming cTokens (only one of redeemTokensIn or redeemAmountIn may be non-zero) * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemFresh(address payable redeemer, uint redeemTokensIn, uint redeemAmountIn) internal returns (uint) { require(redeemTokensIn == 0 || redeemAmountIn == 0, "one of redeemTokensIn or redeemAmountIn must be zero"); RedeemLocalVars memory vars; /* exchangeRate = invoke Exchange Rate Stored() */ (vars.mathErr, vars.exchangeRateMantissa) = exchangeRateStoredInternal(); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_RATE_READ_FAILED, uint(vars.mathErr)); } /* If redeemTokensIn > 0: */ if (redeemTokensIn > 0) { /* * We calculate the exchange rate and the amount of underlying to be redeemed: * redeemTokens = redeemTokensIn * redeemAmount = redeemTokensIn x exchangeRateCurrent */ vars.redeemTokens = redeemTokensIn; (vars.mathErr, vars.redeemAmount) = mulScalarTruncate(Exp({mantissa: vars.exchangeRateMantissa}), redeemTokensIn); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_TOKENS_CALCULATION_FAILED, uint(vars.mathErr)); } } else { /* * We get the current exchange rate and calculate the amount to be redeemed: * redeemTokens = redeemAmountIn / exchangeRate * redeemAmount = redeemAmountIn */ (vars.mathErr, vars.redeemTokens) = divScalarByExpTruncate(redeemAmountIn, Exp({mantissa: vars.exchangeRateMantissa})); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_AMOUNT_CALCULATION_FAILED, uint(vars.mathErr)); } vars.redeemAmount = redeemAmountIn; } /* Fail if redeem not allowed */ uint allowed = comptroller.redeemAllowed(address(this), redeemer, vars.redeemTokens); if (allowed != 0) { return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.REDEEM_COMPTROLLER_REJECTION, allowed); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDEEM_FRESHNESS_CHECK); } /* * We calculate the new total supply and redeemer balance, checking for underflow: * totalSupplyNew = totalSupply - redeemTokens * accountTokensNew = accountTokens[redeemer] - redeemTokens */ (vars.mathErr, vars.totalSupplyNew) = subUInt(totalSupply, vars.redeemTokens); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, uint(vars.mathErr)); } (vars.mathErr, vars.accountTokensNew) = subUInt(accountTokens[redeemer], vars.redeemTokens); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)); } /* Fail gracefully if protocol has insufficient cash */ if (getCashPrior() < vars.redeemAmount) { return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDEEM_TRANSFER_OUT_NOT_POSSIBLE); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We invoke doTransferOut for the redeemer and the redeemAmount. * Note: The cToken must handle variations between ERC-20 and ETH underlying. * On success, the cToken has redeemAmount less of cash. * doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred. */ doTransferOut(redeemer, vars.redeemAmount); /* We write previously calculated values into storage */ totalSupply = vars.totalSupplyNew; accountTokens[redeemer] = vars.accountTokensNew; /* We emit a Transfer event, and a Redeem event */ emit Transfer(redeemer, address(this), vars.redeemTokens); emit Redeem(redeemer, vars.redeemAmount, vars.redeemTokens); /* We call the defense hook */ comptroller.redeemVerify(address(this), redeemer, vars.redeemAmount, vars.redeemTokens); return uint(Error.NO_ERROR); } /** * @notice Sender borrows assets from the protocol to their own address * @param borrowAmount The amount of the underlying asset to borrow * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function borrowInternal(uint borrowAmount) internal nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed return fail(Error(error), FailureInfo.BORROW_ACCRUE_INTEREST_FAILED); } // borrowFresh emits borrow-specific logs on errors, so we don't need to return borrowFresh(msg.sender, borrowAmount); } struct BorrowLocalVars { MathError mathErr; uint accountBorrows; uint accountBorrowsNew; uint totalBorrowsNew; } /** * @notice Users borrow assets from the protocol to their own address * @param borrowAmount The amount of the underlying asset to borrow * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function borrowFresh(address payable borrower, uint borrowAmount) internal returns (uint) { /* Fail if borrow not allowed */ uint allowed = comptroller.borrowAllowed(address(this), borrower, borrowAmount); if (allowed != 0) { return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.BORROW_COMPTROLLER_REJECTION, allowed); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.BORROW_FRESHNESS_CHECK); } /* Fail gracefully if protocol has insufficient underlying cash */ if (getCashPrior() < borrowAmount) { return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.BORROW_CASH_NOT_AVAILABLE); } BorrowLocalVars memory vars; /* * We calculate the new borrower and total borrow balances, failing on overflow: * accountBorrowsNew = accountBorrows + borrowAmount * totalBorrowsNew = totalBorrows + borrowAmount */ (vars.mathErr, vars.accountBorrows) = borrowBalanceStoredInternal(borrower); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)); } (vars.mathErr, vars.accountBorrowsNew) = addUInt(vars.accountBorrows, borrowAmount); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)); } (vars.mathErr, vars.totalBorrowsNew) = addUInt(totalBorrows, borrowAmount); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We invoke doTransferOut for the borrower and the borrowAmount. * Note: The cToken must handle variations between ERC-20 and ETH underlying. * On success, the cToken borrowAmount less of cash. * doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred. */ doTransferOut(borrower, borrowAmount); /* We write the previously calculated values into storage */ accountBorrows[borrower].principal = vars.accountBorrowsNew; accountBorrows[borrower].interestIndex = borrowIndex; totalBorrows = vars.totalBorrowsNew; /* We emit a Borrow event */ emit Borrow(borrower, borrowAmount, vars.accountBorrowsNew, vars.totalBorrowsNew); /* We call the defense hook */ comptroller.borrowVerify(address(this), borrower, borrowAmount); return uint(Error.NO_ERROR); } /** * @notice Sender repays their own borrow * @param repayAmount The amount to repay * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function repayBorrowInternal(uint repayAmount) internal nonReentrant returns (uint, uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed return (fail(Error(error), FailureInfo.REPAY_BORROW_ACCRUE_INTEREST_FAILED), 0); } // repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to return repayBorrowFresh(msg.sender, msg.sender, repayAmount); } /** * @notice Sender repays a borrow belonging to borrower * @param borrower the account with the debt being payed off * @param repayAmount The amount to repay * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function repayBorrowBehalfInternal(address borrower, uint repayAmount) internal nonReentrant returns (uint, uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed return (fail(Error(error), FailureInfo.REPAY_BEHALF_ACCRUE_INTEREST_FAILED), 0); } // repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to return repayBorrowFresh(msg.sender, borrower, repayAmount); } struct RepayBorrowLocalVars { Error err; MathError mathErr; uint repayAmount; uint borrowerIndex; uint accountBorrows; uint accountBorrowsNew; uint totalBorrowsNew; uint actualRepayAmount; } /** * @notice Borrows are repaid by another user (possibly the borrower). * @param payer the account paying off the borrow * @param borrower the account with the debt being payed off * @param repayAmount the amount of undelrying tokens being returned * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function repayBorrowFresh(address payer, address borrower, uint repayAmount) internal returns (uint, uint) { /* Fail if repayBorrow not allowed */ uint allowed = comptroller.repayBorrowAllowed(address(this), payer, borrower, repayAmount); if (allowed != 0) { return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.REPAY_BORROW_COMPTROLLER_REJECTION, allowed), 0); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.REPAY_BORROW_FRESHNESS_CHECK), 0); } RepayBorrowLocalVars memory vars; /* We remember the original borrowerIndex for verification purposes */ vars.borrowerIndex = accountBorrows[borrower].interestIndex; /* We fetch the amount the borrower owes, with accumulated interest */ (vars.mathErr, vars.accountBorrows) = borrowBalanceStoredInternal(borrower); if (vars.mathErr != MathError.NO_ERROR) { return (failOpaque(Error.MATH_ERROR, FailureInfo.REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)), 0); } /* If repayAmount == -1, repayAmount = accountBorrows */ if (repayAmount == uint(-1)) { vars.repayAmount = vars.accountBorrows; } else { vars.repayAmount = repayAmount; } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We call doTransferIn for the payer and the repayAmount * Note: The cToken must handle variations between ERC-20 and ETH underlying. * On success, the cToken holds an additional repayAmount of cash. * doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred. * it returns the amount actually transferred, in case of a fee. */ vars.actualRepayAmount = doTransferIn(payer, vars.repayAmount); /* * We calculate the new borrower and total borrow balances, failing on underflow: * accountBorrowsNew = accountBorrows - actualRepayAmount * totalBorrowsNew = totalBorrows - actualRepayAmount */ (vars.mathErr, vars.accountBorrowsNew) = subUInt(vars.accountBorrows, vars.actualRepayAmount); require(vars.mathErr == MathError.NO_ERROR, "REPAY_BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED"); (vars.mathErr, vars.totalBorrowsNew) = subUInt(totalBorrows, vars.actualRepayAmount); require(vars.mathErr == MathError.NO_ERROR, "REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED"); /* We write the previously calculated values into storage */ accountBorrows[borrower].principal = vars.accountBorrowsNew; accountBorrows[borrower].interestIndex = borrowIndex; totalBorrows = vars.totalBorrowsNew; /* We emit a RepayBorrow event */ emit RepayBorrow(payer, borrower, vars.actualRepayAmount, vars.accountBorrowsNew, vars.totalBorrowsNew); /* We call the defense hook */ comptroller.repayBorrowVerify(address(this), payer, borrower, vars.actualRepayAmount, vars.borrowerIndex); return (uint(Error.NO_ERROR), vars.actualRepayAmount); } /** * @notice The sender liquidates the borrowers collateral. * The collateral seized is transferred to the liquidator. * @param borrower The borrower of this cToken to be liquidated * @param cTokenCollateral The market in which to seize collateral from the borrower * @param repayAmount The amount of the underlying borrowed asset to repay * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function liquidateBorrowInternal(address borrower, uint repayAmount, CTokenInterface cTokenCollateral) internal nonReentrant returns (uint, uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed return (fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED), 0); } error = cTokenCollateral.accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed return (fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED), 0); } // liquidateBorrowFresh emits borrow-specific logs on errors, so we don't need to return liquidateBorrowFresh(msg.sender, borrower, repayAmount, cTokenCollateral); } /** * @notice The liquidator liquidates the borrowers collateral. * The collateral seized is transferred to the liquidator. * @param borrower The borrower of this cToken to be liquidated * @param liquidator The address repaying the borrow and seizing collateral * @param cTokenCollateral The market in which to seize collateral from the borrower * @param repayAmount The amount of the underlying borrowed asset to repay * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function liquidateBorrowFresh(address liquidator, address borrower, uint repayAmount, CTokenInterface cTokenCollateral) internal returns (uint, uint) { /* Fail if liquidate not allowed */ uint allowed = comptroller.liquidateBorrowAllowed(address(this), address(cTokenCollateral), liquidator, borrower, repayAmount); if (allowed != 0) { return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.LIQUIDATE_COMPTROLLER_REJECTION, allowed), 0); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_FRESHNESS_CHECK), 0); } /* Verify cTokenCollateral market's block number equals current block number */ if (cTokenCollateral.accrualBlockNumber() != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_COLLATERAL_FRESHNESS_CHECK), 0); } /* Fail if borrower = liquidator */ if (borrower == liquidator) { return (fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_LIQUIDATOR_IS_BORROWER), 0); } /* Fail if repayAmount = 0 */ if (repayAmount == 0) { return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_ZERO), 0); } /* Fail if repayAmount = -1 */ if (repayAmount == uint(-1)) { return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX), 0); } /* Fail if repayBorrow fails */ (uint repayBorrowError, uint actualRepayAmount) = repayBorrowFresh(liquidator, borrower, repayAmount); if (repayBorrowError != uint(Error.NO_ERROR)) { return (fail(Error(repayBorrowError), FailureInfo.LIQUIDATE_REPAY_BORROW_FRESH_FAILED), 0); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* We calculate the number of collateral tokens that will be seized */ (uint amountSeizeError, uint seizeTokens) = comptroller.liquidateCalculateSeizeTokens(address(this), address(cTokenCollateral), actualRepayAmount); require(amountSeizeError == uint(Error.NO_ERROR), "LIQUIDATE_COMPTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED"); /* Revert if borrower collateral token balance < seizeTokens */ require(cTokenCollateral.balanceOf(borrower) >= seizeTokens, "LIQUIDATE_SEIZE_TOO_MUCH"); // If this is also the collateral, run seizeInternal to avoid re-entrancy, otherwise make an external call uint seizeError; if (address(cTokenCollateral) == address(this)) { seizeError = seizeInternal(address(this), liquidator, borrower, seizeTokens); } else { seizeError = cTokenCollateral.seize(liquidator, borrower, seizeTokens); } /* Revert if seize tokens fails (since we cannot be sure of side effects) */ require(seizeError == uint(Error.NO_ERROR), "token seizure failed"); /* We emit a LiquidateBorrow event */ emit LiquidateBorrow(liquidator, borrower, actualRepayAmount, address(cTokenCollateral), seizeTokens); /* We call the defense hook */ comptroller.liquidateBorrowVerify(address(this), address(cTokenCollateral), liquidator, borrower, actualRepayAmount, seizeTokens); return (uint(Error.NO_ERROR), actualRepayAmount); } /** * @notice Transfers collateral tokens (this market) to the liquidator. * @dev Will fail unless called by another cToken during the process of liquidation. * Its absolutely critical to use msg.sender as the borrowed cToken and not a parameter. * @param liquidator The account receiving seized collateral * @param borrower The account having collateral seized * @param seizeTokens The number of cTokens to seize * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function seize(address liquidator, address borrower, uint seizeTokens) external nonReentrant returns (uint) { return seizeInternal(msg.sender, liquidator, borrower, seizeTokens); } /** * @notice Transfers collateral tokens (this market) to the liquidator. * @dev Called only during an in-kind liquidation, or by liquidateBorrow during the liquidation of another CToken. * Its absolutely critical to use msg.sender as the seizer cToken and not a parameter. * @param seizerToken The contract seizing the collateral (i.e. borrowed cToken) * @param liquidator The account receiving seized collateral * @param borrower The account having collateral seized * @param seizeTokens The number of cTokens to seize * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function seizeInternal(address seizerToken, address liquidator, address borrower, uint seizeTokens) internal returns (uint) { /* Fail if seize not allowed */ uint allowed = comptroller.seizeAllowed(address(this), seizerToken, liquidator, borrower, seizeTokens); if (allowed != 0) { return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.LIQUIDATE_SEIZE_COMPTROLLER_REJECTION, allowed); } /* Fail if borrower = liquidator */ if (borrower == liquidator) { return fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER); } MathError mathErr; uint borrowerTokensNew; uint liquidatorTokensNew; /* * We calculate the new borrower and liquidator token balances, failing on underflow/overflow: * borrowerTokensNew = accountTokens[borrower] - seizeTokens * liquidatorTokensNew = accountTokens[liquidator] + seizeTokens */ (mathErr, borrowerTokensNew) = subUInt(accountTokens[borrower], seizeTokens); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED, uint(mathErr)); } (mathErr, liquidatorTokensNew) = addUInt(accountTokens[liquidator], seizeTokens); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED, uint(mathErr)); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* We write the previously calculated values into storage */ accountTokens[borrower] = borrowerTokensNew; accountTokens[liquidator] = liquidatorTokensNew; /* Emit a Transfer event */ emit Transfer(borrower, liquidator, seizeTokens); /* We call the defense hook */ comptroller.seizeVerify(address(this), seizerToken, liquidator, borrower, seizeTokens); return uint(Error.NO_ERROR); } /*** Admin Functions ***/ /** * @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @param newPendingAdmin New pending admin. * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setPendingAdmin(address payable newPendingAdmin) external returns (uint) { // Check caller = admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK); } // Save current value, if any, for inclusion in log address oldPendingAdmin = pendingAdmin; // Store pendingAdmin with value newPendingAdmin pendingAdmin = newPendingAdmin; // Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin) emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin); return uint(Error.NO_ERROR); } /** * @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin * @dev Admin function for pending admin to accept role and update admin * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _acceptAdmin() external returns (uint) { // Check caller is pendingAdmin and pendingAdmin ≠ address(0) if (msg.sender != pendingAdmin || msg.sender == address(0)) { return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_ADMIN_PENDING_ADMIN_CHECK); } // Save current values for inclusion in log address oldAdmin = admin; address oldPendingAdmin = pendingAdmin; // Store admin with value pendingAdmin admin = pendingAdmin; // Clear the pending value pendingAdmin = address(0); emit NewAdmin(oldAdmin, admin); emit NewPendingAdmin(oldPendingAdmin, pendingAdmin); return uint(Error.NO_ERROR); } /** * @notice Sets a new comptroller for the market * @dev Admin function to set a new comptroller * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setComptroller(ComptrollerInterface newComptroller) public returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_COMPTROLLER_OWNER_CHECK); } ComptrollerInterface oldComptroller = comptroller; // Ensure invoke comptroller.isComptroller() returns true require(newComptroller.isComptroller(), "marker method returned false"); // Set market's comptroller to newComptroller comptroller = newComptroller; // Emit NewComptroller(oldComptroller, newComptroller) emit NewComptroller(oldComptroller, newComptroller); return uint(Error.NO_ERROR); } /** * @notice accrues interest and sets a new reserve factor for the protocol using _setReserveFactorFresh * @dev Admin function to accrue interest and set a new reserve factor * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setReserveFactor(uint newReserveFactorMantissa) external nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reserve factor change failed. return fail(Error(error), FailureInfo.SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED); } // _setReserveFactorFresh emits reserve-factor-specific logs on errors, so we don't need to. return _setReserveFactorFresh(newReserveFactorMantissa); } /** * @notice Sets a new reserve factor for the protocol (*requires fresh interest accrual) * @dev Admin function to set a new reserve factor * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setReserveFactorFresh(uint newReserveFactorMantissa) internal returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_RESERVE_FACTOR_ADMIN_CHECK); } // Verify market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_RESERVE_FACTOR_FRESH_CHECK); } // Check newReserveFactor ≤ maxReserveFactor if (newReserveFactorMantissa > reserveFactorMaxMantissa) { return fail(Error.BAD_INPUT, FailureInfo.SET_RESERVE_FACTOR_BOUNDS_CHECK); } uint oldReserveFactorMantissa = reserveFactorMantissa; reserveFactorMantissa = newReserveFactorMantissa; emit NewReserveFactor(oldReserveFactorMantissa, newReserveFactorMantissa); return uint(Error.NO_ERROR); } /** * @notice Accrues interest and reduces reserves by transferring from msg.sender * @param addAmount Amount of addition to reserves * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _addReservesInternal(uint addAmount) internal nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed. return fail(Error(error), FailureInfo.ADD_RESERVES_ACCRUE_INTEREST_FAILED); } // _addReservesFresh emits reserve-addition-specific logs on errors, so we don't need to. (error, ) = _addReservesFresh(addAmount); return error; } /** * @notice Add reserves by transferring from caller * @dev Requires fresh interest accrual * @param addAmount Amount of addition to reserves * @return (uint, uint) An error code (0=success, otherwise a failure (see ErrorReporter.sol for details)) and the actual amount added, net token fees */ function _addReservesFresh(uint addAmount) internal returns (uint, uint) { // totalReserves + actualAddAmount uint totalReservesNew; uint actualAddAmount; // We fail gracefully unless market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.ADD_RESERVES_FRESH_CHECK), actualAddAmount); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We call doTransferIn for the caller and the addAmount * Note: The cToken must handle variations between ERC-20 and ETH underlying. * On success, the cToken holds an additional addAmount of cash. * doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred. * it returns the amount actually transferred, in case of a fee. */ actualAddAmount = doTransferIn(msg.sender, addAmount); totalReservesNew = totalReserves + actualAddAmount; /* Revert on overflow */ require(totalReservesNew >= totalReserves, "add reserves unexpected overflow"); // Store reserves[n+1] = reserves[n] + actualAddAmount totalReserves = totalReservesNew; /* Emit NewReserves(admin, actualAddAmount, reserves[n+1]) */ emit ReservesAdded(msg.sender, actualAddAmount, totalReservesNew); /* Return (NO_ERROR, actualAddAmount) */ return (uint(Error.NO_ERROR), actualAddAmount); } /** * @notice Accrues interest and reduces reserves by transferring to admin * @param reduceAmount Amount of reduction to reserves * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _reduceReserves(uint reduceAmount) external nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed. return fail(Error(error), FailureInfo.REDUCE_RESERVES_ACCRUE_INTEREST_FAILED); } // _reduceReservesFresh emits reserve-reduction-specific logs on errors, so we don't need to. return _reduceReservesFresh(reduceAmount); } /** * @notice Reduces reserves by transferring to admin * @dev Requires fresh interest accrual * @param reduceAmount Amount of reduction to reserves * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _reduceReservesFresh(uint reduceAmount) internal returns (uint) { // totalReserves - reduceAmount uint totalReservesNew; // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.REDUCE_RESERVES_ADMIN_CHECK); } // We fail gracefully unless market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDUCE_RESERVES_FRESH_CHECK); } // Fail gracefully if protocol has insufficient underlying cash if (getCashPrior() < reduceAmount) { return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDUCE_RESERVES_CASH_NOT_AVAILABLE); } // Check reduceAmount ≤ reserves[n] (totalReserves) if (reduceAmount > totalReserves) { return fail(Error.BAD_INPUT, FailureInfo.REDUCE_RESERVES_VALIDATION); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) totalReservesNew = totalReserves - reduceAmount; // We checked reduceAmount <= totalReserves above, so this should never revert. require(totalReservesNew <= totalReserves, "reduce reserves unexpected underflow"); // Store reserves[n+1] = reserves[n] - reduceAmount totalReserves = totalReservesNew; // doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred. doTransferOut(admin, reduceAmount); emit ReservesReduced(admin, reduceAmount, totalReservesNew); return uint(Error.NO_ERROR); } /** * @notice accrues interest and updates the interest rate model using _setInterestRateModelFresh * @dev Admin function to accrue interest and update the interest rate model * @param newInterestRateModel the new interest rate model to use * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setInterestRateModel(InterestRateModel newInterestRateModel) public returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted change of interest rate model failed return fail(Error(error), FailureInfo.SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED); } // _setInterestRateModelFresh emits interest-rate-model-update-specific logs on errors, so we don't need to. return _setInterestRateModelFresh(newInterestRateModel); } /** * @notice updates the interest rate model (*requires fresh interest accrual) * @dev Admin function to update the interest rate model * @param newInterestRateModel the new interest rate model to use * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setInterestRateModelFresh(InterestRateModel newInterestRateModel) internal returns (uint) { // Used to store old model for use in the event that is emitted on success InterestRateModel oldInterestRateModel; // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_INTEREST_RATE_MODEL_OWNER_CHECK); } // We fail gracefully unless market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_INTEREST_RATE_MODEL_FRESH_CHECK); } // Track the market's current interest rate model oldInterestRateModel = interestRateModel; // Ensure invoke newInterestRateModel.isInterestRateModel() returns true require(newInterestRateModel.isInterestRateModel(), "marker method returned false"); // Set the interest rate model to newInterestRateModel interestRateModel = newInterestRateModel; // Emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel) emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel); return uint(Error.NO_ERROR); } /*** Safe Token ***/ /** * @notice Gets balance of this contract in terms of the underlying * @dev This excludes the value of the current message, if any * @return The quantity of underlying owned by this contract */ function getCashPrior() internal view returns (uint); /** * @dev Performs a transfer in, reverting upon failure. Returns the amount actually transferred to the protocol, in case of a fee. * This may revert due to insufficient balance or insufficient allowance. */ function doTransferIn(address from, uint amount) internal returns (uint); /** * @dev Performs a transfer out, ideally returning an explanatory error code upon failure tather than reverting. * If caller has not called checked protocol's balance, may revert due to insufficient cash held in the contract. * If caller has checked protocol's balance, and verified it is >= amount, this should not revert in normal conditions. */ function doTransferOut(address payable to, uint amount) internal; /*** Reentrancy Guard ***/ /** * @dev Prevents a contract from calling itself, directly or indirectly. */ modifier nonReentrant() { require(_notEntered, "re-entered"); _notEntered = false; _; _notEntered = true; // get a gas-refund post-Istanbul } } pragma solidity ^0.5.16; contract ComptrollerInterface { /// @notice Indicator that this is a Comptroller contract (for inspection) bool public constant isComptroller = true; /*** Assets You Are In ***/ function enterMarkets(address[] calldata cTokens) external returns (uint[] memory); function exitMarket(address cToken) external returns (uint); /*** Policy Hooks ***/ function mintAllowed(address cToken, address minter, uint mintAmount) external returns (uint); function mintVerify(address cToken, address minter, uint mintAmount, uint mintTokens) external; function redeemAllowed(address cToken, address redeemer, uint redeemTokens) external returns (uint); function redeemVerify(address cToken, address redeemer, uint redeemAmount, uint redeemTokens) external; function borrowAllowed(address cToken, address borrower, uint borrowAmount) external returns (uint); function borrowVerify(address cToken, address borrower, uint borrowAmount) external; function repayBorrowAllowed( address cToken, address payer, address borrower, uint repayAmount) external returns (uint); function repayBorrowVerify( address cToken, address payer, address borrower, uint repayAmount, uint borrowerIndex) external; function liquidateBorrowAllowed( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint repayAmount) external returns (uint); function liquidateBorrowVerify( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint repayAmount, uint seizeTokens) external; function seizeAllowed( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint seizeTokens) external returns (uint); function seizeVerify( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint seizeTokens) external; function transferAllowed(address cToken, address src, address dst, uint transferTokens) external returns (uint); function transferVerify(address cToken, address src, address dst, uint transferTokens) external; /*** Liquidity/Liquidation Calculations ***/ function liquidateCalculateSeizeTokens( address cTokenBorrowed, address cTokenCollateral, uint repayAmount) external view returns (uint, uint); } pragma solidity ^0.5.16; import "./ComptrollerInterface.sol"; import "./InterestRateModel.sol"; contract CTokenStorage { /** * @dev Guard variable for re-entrancy checks */ bool internal _notEntered; /** * @notice EIP-20 token name for this token */ string public name; /** * @notice EIP-20 token symbol for this token */ string public symbol; /** * @notice EIP-20 token decimals for this token */ uint8 public decimals; /** * @notice Maximum borrow rate that can ever be applied (.0005% / block) */ uint internal constant borrowRateMaxMantissa = 0.0005e16; /** * @notice Maximum fraction of interest that can be set aside for reserves */ uint internal constant reserveFactorMaxMantissa = 1e18; /** * @notice Administrator for this contract */ address payable public admin; /** * @notice Pending administrator for this contract */ address payable public pendingAdmin; /** * @notice Contract which oversees inter-cToken operations */ ComptrollerInterface public comptroller; /** * @notice Model which tells what the current interest rate should be */ InterestRateModel public interestRateModel; /** * @notice Initial exchange rate used when minting the first CTokens (used when totalSupply = 0) */ uint internal initialExchangeRateMantissa; /** * @notice Fraction of interest currently set aside for reserves */ uint public reserveFactorMantissa; /** * @notice Block number that interest was last accrued at */ uint public accrualBlockNumber; /** * @notice Accumulator of the total earned interest rate since the opening of the market */ uint public borrowIndex; /** * @notice Total amount of outstanding borrows of the underlying in this market */ uint public totalBorrows; /** * @notice Total amount of reserves of the underlying held in this market */ uint public totalReserves; /** * @notice Total number of tokens in circulation */ uint public totalSupply; /** * @notice Official record of token balances for each account */ mapping (address => uint) internal accountTokens; /** * @notice Approved token transfer amounts on behalf of others */ mapping (address => mapping (address => uint)) internal transferAllowances; /** * @notice Container for borrow balance information * @member principal Total balance (with accrued interest), after applying the most recent balance-changing action * @member interestIndex Global borrowIndex as of the most recent balance-changing action */ struct BorrowSnapshot { uint principal; uint interestIndex; } /** * @notice Mapping of account addresses to outstanding borrow balances */ mapping(address => BorrowSnapshot) internal accountBorrows; } contract CTokenInterface is CTokenStorage { /** * @notice Indicator that this is a CToken contract (for inspection) */ bool public constant isCToken = true; /*** Market Events ***/ /** * @notice Event emitted when interest is accrued */ event AccrueInterest(uint cashPrior, uint interestAccumulated, uint borrowIndex, uint totalBorrows); /** * @notice Event emitted when tokens are minted */ event Mint(address minter, uint mintAmount, uint mintTokens); /** * @notice Event emitted when tokens are redeemed */ event Redeem(address redeemer, uint redeemAmount, uint redeemTokens); /** * @notice Event emitted when underlying is borrowed */ event Borrow(address borrower, uint borrowAmount, uint accountBorrows, uint totalBorrows); /** * @notice Event emitted when a borrow is repaid */ event RepayBorrow(address payer, address borrower, uint repayAmount, uint accountBorrows, uint totalBorrows); /** * @notice Event emitted when a borrow is liquidated */ event LiquidateBorrow(address liquidator, address borrower, uint repayAmount, address cTokenCollateral, uint seizeTokens); /*** Admin Events ***/ /** * @notice Event emitted when pendingAdmin is changed */ event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin); /** * @notice Event emitted when pendingAdmin is accepted, which means admin is updated */ event NewAdmin(address oldAdmin, address newAdmin); /** * @notice Event emitted when comptroller is changed */ event NewComptroller(ComptrollerInterface oldComptroller, ComptrollerInterface newComptroller); /** * @notice Event emitted when interestRateModel is changed */ event NewMarketInterestRateModel(InterestRateModel oldInterestRateModel, InterestRateModel newInterestRateModel); /** * @notice Event emitted when the reserve factor is changed */ event NewReserveFactor(uint oldReserveFactorMantissa, uint newReserveFactorMantissa); /** * @notice Event emitted when the reserves are added */ event ReservesAdded(address benefactor, uint addAmount, uint newTotalReserves); /** * @notice Event emitted when the reserves are reduced */ event ReservesReduced(address admin, uint reduceAmount, uint newTotalReserves); /** * @notice EIP20 Transfer event */ event Transfer(address indexed from, address indexed to, uint amount); /** * @notice EIP20 Approval event */ event Approval(address indexed owner, address indexed spender, uint amount); /** * @notice Failure event */ event Failure(uint error, uint info, uint detail); /*** User Interface ***/ function transfer(address dst, uint amount) external returns (bool); function transferFrom(address src, address dst, uint amount) external returns (bool); function approve(address spender, uint amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint); function balanceOf(address owner) external view returns (uint); function balanceOfUnderlying(address owner) external returns (uint); function getAccountSnapshot(address account) external view returns (uint, uint, uint, uint); function borrowRatePerBlock() external view returns (uint); function supplyRatePerBlock() external view returns (uint); function totalBorrowsCurrent() external returns (uint); function borrowBalanceCurrent(address account) external returns (uint); function borrowBalanceStored(address account) public view returns (uint); function exchangeRateCurrent() public returns (uint); function exchangeRateStored() public view returns (uint); function getCash() external view returns (uint); function accrueInterest() public returns (uint); function seize(address liquidator, address borrower, uint seizeTokens) external returns (uint); /*** Admin Functions ***/ function _setPendingAdmin(address payable newPendingAdmin) external returns (uint); function _acceptAdmin() external returns (uint); function _setComptroller(ComptrollerInterface newComptroller) public returns (uint); function _setReserveFactor(uint newReserveFactorMantissa) external returns (uint); function _reduceReserves(uint reduceAmount) external returns (uint); function _setInterestRateModel(InterestRateModel newInterestRateModel) public returns (uint); } contract CErc20Storage { /** * @notice Underlying asset for this CToken */ address public underlying; } contract CErc20Interface is CErc20Storage { /*** User Interface ***/ function mint(uint mintAmount) external returns (uint); function redeem(uint redeemTokens) external returns (uint); function redeemUnderlying(uint redeemAmount) external returns (uint); function borrow(uint borrowAmount) external returns (uint); function repayBorrow(uint repayAmount) external returns (uint); function repayBorrowBehalf(address borrower, uint repayAmount) external returns (uint); function liquidateBorrow(address borrower, uint repayAmount, CTokenInterface cTokenCollateral) external returns (uint); /*** Admin Functions ***/ function _addReserves(uint addAmount) external returns (uint); } contract CDelegationStorage { /** * @notice Implementation address for this contract */ address public implementation; } contract CDelegatorInterface is CDelegationStorage { /** * @notice Emitted when implementation is changed */ event NewImplementation(address oldImplementation, address newImplementation); /** * @notice Called by the admin to update the implementation of the delegator * @param implementation_ The address of the new implementation for delegation * @param allowResign Flag to indicate whether to call _resignImplementation on the old implementation * @param becomeImplementationData The encoded bytes data to be passed to _becomeImplementation */ function _setImplementation(address implementation_, bool allowResign, bytes memory becomeImplementationData) public; } contract CDelegateInterface is CDelegationStorage { /** * @notice Called by the delegator on a delegate to initialize it for duty * @dev Should revert if any issues arise which make it unfit for delegation * @param data The encoded bytes data for any initialization */ function _becomeImplementation(bytes memory data) public; /** * @notice Called by the delegator on a delegate to forfeit its responsibility */ function _resignImplementation() public; } pragma solidity ^0.5.16; contract ComptrollerErrorReporter { enum Error { NO_ERROR, UNAUTHORIZED, COMPTROLLER_MISMATCH, INSUFFICIENT_SHORTFALL, INSUFFICIENT_LIQUIDITY, INVALID_CLOSE_FACTOR, INVALID_COLLATERAL_FACTOR, INVALID_LIQUIDATION_INCENTIVE, MARKET_NOT_ENTERED, // no longer possible MARKET_NOT_LISTED, MARKET_ALREADY_LISTED, MATH_ERROR, NONZERO_BORROW_BALANCE, PRICE_ERROR, REJECTION, SNAPSHOT_ERROR, TOO_MANY_ASSETS, TOO_MUCH_REPAY } enum FailureInfo { ACCEPT_ADMIN_PENDING_ADMIN_CHECK, ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK, EXIT_MARKET_BALANCE_OWED, EXIT_MARKET_REJECTION, SET_CLOSE_FACTOR_OWNER_CHECK, SET_CLOSE_FACTOR_VALIDATION, SET_COLLATERAL_FACTOR_OWNER_CHECK, SET_COLLATERAL_FACTOR_NO_EXISTS, SET_COLLATERAL_FACTOR_VALIDATION, SET_COLLATERAL_FACTOR_WITHOUT_PRICE, SET_IMPLEMENTATION_OWNER_CHECK, SET_LIQUIDATION_INCENTIVE_OWNER_CHECK, SET_LIQUIDATION_INCENTIVE_VALIDATION, SET_MAX_ASSETS_OWNER_CHECK, SET_PENDING_ADMIN_OWNER_CHECK, SET_PENDING_IMPLEMENTATION_OWNER_CHECK, SET_PRICE_ORACLE_OWNER_CHECK, SUPPORT_MARKET_EXISTS, SUPPORT_MARKET_OWNER_CHECK, SET_PAUSE_GUARDIAN_OWNER_CHECK } /** * @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary * contract-specific code that enables us to report opaque error codes from upgradeable contracts. **/ event Failure(uint error, uint info, uint detail); /** * @dev use this when reporting a known error from the money market or a non-upgradeable collaborator */ function fail(Error err, FailureInfo info) internal returns (uint) { emit Failure(uint(err), uint(info), 0); return uint(err); } /** * @dev use this when reporting an opaque error from an upgradeable collaborator contract */ function failOpaque(Error err, FailureInfo info, uint opaqueError) internal returns (uint) { emit Failure(uint(err), uint(info), opaqueError); return uint(err); } } contract TokenErrorReporter { enum Error { NO_ERROR, UNAUTHORIZED, BAD_INPUT, COMPTROLLER_REJECTION, COMPTROLLER_CALCULATION_ERROR, INTEREST_RATE_MODEL_ERROR, INVALID_ACCOUNT_PAIR, INVALID_CLOSE_AMOUNT_REQUESTED, INVALID_COLLATERAL_FACTOR, MATH_ERROR, MARKET_NOT_FRESH, MARKET_NOT_LISTED, TOKEN_INSUFFICIENT_ALLOWANCE, TOKEN_INSUFFICIENT_BALANCE, TOKEN_INSUFFICIENT_CASH, TOKEN_TRANSFER_IN_FAILED, TOKEN_TRANSFER_OUT_FAILED } /* * Note: FailureInfo (but not Error) is kept in alphabetical order * This is because FailureInfo grows significantly faster, and * the order of Error has some meaning, while the order of FailureInfo * is entirely arbitrary. */ enum FailureInfo { ACCEPT_ADMIN_PENDING_ADMIN_CHECK, ACCRUE_INTEREST_ACCUMULATED_INTEREST_CALCULATION_FAILED, ACCRUE_INTEREST_BORROW_RATE_CALCULATION_FAILED, ACCRUE_INTEREST_NEW_BORROW_INDEX_CALCULATION_FAILED, ACCRUE_INTEREST_NEW_TOTAL_BORROWS_CALCULATION_FAILED, ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED, ACCRUE_INTEREST_SIMPLE_INTEREST_FACTOR_CALCULATION_FAILED, BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, BORROW_ACCRUE_INTEREST_FAILED, BORROW_CASH_NOT_AVAILABLE, BORROW_FRESHNESS_CHECK, BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED, BORROW_MARKET_NOT_LISTED, BORROW_COMPTROLLER_REJECTION, LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED, LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED, LIQUIDATE_COLLATERAL_FRESHNESS_CHECK, LIQUIDATE_COMPTROLLER_REJECTION, LIQUIDATE_COMPTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED, LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX, LIQUIDATE_CLOSE_AMOUNT_IS_ZERO, LIQUIDATE_FRESHNESS_CHECK, LIQUIDATE_LIQUIDATOR_IS_BORROWER, LIQUIDATE_REPAY_BORROW_FRESH_FAILED, LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED, LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED, LIQUIDATE_SEIZE_COMPTROLLER_REJECTION, LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER, LIQUIDATE_SEIZE_TOO_MUCH, MINT_ACCRUE_INTEREST_FAILED, MINT_COMPTROLLER_REJECTION, MINT_EXCHANGE_CALCULATION_FAILED, MINT_EXCHANGE_RATE_READ_FAILED, MINT_FRESHNESS_CHECK, MINT_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, MINT_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, MINT_TRANSFER_IN_FAILED, MINT_TRANSFER_IN_NOT_POSSIBLE, REDEEM_ACCRUE_INTEREST_FAILED, REDEEM_COMPTROLLER_REJECTION, REDEEM_EXCHANGE_TOKENS_CALCULATION_FAILED, REDEEM_EXCHANGE_AMOUNT_CALCULATION_FAILED, REDEEM_EXCHANGE_RATE_READ_FAILED, REDEEM_FRESHNESS_CHECK, REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, REDEEM_TRANSFER_OUT_NOT_POSSIBLE, REDUCE_RESERVES_ACCRUE_INTEREST_FAILED, REDUCE_RESERVES_ADMIN_CHECK, REDUCE_RESERVES_CASH_NOT_AVAILABLE, REDUCE_RESERVES_FRESH_CHECK, REDUCE_RESERVES_VALIDATION, REPAY_BEHALF_ACCRUE_INTEREST_FAILED, REPAY_BORROW_ACCRUE_INTEREST_FAILED, REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, REPAY_BORROW_COMPTROLLER_REJECTION, REPAY_BORROW_FRESHNESS_CHECK, REPAY_BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED, REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, REPAY_BORROW_TRANSFER_IN_NOT_POSSIBLE, SET_COLLATERAL_FACTOR_OWNER_CHECK, SET_COLLATERAL_FACTOR_VALIDATION, SET_COMPTROLLER_OWNER_CHECK, SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED, SET_INTEREST_RATE_MODEL_FRESH_CHECK, SET_INTEREST_RATE_MODEL_OWNER_CHECK, SET_MAX_ASSETS_OWNER_CHECK, SET_ORACLE_MARKET_NOT_LISTED, SET_PENDING_ADMIN_OWNER_CHECK, SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED, SET_RESERVE_FACTOR_ADMIN_CHECK, SET_RESERVE_FACTOR_FRESH_CHECK, SET_RESERVE_FACTOR_BOUNDS_CHECK, TRANSFER_COMPTROLLER_REJECTION, TRANSFER_NOT_ALLOWED, TRANSFER_NOT_ENOUGH, TRANSFER_TOO_MUCH, ADD_RESERVES_ACCRUE_INTEREST_FAILED, ADD_RESERVES_FRESH_CHECK, ADD_RESERVES_TRANSFER_IN_NOT_POSSIBLE } /** * @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary * contract-specific code that enables us to report opaque error codes from upgradeable contracts. **/ event Failure(uint error, uint info, uint detail); /** * @dev use this when reporting a known error from the money market or a non-upgradeable collaborator */ function fail(Error err, FailureInfo info) internal returns (uint) { emit Failure(uint(err), uint(info), 0); return uint(err); } /** * @dev use this when reporting an opaque error from an upgradeable collaborator contract */ function failOpaque(Error err, FailureInfo info, uint opaqueError) internal returns (uint) { emit Failure(uint(err), uint(info), opaqueError); return uint(err); } } pragma solidity ^0.5.16; import "./CarefulMath.sol"; import "./ExponentialNoError.sol"; /** * @title Exponential module for storing fixed-precision decimals * @author Compound * @dev Legacy contract for compatibility reasons with existing contracts that still use MathError * @notice Exp is a struct which stores decimals with a fixed precision of 18 decimal places. * Thus, if we wanted to store the 5.1, mantissa would store 5.1e18. That is: * `Exp({mantissa: 5100000000000000000})`. */ contract Exponential is CarefulMath, ExponentialNoError { /** * @dev Creates an exponential from numerator and denominator values. * Note: Returns an error if (`num` * 10e18) > MAX_INT, * or if `denom` is zero. */ function getExp(uint num, uint denom) pure internal returns (MathError, Exp memory) { (MathError err0, uint scaledNumerator) = mulUInt(num, expScale); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } (MathError err1, uint rational) = divUInt(scaledNumerator, denom); if (err1 != MathError.NO_ERROR) { return (err1, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: rational})); } /** * @dev Adds two exponentials, returning a new exponential. */ function addExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { (MathError error, uint result) = addUInt(a.mantissa, b.mantissa); return (error, Exp({mantissa: result})); } /** * @dev Subtracts two exponentials, returning a new exponential. */ function subExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { (MathError error, uint result) = subUInt(a.mantissa, b.mantissa); return (error, Exp({mantissa: result})); } /** * @dev Multiply an Exp by a scalar, returning a new Exp. */ function mulScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) { (MathError err0, uint scaledMantissa) = mulUInt(a.mantissa, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: scaledMantissa})); } /** * @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer. */ function mulScalarTruncate(Exp memory a, uint scalar) pure internal returns (MathError, uint) { (MathError err, Exp memory product) = mulScalar(a, scalar); if (err != MathError.NO_ERROR) { return (err, 0); } return (MathError.NO_ERROR, truncate(product)); } /** * @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer. */ function mulScalarTruncateAddUInt(Exp memory a, uint scalar, uint addend) pure internal returns (MathError, uint) { (MathError err, Exp memory product) = mulScalar(a, scalar); if (err != MathError.NO_ERROR) { return (err, 0); } return addUInt(truncate(product), addend); } /** * @dev Divide an Exp by a scalar, returning a new Exp. */ function divScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) { (MathError err0, uint descaledMantissa) = divUInt(a.mantissa, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: descaledMantissa})); } /** * @dev Divide a scalar by an Exp, returning a new Exp. */ function divScalarByExp(uint scalar, Exp memory divisor) pure internal returns (MathError, Exp memory) { /* We are doing this as: getExp(mulUInt(expScale, scalar), divisor.mantissa) How it works: Exp = a / b; Scalar = s; `s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale` */ (MathError err0, uint numerator) = mulUInt(expScale, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return getExp(numerator, divisor.mantissa); } /** * @dev Divide a scalar by an Exp, then truncate to return an unsigned integer. */ function divScalarByExpTruncate(uint scalar, Exp memory divisor) pure internal returns (MathError, uint) { (MathError err, Exp memory fraction) = divScalarByExp(scalar, divisor); if (err != MathError.NO_ERROR) { return (err, 0); } return (MathError.NO_ERROR, truncate(fraction)); } /** * @dev Multiplies two exponentials, returning a new exponential. */ function mulExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { (MathError err0, uint doubleScaledProduct) = mulUInt(a.mantissa, b.mantissa); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } // We add half the scale before dividing so that we get rounding instead of truncation. // See "Listing 6" and text above it at https://accu.org/index.php/journals/1717 // Without this change, a result like 6.6...e-19 will be truncated to 0 instead of being rounded to 1e-18. (MathError err1, uint doubleScaledProductWithHalfScale) = addUInt(halfExpScale, doubleScaledProduct); if (err1 != MathError.NO_ERROR) { return (err1, Exp({mantissa: 0})); } (MathError err2, uint product) = divUInt(doubleScaledProductWithHalfScale, expScale); // The only error `div` can return is MathError.DIVISION_BY_ZERO but we control `expScale` and it is not zero. assert(err2 == MathError.NO_ERROR); return (MathError.NO_ERROR, Exp({mantissa: product})); } /** * @dev Multiplies two exponentials given their mantissas, returning a new exponential. */ function mulExp(uint a, uint b) pure internal returns (MathError, Exp memory) { return mulExp(Exp({mantissa: a}), Exp({mantissa: b})); } /** * @dev Multiplies three exponentials, returning a new exponential. */ function mulExp3(Exp memory a, Exp memory b, Exp memory c) pure internal returns (MathError, Exp memory) { (MathError err, Exp memory ab) = mulExp(a, b); if (err != MathError.NO_ERROR) { return (err, ab); } return mulExp(ab, c); } /** * @dev Divides two exponentials, returning a new exponential. * (a/scale) / (b/scale) = (a/scale) * (scale/b) = a/b, * which we can scale as an Exp by calling getExp(a.mantissa, b.mantissa) */ function divExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { return getExp(a.mantissa, b.mantissa); } } pragma solidity ^0.5.16; /** * @title ERC 20 Token Standard Interface * https://eips.ethereum.org/EIPS/eip-20 */ interface EIP20Interface { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); /** * @notice Get the total number of tokens in circulation * @return The supply of tokens */ function totalSupply() external view returns (uint256); /** * @notice Gets the balance of the specified address * @param owner The address from which the balance will be retrieved * @return The balance */ function balanceOf(address owner) external view returns (uint256 balance); /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address dst, uint256 amount) external returns (bool success); /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom(address src, address dst, uint256 amount) external returns (bool success); /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param amount The number of tokens that are approved (-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint256 amount) external returns (bool success); /** * @notice Get the current allowance from `owner` for `spender` * @param owner The address of the account which owns the tokens to be spent * @param spender The address of the account which may transfer tokens * @return The number of tokens allowed to be spent (-1 means infinite) */ function allowance(address owner, address spender) external view returns (uint256 remaining); event Transfer(address indexed from, address indexed to, uint256 amount); event Approval(address indexed owner, address indexed spender, uint256 amount); } pragma solidity ^0.5.16; /** * @title EIP20NonStandardInterface * @dev Version of ERC20 with no return values for `transfer` and `transferFrom` * See https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca */ interface EIP20NonStandardInterface { /** * @notice Get the total number of tokens in circulation * @return The supply of tokens */ function totalSupply() external view returns (uint256); /** * @notice Gets the balance of the specified address * @param owner The address from which the balance will be retrieved * @return The balance */ function balanceOf(address owner) external view returns (uint256 balance); /// /// !!!!!!!!!!!!!! /// !!! NOTICE !!! `transfer` does not return a value, in violation of the ERC-20 specification /// !!!!!!!!!!!!!! /// /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param amount The number of tokens to transfer */ function transfer(address dst, uint256 amount) external; /// /// !!!!!!!!!!!!!! /// !!! NOTICE !!! `transferFrom` does not return a value, in violation of the ERC-20 specification /// !!!!!!!!!!!!!! /// /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param amount The number of tokens to transfer */ function transferFrom(address src, address dst, uint256 amount) external; /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param amount The number of tokens that are approved * @return Whether or not the approval succeeded */ function approve(address spender, uint256 amount) external returns (bool success); /** * @notice Get the current allowance from `owner` for `spender` * @param owner The address of the account which owns the tokens to be spent * @param spender The address of the account which may transfer tokens * @return The number of tokens allowed to be spent */ function allowance(address owner, address spender) external view returns (uint256 remaining); event Transfer(address indexed from, address indexed to, uint256 amount); event Approval(address indexed owner, address indexed spender, uint256 amount); } pragma solidity ^0.5.16; /** * @title Compound's InterestRateModel Interface * @author Compound */ contract InterestRateModel { /// @notice Indicator that this is an InterestRateModel contract (for inspection) bool public constant isInterestRateModel = true; /** * @notice Calculates the current borrow interest rate per block * @param cash The total amount of cash the market has * @param borrows The total amount of borrows the market has outstanding * @param reserves The total amount of reserves the market has * @return The borrow rate per block (as a percentage, and scaled by 1e18) */ function getBorrowRate(uint cash, uint borrows, uint reserves) external view returns (uint); /** * @notice Calculates the current supply interest rate per block * @param cash The total amount of cash the market has * @param borrows The total amount of borrows the market has outstanding * @param reserves The total amount of reserves the market has * @param reserveFactorMantissa The current reserve factor the market has * @return The supply rate per block (as a percentage, and scaled by 1e18) */ function getSupplyRate(uint cash, uint borrows, uint reserves, uint reserveFactorMantissa) external view returns (uint); } pragma solidity ^0.5.16; /** * @title Careful Math * @author Compound * @notice Derived from OpenZeppelin's SafeMath library * https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/math/SafeMath.sol */ contract CarefulMath { /** * @dev Possible error codes that we can return */ enum MathError { NO_ERROR, DIVISION_BY_ZERO, INTEGER_OVERFLOW, INTEGER_UNDERFLOW } /** * @dev Multiplies two numbers, returns an error on overflow. */ function mulUInt(uint a, uint b) internal pure returns (MathError, uint) { if (a == 0) { return (MathError.NO_ERROR, 0); } uint c = a * b; if (c / a != b) { return (MathError.INTEGER_OVERFLOW, 0); } else { return (MathError.NO_ERROR, c); } } /** * @dev Integer division of two numbers, truncating the quotient. */ function divUInt(uint a, uint b) internal pure returns (MathError, uint) { if (b == 0) { return (MathError.DIVISION_BY_ZERO, 0); } return (MathError.NO_ERROR, a / b); } /** * @dev Subtracts two numbers, returns an error on overflow (i.e. if subtrahend is greater than minuend). */ function subUInt(uint a, uint b) internal pure returns (MathError, uint) { if (b <= a) { return (MathError.NO_ERROR, a - b); } else { return (MathError.INTEGER_UNDERFLOW, 0); } } /** * @dev Adds two numbers, returns an error on overflow. */ function addUInt(uint a, uint b) internal pure returns (MathError, uint) { uint c = a + b; if (c >= a) { return (MathError.NO_ERROR, c); } else { return (MathError.INTEGER_OVERFLOW, 0); } } /** * @dev add a and b and then subtract c */ function addThenSubUInt(uint a, uint b, uint c) internal pure returns (MathError, uint) { (MathError err0, uint sum) = addUInt(a, b); if (err0 != MathError.NO_ERROR) { return (err0, 0); } return subUInt(sum, c); } } pragma solidity ^0.5.16; /** * @title Exponential module for storing fixed-precision decimals * @author Compound * @notice Exp is a struct which stores decimals with a fixed precision of 18 decimal places. * Thus, if we wanted to store the 5.1, mantissa would store 5.1e18. That is: * `Exp({mantissa: 5100000000000000000})`. */ contract ExponentialNoError { uint constant expScale = 1e18; uint constant doubleScale = 1e36; uint constant halfExpScale = expScale/2; uint constant mantissaOne = expScale; struct Exp { uint mantissa; } struct Double { uint mantissa; } /** * @dev Truncates the given exp to a whole number value. * For example, truncate(Exp{mantissa: 15 * expScale}) = 15 */ function truncate(Exp memory exp) pure internal returns (uint) { // Note: We are not using careful math here as we're performing a division that cannot fail return exp.mantissa / expScale; } /** * @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer. */ function mul_ScalarTruncate(Exp memory a, uint scalar) pure internal returns (uint) { Exp memory product = mul_(a, scalar); return truncate(product); } /** * @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer. */ function mul_ScalarTruncateAddUInt(Exp memory a, uint scalar, uint addend) pure internal returns (uint) { Exp memory product = mul_(a, scalar); return add_(truncate(product), addend); } /** * @dev Checks if first Exp is less than second Exp. */ function lessThanExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa < right.mantissa; } /** * @dev Checks if left Exp <= right Exp. */ function lessThanOrEqualExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa <= right.mantissa; } /** * @dev Checks if left Exp > right Exp. */ function greaterThanExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa > right.mantissa; } /** * @dev returns true if Exp is exactly zero */ function isZeroExp(Exp memory value) pure internal returns (bool) { return value.mantissa == 0; } function safe224(uint n, string memory errorMessage) pure internal returns (uint224) { require(n < 2**224, errorMessage); return uint224(n); } function safe32(uint n, string memory errorMessage) pure internal returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function add_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: add_(a.mantissa, b.mantissa)}); } function add_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: add_(a.mantissa, b.mantissa)}); } function add_(uint a, uint b) pure internal returns (uint) { return add_(a, b, "addition overflow"); } function add_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { uint c = a + b; require(c >= a, errorMessage); return c; } function sub_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: sub_(a.mantissa, b.mantissa)}); } function sub_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: sub_(a.mantissa, b.mantissa)}); } function sub_(uint a, uint b) pure internal returns (uint) { return sub_(a, b, "subtraction underflow"); } function sub_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { require(b <= a, errorMessage); return a - b; } function mul_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: mul_(a.mantissa, b.mantissa) / expScale}); } function mul_(Exp memory a, uint b) pure internal returns (Exp memory) { return Exp({mantissa: mul_(a.mantissa, b)}); } function mul_(uint a, Exp memory b) pure internal returns (uint) { return mul_(a, b.mantissa) / expScale; } function mul_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: mul_(a.mantissa, b.mantissa) / doubleScale}); } function mul_(Double memory a, uint b) pure internal returns (Double memory) { return Double({mantissa: mul_(a.mantissa, b)}); } function mul_(uint a, Double memory b) pure internal returns (uint) { return mul_(a, b.mantissa) / doubleScale; } function mul_(uint a, uint b) pure internal returns (uint) { return mul_(a, b, "multiplication overflow"); } function mul_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { if (a == 0 || b == 0) { return 0; } uint c = a * b; require(c / a == b, errorMessage); return c; } function div_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: div_(mul_(a.mantissa, expScale), b.mantissa)}); } function div_(Exp memory a, uint b) pure internal returns (Exp memory) { return Exp({mantissa: div_(a.mantissa, b)}); } function div_(uint a, Exp memory b) pure internal returns (uint) { return div_(mul_(a, expScale), b.mantissa); } function div_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: div_(mul_(a.mantissa, doubleScale), b.mantissa)}); } function div_(Double memory a, uint b) pure internal returns (Double memory) { return Double({mantissa: div_(a.mantissa, b)}); } function div_(uint a, Double memory b) pure internal returns (uint) { return div_(mul_(a, doubleScale), b.mantissa); } function div_(uint a, uint b) pure internal returns (uint) { return div_(a, b, "divide by zero"); } function div_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { require(b > 0, errorMessage); return a / b; } function fraction(uint a, uint b) pure internal returns (Double memory) { return Double({mantissa: div_(mul_(a, doubleScale), b)}); } }
Store admin with value pendingAdmin
admin = pendingAdmin;
17,724
[ 1, 2257, 3981, 598, 460, 4634, 4446, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 3981, 273, 4634, 4446, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@chainlink/contracts/src/v0.8/ChainlinkClient.sol"; contract KrishiCoin is ERC20, ChainlinkClient, Ownable { address curr_owner; using Chainlink for Chainlink.Request; uint256 public volume; address private oracle; bytes32 private jobId; uint256 private fee; mapping(bytes32 => address) public requestId_toSender; mapping(address => uint256) public address_to_ethgiven; constructor(uint256 initialSupply) ERC20("Krishi Coin", "KC") { _mint(msg.sender, initialSupply); _approve(msg.sender, address(this), initialSupply); curr_owner = msg.sender; // For connecting external API setPublicChainlinkToken(); oracle = 0x3A56aE4a2831C3d3514b5D7Af5578E45eBDb7a40; jobId = "3b7ca0d48c7a4b2da9268456665d11ae"; fee = 0.01 * 10**18; } function payUser() public payable { bytes32 requestId = requestVolumeData(); requestId_toSender[requestId] = msg.sender; address_to_ethgiven[msg.sender] = msg.value; } function requestVolumeData() public returns (bytes32 requestId) { Chainlink.Request memory request = buildChainlinkRequest( jobId, address(this), this.fulfill.selector ); // Set the URL to perform the GET request on request.add( "get", "https://min-api.cryptocompare.com/data/pricemultifull?fsyms=INR&tsyms=ETH" ); request.add("path", "RAW.INR.ETH.OPEN24HOUR"); // Multiply the result by 1000000000000000000 to remove decimals int256 timesAmount = 10**18; request.addInt("times", timesAmount); // Sends the request return sendChainlinkRequestTo(oracle, request, fee); } /** * Receive the response in the form of uint256 */ function fulfill(bytes32 _requestId, uint256 _volume) public recordChainlinkFulfillment(_requestId) { volume = _volume; uint256 amount_in_eth = address_to_ethgiven[ requestId_toSender[_requestId] ]; require(amount_in_eth > 0, "Insufficient ETH"); uint256 amount_of_tokens = ((amount_in_eth / _volume) * (10**18)) / 10; IERC20 paymentToken = IERC20(address(this)); require(amount_of_tokens > 0, "Tokens too less!"); require( paymentToken.transferFrom( curr_owner, requestId_toSender[_requestId], amount_of_tokens ), "transfer Failed" ); address_to_ethgiven[requestId_toSender[_requestId]] = 0; } }
* Receive the response in the form of uint256/
function fulfill(bytes32 _requestId, uint256 _volume) public recordChainlinkFulfillment(_requestId) { volume = _volume; uint256 amount_in_eth = address_to_ethgiven[ requestId_toSender[_requestId] ]; require(amount_in_eth > 0, "Insufficient ETH"); uint256 amount_of_tokens = ((amount_in_eth / _volume) * (10**18)) / 10; IERC20 paymentToken = IERC20(address(this)); require(amount_of_tokens > 0, "Tokens too less!"); require( paymentToken.transferFrom( curr_owner, requestId_toSender[_requestId], amount_of_tokens ), "transfer Failed" ); address_to_ethgiven[requestId_toSender[_requestId]] = 0; }
7,292,230
[ 1, 11323, 326, 766, 316, 326, 646, 434, 2254, 5034, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 22290, 12, 3890, 1578, 389, 2293, 548, 16, 2254, 5034, 389, 9491, 13, 203, 3639, 1071, 203, 3639, 1409, 3893, 1232, 23747, 5935, 475, 24899, 2293, 548, 13, 203, 565, 288, 203, 3639, 3940, 273, 389, 9491, 31, 203, 203, 3639, 2254, 5034, 3844, 67, 267, 67, 546, 273, 1758, 67, 869, 67, 546, 10822, 63, 203, 5411, 14459, 67, 869, 12021, 63, 67, 2293, 548, 65, 203, 3639, 308, 31, 203, 203, 3639, 2583, 12, 8949, 67, 267, 67, 546, 405, 374, 16, 315, 5048, 11339, 512, 2455, 8863, 203, 203, 3639, 2254, 5034, 3844, 67, 792, 67, 7860, 273, 14015, 8949, 67, 267, 67, 546, 342, 389, 9491, 13, 380, 261, 2163, 636, 2643, 3719, 342, 1728, 31, 203, 203, 3639, 467, 654, 39, 3462, 5184, 1345, 273, 467, 654, 39, 3462, 12, 2867, 12, 2211, 10019, 203, 203, 3639, 2583, 12, 8949, 67, 792, 67, 7860, 405, 374, 16, 315, 5157, 4885, 5242, 4442, 1769, 203, 203, 3639, 2583, 12, 203, 5411, 5184, 1345, 18, 13866, 1265, 12, 203, 7734, 4306, 67, 8443, 16, 203, 7734, 14459, 67, 869, 12021, 63, 67, 2293, 548, 6487, 203, 7734, 3844, 67, 792, 67, 7860, 203, 5411, 262, 16, 203, 5411, 315, 13866, 11175, 6, 203, 3639, 11272, 203, 203, 3639, 1758, 67, 869, 67, 546, 10822, 63, 2293, 548, 67, 869, 12021, 63, 67, 2293, 548, 13563, 273, 374, 31, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity 0.6.11; import './Interfaces/IDefaultPool.sol'; import './Interfaces/IActivePool.sol'; import "./Dependencies/SafeMath.sol"; import "./Dependencies/Ownable.sol"; import "./Dependencies/CheckContract.sol"; import "./Dependencies/console.sol"; import "./Dependencies/IERC20.sol"; /* * The Default Pool holds the ETH and LUSD debt (but not LUSD tokens) from liquidations that have been redistributed * to active troves but not yet "applied", i.e. not yet recorded on a recipient active trove's struct. * * When a trove makes an operation that applies its pending ETH and LUSD debt, its pending ETH and LUSD debt is moved * from the Default Pool to the Active Pool. */ contract DefaultPool is Ownable, CheckContract, IDefaultPool { using SafeMath for uint256; string constant public NAME = "DefaultPool"; address public troveManagerAddress; address public activePoolAddress; uint256 internal ETH; // deposited ETH tracker uint256 internal LUSDDebt; // debt IERC20 wethToken; IActivePool public activePool; event TroveManagerAddressChanged(address _newTroveManagerAddress); event DefaultPoolLUSDDebtUpdated(uint _LUSDDebt); event DefaultPoolETHBalanceUpdated(uint _ETH); event WethTokenAddressSet(address _newWethAddress); // --- Dependency setters --- function setAddresses( address _troveManagerAddress, address _activePoolAddress, address _wethTokenAddress ) external onlyOwner { checkContract(_troveManagerAddress); checkContract(_activePoolAddress); checkContract(_wethTokenAddress); troveManagerAddress = _troveManagerAddress; activePoolAddress = _activePoolAddress; activePool = IActivePool(_activePoolAddress); wethToken = IERC20(_wethTokenAddress); emit TroveManagerAddressChanged(_troveManagerAddress); emit ActivePoolAddressChanged(_activePoolAddress); emit WethTokenAddressSet(_wethTokenAddress); _renounceOwnership(); } // --- Getters for public variables. Required by IPool interface --- /* * Returns the ETH state variable. * * Not necessarily equal to the the contract's raw ETH balance - ether can be forcibly sent to contracts. */ function getETH() external view override returns (uint) { return ETH; } function getLUSDDebt() external view override returns (uint) { return LUSDDebt; } // --- Pool functionality --- function sendETHToActivePool(uint _amount) external override { _requireCallerIsTroveManager(); address _activePool = activePoolAddress; // cache to save an SLOAD ETH = ETH.sub(_amount); emit DefaultPoolETHBalanceUpdated(ETH); emit EtherSent(_activePool, _amount); bool success = wethToken.transfer(_activePool,_amount); //(bool success, ) = activePool.call{ value: _amount }(""); require(success, "DefaultPool: sending ETH failed"); activePool.addWeth(_amount); } function increaseLUSDDebt(uint _amount) external override { _requireCallerIsTroveManager(); LUSDDebt = LUSDDebt.add(_amount); emit DefaultPoolLUSDDebtUpdated(LUSDDebt); } function addWeth(uint _amount) external override{ _requireCallerIsActivePool(); ETH = ETH.add(_amount); emit DefaultPoolETHBalanceUpdated(ETH); } function decreaseLUSDDebt(uint _amount) external override { _requireCallerIsTroveManager(); LUSDDebt = LUSDDebt.sub(_amount); emit DefaultPoolLUSDDebtUpdated(LUSDDebt); } // --- 'require' functions --- function _requireCallerIsActivePool() internal view { require(msg.sender == activePoolAddress, "DefaultPool: Caller is not the ActivePool"); } function _requireCallerIsTroveManager() internal view { require(msg.sender == troveManagerAddress, "DefaultPool: Caller is not the TroveManager"); } // --- Fallback function --- receive() external payable { _requireCallerIsActivePool(); //ETH = ETH.add(msg.value); emit DefaultPoolETHBalanceUpdated(ETH); } }
ETH = ETH.add(msg.value);
receive() external payable { _requireCallerIsActivePool(); emit DefaultPoolETHBalanceUpdated(ETH); }
2,505,915
[ 1, 1584, 44, 273, 512, 2455, 18, 1289, 12, 3576, 18, 1132, 1769, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 6798, 1435, 3903, 8843, 429, 288, 203, 3639, 389, 6528, 11095, 2520, 3896, 2864, 5621, 203, 3639, 3626, 2989, 2864, 1584, 44, 13937, 7381, 12, 1584, 44, 1769, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.21; contract GuessTheNewNumberChallenge { // solium-disable-next-line constructor function GuessTheNewNumberChallenge() public payable { // solhint-disable-next-line reason-string require(msg.value == 1 ether); // solium-disable-line error-reason } function isComplete() public view returns (bool) { return address(this).balance == 0; } function guess(uint8 n) public payable { // solhint-disable-next-line reason-string require(msg.value == 1 ether); // solium-disable-line error-reason // solhint-disable-next-line not-rely-on-block-hash, not-rely-on-time uint8 answer = uint8(keccak256(block.blockhash(block.number - 1), now)); // solium-disable-line security/no-block-members if (n == answer) { msg.sender.transfer(2 ether); } } }
solium-disable-next-line constructor
contract GuessTheNewNumberChallenge { function GuessTheNewNumberChallenge() public payable { } function isComplete() public view returns (bool) { return address(this).balance == 0; } function guess(uint8 n) public payable { if (n == answer) { msg.sender.transfer(2 ether); } } function guess(uint8 n) public payable { if (n == answer) { msg.sender.transfer(2 ether); } } }
5,439,539
[ 1, 18281, 5077, 17, 8394, 17, 4285, 17, 1369, 3885, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 30282, 1986, 1908, 1854, 18359, 288, 203, 565, 445, 30282, 1986, 1908, 1854, 18359, 1435, 1071, 8843, 429, 288, 203, 565, 289, 203, 203, 565, 445, 353, 6322, 1435, 1071, 1476, 1135, 261, 6430, 13, 288, 203, 3639, 327, 1758, 12, 2211, 2934, 12296, 422, 374, 31, 203, 565, 289, 203, 203, 565, 445, 7274, 12, 11890, 28, 290, 13, 1071, 8843, 429, 288, 203, 203, 3639, 309, 261, 82, 422, 5803, 13, 288, 203, 5411, 1234, 18, 15330, 18, 13866, 12, 22, 225, 2437, 1769, 203, 3639, 289, 203, 565, 289, 203, 565, 445, 7274, 12, 11890, 28, 290, 13, 1071, 8843, 429, 288, 203, 203, 3639, 309, 261, 82, 422, 5803, 13, 288, 203, 5411, 1234, 18, 15330, 18, 13866, 12, 22, 225, 2437, 1769, 203, 3639, 289, 203, 565, 289, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/100/0x0a134507b524C7D40525E128E22E7717c51e5865/sources/home/christoph/Documents/sandbox/GIF/dip-platform/gif-contracts/contracts/shared/Delegator.sol
solhint-disable no-inline-assembly */
function _delegate(address _implementation) internal { require(_implementation != address(0), "ERROR::UNKNOWN_IMPLEMENTATION"); bytes memory data = msg.data; assembly { let result := delegatecall( gas(), _implementation, add(data, 0x20), mload(data), 0, 0 ) let size := returndatasize() let ptr := mload(0x40) returndatacopy(ptr, 0, size) switch result case 0 { revert(ptr, size) } default { return(ptr, size) } }
14,266,184
[ 1, 18281, 11317, 17, 8394, 1158, 17, 10047, 17, 28050, 342, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 22216, 12, 2867, 389, 30810, 13, 2713, 288, 203, 3639, 2583, 24899, 30810, 480, 1758, 12, 20, 3631, 315, 3589, 2866, 14737, 67, 9883, 7618, 2689, 8863, 203, 203, 3639, 1731, 3778, 501, 273, 1234, 18, 892, 31, 203, 203, 3639, 19931, 288, 203, 5411, 2231, 563, 519, 7152, 1991, 12, 203, 7734, 16189, 9334, 203, 7734, 389, 30810, 16, 203, 7734, 527, 12, 892, 16, 374, 92, 3462, 3631, 203, 7734, 312, 945, 12, 892, 3631, 203, 7734, 374, 16, 203, 7734, 374, 203, 5411, 262, 203, 5411, 2231, 963, 519, 327, 13178, 554, 1435, 203, 5411, 2231, 6571, 519, 312, 945, 12, 20, 92, 7132, 13, 203, 5411, 327, 892, 3530, 12, 6723, 16, 374, 16, 963, 13, 203, 5411, 1620, 563, 203, 5411, 648, 374, 288, 203, 7734, 15226, 12, 6723, 16, 963, 13, 203, 5411, 289, 203, 5411, 805, 288, 203, 7734, 327, 12, 6723, 16, 963, 13, 203, 5411, 289, 203, 3639, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x8bf396786A2911b56F25B83E3902da3a3129E59f/sources/contracts/VotingEscrow.sol
**@notice Record global and per-user data to checkpoint@param _addr User's wallet address. No user checkpoint if 0x0@param _old_locked Pevious locked amount / end lock time for the user@param _new_locked New locked amount / end lock time for the user/ Calculate slopes and biases Kept at zero when they have to Hopefully it won't happen that this won't get used in 5 years! If it does, users will be able to withdraw but vote weight will be broken This can happen This cannot happen - just in case If last point was in this block, the slope change has been applied already But in such case we have 0 slope(s) Schedule the slope changes (slope is going down) We subtract new_user_slope from [_new_locked.end] and add old_user_slope to [_old_locked.end] _old_dslope was <something> - _u_old.slope, so we cancel that
function _checkpoint( address _addr, LockedBalance memory _old_locked, LockedBalance memory _new_locked ) internal { Point memory _u_old; Point memory _u_new; int256 _old_dslope = 0; int256 _new_dslope = 0; uint256 _epoch = epoch; if (_addr != address(0)) { if (_old_locked.end > block.timestamp && _old_locked.amount > 0) { unchecked { _u_old.slope = _old_locked.amount / int256(MAXTIME); } _u_old.bias = _u_old.slope * int256(_old_locked.end - block.timestamp); } if (_new_locked.end > block.timestamp && _new_locked.amount > 0) { unchecked { _u_new.slope = _new_locked.amount / int256(MAXTIME); } _u_new.bias = _u_new.slope * int256(_new_locked.end - block.timestamp); } if (_new_locked.end != 0) { if (_new_locked.end == _old_locked.end) { _new_dslope = _old_dslope; _new_dslope = slope_changes[_new_locked.end]; } } } Point memory _last_point = Point({ bias: 0, slope: 0, ts: block.timestamp, blk: block.number }); if (_epoch > 0) { _last_point = point_history[_epoch]; } uint256 _last_checkpoint = _last_point.ts; if (block.timestamp > _last_point.ts) { _block_slope = (MULTIPLIER * (block.number - _last_point.blk)) / (block.timestamp - _last_point.ts); } unchecked { _t_i = (_last_checkpoint / WEEK) * WEEK; } for (uint256 i; i < 255; ) { _t_i += WEEK; int256 d_slope = 0; if (_t_i > block.timestamp) { _t_i = block.timestamp; d_slope = slope_changes[_t_i]; } _last_point.bias = _last_point.bias - _last_point.slope * int256(_t_i - _last_checkpoint); _last_point.slope += d_slope; if (_last_point.bias < 0) { _last_point.bias = 0; } if (_last_point.slope < 0) { _last_point.slope = 0; } _last_checkpoint = _t_i; _last_point.ts = _t_i; _last_point.blk = _initial_last_point.blk + ((_block_slope * (_t_i - _initial_last_point.ts)) / MULTIPLIER); _epoch += 1; if (_t_i == block.timestamp) { _last_point.blk = block.number; break; point_history[_epoch] = _last_point; } unchecked { ++i; } } epoch = _epoch; if (_addr != address(0)) { _last_point.slope += _u_new.slope - _u_old.slope; _last_point.bias += _u_new.bias - _u_old.bias; if (_last_point.slope < 0) { _last_point.slope = 0; } if (_last_point.bias < 0) { _last_point.bias = 0; } } if (_addr2 != address(0)) { if (_old_locked.end > block.timestamp) { _old_dslope += _u_old.slope; if (_new_locked.end == _old_locked.end) { } slope_changes[_old_locked.end] = _old_dslope; } if (_new_locked.end > block.timestamp) { if (_new_locked.end > _old_locked.end) { slope_changes[_new_locked.end] = _new_dslope; } unchecked { _user_epoch = user_point_epoch[_addr2] + 1; } user_point_epoch[_addr2] = _user_epoch; _u_new.ts = block.timestamp; _u_new.blk = block.number; user_point_history[_addr2][_user_epoch] = _u_new; } }
8,324,149
[ 1, 2115, 2552, 471, 1534, 17, 1355, 501, 358, 9776, 389, 4793, 2177, 1807, 9230, 1758, 18, 2631, 729, 9776, 309, 374, 92, 20, 389, 1673, 67, 15091, 19622, 2084, 8586, 3844, 342, 679, 2176, 813, 364, 326, 729, 389, 2704, 67, 15091, 1166, 8586, 3844, 342, 679, 2176, 813, 364, 326, 729, 19, 9029, 30748, 281, 471, 12005, 281, 1475, 73, 337, 622, 3634, 1347, 2898, 1240, 358, 670, 1306, 4095, 518, 8462, 1404, 5865, 716, 333, 8462, 1404, 336, 1399, 316, 1381, 11387, 5, 971, 518, 1552, 16, 3677, 903, 506, 7752, 358, 598, 9446, 1496, 12501, 3119, 903, 506, 12933, 1220, 848, 5865, 1220, 2780, 5865, 300, 2537, 316, 648, 971, 1142, 1634, 1703, 316, 333, 1203, 16, 326, 17543, 2549, 711, 2118, 6754, 1818, 12484, 316, 4123, 648, 732, 1240, 374, 17543, 12, 87, 13, 10674, 326, 17543, 3478, 261, 30320, 353, 8554, 2588, 13, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 565, 445, 389, 25414, 12, 203, 3639, 1758, 389, 4793, 16, 203, 3639, 3488, 329, 13937, 3778, 389, 1673, 67, 15091, 16, 203, 3639, 3488, 329, 13937, 3778, 389, 2704, 67, 15091, 203, 565, 262, 2713, 288, 203, 3639, 4686, 3778, 389, 89, 67, 1673, 31, 203, 3639, 4686, 3778, 389, 89, 67, 2704, 31, 203, 3639, 509, 5034, 389, 1673, 67, 2377, 12232, 273, 374, 31, 203, 3639, 509, 5034, 389, 2704, 67, 2377, 12232, 273, 374, 31, 203, 3639, 2254, 5034, 389, 12015, 273, 7632, 31, 203, 203, 3639, 309, 261, 67, 4793, 480, 1758, 12, 20, 3719, 288, 203, 5411, 309, 261, 67, 1673, 67, 15091, 18, 409, 405, 1203, 18, 5508, 597, 389, 1673, 67, 15091, 18, 8949, 405, 374, 13, 288, 203, 7734, 22893, 288, 203, 10792, 389, 89, 67, 1673, 18, 30320, 273, 389, 1673, 67, 15091, 18, 8949, 342, 509, 5034, 12, 6694, 4684, 1769, 203, 7734, 289, 203, 7734, 389, 89, 67, 1673, 18, 13931, 273, 203, 10792, 389, 89, 67, 1673, 18, 30320, 380, 203, 10792, 509, 5034, 24899, 1673, 67, 15091, 18, 409, 300, 1203, 18, 5508, 1769, 203, 5411, 289, 203, 5411, 309, 261, 67, 2704, 67, 15091, 18, 409, 405, 1203, 18, 5508, 597, 389, 2704, 67, 15091, 18, 8949, 405, 374, 13, 288, 203, 7734, 22893, 288, 203, 10792, 389, 89, 67, 2704, 18, 30320, 273, 389, 2704, 67, 15091, 18, 8949, 342, 509, 5034, 12, 6694, 4684, 1769, 203, 7734, 289, 203, 7734, 389, 89, 67, 2704, 18, 13931, 273, 2 ]
./full_match/3/0x0840bdFDF3d74df8146C01E3C1828A383BDcF0aB/sources/contracts/TransferMoneyContract.sol
constructor is called only once when the smart contract is deployed
{ address owner; constructor() { owner = msg.sender; } function addFundsToContract() public payable { } function getContractBalance() public view returns(uint) { return address(this).balance; } function withdrawBalance() public { address payable to = payable(msg.sender); to.transfer(this.getContractBalance()); } function withdrawTo(address payable _to, uint256 amount) public { require(msg.sender == owner, "Unauthorized Smart Contract Owner"); _to.transfer(amount); } }
8,174,915
[ 1, 12316, 353, 2566, 1338, 3647, 1347, 326, 13706, 6835, 353, 19357, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 95, 203, 565, 1758, 3410, 31, 203, 377, 203, 565, 3885, 1435, 7010, 203, 565, 288, 203, 3639, 3410, 273, 1234, 18, 15330, 31, 203, 565, 289, 203, 377, 203, 565, 445, 527, 42, 1074, 11634, 8924, 1435, 1071, 8843, 429, 203, 565, 288, 203, 565, 289, 203, 377, 203, 565, 445, 336, 8924, 13937, 1435, 1071, 1476, 1135, 12, 11890, 13, 203, 565, 288, 203, 3639, 327, 1758, 12, 2211, 2934, 12296, 31, 203, 565, 289, 203, 377, 203, 565, 445, 598, 9446, 13937, 1435, 1071, 203, 565, 288, 203, 3639, 1758, 8843, 429, 358, 273, 8843, 429, 12, 3576, 18, 15330, 1769, 203, 3639, 358, 18, 13866, 12, 2211, 18, 588, 8924, 13937, 10663, 203, 565, 289, 203, 377, 203, 565, 445, 598, 9446, 774, 12, 2867, 8843, 429, 389, 869, 16, 2254, 5034, 3844, 13, 1071, 203, 565, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 3410, 16, 315, 13981, 19656, 13456, 16837, 8863, 203, 3639, 389, 869, 18, 13866, 12, 8949, 1769, 203, 565, 289, 203, 97, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
//Address: 0x752673c6d104e045129247fbbd806dbbfdfa64da //Contract name: Crowdsale //Balance: 0 Ether //Verification Date: 5/27/2017 //Transacion Count: 1 // CODE STARTS HERE pragma solidity ^0.4.11; /** * Copyright (c) 2016 Smart Contract Solutions, Inc. * Math operations with safety checks */ contract SafeMath { function safeMul(uint a, uint b) internal returns (uint) { uint c = a * b; assert(a == 0 || c / a == b); return c; } function safeDiv(uint a, uint b) internal returns (uint) { assert(b > 0); uint c = a / b; assert(a == b * c + a % b); return c; } function safeSub(uint a, uint b) internal returns (uint) { assert(b <= a); return a - b; } function safeAdd(uint a, uint b) internal returns (uint) { uint c = a + b; assert(c>=a && c>=b); 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 assert(bool assertion) internal { if (!assertion) { throw; } } } /* * Copyright (c) 2016 Smart Contract Solutions, Inc. * ERC20 interface * see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 { uint public totalSupply; function balanceOf(address who) constant returns (uint); function allowance(address owner, address spender) constant returns (uint); function transfer(address to, uint value) returns (bool ok); function transferFrom(address from, address to, uint value) returns (bool ok); function approve(address spender, uint value) returns (bool ok); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } /** * Copyright (c) 2016 Smart Contract Solutions, Inc. * Standard ERC20 token * * https://github.com/ethereum/EIPs/issues/20 * Based on code by FirstBlood: * https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, SafeMath { mapping (address => uint) balances; mapping (address => mapping (address => uint)) allowed; function transfer(address _to, uint _value) returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], _value); balances[_to] = safeAdd(balances[_to], _value); Transfer(msg.sender, _to, _value); return true; } function transferFrom(address _from, address _to, uint _value) returns (bool success) { var _allowance = allowed[_from][msg.sender]; // Check is not needed because safeSub(_allowance, _value) will already throw if this condition is not met // if (_value > _allowance) throw; 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; } function balanceOf(address _owner) constant returns (uint balance) { return balances[_owner]; } function approve(address _spender, uint _value) returns (bool success) { 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]; } } /* * Copyright (c) 2016 Smart Contract Solutions, Inc. * 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) { throw; } _; } function transferOwnership(address newOwner) onlyOwner { if (newOwner != address(0)) { owner = newOwner; } } } /// @title Moeda Loaylty Points token contract contract MoedaToken is StandardToken, Ownable { string public constant name = "Moeda Loyalty Points"; string public constant symbol = "MLO"; uint8 public constant decimals = 18; // don't allow creation of more than this number of tokens uint public constant MAX_TOKENS = 20000000 ether; // transfers are locked during the sale bool public saleActive; // only emitted during the crowdsale event Created(address indexed donor, uint256 tokensReceived); // determine whether transfers can be made modifier onlyAfterSale() { if (saleActive) { throw; } _; } modifier onlyDuringSale() { if (!saleActive) { throw; } _; } /// @dev Create moeda token and lock transfers function MoedaToken() { saleActive = true; } /// @dev unlock transfers function unlock() onlyOwner { saleActive = false; } /// @dev create tokens, only usable while saleActive /// @param recipient address that will receive the created tokens /// @param amount the number of tokens to create function create(address recipient, uint256 amount) onlyOwner onlyDuringSale { if (amount == 0) throw; if (safeAdd(totalSupply, amount) > MAX_TOKENS) throw; balances[recipient] = safeAdd(balances[recipient], amount); totalSupply = safeAdd(totalSupply, amount); Created(recipient, amount); } // transfer tokens // only allowed after sale has ended function transfer(address _to, uint _value) onlyAfterSale returns (bool) { return super.transfer(_to, _value); } // transfer tokens // only allowed after sale has ended function transferFrom(address from, address to, uint value) onlyAfterSale returns (bool) { return super.transferFrom(from, to, value); } } /// @title Moeda crowdsale contract Crowdsale is Ownable, SafeMath { bool public crowdsaleClosed; // whether the crowdsale has been closed // manually address public wallet; // recipient of all crowdsale funds MoedaToken public moedaToken; // token that will be sold during sale uint256 public etherReceived; // total ether received uint256 public totalTokensSold; // number of tokens sold uint256 public startBlock; // block where sale starts uint256 public endBlock; // block where sale ends // used to scale token amounts to 18 decimals uint256 public constant TOKEN_MULTIPLIER = 10 ** 18; // number of tokens allocated to presale (prior to crowdsale) uint256 public constant PRESALE_TOKEN_ALLOCATION = 5000000 * TOKEN_MULTIPLIER; // recipient of presale tokens address public PRESALE_WALLET = "0x30B3C64d43e7A1E8965D934Fa96a3bFB33Eee0d2"; // smallest possible donation uint256 public constant DUST_LIMIT = 1 finney; // token generation rates (tokens per eth) uint256 public constant TIER1_RATE = 160; uint256 public constant TIER2_RATE = 125; uint256 public constant TIER3_RATE = 80; // limits for each pricing tier (how much can be bought) uint256 public constant TIER1_CAP = 31250 ether; uint256 public constant TIER2_CAP = 71250 ether; uint256 public constant TIER3_CAP = 133750 ether; // Total ether cap // Log a purchase event Purchase(address indexed donor, uint256 amount, uint256 tokenAmount); // Log transfer of tokens that were sent to this contract by mistake event TokenDrain(address token, address to, uint256 amount); modifier onlyDuringSale() { if (crowdsaleClosed) { throw; } if (block.number < startBlock) { throw; } if (block.number >= endBlock) { throw; } _; } /// @dev Initialize a new Crowdsale contract /// @param _wallet address of multisig wallet that will store received ether /// @param _startBlock block at which to start the sale /// @param _endBlock block at which to end the sale function Crowdsale(address _wallet, uint _startBlock, uint _endBlock) { if (_wallet == address(0)) throw; if (_startBlock <= block.number) throw; if (_endBlock <= _startBlock) throw; crowdsaleClosed = false; wallet = _wallet; moedaToken = new MoedaToken(); startBlock = _startBlock; endBlock = _endBlock; } /// @dev Determine the lowest rate to acquire tokens given an amount of /// donated ethers /// @param totalReceived amount of ether that has been received /// @return pair of the current tier's donation limit and a token creation rate function getLimitAndPrice(uint256 totalReceived) constant returns (uint256, uint256) { uint256 limit = 0; uint256 price = 0; if (totalReceived < TIER1_CAP) { limit = TIER1_CAP; price = TIER1_RATE; } else if (totalReceived < TIER2_CAP) { limit = TIER2_CAP; price = TIER2_RATE; } else if (totalReceived < TIER3_CAP) { limit = TIER3_CAP; price = TIER3_RATE; } else { throw; // this shouldn't happen } return (limit, price); } /// @dev Determine how many tokens we can get from each pricing tier, in /// case a donation's amount overlaps multiple pricing tiers. /// /// @param totalReceived ether received by contract plus spent by this donation /// @param requestedAmount total ether to spend on tokens in a donation /// @return amount of tokens to get for the requested ether donation function getTokenAmount(uint256 totalReceived, uint256 requestedAmount) constant returns (uint256) { // base case, we've spent the entire donation and can stop if (requestedAmount == 0) return 0; uint256 limit = 0; uint256 price = 0; // 1. Determine cheapest token price (limit, price) = getLimitAndPrice(totalReceived); // 2. Since there are multiple pricing levels based on how much has been // received so far, we need to determine how much can be spent at // any given tier. This in case a donation will overlap more than one // tier uint256 maxETHSpendableInTier = safeSub(limit, totalReceived); uint256 amountToSpend = min256(maxETHSpendableInTier, requestedAmount); // 3. Given a price determine how many tokens the unspent ether in this // donation will get you uint256 tokensToReceiveAtCurrentPrice = safeMul(amountToSpend, price); // You've spent everything you could at this level, continue to the next // one, in case there is some ETH left unspent in this donation. uint256 additionalTokens = getTokenAmount( safeAdd(totalReceived, amountToSpend), safeSub(requestedAmount, amountToSpend)); return safeAdd(tokensToReceiveAtCurrentPrice, additionalTokens); } /// grant tokens to buyer when we receive ether /// @dev buy tokens, only usable while crowdsale is active function () payable onlyDuringSale { if (msg.value < DUST_LIMIT) throw; if (safeAdd(etherReceived, msg.value) > TIER3_CAP) throw; uint256 tokenAmount = getTokenAmount(etherReceived, msg.value); moedaToken.create(msg.sender, tokenAmount); etherReceived = safeAdd(etherReceived, msg.value); totalTokensSold = safeAdd(totalTokensSold, tokenAmount); Purchase(msg.sender, msg.value, tokenAmount); if (!wallet.send(msg.value)) throw; } /// @dev close the crowdsale manually and unlock the tokens /// this will only be successful if not already executed, /// if endBlock has been reached, or if the cap has been reached function finalize() onlyOwner { if (block.number < startBlock) throw; if (crowdsaleClosed) throw; // if amount remaining is too small we can allow sale to end earlier uint256 amountRemaining = safeSub(TIER3_CAP, etherReceived); if (block.number < endBlock && amountRemaining >= DUST_LIMIT) throw; // create and assign presale tokens to presale wallet moedaToken.create(PRESALE_WALLET, PRESALE_TOKEN_ALLOCATION); // unlock tokens for spending moedaToken.unlock(); crowdsaleClosed = true; } /// @dev Drain tokens that were sent here by mistake /// because people will. /// @param _token address of token to transfer /// @param _to address where tokens will be transferred function drainToken(address _token, address _to) onlyOwner { if (_token == address(0)) throw; if (_to == address(0)) throw; ERC20 token = ERC20(_token); uint256 balance = token.balanceOf(this); token.transfer(_to, balance); TokenDrain(_token, _to, balance); } }
transfer tokens only allowed after sale has ended
function transfer(address _to, uint _value) onlyAfterSale returns (bool) { return super.transfer(_to, _value); }
12,701,788
[ 1, 13866, 2430, 1338, 2935, 1839, 272, 5349, 711, 16926, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 7412, 12, 2867, 389, 869, 16, 2254, 389, 1132, 13, 1338, 4436, 30746, 1135, 261, 6430, 13, 288, 203, 3639, 327, 2240, 18, 13866, 24899, 869, 16, 389, 1132, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2022-01-07 */ // contracts/XChainTrade.sol // SPDX-License-Identifier: GPL-3.0 // This is the flattened NFT sale contract for XChain Tech NFTs (ID 0) // More info at https://xchain.tech and via email at [email protected] // To contact the XChain Tech Foundation: [email protected] pragma solidity ^0.8.7; // File: IXChainTrade.sol // XChain Tech Trade Contract interface IXChainTrade { function currentPrice() external view returns(uint256); function purchase() external payable; function withdraw(uint256 amount, address payable destAddr) external; function mint(address to, uint256 id, uint256 amount, uint lockedUntilTimestamp) external; function totalSupply(uint256 id) external view returns (uint256); } // File: Context.sol // OpenZeppelin Contracts v4.4.1 (utils/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 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: Address.sol // OpenZeppelin Contracts v4.4.1 (utils/Address.sol) /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: IERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: ERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: IERC1155Receiver.sol // OpenZeppelin Contracts v4.4.1 (token/ERC1155/IERC1155Receiver.sol) /** * @dev _Available since v3.1._ */ interface IERC1155Receiver is IERC165 { /** * @dev Handles the receipt of a single ERC1155 token type. This function is * called at the end of a `safeTransferFrom` after the balance has been updated. * * NOTE: To accept the transfer, this must return * `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` * (i.e. 0xf23a6e61, or its own function selector). * * @param operator The address which initiated the transfer (i.e. msg.sender) * @param from The address which previously owned the token * @param id The ID of the token being transferred * @param value The amount of tokens being transferred * @param data Additional data with no specified format * @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed */ function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external returns (bytes4); /** * @dev Handles the receipt of a multiple ERC1155 token types. This function * is called at the end of a `safeBatchTransferFrom` after the balances have * been updated. * * NOTE: To accept the transfer(s), this must return * `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` * (i.e. 0xbc197c81, or its own function selector). * * @param operator The address which initiated the batch transfer (i.e. msg.sender) * @param from The address which previously owned the token * @param ids An array containing ids of each token being transferred (order and length must match values array) * @param values An array containing amounts of each token being transferred (order and length must match ids array) * @param data Additional data with no specified format * @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed */ function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external returns (bytes4); } // File: IERC1155.sol // OpenZeppelin Contracts v4.4.1 (token/ERC1155/IERC1155.sol) /** * @dev Required interface of an ERC1155 compliant contract, as defined in the * https://eips.ethereum.org/EIPS/eip-1155[EIP]. * * _Available since v3.1._ */ interface IERC1155 is IERC165 { /** * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`. */ event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); /** * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all * transfers. */ event TransferBatch( address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values ); /** * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to * `approved`. */ event ApprovalForAll(address indexed account, address indexed operator, bool approved); /** * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI. * * If an {URI} event was emitted for `id`, the standard * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value * returned by {IERC1155MetadataURI-uri}. */ event URI(string value, uint256 indexed id); /** * @dev Returns the amount of tokens of token type `id` owned by `account`. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, * * Emits an {ApprovalForAll} event. * * Requirements: * * - `operator` cannot be the caller. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns true if `operator` is approved to transfer ``account``'s tokens. * * See {setApprovalForAll}. */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes calldata data ) external; /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function safeBatchTransferFrom( address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data ) external; } // File: IERC1155MetadataURI.sol // OpenZeppelin Contracts v4.4.1 (token/ERC1155/extensions/IERC1155MetadataURI.sol) /** * @dev Interface of the optional ERC1155MetadataExtension interface, as defined * in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP]. * * _Available since v3.1._ */ interface IERC1155MetadataURI is IERC1155 { /** * @dev Returns the URI for token type `id`. * * If the `\{id\}` substring is present in the URI, it must be replaced by * clients with the actual token type ID. */ function uri(uint256 id) external view returns (string memory); } // File: ERC1155.sol // OpenZeppelin Contracts v4.4.1 (token/ERC1155/ERC1155.sol) /** * @dev Implementation of the basic standard multi-token. * See https://eips.ethereum.org/EIPS/eip-1155 * Originally based on code by Enjin: https://github.com/enjin/erc-1155 * * _Available since v3.1._ */ contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI { using Address for address; // Mapping from token ID to account balances mapping(uint256 => mapping(address => uint256)) private _balances; // Mapping from account to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; // Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json string private _uri; /** * @dev See {_setURI}. */ constructor(string memory uri_) { _setURI(uri_); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC1155).interfaceId || interfaceId == type(IERC1155MetadataURI).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC1155MetadataURI-uri}. * * This implementation returns the same URI for *all* token types. It relies * on the token type ID substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * Clients calling this function must replace the `\{id\}` substring with the * actual token type ID. */ function uri(uint256) public view virtual override returns (string memory) { return _uri; } /** * @dev See {IERC1155-balanceOf}. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) public view virtual override returns (uint256) { require(account != address(0), "ERC1155: balance query for the zero address"); return _balances[id][account]; } /** * @dev See {IERC1155-balanceOfBatch}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] memory accounts, uint256[] memory ids) public view virtual override returns (uint256[] memory) { require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch"); uint256[] memory batchBalances = new uint256[](accounts.length); for (uint256 i = 0; i < accounts.length; ++i) { batchBalances[i] = balanceOf(accounts[i], ids[i]); } return batchBalances; } /** * @dev See {IERC1155-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC1155-isApprovedForAll}. */ function isApprovedForAll(address account, address operator) public view virtual override returns (bool) { return _operatorApprovals[account][operator]; } /** * @dev See {IERC1155-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) public virtual override { require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: caller is not owner nor approved" ); _safeTransferFrom(from, to, id, amount, data); } /** * @dev See {IERC1155-safeBatchTransferFrom}. */ function safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) public virtual override { require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: transfer caller is not owner nor approved" ); _safeBatchTransferFrom(from, to, ids, amounts, data); } /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: transfer to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data); uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: insufficient balance for transfer"); unchecked { _balances[id][from] = fromBalance - amount; } _balances[id][to] += amount; emit TransferSingle(operator, from, to, id, amount); _doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function _safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); require(to != address(0), "ERC1155: transfer to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, ids, amounts, data); for (uint256 i = 0; i < ids.length; ++i) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: insufficient balance for transfer"); unchecked { _balances[id][from] = fromBalance - amount; } _balances[id][to] += amount; } emit TransferBatch(operator, from, to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data); } /** * @dev Sets a new URI for all token types, by relying on the token type ID * substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * By this mechanism, any occurrence of the `\{id\}` substring in either the * URI or any of the amounts in the JSON file at said URI will be replaced by * clients with the token type ID. * * For example, the `https://token-cdn-domain/\{id\}.json` URI would be * interpreted by clients as * `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json` * for token type ID 0x4cce0. * * See {uri}. * * Because these URIs cannot be meaningfully represented by the {URI} event, * this function emits no events. */ function _setURI(string memory newuri) internal virtual { _uri = newuri; } /** * @dev Creates `amount` tokens of token type `id`, and assigns them to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _mint( address to, uint256 id, uint256 amount, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: mint to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), to, _asSingletonArray(id), _asSingletonArray(amount), data); _balances[id][to] += amount; emit TransferSingle(operator, address(0), to, id, amount); _doSafeTransferAcceptanceCheck(operator, address(0), to, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function _mintBatch( address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: mint to the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), to, ids, amounts, data); for (uint256 i = 0; i < ids.length; i++) { _balances[ids[i]][to] += amounts[i]; } emit TransferBatch(operator, address(0), to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data); } /** * @dev Destroys `amount` tokens of token type `id` from `from` * * Requirements: * * - `from` cannot be the zero address. * - `from` must have at least `amount` tokens of token type `id`. */ function _burn( address from, uint256 id, uint256 amount ) internal virtual { require(from != address(0), "ERC1155: burn from the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, address(0), _asSingletonArray(id), _asSingletonArray(amount), ""); uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: burn amount exceeds balance"); unchecked { _balances[id][from] = fromBalance - amount; } emit TransferSingle(operator, from, address(0), id, amount); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}. * * Requirements: * * - `ids` and `amounts` must have the same length. */ function _burnBatch( address from, uint256[] memory ids, uint256[] memory amounts ) internal virtual { require(from != address(0), "ERC1155: burn from the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, address(0), ids, amounts, ""); for (uint256 i = 0; i < ids.length; i++) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: burn amount exceeds balance"); unchecked { _balances[id][from] = fromBalance - amount; } } emit TransferBatch(operator, from, address(0), ids, amounts); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC1155: setting approval status for self"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Hook that is called before any token transfer. This includes minting * and burning, as well as batched variants. * * The same hook is called on both single and batched variants. For single * transfers, the length of the `id` and `amount` arrays will be 1. * * Calling conditions (for each `id` and `amount` pair): * * - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens * of token type `id` will be transferred to `to`. * - When `from` is zero, `amount` tokens of token type `id` will be minted * for `to`. * - when `to` is zero, `amount` of ``from``'s tokens of token type `id` * will be burned. * - `from` and `to` are never both zero. * - `ids` and `amounts` have the same, non-zero length. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual {} function _doSafeTransferAcceptanceCheck( address operator, address from, address to, uint256 id, uint256 amount, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) { if (response != IERC1155Receiver.onERC1155Received.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _doSafeBatchTransferAcceptanceCheck( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns ( bytes4 response ) { if (response != IERC1155Receiver.onERC1155BatchReceived.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) { uint256[] memory array = new uint256[](1); array[0] = element; return array; } } // File: XChainTrade.sol // contracts/XChainTrade.sol contract XChainTrade { mapping(address => uint256) public balances; ERC1155 token = ERC1155(0x930a9eb59E15Cd875532B26AEF73B006D4B82779); // This is the ERC 1155 NFT contract for XChain (you can find it also at xchainnft.eth) function currentPrice() public view returns(uint256) { uint256 price = 1 ether; if (block.timestamp < 1647302400) {price = 1 ether;} // if before start of sale period 15/03/2022 else if (block.timestamp > 1695686400) {price = 49.56144107 ether;} // if after end of sale period 26/09/2023 else { for (uint i=0; i < ((block.timestamp - 1647302400) / uint256(604800)); i++) { // given 48384000 epoch difference from start to end, and / by 80 weeks = 604800 price = price + ((price * 5) / 100); // price increase by 5 percent per week } } return price; } function purchase() public payable { XChain c = XChain(0x930a9eb59E15Cd875532B26AEF73B006D4B82779); // This is the ERC 1155 NFT contract for XChain (you can find it also at xchainnft.eth) uint minted = c.totalSupply(0); uint256 incwei = msg.value; uint256 price = currentPrice(); uint256 spent = 0; uint toBeMinted = 0; uint lockUntil = 0; bool done = false; // the contract will terminate if one of the following 3 checks fails require(minted < 50000, "Sold Out: Sorry all the XChain NFTs have been sold!"); // Maximum 5000 ID 0 NFTs will be minted require(block.timestamp >= 1642204800, "XChain: NFT presale not started yet!"); // If someone try to purchase a package before 15 January 2022 require(incwei >= price, "XChain: Not enough funds to perform a purchase!"); // if somoone sends less ETH than the price of a single NFT // The loop below is the heart of the token sale. The amount sent to the contract is looped and used to get the best deals first. // For example, sending 362 ETH March 23th 20200 (when pre-sale is still open, 1 NFT price is ETH 1.05, and sale is open too) the loop will generate // the purchase of a ETH 200 packet, thus 400 NFTs, // the purchase of a ETH 100 packet, thus +150 NFTs, // the purchase of a ETH 50 packet, thus +65 NFTs, // the purchase of a ETH 10 packet, thus +11 NFTs, // the purchase of a single NFT for 1.05 ETH, // for a total of 626 NFTs, leaving a balance of 0.95 ETH to the address while (incwei >= price || done) { // keeps looping until one of the below conditions is met if (incwei >= 200000000000000000000 && minted + 400 <= 5000 && block.timestamp < 1656547200) { // if someone sends more than 200 ETH and the date is before June 30, 2022 spent = spent + 200000000000000000000; // adds 200 ETH to the bill incwei = incwei - 200000000000000000000; // removes 200 ETH from the budget toBeMinted = toBeMinted + 400; // adds 400 NFTs to the amount of NFTs to be minted lockUntil = block.timestamp + 3888000; // lock the account for 45 days since the current time } else if (incwei >= 100000000000000000000 && minted + 150 <= 5000 && block.timestamp < 1656547200) { // else if someone sends more than 100 ETH and the date is before June 30, 2022 spent = spent + 100000000000000000000; // adds 100 ETH to the bill incwei = incwei - 100000000000000000000; // removes 100 ETH from the budget toBeMinted = toBeMinted + 150; // adds 150 NFTs to the amount of NFTs to be minted if (lockUntil < block.timestamp + 2592000) {lockUntil = block.timestamp + 2592000;} } else if (incwei >= 50000000000000000000 && minted + 65 <= 5000 && block.timestamp < 1656547200) { // else if someone sends more than 50 ETH and the date is before June 30, 2022 spent = spent + 50000000000000000000; // adds 50 ETH to the bill incwei = incwei - 50000000000000000000; // removes 50 ETH from the budget toBeMinted = toBeMinted + 65; // adds 65 NFTs to the amount of NFTs to be minted if (lockUntil < block.timestamp + 1728000) {lockUntil = block.timestamp + 1728000;} } else if (incwei >= 10000000000000000000 && minted + 11 <= 5000 && block.timestamp < 1656547200) { // else if someone sends more than 10 ETH and the date is before June 30, 2022 spent = spent + 10000000000000000000; // adds 10 ETH to the bill incwei = incwei - 10000000000000000000; // removes 10 ETH from the budget toBeMinted = toBeMinted + 11; // adds 11 NFTs to the amount of NFTs to be minted if (lockUntil < block.timestamp + 864000) {lockUntil = block.timestamp + 864000;} } else if (incwei >= price && minted + 1 <= 5000 && block.timestamp > 1647302400) { // else if someone sends more than current NFT price and the date is after March 15, 2022 spent = spent + price; // adds the current price of 1 NFT to the bill incwei = incwei - price; // removes the current price of 1 NFT from the budget toBeMinted = toBeMinted + 1; // adds 1 NFT to the amount of NFTs to be minted if (lockUntil < 1643068800) {lockUntil = 1643068800;} // if account lock time is before Jan 25th 2022, set it at Jan 25th 2022 } else { done = true; // if none of the previous conditions is met, exit the loop } } // the contract will terminate if one of the following 4 checks fails require(toBeMinted > 0, "XChain: Sorry you didn't manage to purchase any NFT!"); // if somehow someone has managed to go through the loop and come out with 0 NFTs to be minted require(toBeMinted + minted <= 5000, "XChain: Sorry your ourchase went above the total 5000 NFTs limit!"); // if someone managed to go through the loop and purchase more than the available NFTs require(msg.value == spent + incwei, "XChain: PANIC something wrong with money math. Exiting"); // if somehow the amount spent plus the change is different than the amount sent require(lockUntil > 0, "XChain: PANIC something wrong with lock time math. Exiting"); // if the date the account is locked is not being set balances[0x8b8E1624814975aD4D52BFFA7c38C05101675bB7] += spent; // XChainTech.eth gets the amount spent in its balance balances[msg.sender] += incwei; // the account that made the purchase gets the change in its balance c.mint(msg.sender, 0, toBeMinted, lockUntil); // the NFTs are minted and the account locked until the longest date. } // This is the function to withdraw funds from an account balance function withdraw(uint256 amount, address payable destAddr) public { require(amount <= balances[msg.sender], "XChain: Not enough balance. Withdraw a lower amount."); balances[msg.sender] -= amount; destAddr.transfer(amount); } } contract XChain { function mint(address to, uint256 id, uint256 amount, uint lockedUntilTimestamp) public virtual {} function totalSupply(uint256 id) public view virtual returns (uint256) {} }
lock the account for 45 days since the current time
lockUntil = block.timestamp + 3888000;
10,838,252
[ 1, 739, 326, 2236, 364, 12292, 4681, 3241, 326, 783, 813, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 7734, 2176, 9716, 273, 1203, 18, 5508, 397, 890, 5482, 26021, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.24; // File: contracts/lib/ownership/Ownable.sol 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 contract other than latest designated caller 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/lib/ownership/ZapCoordinatorInterface.sol contract ZapCoordinatorInterface is Ownable { function addImmutableContract(string contractName, address newAddress) external; function updateContract(string contractName, address newAddress) external; function getContractName(uint index) public view returns (string); function getContract(string contractName) public view returns (address); function updateAllDependencies() external; } // File: contracts/lib/ownership/Upgradable.sol pragma solidity ^0.4.24; contract Upgradable { address coordinatorAddr; ZapCoordinatorInterface coordinator; constructor(address c) public{ coordinatorAddr = c; coordinator = ZapCoordinatorInterface(c); } function updateDependencies() external coordinatorOnly { _updateDependencies(); } function _updateDependencies() internal; modifier coordinatorOnly() { require(msg.sender == coordinatorAddr, "Error: Coordinator Only Function"); _; } } // File: contracts/lib/lifecycle/Destructible.sol contract Destructible is Ownable { function selfDestruct() public onlyOwner { selfdestruct(owner); } } // File: contracts/lib/platform/Client.sol contract Client1 { /// @dev callback that provider will call after Dispatch.query() call /// @param id request id /// @param response1 first provider-specified param function callback(uint256 id, string response1) external; } contract Client2 { /// @dev callback that provider will call after Dispatch.query() call /// @param id request id /// @param response1 first provider-specified param /// @param response2 second provider-specified param function callback(uint256 id, string response1, string response2) external; } contract Client3 { /// @dev callback that provider will call after Dispatch.query() call /// @param id request id /// @param response1 first provider-specified param /// @param response2 second provider-specified param /// @param response3 third provider-specified param function callback(uint256 id, string response1, string response2, string response3) external; } contract Client4 { /// @dev callback that provider will call after Dispatch.query() call /// @param id request id /// @param response1 first provider-specified param /// @param response2 second provider-specified param /// @param response3 third provider-specified param /// @param response4 fourth provider-specified param function callback(uint256 id, string response1, string response2, string response3, string response4) external; } contract ClientBytes32Array { /// @dev callback that provider will call after Dispatch.query() call /// @param id request id /// @param response bytes32 array function callback(uint256 id, bytes32[] response) external; } contract ClientIntArray{ /// @dev callback that provider will call after Dispatch.query() call /// @param id request id /// @param response int array function callback(uint256 id, int[] response) external; } // File: contracts/lib/platform/OnChainProvider.sol contract OnChainProvider { /// @dev function for requesting data from on-chain provider /// @param id request id /// @param userQuery query string /// @param endpoint endpoint specifier ala 'smart_contract' /// @param endpointParams endpoint-specific params function receive(uint256 id, string userQuery, bytes32 endpoint, bytes32[] endpointParams, bool onchainSubscriber) external; } // File: contracts/platform/bondage/BondageInterface.sol contract BondageInterface { function bond(address, bytes32, uint256) external returns(uint256); function unbond(address, bytes32, uint256) external returns (uint256); function delegateBond(address, address, bytes32, uint256) external returns(uint256); function escrowDots(address, address, bytes32, uint256) external returns (bool); function releaseDots(address, address, bytes32, uint256) external returns (bool); function returnDots(address, address, bytes32, uint256) external returns (bool success); function calcZapForDots(address, bytes32, uint256) external view returns (uint256); function currentCostOfDot(address, bytes32, uint256) public view returns (uint256); function getDotsIssued(address, bytes32) public view returns (uint256); function getBoundDots(address, address, bytes32) public view returns (uint256); function getZapBound(address, bytes32) public view returns (uint256); function dotLimit( address, bytes32) public view returns (uint256); } // File: contracts/platform/dispatch/DispatchInterface.sol interface DispatchInterface { function query(address, string, bytes32, bytes32[]) external returns (uint256); function respond1(uint256, string) external returns (bool); function respond2(uint256, string, string) external returns (bool); function respond3(uint256, string, string, string) external returns (bool); function respond4(uint256, string, string, string, string) external returns (bool); function respondBytes32Array(uint256, bytes32[]) external returns (bool); function respondIntArray(uint256,int[] ) external returns (bool); function cancelQuery(uint256) external; function getProvider(uint256 id) public view returns (address); function getSubscriber(uint256 id) public view returns (address); function getEndpoint(uint256 id) public view returns (bytes32); function getStatus(uint256 id) public view returns (uint256); function getCancel(uint256 id) public view returns (uint256); function getUserQuery(uint256 id) public view returns (string); function getSubscriberOnchain(uint256 id) public view returns (bool); } // File: contracts/platform/database/DatabaseInterface.sol contract DatabaseInterface is Ownable { function setStorageContract(address _storageContract, bool _allowed) public; /*** Bytes32 ***/ function getBytes32(bytes32 key) external view returns(bytes32); function setBytes32(bytes32 key, bytes32 value) external; /*** Number **/ function getNumber(bytes32 key) external view returns(uint256); function setNumber(bytes32 key, uint256 value) external; /*** Bytes ***/ function getBytes(bytes32 key) external view returns(bytes); function setBytes(bytes32 key, bytes value) external; /*** String ***/ function getString(bytes32 key) external view returns(string); function setString(bytes32 key, string value) external; /*** Bytes Array ***/ function getBytesArray(bytes32 key) external view returns (bytes32[]); function getBytesArrayIndex(bytes32 key, uint256 index) external view returns (bytes32); function getBytesArrayLength(bytes32 key) external view returns (uint256); function pushBytesArray(bytes32 key, bytes32 value) external; function setBytesArrayIndex(bytes32 key, uint256 index, bytes32 value) external; function setBytesArray(bytes32 key, bytes32[] value) external; /*** Int Array ***/ function getIntArray(bytes32 key) external view returns (int[]); function getIntArrayIndex(bytes32 key, uint256 index) external view returns (int); function getIntArrayLength(bytes32 key) external view returns (uint256); function pushIntArray(bytes32 key, int value) external; function setIntArrayIndex(bytes32 key, uint256 index, int value) external; function setIntArray(bytes32 key, int[] value) external; /*** Address Array ***/ function getAddressArray(bytes32 key) external view returns (address[]); function getAddressArrayIndex(bytes32 key, uint256 index) external view returns (address); function getAddressArrayLength(bytes32 key) external view returns (uint256); function pushAddressArray(bytes32 key, address value) external; function setAddressArrayIndex(bytes32 key, uint256 index, address value) external; function setAddressArray(bytes32 key, address[] value) external; } // File: contracts/platform/dispatch/Dispatch.sol // v1.0 contract Dispatch is Destructible, DispatchInterface, Upgradable { enum Status { Pending, Fulfilled, Canceled } //event data provider is listening for, containing all relevant request parameters event Incoming( uint256 indexed id, address indexed provider, address indexed subscriber, string query, bytes32 endpoint, bytes32[] endpointParams, bool onchainSubscriber ); event FulfillQuery( address indexed subscriber, address indexed provider, bytes32 indexed endpoint ); event OffchainResponse( uint256 indexed id, address indexed subscriber, address indexed provider, bytes32[] response ); event OffchainResponseInt( uint256 indexed id, address indexed subscriber, address indexed provider, int[] response ); event OffchainResult1( uint256 indexed id, address indexed subscriber, address indexed provider, string response1 ); event OffchainResult2( uint256 indexed id, address indexed subscriber, address indexed provider, string response1, string response2 ); event OffchainResult3( uint256 indexed id, address indexed subscriber, address indexed provider, string response1, string response2, string response3 ); event OffchainResult4( uint256 indexed id, address indexed subscriber, address indexed provider, string response1, string response2, string response3, string response4 ); event CanceledRequest( uint256 indexed id, address indexed subscriber, address indexed provider ); event RevertCancelation( uint256 indexed id, address indexed subscriber, address indexed provider ); BondageInterface public bondage; address public bondageAddress; DatabaseInterface public db; constructor(address c) Upgradable(c) public { //_updateDependencies(); } function _updateDependencies() internal { address databaseAddress = coordinator.getContract("DATABASE"); db = DatabaseInterface(databaseAddress); bondageAddress = coordinator.getContract("BONDAGE"); bondage = BondageInterface(bondageAddress); } /// @notice Escrow dot for oracle request /// @dev Called by user contract function query( address provider, // data provider address string userQuery, // query string bytes32 endpoint, // endpoint specifier ala 'smart_contract' bytes32[] endpointParams // endpoint-specific params ) external returns (uint256 id) { uint256 dots = bondage.getBoundDots(msg.sender, provider, endpoint); bool onchainProvider = isContract(provider); bool onchainSubscriber = isContract(msg.sender); if(dots >= 1) { //enough dots bondage.escrowDots(msg.sender, provider, endpoint, 1); id = uint256(keccak256(abi.encodePacked(block.number, now, userQuery, msg.sender, provider))); createQuery(id, provider, msg.sender, endpoint, userQuery, onchainSubscriber); if(onchainProvider) { OnChainProvider(provider).receive(id, userQuery, endpoint, endpointParams, onchainSubscriber); } else{ emit Incoming(id, provider, msg.sender, userQuery, endpoint, endpointParams, onchainSubscriber); } } else { // NOT ENOUGH DOTS revert("Subscriber does not have any dots."); } } /// @notice Transfer dots from Bondage escrow to data provider's Holder object under its own address /// @dev Called upon data-provider request fulfillment function fulfillQuery(uint256 id) private returns (bool) { Status status = Status(getStatus(id)); require(status != Status.Fulfilled, "Error: Status already fulfilled"); address subscriber = getSubscriber(id); address provider = getProvider(id); bytes32 endpoint = getEndpoint(id); if ( status == Status.Canceled ) { uint256 canceled = getCancel(id); // Make sure we've canceled in the past, // if it's current block ignore the cancel require(block.number == canceled, "Error: Cancel ignored"); // Uncancel the query setCanceled(id, false); // Re-escrow the previously returned dots bondage.escrowDots(subscriber, provider, endpoint, 1); // Emit the events emit RevertCancelation(id, subscriber, provider); } setFulfilled(id); bondage.releaseDots(subscriber, provider, endpoint, 1); emit FulfillQuery(subscriber, provider, endpoint); return true; } /// @notice Cancel a query. /// @dev If responded on the same block, ignore the cancel. function cancelQuery(uint256 id) external { address subscriber = getSubscriber(id); address provider = getProvider(id); bytes32 endpoint = getEndpoint(id); require(subscriber == msg.sender, "Error: Wrong subscriber"); require(Status(getStatus(id)) == Status.Pending, "Error: Query is not pending"); // Cancel the query setCanceled(id, true); // Return the dots to the subscriber bondage.returnDots(subscriber, provider, endpoint, 1); // Release an event emit CanceledRequest(id, getSubscriber(id), getProvider(id)); } /// @dev Parameter-count specific method called by data provider in response function respondBytes32Array( uint256 id, bytes32[] response ) external returns (bool) { if (getProvider(id) != msg.sender || !fulfillQuery(id)) revert(); if(getSubscriberOnchain(id)) { ClientBytes32Array(getSubscriber(id)).callback(id, response); } else { emit OffchainResponse(id, getSubscriber(id), msg.sender, response); } return true; } /// @dev Parameter-count specific method called by data provider in response function respondIntArray( uint256 id, int[] response ) external returns (bool) { if (getProvider(id) != msg.sender || !fulfillQuery(id)) revert(); if(getSubscriberOnchain(id)) { ClientIntArray(getSubscriber(id)).callback(id, response); } else { emit OffchainResponseInt(id, getSubscriber(id), msg.sender, response); } return true; } /// @dev Parameter-count specific method called by data provider in response function respond1( uint256 id, string response ) external returns (bool) { if (getProvider(id) != msg.sender || !fulfillQuery(id)) revert(); if(getSubscriberOnchain(id)) { Client1(getSubscriber(id)).callback(id, response); } else { emit OffchainResult1(id, getSubscriber(id), msg.sender, response); } return true; } /// @dev Parameter-count specific method called by data provider in response function respond2( uint256 id, string response1, string response2 ) external returns (bool) { if (getProvider(id) != msg.sender || !fulfillQuery(id)) revert(); if(getSubscriberOnchain(id)) { Client2(getSubscriber(id)).callback(id, response1, response2); } else { emit OffchainResult2(id, getSubscriber(id), msg.sender, response1, response2); } return true; } /// @dev Parameter-count specific method called by data provider in response function respond3( uint256 id, string response1, string response2, string response3 ) external returns (bool) { if (getProvider(id) != msg.sender || !fulfillQuery(id)) revert(); if(getSubscriberOnchain(id)) { Client3(getSubscriber(id)).callback(id, response1, response2, response3); } else { emit OffchainResult3(id, getSubscriber(id), msg.sender, response1, response2, response3); } return true; } /// @dev Parameter-count specific method called by data provider in response function respond4( uint256 id, string response1, string response2, string response3, string response4 ) external returns (bool) { if (getProvider(id) != msg.sender || !fulfillQuery(id)) revert(); if(getSubscriberOnchain(id)) { Client4(getSubscriber(id)).callback(id, response1, response2, response3, response4); } else { emit OffchainResult4(id, getSubscriber(id), msg.sender, response1, response2, response3, response4); } return true; } /*** STORAGE METHODS ***/ /// @dev get provider address of request /// @param id request id function getProvider(uint256 id) public view returns (address) { return address(db.getNumber(keccak256(abi.encodePacked('queries', id, 'provider')))); } /// @dev get subscriber address of request /// @param id request id function getSubscriber(uint256 id) public view returns (address) { return address(db.getNumber(keccak256(abi.encodePacked('queries', id, 'subscriber')))); } /// @dev get endpoint of request /// @param id request id function getEndpoint(uint256 id) public view returns (bytes32) { return db.getBytes32(keccak256(abi.encodePacked('queries', id, 'endpoint'))); } /// @dev get status of request /// @param id request id function getStatus(uint256 id) public view returns (uint256) { return db.getNumber(keccak256(abi.encodePacked('queries', id, 'status'))); } /// @dev get the cancelation block of a request /// @param id request id function getCancel(uint256 id) public view returns (uint256) { return db.getNumber(keccak256(abi.encodePacked('queries', id, 'cancelBlock'))); } /// @dev get user specified query of request /// @param id request id function getUserQuery(uint256 id) public view returns (string) { return db.getString(keccak256(abi.encodePacked('queries', id, 'userQuery'))); } /// @dev is subscriber contract or offchain /// @param id request id function getSubscriberOnchain(uint256 id) public view returns (bool) { uint res = db.getNumber(keccak256(abi.encodePacked('queries', id, 'onchainSubscriber'))); return res == 1 ? true : false; } /**** Set Methods ****/ function createQuery( uint256 id, address provider, address subscriber, bytes32 endpoint, string userQuery, bool onchainSubscriber ) private { db.setNumber(keccak256(abi.encodePacked('queries', id, 'provider')), uint256(provider)); db.setNumber(keccak256(abi.encodePacked('queries', id, 'subscriber')), uint256(subscriber)); db.setBytes32(keccak256(abi.encodePacked('queries', id, 'endpoint')), endpoint); db.setString(keccak256(abi.encodePacked('queries', id, 'userQuery')), userQuery); db.setNumber(keccak256(abi.encodePacked('queries', id, 'status')), uint256(Status.Pending)); db.setNumber(keccak256(abi.encodePacked('queries', id, 'onchainSubscriber')), onchainSubscriber ? 1 : 0); } function setFulfilled(uint256 id) private { db.setNumber(keccak256(abi.encodePacked('queries', id, 'status')), uint256(Status.Fulfilled)); } function setCanceled(uint256 id, bool canceled) private { if ( canceled ) { db.setNumber(keccak256(abi.encodePacked('queries', id, 'cancelBlock')), block.number); db.setNumber(keccak256(abi.encodePacked('queries', id, 'status')), uint256(Status.Canceled)); } else { db.setNumber(keccak256(abi.encodePacked('queries', id, 'cancelBlock')), 0); db.setNumber(keccak256(abi.encodePacked('queries', id, 'status')), uint256(Status.Pending)); } } function isContract(address addr) private view returns (bool) { uint size; assembly { size := extcodesize(addr) } return size > 0; } } /* /* For use in example contract, see TestContracts.sol /* /* When User Contract calls ZapDispatch.query(), /* 1 oracle specific dot is escrowed by ZapBondage and Incoming event is ted. /* /* When provider's client hears an Incoming event containing provider's address and responds, /* the provider calls a ZapDispatch.respondX function corresponding to number of response params. /* /* Dots are moved from ZapBondage escrow to data-provider's bond Holder struct, /* with data provider address set as self's address. /*/ /*************************************** STORAGE **************************************** * 'queries', id, 'provider' => {address} address of provider that this query was sent to * 'queries', id, 'subscriber' => {address} address of subscriber that this query was sent by * 'queries', id, 'endpoint' => {bytes32} endpoint that this query was sent to * 'queries', id, 'status' => {Status} current status of this query * 'queries', id, 'cancelBlock' => {uint256} the block number of the cancellation request (0 if none) * 'queries', id, 'userQuery' => {uint256} the query that was sent with this queryId * 'queries', id, 'onchainSubscriber' => {uint256} 1 -> onchainSubscriber, 0 -> offchainSubscriber ****************************************************************************************/
event data provider is listening for, containing all relevant request parameters
contract Dispatch is Destructible, DispatchInterface, Upgradable { event Incoming( uint256 indexed id, address indexed provider, address indexed subscriber, string query, bytes32 endpoint, bytes32[] endpointParams, bool onchainSubscriber ); event FulfillQuery( address indexed subscriber, address indexed provider, bytes32 indexed endpoint ); event OffchainResponse( uint256 indexed id, address indexed subscriber, address indexed provider, bytes32[] response ); event OffchainResponseInt( uint256 indexed id, address indexed subscriber, address indexed provider, int[] response ); event OffchainResult1( uint256 indexed id, address indexed subscriber, address indexed provider, string response1 ); event OffchainResult2( uint256 indexed id, address indexed subscriber, address indexed provider, string response1, string response2 ); event OffchainResult3( uint256 indexed id, address indexed subscriber, address indexed provider, string response1, string response2, string response3 ); event OffchainResult4( uint256 indexed id, address indexed subscriber, address indexed provider, string response1, string response2, string response3, string response4 ); event CanceledRequest( uint256 indexed id, address indexed subscriber, address indexed provider ); event RevertCancelation( uint256 indexed id, address indexed subscriber, address indexed provider ); BondageInterface public bondage; address public bondageAddress; DatabaseInterface public db; } enum Status { Pending, Fulfilled, Canceled } constructor(address c) Upgradable(c) public { } function _updateDependencies() internal { address databaseAddress = coordinator.getContract("DATABASE"); db = DatabaseInterface(databaseAddress); bondageAddress = coordinator.getContract("BONDAGE"); bondage = BondageInterface(bondageAddress); } function query( ) external returns (uint256 id) { uint256 dots = bondage.getBoundDots(msg.sender, provider, endpoint); bool onchainProvider = isContract(provider); bool onchainSubscriber = isContract(msg.sender); if(dots >= 1) { bondage.escrowDots(msg.sender, provider, endpoint, 1); id = uint256(keccak256(abi.encodePacked(block.number, now, userQuery, msg.sender, provider))); createQuery(id, provider, msg.sender, endpoint, userQuery, onchainSubscriber); if(onchainProvider) { OnChainProvider(provider).receive(id, userQuery, endpoint, endpointParams, onchainSubscriber); emit Incoming(id, provider, msg.sender, userQuery, endpoint, endpointParams, onchainSubscriber); } revert("Subscriber does not have any dots."); } } function query( ) external returns (uint256 id) { uint256 dots = bondage.getBoundDots(msg.sender, provider, endpoint); bool onchainProvider = isContract(provider); bool onchainSubscriber = isContract(msg.sender); if(dots >= 1) { bondage.escrowDots(msg.sender, provider, endpoint, 1); id = uint256(keccak256(abi.encodePacked(block.number, now, userQuery, msg.sender, provider))); createQuery(id, provider, msg.sender, endpoint, userQuery, onchainSubscriber); if(onchainProvider) { OnChainProvider(provider).receive(id, userQuery, endpoint, endpointParams, onchainSubscriber); emit Incoming(id, provider, msg.sender, userQuery, endpoint, endpointParams, onchainSubscriber); } revert("Subscriber does not have any dots."); } } function query( ) external returns (uint256 id) { uint256 dots = bondage.getBoundDots(msg.sender, provider, endpoint); bool onchainProvider = isContract(provider); bool onchainSubscriber = isContract(msg.sender); if(dots >= 1) { bondage.escrowDots(msg.sender, provider, endpoint, 1); id = uint256(keccak256(abi.encodePacked(block.number, now, userQuery, msg.sender, provider))); createQuery(id, provider, msg.sender, endpoint, userQuery, onchainSubscriber); if(onchainProvider) { OnChainProvider(provider).receive(id, userQuery, endpoint, endpointParams, onchainSubscriber); emit Incoming(id, provider, msg.sender, userQuery, endpoint, endpointParams, onchainSubscriber); } revert("Subscriber does not have any dots."); } } } else{ function fulfillQuery(uint256 id) private returns (bool) { Status status = Status(getStatus(id)); require(status != Status.Fulfilled, "Error: Status already fulfilled"); address subscriber = getSubscriber(id); address provider = getProvider(id); bytes32 endpoint = getEndpoint(id); if ( status == Status.Canceled ) { uint256 canceled = getCancel(id); require(block.number == canceled, "Error: Cancel ignored"); setCanceled(id, false); bondage.escrowDots(subscriber, provider, endpoint, 1); emit RevertCancelation(id, subscriber, provider); } setFulfilled(id); bondage.releaseDots(subscriber, provider, endpoint, 1); emit FulfillQuery(subscriber, provider, endpoint); return true; } function fulfillQuery(uint256 id) private returns (bool) { Status status = Status(getStatus(id)); require(status != Status.Fulfilled, "Error: Status already fulfilled"); address subscriber = getSubscriber(id); address provider = getProvider(id); bytes32 endpoint = getEndpoint(id); if ( status == Status.Canceled ) { uint256 canceled = getCancel(id); require(block.number == canceled, "Error: Cancel ignored"); setCanceled(id, false); bondage.escrowDots(subscriber, provider, endpoint, 1); emit RevertCancelation(id, subscriber, provider); } setFulfilled(id); bondage.releaseDots(subscriber, provider, endpoint, 1); emit FulfillQuery(subscriber, provider, endpoint); return true; } function cancelQuery(uint256 id) external { address subscriber = getSubscriber(id); address provider = getProvider(id); bytes32 endpoint = getEndpoint(id); require(subscriber == msg.sender, "Error: Wrong subscriber"); require(Status(getStatus(id)) == Status.Pending, "Error: Query is not pending"); setCanceled(id, true); bondage.returnDots(subscriber, provider, endpoint, 1); emit CanceledRequest(id, getSubscriber(id), getProvider(id)); } function respondBytes32Array( uint256 id, bytes32[] response ) external returns (bool) { if (getProvider(id) != msg.sender || !fulfillQuery(id)) revert(); if(getSubscriberOnchain(id)) { ClientBytes32Array(getSubscriber(id)).callback(id, response); } else { emit OffchainResponse(id, getSubscriber(id), msg.sender, response); } return true; } function respondBytes32Array( uint256 id, bytes32[] response ) external returns (bool) { if (getProvider(id) != msg.sender || !fulfillQuery(id)) revert(); if(getSubscriberOnchain(id)) { ClientBytes32Array(getSubscriber(id)).callback(id, response); } else { emit OffchainResponse(id, getSubscriber(id), msg.sender, response); } return true; } function respondBytes32Array( uint256 id, bytes32[] response ) external returns (bool) { if (getProvider(id) != msg.sender || !fulfillQuery(id)) revert(); if(getSubscriberOnchain(id)) { ClientBytes32Array(getSubscriber(id)).callback(id, response); } else { emit OffchainResponse(id, getSubscriber(id), msg.sender, response); } return true; } function respondIntArray( uint256 id, int[] response ) external returns (bool) { if (getProvider(id) != msg.sender || !fulfillQuery(id)) revert(); if(getSubscriberOnchain(id)) { ClientIntArray(getSubscriber(id)).callback(id, response); } else { emit OffchainResponseInt(id, getSubscriber(id), msg.sender, response); } return true; } function respondIntArray( uint256 id, int[] response ) external returns (bool) { if (getProvider(id) != msg.sender || !fulfillQuery(id)) revert(); if(getSubscriberOnchain(id)) { ClientIntArray(getSubscriber(id)).callback(id, response); } else { emit OffchainResponseInt(id, getSubscriber(id), msg.sender, response); } return true; } function respondIntArray( uint256 id, int[] response ) external returns (bool) { if (getProvider(id) != msg.sender || !fulfillQuery(id)) revert(); if(getSubscriberOnchain(id)) { ClientIntArray(getSubscriber(id)).callback(id, response); } else { emit OffchainResponseInt(id, getSubscriber(id), msg.sender, response); } return true; } function respond1( uint256 id, string response ) external returns (bool) { if (getProvider(id) != msg.sender || !fulfillQuery(id)) revert(); if(getSubscriberOnchain(id)) { Client1(getSubscriber(id)).callback(id, response); } else { emit OffchainResult1(id, getSubscriber(id), msg.sender, response); } return true; } function respond1( uint256 id, string response ) external returns (bool) { if (getProvider(id) != msg.sender || !fulfillQuery(id)) revert(); if(getSubscriberOnchain(id)) { Client1(getSubscriber(id)).callback(id, response); } else { emit OffchainResult1(id, getSubscriber(id), msg.sender, response); } return true; } function respond1( uint256 id, string response ) external returns (bool) { if (getProvider(id) != msg.sender || !fulfillQuery(id)) revert(); if(getSubscriberOnchain(id)) { Client1(getSubscriber(id)).callback(id, response); } else { emit OffchainResult1(id, getSubscriber(id), msg.sender, response); } return true; } function respond2( uint256 id, string response1, string response2 ) external returns (bool) { if (getProvider(id) != msg.sender || !fulfillQuery(id)) revert(); if(getSubscriberOnchain(id)) { Client2(getSubscriber(id)).callback(id, response1, response2); } else { emit OffchainResult2(id, getSubscriber(id), msg.sender, response1, response2); } return true; } function respond2( uint256 id, string response1, string response2 ) external returns (bool) { if (getProvider(id) != msg.sender || !fulfillQuery(id)) revert(); if(getSubscriberOnchain(id)) { Client2(getSubscriber(id)).callback(id, response1, response2); } else { emit OffchainResult2(id, getSubscriber(id), msg.sender, response1, response2); } return true; } function respond2( uint256 id, string response1, string response2 ) external returns (bool) { if (getProvider(id) != msg.sender || !fulfillQuery(id)) revert(); if(getSubscriberOnchain(id)) { Client2(getSubscriber(id)).callback(id, response1, response2); } else { emit OffchainResult2(id, getSubscriber(id), msg.sender, response1, response2); } return true; } function respond3( uint256 id, string response1, string response2, string response3 ) external returns (bool) { if (getProvider(id) != msg.sender || !fulfillQuery(id)) revert(); if(getSubscriberOnchain(id)) { Client3(getSubscriber(id)).callback(id, response1, response2, response3); } else { emit OffchainResult3(id, getSubscriber(id), msg.sender, response1, response2, response3); } return true; } function respond3( uint256 id, string response1, string response2, string response3 ) external returns (bool) { if (getProvider(id) != msg.sender || !fulfillQuery(id)) revert(); if(getSubscriberOnchain(id)) { Client3(getSubscriber(id)).callback(id, response1, response2, response3); } else { emit OffchainResult3(id, getSubscriber(id), msg.sender, response1, response2, response3); } return true; } function respond3( uint256 id, string response1, string response2, string response3 ) external returns (bool) { if (getProvider(id) != msg.sender || !fulfillQuery(id)) revert(); if(getSubscriberOnchain(id)) { Client3(getSubscriber(id)).callback(id, response1, response2, response3); } else { emit OffchainResult3(id, getSubscriber(id), msg.sender, response1, response2, response3); } return true; } function respond4( uint256 id, string response1, string response2, string response3, string response4 ) external returns (bool) { if (getProvider(id) != msg.sender || !fulfillQuery(id)) revert(); if(getSubscriberOnchain(id)) { Client4(getSubscriber(id)).callback(id, response1, response2, response3, response4); } else { emit OffchainResult4(id, getSubscriber(id), msg.sender, response1, response2, response3, response4); } return true; } function respond4( uint256 id, string response1, string response2, string response3, string response4 ) external returns (bool) { if (getProvider(id) != msg.sender || !fulfillQuery(id)) revert(); if(getSubscriberOnchain(id)) { Client4(getSubscriber(id)).callback(id, response1, response2, response3, response4); } else { emit OffchainResult4(id, getSubscriber(id), msg.sender, response1, response2, response3, response4); } return true; } function respond4( uint256 id, string response1, string response2, string response3, string response4 ) external returns (bool) { if (getProvider(id) != msg.sender || !fulfillQuery(id)) revert(); if(getSubscriberOnchain(id)) { Client4(getSubscriber(id)).callback(id, response1, response2, response3, response4); } else { emit OffchainResult4(id, getSubscriber(id), msg.sender, response1, response2, response3, response4); } return true; } function getProvider(uint256 id) public view returns (address) { return address(db.getNumber(keccak256(abi.encodePacked('queries', id, 'provider')))); } function getSubscriber(uint256 id) public view returns (address) { return address(db.getNumber(keccak256(abi.encodePacked('queries', id, 'subscriber')))); } function getEndpoint(uint256 id) public view returns (bytes32) { return db.getBytes32(keccak256(abi.encodePacked('queries', id, 'endpoint'))); } function getStatus(uint256 id) public view returns (uint256) { return db.getNumber(keccak256(abi.encodePacked('queries', id, 'status'))); } function getCancel(uint256 id) public view returns (uint256) { return db.getNumber(keccak256(abi.encodePacked('queries', id, 'cancelBlock'))); } function getUserQuery(uint256 id) public view returns (string) { return db.getString(keccak256(abi.encodePacked('queries', id, 'userQuery'))); } function getSubscriberOnchain(uint256 id) public view returns (bool) { uint res = db.getNumber(keccak256(abi.encodePacked('queries', id, 'onchainSubscriber'))); return res == 1 ? true : false; } function createQuery( uint256 id, address provider, address subscriber, bytes32 endpoint, string userQuery, bool onchainSubscriber ) private { db.setNumber(keccak256(abi.encodePacked('queries', id, 'provider')), uint256(provider)); db.setNumber(keccak256(abi.encodePacked('queries', id, 'subscriber')), uint256(subscriber)); db.setBytes32(keccak256(abi.encodePacked('queries', id, 'endpoint')), endpoint); db.setString(keccak256(abi.encodePacked('queries', id, 'userQuery')), userQuery); db.setNumber(keccak256(abi.encodePacked('queries', id, 'status')), uint256(Status.Pending)); db.setNumber(keccak256(abi.encodePacked('queries', id, 'onchainSubscriber')), onchainSubscriber ? 1 : 0); } function setFulfilled(uint256 id) private { db.setNumber(keccak256(abi.encodePacked('queries', id, 'status')), uint256(Status.Fulfilled)); } function setCanceled(uint256 id, bool canceled) private { if ( canceled ) { db.setNumber(keccak256(abi.encodePacked('queries', id, 'cancelBlock')), block.number); db.setNumber(keccak256(abi.encodePacked('queries', id, 'status')), uint256(Status.Canceled)); } else { db.setNumber(keccak256(abi.encodePacked('queries', id, 'cancelBlock')), 0); db.setNumber(keccak256(abi.encodePacked('queries', id, 'status')), uint256(Status.Pending)); } } function setCanceled(uint256 id, bool canceled) private { if ( canceled ) { db.setNumber(keccak256(abi.encodePacked('queries', id, 'cancelBlock')), block.number); db.setNumber(keccak256(abi.encodePacked('queries', id, 'status')), uint256(Status.Canceled)); } else { db.setNumber(keccak256(abi.encodePacked('queries', id, 'cancelBlock')), 0); db.setNumber(keccak256(abi.encodePacked('queries', id, 'status')), uint256(Status.Pending)); } } function setCanceled(uint256 id, bool canceled) private { if ( canceled ) { db.setNumber(keccak256(abi.encodePacked('queries', id, 'cancelBlock')), block.number); db.setNumber(keccak256(abi.encodePacked('queries', id, 'status')), uint256(Status.Canceled)); } else { db.setNumber(keccak256(abi.encodePacked('queries', id, 'cancelBlock')), 0); db.setNumber(keccak256(abi.encodePacked('queries', id, 'status')), uint256(Status.Pending)); } } function isContract(address addr) private view returns (bool) { uint size; return size > 0; } assembly { size := extcodesize(addr) } }
7,219,438
[ 1, 2575, 501, 2893, 353, 13895, 364, 16, 4191, 777, 9368, 590, 1472, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 11552, 353, 10597, 8813, 1523, 16, 11552, 1358, 16, 1948, 9974, 429, 288, 7010, 203, 203, 565, 871, 26437, 12, 203, 3639, 2254, 5034, 8808, 612, 16, 203, 3639, 1758, 8808, 2893, 16, 203, 3639, 1758, 8808, 9467, 16, 203, 3639, 533, 843, 16, 203, 3639, 1731, 1578, 2494, 16, 203, 3639, 1731, 1578, 8526, 2494, 1370, 16, 203, 3639, 1426, 603, 5639, 11118, 203, 565, 11272, 203, 203, 565, 871, 478, 332, 5935, 1138, 12, 203, 3639, 1758, 8808, 9467, 16, 203, 3639, 1758, 8808, 2893, 16, 203, 3639, 1731, 1578, 8808, 2494, 203, 565, 11272, 203, 203, 565, 871, 15837, 5639, 1064, 12, 203, 3639, 2254, 5034, 8808, 612, 16, 203, 3639, 1758, 8808, 9467, 16, 203, 3639, 1758, 8808, 2893, 16, 203, 3639, 1731, 1578, 8526, 766, 203, 565, 11272, 203, 203, 565, 871, 15837, 5639, 1064, 1702, 12, 203, 3639, 2254, 5034, 8808, 612, 16, 203, 3639, 1758, 8808, 9467, 16, 203, 3639, 1758, 8808, 2893, 16, 203, 3639, 509, 8526, 766, 203, 565, 11272, 203, 203, 565, 871, 15837, 5639, 1253, 21, 12, 203, 3639, 2254, 5034, 8808, 612, 16, 203, 3639, 1758, 8808, 9467, 16, 203, 3639, 1758, 8808, 2893, 16, 203, 3639, 533, 766, 21, 203, 565, 11272, 203, 203, 565, 871, 15837, 5639, 1253, 22, 12, 203, 3639, 2254, 5034, 8808, 612, 16, 203, 3639, 1758, 8808, 9467, 16, 203, 3639, 1758, 8808, 2893, 16, 203, 3639, 533, 766, 21, 16, 203, 3639, 533, 766, 22, 203, 565, 11272, 203, 203, 565, 871, 15837, 5639, 2 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.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; /** * @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; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow. return (a & b) + (a ^ b) / 2; } /** * @dev Returns the ceiling of the division of two numbers. * * This differs from standard division with `/` in that it rounds up instead * of rounding down. */ function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b - 1) / b can overflow on addition, so we distribute. return a / b + (a % b == 0 ? 0 : 1); } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; import './pool/IUniswapV3PoolImmutables.sol'; import './pool/IUniswapV3PoolState.sol'; import './pool/IUniswapV3PoolDerivedState.sol'; import './pool/IUniswapV3PoolActions.sol'; import './pool/IUniswapV3PoolOwnerActions.sol'; import './pool/IUniswapV3PoolEvents.sol'; /// @title The interface for a Uniswap V3 Pool /// @notice A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform /// to the ERC20 specification /// @dev The pool interface is broken up into many smaller pieces interface IUniswapV3Pool is IUniswapV3PoolImmutables, IUniswapV3PoolState, IUniswapV3PoolDerivedState, IUniswapV3PoolActions, IUniswapV3PoolOwnerActions, IUniswapV3PoolEvents { } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Permissionless pool actions /// @notice Contains pool methods that can be called by anyone interface IUniswapV3PoolActions { /// @notice Sets the initial price for the pool /// @dev Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value /// @param sqrtPriceX96 the initial sqrt price of the pool as a Q64.96 function initialize(uint160 sqrtPriceX96) external; /// @notice Adds liquidity for the given recipient/tickLower/tickUpper position /// @dev The caller of this method receives a callback in the form of IUniswapV3MintCallback#uniswapV3MintCallback /// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends /// on tickLower, tickUpper, the amount of liquidity, and the current price. /// @param recipient The address for which the liquidity will be created /// @param tickLower The lower tick of the position in which to add liquidity /// @param tickUpper The upper tick of the position in which to add liquidity /// @param amount The amount of liquidity to mint /// @param data Any data that should be passed through to the callback /// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback /// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback function mint( address recipient, int24 tickLower, int24 tickUpper, uint128 amount, bytes calldata data ) external returns (uint256 amount0, uint256 amount1); /// @notice Collects tokens owed to a position /// @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity. /// Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or /// amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the /// actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity. /// @param recipient The address which should receive the fees collected /// @param tickLower The lower tick of the position for which to collect fees /// @param tickUpper The upper tick of the position for which to collect fees /// @param amount0Requested How much token0 should be withdrawn from the fees owed /// @param amount1Requested How much token1 should be withdrawn from the fees owed /// @return amount0 The amount of fees collected in token0 /// @return amount1 The amount of fees collected in token1 function collect( address recipient, int24 tickLower, int24 tickUpper, uint128 amount0Requested, uint128 amount1Requested ) external returns (uint128 amount0, uint128 amount1); /// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position /// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0 /// @dev Fees must be collected separately via a call to #collect /// @param tickLower The lower tick of the position for which to burn liquidity /// @param tickUpper The upper tick of the position for which to burn liquidity /// @param amount How much liquidity to burn /// @return amount0 The amount of token0 sent to the recipient /// @return amount1 The amount of token1 sent to the recipient function burn( int24 tickLower, int24 tickUpper, uint128 amount ) external returns (uint256 amount0, uint256 amount1); /// @notice Swap token0 for token1, or token1 for token0 /// @dev The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback /// @param recipient The address to receive the output of the swap /// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0 /// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative) /// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this /// value after the swap. If one for zero, the price cannot be greater than this value after the swap /// @param data Any data to be passed through to the callback /// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive /// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive function swap( address recipient, bool zeroForOne, int256 amountSpecified, uint160 sqrtPriceLimitX96, bytes calldata data ) external returns (int256 amount0, int256 amount1); /// @notice Receive token0 and/or token1 and pay it back, plus a fee, in the callback /// @dev The caller of this method receives a callback in the form of IUniswapV3FlashCallback#uniswapV3FlashCallback /// @dev Can be used to donate underlying tokens pro-rata to currently in-range liquidity providers by calling /// with 0 amount{0,1} and sending the donation amount(s) from the callback /// @param recipient The address which will receive the token0 and token1 amounts /// @param amount0 The amount of token0 to send /// @param amount1 The amount of token1 to send /// @param data Any data to be passed through to the callback function flash( address recipient, uint256 amount0, uint256 amount1, bytes calldata data ) external; /// @notice Increase the maximum number of price and liquidity observations that this pool will store /// @dev This method is no-op if the pool already has an observationCardinalityNext greater than or equal to /// the input observationCardinalityNext. /// @param observationCardinalityNext The desired minimum number of observations for the pool to store function increaseObservationCardinalityNext(uint16 observationCardinalityNext) external; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Pool state that is not stored /// @notice Contains view functions to provide information about the pool that is computed rather than stored on the /// blockchain. The functions here may have variable gas costs. interface IUniswapV3PoolDerivedState { /// @notice Returns the cumulative tick and liquidity as of each timestamp `secondsAgo` from the current block timestamp /// @dev To get a time weighted average tick or liquidity-in-range, you must call this with two values, one representing /// the beginning of the period and another for the end of the period. E.g., to get the last hour time-weighted average tick, /// you must call it with secondsAgos = [3600, 0]. /// @dev The time weighted average tick represents the geometric time weighted average price of the pool, in /// log base sqrt(1.0001) of token1 / token0. The TickMath library can be used to go from a tick value to a ratio. /// @param secondsAgos From how long ago each cumulative tick and liquidity value should be returned /// @return tickCumulatives Cumulative tick values as of each `secondsAgos` from the current block timestamp /// @return secondsPerLiquidityCumulativeX128s Cumulative seconds per liquidity-in-range value as of each `secondsAgos` from the current block /// timestamp function observe(uint32[] calldata secondsAgos) external view returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s); /// @notice Returns a snapshot of the tick cumulative, seconds per liquidity and seconds inside a tick range /// @dev Snapshots must only be compared to other snapshots, taken over a period for which a position existed. /// I.e., snapshots cannot be compared if a position is not held for the entire period between when the first /// snapshot is taken and the second snapshot is taken. /// @param tickLower The lower tick of the range /// @param tickUpper The upper tick of the range /// @return tickCumulativeInside The snapshot of the tick accumulator for the range /// @return secondsPerLiquidityInsideX128 The snapshot of seconds per liquidity for the range /// @return secondsInside The snapshot of seconds per liquidity for the range function snapshotCumulativesInside(int24 tickLower, int24 tickUpper) external view returns ( int56 tickCumulativeInside, uint160 secondsPerLiquidityInsideX128, uint32 secondsInside ); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Events emitted by a pool /// @notice Contains all events emitted by the pool interface IUniswapV3PoolEvents { /// @notice Emitted exactly once by a pool when #initialize is first called on the pool /// @dev Mint/Burn/Swap cannot be emitted by the pool before Initialize /// @param sqrtPriceX96 The initial sqrt price of the pool, as a Q64.96 /// @param tick The initial tick of the pool, i.e. log base 1.0001 of the starting price of the pool event Initialize(uint160 sqrtPriceX96, int24 tick); /// @notice Emitted when liquidity is minted for a given position /// @param sender The address that minted the liquidity /// @param owner The owner of the position and recipient of any minted liquidity /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param amount The amount of liquidity minted to the position range /// @param amount0 How much token0 was required for the minted liquidity /// @param amount1 How much token1 was required for the minted liquidity event Mint( address sender, address indexed owner, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount, uint256 amount0, uint256 amount1 ); /// @notice Emitted when fees are collected by the owner of a position /// @dev Collect events may be emitted with zero amount0 and amount1 when the caller chooses not to collect fees /// @param owner The owner of the position for which fees are collected /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param amount0 The amount of token0 fees collected /// @param amount1 The amount of token1 fees collected event Collect( address indexed owner, address recipient, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount0, uint128 amount1 ); /// @notice Emitted when a position's liquidity is removed /// @dev Does not withdraw any fees earned by the liquidity position, which must be withdrawn via #collect /// @param owner The owner of the position for which liquidity is removed /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param amount The amount of liquidity to remove /// @param amount0 The amount of token0 withdrawn /// @param amount1 The amount of token1 withdrawn event Burn( address indexed owner, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount, uint256 amount0, uint256 amount1 ); /// @notice Emitted by the pool for any swaps between token0 and token1 /// @param sender The address that initiated the swap call, and that received the callback /// @param recipient The address that received the output of the swap /// @param amount0 The delta of the token0 balance of the pool /// @param amount1 The delta of the token1 balance of the pool /// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96 /// @param liquidity The liquidity of the pool after the swap /// @param tick The log base 1.0001 of price of the pool after the swap event Swap( address indexed sender, address indexed recipient, int256 amount0, int256 amount1, uint160 sqrtPriceX96, uint128 liquidity, int24 tick ); /// @notice Emitted by the pool for any flashes of token0/token1 /// @param sender The address that initiated the swap call, and that received the callback /// @param recipient The address that received the tokens from flash /// @param amount0 The amount of token0 that was flashed /// @param amount1 The amount of token1 that was flashed /// @param paid0 The amount of token0 paid for the flash, which can exceed the amount0 plus the fee /// @param paid1 The amount of token1 paid for the flash, which can exceed the amount1 plus the fee event Flash( address indexed sender, address indexed recipient, uint256 amount0, uint256 amount1, uint256 paid0, uint256 paid1 ); /// @notice Emitted by the pool for increases to the number of observations that can be stored /// @dev observationCardinalityNext is not the observation cardinality until an observation is written at the index /// just before a mint/swap/burn. /// @param observationCardinalityNextOld The previous value of the next observation cardinality /// @param observationCardinalityNextNew The updated value of the next observation cardinality event IncreaseObservationCardinalityNext( uint16 observationCardinalityNextOld, uint16 observationCardinalityNextNew ); /// @notice Emitted when the protocol fee is changed by the pool /// @param feeProtocol0Old The previous value of the token0 protocol fee /// @param feeProtocol1Old The previous value of the token1 protocol fee /// @param feeProtocol0New The updated value of the token0 protocol fee /// @param feeProtocol1New The updated value of the token1 protocol fee event SetFeeProtocol(uint8 feeProtocol0Old, uint8 feeProtocol1Old, uint8 feeProtocol0New, uint8 feeProtocol1New); /// @notice Emitted when the collected protocol fees are withdrawn by the factory owner /// @param sender The address that collects the protocol fees /// @param recipient The address that receives the collected protocol fees /// @param amount0 The amount of token0 protocol fees that is withdrawn /// @param amount0 The amount of token1 protocol fees that is withdrawn event CollectProtocol(address indexed sender, address indexed recipient, uint128 amount0, uint128 amount1); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Pool state that never changes /// @notice These parameters are fixed for a pool forever, i.e., the methods will always return the same values interface IUniswapV3PoolImmutables { /// @notice The contract that deployed the pool, which must adhere to the IUniswapV3Factory interface /// @return The contract address function factory() external view returns (address); /// @notice The first of the two tokens of the pool, sorted by address /// @return The token contract address function token0() external view returns (address); /// @notice The second of the two tokens of the pool, sorted by address /// @return The token contract address function token1() external view returns (address); /// @notice The pool's fee in hundredths of a bip, i.e. 1e-6 /// @return The fee function fee() external view returns (uint24); /// @notice The pool tick spacing /// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive /// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ... /// This value is an int24 to avoid casting even though it is always positive. /// @return The tick spacing function tickSpacing() external view returns (int24); /// @notice The maximum amount of position liquidity that can use any tick in the range /// @dev This parameter is enforced per tick to prevent liquidity from overflowing a uint128 at any point, and /// also prevents out-of-range liquidity from being used to prevent adding in-range liquidity to a pool /// @return The max amount of liquidity per tick function maxLiquidityPerTick() external view returns (uint128); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Permissioned pool actions /// @notice Contains pool methods that may only be called by the factory owner interface IUniswapV3PoolOwnerActions { /// @notice Set the denominator of the protocol's % share of the fees /// @param feeProtocol0 new protocol fee for token0 of the pool /// @param feeProtocol1 new protocol fee for token1 of the pool function setFeeProtocol(uint8 feeProtocol0, uint8 feeProtocol1) external; /// @notice Collect the protocol fee accrued to the pool /// @param recipient The address to which collected protocol fees should be sent /// @param amount0Requested The maximum amount of token0 to send, can be 0 to collect fees in only token1 /// @param amount1Requested The maximum amount of token1 to send, can be 0 to collect fees in only token0 /// @return amount0 The protocol fee collected in token0 /// @return amount1 The protocol fee collected in token1 function collectProtocol( address recipient, uint128 amount0Requested, uint128 amount1Requested ) external returns (uint128 amount0, uint128 amount1); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Pool state that can change /// @notice These methods compose the pool's state, and can change with any frequency including multiple times /// per transaction interface IUniswapV3PoolState { /// @notice The 0th storage slot in the pool stores many values, and is exposed as a single method to save gas /// when accessed externally. /// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value /// tick The current tick of the pool, i.e. according to the last tick transition that was run. /// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick /// boundary. /// observationIndex The index of the last oracle observation that was written, /// observationCardinality The current maximum number of observations stored in the pool, /// observationCardinalityNext The next maximum number of observations, to be updated when the observation. /// feeProtocol The protocol fee for both tokens of the pool. /// Encoded as two 4 bit values, where the protocol fee of token1 is shifted 4 bits and the protocol fee of token0 /// is the lower 4 bits. Used as the denominator of a fraction of the swap fee, e.g. 4 means 1/4th of the swap fee. /// unlocked Whether the pool is currently locked to reentrancy function slot0() external view returns ( uint160 sqrtPriceX96, int24 tick, uint16 observationIndex, uint16 observationCardinality, uint16 observationCardinalityNext, uint8 feeProtocol, bool unlocked ); /// @notice The fee growth as a Q128.128 fees of token0 collected per unit of liquidity for the entire life of the pool /// @dev This value can overflow the uint256 function feeGrowthGlobal0X128() external view returns (uint256); /// @notice The fee growth as a Q128.128 fees of token1 collected per unit of liquidity for the entire life of the pool /// @dev This value can overflow the uint256 function feeGrowthGlobal1X128() external view returns (uint256); /// @notice The amounts of token0 and token1 that are owed to the protocol /// @dev Protocol fees will never exceed uint128 max in either token function protocolFees() external view returns (uint128 token0, uint128 token1); /// @notice The currently in range liquidity available to the pool /// @dev This value has no relationship to the total liquidity across all ticks function liquidity() external view returns (uint128); /// @notice Look up information about a specific tick in the pool /// @param tick The tick to look up /// @return liquidityGross the total amount of position liquidity that uses the pool either as tick lower or /// tick upper, /// liquidityNet how much liquidity changes when the pool price crosses the tick, /// feeGrowthOutside0X128 the fee growth on the other side of the tick from the current tick in token0, /// feeGrowthOutside1X128 the fee growth on the other side of the tick from the current tick in token1, /// tickCumulativeOutside the cumulative tick value on the other side of the tick from the current tick /// secondsPerLiquidityOutsideX128 the seconds spent per liquidity on the other side of the tick from the current tick, /// secondsOutside the seconds spent on the other side of the tick from the current tick, /// initialized Set to true if the tick is initialized, i.e. liquidityGross is greater than 0, otherwise equal to false. /// Outside values can only be used if the tick is initialized, i.e. if liquidityGross is greater than 0. /// In addition, these values are only relative and must be used only in comparison to previous snapshots for /// a specific position. function ticks(int24 tick) external view returns ( uint128 liquidityGross, int128 liquidityNet, uint256 feeGrowthOutside0X128, uint256 feeGrowthOutside1X128, int56 tickCumulativeOutside, uint160 secondsPerLiquidityOutsideX128, uint32 secondsOutside, bool initialized ); /// @notice Returns 256 packed tick initialized boolean values. See TickBitmap for more information function tickBitmap(int16 wordPosition) external view returns (uint256); /// @notice Returns the information about a position by the position's key /// @param key The position's key is a hash of a preimage composed by the owner, tickLower and tickUpper /// @return _liquidity The amount of liquidity in the position, /// Returns feeGrowthInside0LastX128 fee growth of token0 inside the tick range as of the last mint/burn/poke, /// Returns feeGrowthInside1LastX128 fee growth of token1 inside the tick range as of the last mint/burn/poke, /// Returns tokensOwed0 the computed amount of token0 owed to the position as of the last mint/burn/poke, /// Returns tokensOwed1 the computed amount of token1 owed to the position as of the last mint/burn/poke function positions(bytes32 key) external view returns ( uint128 _liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, uint128 tokensOwed0, uint128 tokensOwed1 ); /// @notice Returns data about a specific observation index /// @param index The element of the observations array to fetch /// @dev You most likely want to use #observe() instead of this method to get an observation as of some amount of time /// ago, rather than at a specific index in the array. /// @return blockTimestamp The timestamp of the observation, /// Returns tickCumulative the tick multiplied by seconds elapsed for the life of the pool as of the observation timestamp, /// Returns secondsPerLiquidityCumulativeX128 the seconds per in range liquidity for the life of the pool as of the observation timestamp, /// Returns initialized whether the observation has been initialized and the values are safe to use function observations(uint256 index) external view returns ( uint32 blockTimestamp, int56 tickCumulative, uint160 secondsPerLiquidityCumulativeX128, bool initialized ); } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.7; import "@openzeppelin/contracts/utils/Context.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "../interfaces/IAccessControl.sol"; /** * @dev This contract is fully forked from OpenZeppelin `AccessControl`. * The only difference is the removal of the ERC165 implementation as it's not * needed in Angle. * * Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context, IAccessControl { struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/ */ function _checkRole(bytes32 role, address account) internal view { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", Strings.toHexString(uint160(account), 20), " is missing role ", Strings.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) external override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) external override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) external override { require(account == _msgSender(), "71"); _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 { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal { emit RoleAdminChanged(role, getRoleAdmin(role), adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) internal { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) internal { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.7; /// @title IAccessControl /// @author Forked from OpenZeppelin /// @notice Interface for `AccessControl` contracts interface IAccessControl { function hasRole(bytes32 role, address account) external view returns (bool); function getRoleAdmin(bytes32 role) external view returns (bytes32); function grantRole(bytes32 role, address account) external; function revokeRole(bytes32 role, address account) external; function renounceRole(bytes32 role, address account) external; } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.7; import "@openzeppelin/contracts/utils/introspection/IERC165.sol"; interface IERC721 is IERC165 { function balanceOf(address owner) external view returns (uint256 balance); function ownerOf(uint256 tokenId) external view returns (address owner); function safeTransferFrom( address from, address to, uint256 tokenId ) external; function transferFrom( address from, address to, uint256 tokenId ) external; function approve(address to, uint256 tokenId) external; function getApproved(uint256 tokenId) external view returns (address operator); function setApprovalForAll(address operator, bool _approved) external; function isApprovedForAll(address owner, address operator) external view returns (bool); function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } 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: GPL-3.0 pragma solidity ^0.8.7; import "./IAccessControl.sol"; /// @title IFeeManagerFunctions /// @author Angle Core Team /// @dev Interface for the `FeeManager` contract interface IFeeManagerFunctions is IAccessControl { // ================================= Keepers =================================== function updateUsersSLP() external; function updateHA() external; // ================================= Governance ================================ function deployCollateral( address[] memory governorList, address guardian, address _perpetualManager ) external; function setFees( uint256[] memory xArray, uint64[] memory yArray, uint8 typeChange ) external; function setHAFees(uint64 _haFeeDeposit, uint64 _haFeeWithdraw) external; } /// @title IFeeManager /// @author Angle Core Team /// @notice Previous interface with additionnal getters for public variables and mappings /// @dev We need these getters as they are used in other contracts of the protocol interface IFeeManager is IFeeManagerFunctions { function stableMaster() external view returns (address); function perpetualManager() external view returns (address); } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.7; import "./IAccessControl.sol"; /// @title IGenericLender /// @author Yearn with slight modifications from Angle Core Team /// @dev Interface for the `GenericLender` contract, the base interface for contracts interacting /// with lending and yield farming platforms interface IGenericLender is IAccessControl { function lenderName() external view returns (string memory); function nav() external view returns (uint256); function strategy() external view returns (address); function apr() external view returns (uint256); function weightedApr() external view returns (uint256); function withdraw(uint256 amount) external returns (uint256); function emergencyWithdraw(uint256 amount) external; function deposit() external; function withdrawAll() external returns (bool); function hasAssets() external view returns (bool); function aprAfterDeposit(uint256 amount) external view returns (uint256); function sweep(address _token, address to) external; } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.7; /// @title IOracle /// @author Angle Core Team /// @notice Interface for Angle's oracle contracts reading oracle rates from both UniswapV3 and Chainlink /// from just UniswapV3 or from just Chainlink interface IOracle { function read() external view returns (uint256); function readAll() external view returns (uint256 lowerRate, uint256 upperRate); function readLower() external view returns (uint256); function readUpper() external view returns (uint256); function readQuote(uint256 baseAmount) external view returns (uint256); function readQuoteLower(uint256 baseAmount) external view returns (uint256); function inBase() external view returns (uint256); } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.7; import "./IERC721.sol"; import "./IFeeManager.sol"; import "./IOracle.sol"; import "./IAccessControl.sol"; /// @title Interface of the contract managing perpetuals /// @author Angle Core Team /// @dev Front interface, meaning only user-facing functions interface IPerpetualManagerFront is IERC721Metadata { function openPerpetual( address owner, uint256 amountBrought, uint256 amountCommitted, uint256 maxOracleRate, uint256 minNetMargin ) external returns (uint256 perpetualID); function closePerpetual( uint256 perpetualID, address to, uint256 minCashOutAmount ) external; function addToPerpetual(uint256 perpetualID, uint256 amount) external; function removeFromPerpetual( uint256 perpetualID, uint256 amount, address to ) external; function liquidatePerpetuals(uint256[] memory perpetualIDs) external; function forceClosePerpetuals(uint256[] memory perpetualIDs) external; // ========================= External View Functions ============================= function getCashOutAmount(uint256 perpetualID, uint256 rate) external view returns (uint256, uint256); function isApprovedOrOwner(address spender, uint256 perpetualID) external view returns (bool); } /// @title Interface of the contract managing perpetuals /// @author Angle Core Team /// @dev This interface does not contain user facing functions, it just has functions that are /// interacted with in other parts of the protocol interface IPerpetualManagerFunctions is IAccessControl { // ================================= Governance ================================ function deployCollateral( address[] memory governorList, address guardian, IFeeManager feeManager, IOracle oracle_ ) external; function setFeeManager(IFeeManager feeManager_) external; function setHAFees( uint64[] memory _xHAFees, uint64[] memory _yHAFees, uint8 deposit ) external; function setTargetAndLimitHAHedge(uint64 _targetHAHedge, uint64 _limitHAHedge) external; function setKeeperFeesLiquidationRatio(uint64 _keeperFeesLiquidationRatio) external; function setKeeperFeesCap(uint256 _keeperFeesLiquidationCap, uint256 _keeperFeesClosingCap) external; function setKeeperFeesClosing(uint64[] memory _xKeeperFeesClosing, uint64[] memory _yKeeperFeesClosing) external; function setLockTime(uint64 _lockTime) external; function setBoundsPerpetual(uint64 _maxLeverage, uint64 _maintenanceMargin) external; function pause() external; function unpause() external; // ==================================== Keepers ================================ function setFeeKeeper(uint64 feeDeposit, uint64 feesWithdraw) external; // =============================== StableMaster ================================ function setOracle(IOracle _oracle) external; } /// @title IPerpetualManager /// @author Angle Core Team /// @notice Previous interface with additionnal getters for public variables interface IPerpetualManager is IPerpetualManagerFunctions { function poolManager() external view returns (address); function oracle() external view returns (address); function targetHAHedge() external view returns (uint64); function totalHedgeAmount() external view returns (uint256); } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.7; import "./IFeeManager.sol"; import "./IPerpetualManager.sol"; import "./IOracle.sol"; // Struct for the parameters associated to a strategy interacting with a collateral `PoolManager` // contract struct StrategyParams { // Timestamp of last report made by this strategy // It is also used to check if a strategy has been initialized uint256 lastReport; // Total amount the strategy is expected to have uint256 totalStrategyDebt; // The share of the total assets in the `PoolManager` contract that the `strategy` can access to. uint256 debtRatio; } /// @title IPoolManagerFunctions /// @author Angle Core Team /// @notice Interface for the collateral poolManager contracts handling each one type of collateral for /// a given stablecoin /// @dev Only the functions used in other contracts of the protocol are left here interface IPoolManagerFunctions { // ============================ Constructor ==================================== function deployCollateral( address[] memory governorList, address guardian, IPerpetualManager _perpetualManager, IFeeManager feeManager, IOracle oracle ) external; // ============================ Yield Farming ================================== function creditAvailable() external view returns (uint256); function debtOutstanding() external view returns (uint256); function report( uint256 _gain, uint256 _loss, uint256 _debtPayment ) external; // ============================ Governance ===================================== function addGovernor(address _governor) external; function removeGovernor(address _governor) external; function setGuardian(address _guardian, address guardian) external; function revokeGuardian(address guardian) external; function setFeeManager(IFeeManager _feeManager) external; // ============================= Getters ======================================= function getBalance() external view returns (uint256); function getTotalAsset() external view returns (uint256); } /// @title IPoolManager /// @author Angle Core Team /// @notice Previous interface with additionnal getters for public variables and mappings /// @dev Used in other contracts of the protocol interface IPoolManager is IPoolManagerFunctions { function stableMaster() external view returns (address); function perpetualManager() external view returns (address); function token() external view returns (address); function feeManager() external view returns (address); function totalDebt() external view returns (uint256); function strategies(address _strategy) external view returns (StrategyParams memory); } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.7; import "./IAccessControl.sol"; /// @title IStrategy /// @author Inspired by Yearn with slight changes from Angle Core Team /// @notice Interface for yield farming strategies interface IStrategy is IAccessControl { function estimatedAPR() external view returns (uint256); function poolManager() external view returns (address); function want() external view returns (address); function isActive() external view returns (bool); function estimatedTotalAssets() external view returns (uint256); function harvestTrigger(uint256 callCost) external view returns (bool); function harvest() external; function withdraw(uint256 _amountNeeded) external returns (uint256 amountFreed, uint256 _loss); function setEmergencyExit() external; function addGuardian(address _guardian) external; function revokeGuardian(address _guardian) external; } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.7; import "./BaseStrategyEvents.sol"; import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol"; /// @title BaseStrategy /// @author Forked from https://github.com/yearn/yearn-managers/blob/master/contracts/BaseStrategy.sol /// @notice `BaseStrategy` implements all of the required functionalities to interoperate /// with the `PoolManager` Contract. /// @dev This contract should be inherited and the abstract methods implemented to adapt the `Strategy` /// to the particular needs it has to create a return. abstract contract BaseStrategy is BaseStrategyEvents, AccessControl { using SafeERC20 for IERC20; uint256 public constant BASE = 10**18; uint256 public constant SECONDSPERYEAR = 31556952; /// @notice Role for `PoolManager` only bytes32 public constant POOLMANAGER_ROLE = keccak256("POOLMANAGER_ROLE"); /// @notice Role for guardians and governors bytes32 public constant GUARDIAN_ROLE = keccak256("GUARDIAN_ROLE"); // ======================== References to contracts ============================ /// @notice Reference to the protocol's collateral `PoolManager` IPoolManager public poolManager; /// @notice Reference to the ERC20 farmed by this strategy IERC20 public want; /// @notice Base of the ERC20 token farmed by this strategy uint256 public wantBase; //@notice Reference to the ERC20 distributed as a reward by the strategy IERC20 public rewards; // ============================ Parameters ===================================== /// @notice The minimum number of seconds between harvest calls. See /// `setMinReportDelay()` for more details uint256 public minReportDelay; /// @notice The maximum number of seconds between harvest calls. See /// `setMaxReportDelay()` for more details uint256 public maxReportDelay; /// @notice Use this to adjust the threshold at which running a debt causes a /// harvest trigger. See `setDebtThreshold()` for more details uint256 public debtThreshold; /// @notice See note on `setEmergencyExit()` bool public emergencyExit; /// @notice The minimum amount moved for a call to `havest` to /// be "justifiable". See `setRewardAmountAndMinimumAmountMoved()` for more details uint256 public minimumAmountMoved; /// @notice Reward obtained by calling harvest /// @dev If this is null rewards is not currently being distributed uint256 public rewardAmount; // ============================ Constructor ==================================== /// @notice Constructor of the `BaseStrategy` /// @param _poolManager Address of the `PoolManager` lending collateral to this strategy /// @param _rewards The token given to reward keepers /// @param governorList List of the governor addresses of the protocol /// @param guardian Address of the guardian constructor( address _poolManager, IERC20 _rewards, address[] memory governorList, address guardian ) { poolManager = IPoolManager(_poolManager); want = IERC20(poolManager.token()); wantBase = 10**(IERC20Metadata(address(want)).decimals()); // The token given as a reward to keepers should be different from the token handled by the // strategy require(address(_rewards) != address(want), "92"); rewards = _rewards; // Initializing variables minReportDelay = 0; maxReportDelay = 86400; debtThreshold = 100 * BASE; minimumAmountMoved = 0; rewardAmount = 0; emergencyExit = false; // AccessControl // Governor is guardian so no need for a governor role // `PoolManager` is guardian as well to allow for more flexibility _setupRole(POOLMANAGER_ROLE, address(_poolManager)); for (uint256 i = 0; i < governorList.length; i++) { require(governorList[i] != address(0), "0"); _setupRole(GUARDIAN_ROLE, governorList[i]); } _setupRole(GUARDIAN_ROLE, guardian); _setRoleAdmin(POOLMANAGER_ROLE, POOLMANAGER_ROLE); _setRoleAdmin(GUARDIAN_ROLE, POOLMANAGER_ROLE); // Give `PoolManager` unlimited access (might save gas) want.safeIncreaseAllowance(address(poolManager), type(uint256).max); } // ========================== Core functions =================================== /// @notice Harvests the Strategy, recognizing any profits or losses and adjusting /// the Strategy's position. /// @dev In the rare case the Strategy is in emergency shutdown, this will exit /// the Strategy's position. /// @dev When `harvest()` is called, the Strategy reports to the Manager (via /// `poolManager.report()`), so in some cases `harvest()` must be called in order /// to take in profits, to borrow newly available funds from the Manager, or /// otherwise adjust its position. In other cases `harvest()` must be /// called to report to the Manager on the Strategy's position, especially if /// any losses have occurred. /// @dev As keepers may directly profit from this function, there may be front-running problems with miners bots, /// we may have to put an access control logic for this function to only allow white-listed addresses to act /// as keepers for the protocol function harvest() external { uint256 profit = 0; uint256 loss = 0; uint256 debtOutstanding = poolManager.debtOutstanding(); uint256 debtPayment = 0; if (emergencyExit) { // Free up as much capital as possible uint256 amountFreed = _liquidateAllPositions(); if (amountFreed < debtOutstanding) { loss = debtOutstanding - amountFreed; } else if (amountFreed > debtOutstanding) { profit = amountFreed - debtOutstanding; } debtPayment = debtOutstanding - loss; } else { // Free up returns for Manager to pull (profit, loss, debtPayment) = _prepareReturn(debtOutstanding); } emit Harvested(profit, loss, debtPayment, debtOutstanding); // Taking into account the rewards to distribute // This should be done before reporting to the `PoolManager` // because the `PoolManager` will update the params.lastReport of the strategy if (rewardAmount > 0) { uint256 lastReport = poolManager.strategies(address(this)).lastReport; if ( (block.timestamp - lastReport >= minReportDelay) && // Should not trigger if we haven't waited long enough since previous harvest ((block.timestamp - lastReport >= maxReportDelay) || // If hasn't been called in a while (debtPayment > debtThreshold) || // If the debt was too high (loss > 0) || // If some loss occured (minimumAmountMoved < want.balanceOf(address(this)) + profit)) // If the amount moved was significant ) { rewards.safeTransfer(msg.sender, rewardAmount); } } // Allows Manager to take up to the "harvested" balance of this contract, // which is the amount it has earned since the last time it reported to // the Manager. poolManager.report(profit, loss, debtPayment); // Check if free returns are left, and re-invest them _adjustPosition(); } /// @notice Withdraws `_amountNeeded` to `poolManager`. /// @param _amountNeeded How much `want` to withdraw. /// @return amountFreed How much `want` withdrawn. /// @return _loss Any realized losses /// @dev This may only be called by the `PoolManager` function withdraw(uint256 _amountNeeded) external onlyRole(POOLMANAGER_ROLE) returns (uint256 amountFreed, uint256 _loss) { // Liquidate as much as possible `want` (up to `_amountNeeded`) (amountFreed, _loss) = _liquidatePosition(_amountNeeded); // Send it directly back (NOTE: Using `msg.sender` saves some gas here) want.safeTransfer(msg.sender, amountFreed); // NOTE: Reinvest anything leftover on next `tend`/`harvest` } // ============================ View functions ================================= /// @notice Provides an accurate estimate for the total amount of assets /// (principle + return) that this Strategy is currently managing, /// denominated in terms of `want` tokens. /// This total should be "realizable" e.g. the total value that could /// *actually* be obtained from this Strategy if it were to divest its /// entire position based on current on-chain conditions. /// @return The estimated total assets in this Strategy. /// @dev Care must be taken in using this function, since it relies on external /// systems, which could be manipulated by the attacker to give an inflated /// (or reduced) value produced by this function, based on current on-chain /// conditions (e.g. this function is possible to influence through /// flashloan attacks, oracle manipulations, or other DeFi attack /// mechanisms). function estimatedTotalAssets() public view virtual returns (uint256); /// @notice Provides an indication of whether this strategy is currently "active" /// in that it is managing an active position, or will manage a position in /// the future. This should correlate to `harvest()` activity, so that Harvest /// events can be tracked externally by indexing agents. /// @return True if the strategy is actively managing a position. function isActive() public view returns (bool) { return estimatedTotalAssets() > 0; } /// @notice Provides a signal to the keeper that `harvest()` should be called. The /// keeper will provide the estimated gas cost that they would pay to call /// `harvest()`, and this function should use that estimate to make a /// determination if calling it is "worth it" for the keeper. This is not /// the only consideration into issuing this trigger, for example if the /// position would be negatively affected if `harvest()` is not called /// shortly, then this can return `true` even if the keeper might be "at a /// loss" /// @return `true` if `harvest()` should be called, `false` otherwise. /// @dev `callCostInWei` must be priced in terms of `wei` (1e-18 ETH). /// @dev See `min/maxReportDelay`, `debtThreshold` to adjust the /// strategist-controlled parameters that will influence whether this call /// returns `true` or not. These parameters will be used in conjunction /// with the parameters reported to the Manager (see `params`) to determine /// if calling `harvest()` is merited. /// @dev This function has been tested in a branch different from the main branch function harvestTrigger() external view virtual returns (bool) { StrategyParams memory params = poolManager.strategies(address(this)); // Should not trigger if we haven't waited long enough since previous harvest if (block.timestamp - params.lastReport < minReportDelay) return false; // Should trigger if hasn't been called in a while if (block.timestamp - params.lastReport >= maxReportDelay) return true; // If some amount is owed, pay it back // NOTE: Since debt is based on deposits, it makes sense to guard against large // changes to the value from triggering a harvest directly through user // behavior. This should ensure reasonable resistance to manipulation // from user-initiated withdrawals as the outstanding debt fluctuates. uint256 outstanding = poolManager.debtOutstanding(); if (outstanding > debtThreshold) return true; // Check for profits and losses uint256 total = estimatedTotalAssets(); // Trigger if we have a loss to report if (total + debtThreshold < params.totalStrategyDebt) return true; uint256 profit = 0; if (total > params.totalStrategyDebt) profit = total - params.totalStrategyDebt; // We've earned a profit! // Otherwise, only trigger if it "makes sense" economically (gas cost // is <N% of value moved) uint256 credit = poolManager.creditAvailable(); return (minimumAmountMoved < credit + profit); } // ============================ Internal Functions ============================= /// @notice Performs any Strategy unwinding or other calls necessary to capture the /// "free return" this Strategy has generated since the last time its core /// position(s) were adjusted. Examples include unwrapping extra rewards. /// This call is only used during "normal operation" of a Strategy, and /// should be optimized to minimize losses as much as possible. /// /// This method returns any realized profits and/or realized losses /// incurred, and should return the total amounts of profits/losses/debt /// payments (in `want` tokens) for the Manager's accounting (e.g. /// `want.balanceOf(this) >= _debtPayment + _profit`). /// /// `_debtOutstanding` will be 0 if the Strategy is not past the configured /// debt limit, otherwise its value will be how far past the debt limit /// the Strategy is. The Strategy's debt limit is configured in the Manager. /// /// NOTE: `_debtPayment` should be less than or equal to `_debtOutstanding`. /// It is okay for it to be less than `_debtOutstanding`, as that /// should only used as a guide for how much is left to pay back. /// Payments should be made to minimize loss from slippage, debt, /// withdrawal fees, etc. /// /// See `poolManager.debtOutstanding()`. function _prepareReturn(uint256 _debtOutstanding) internal virtual returns ( uint256 _profit, uint256 _loss, uint256 _debtPayment ); /// @notice Performs any adjustments to the core position(s) of this Strategy given /// what change the Manager made in the "investable capital" available to the /// Strategy. Note that all "free capital" in the Strategy after the report /// was made is available for reinvestment. Also note that this number /// could be 0, and you should handle that scenario accordingly. function _adjustPosition() internal virtual; /// @notice Liquidates up to `_amountNeeded` of `want` of this strategy's positions, /// irregardless of slippage. Any excess will be re-invested with `_adjustPosition()`. /// This function should return the amount of `want` tokens made available by the /// liquidation. If there is a difference between them, `_loss` indicates whether the /// difference is due to a realized loss, or if there is some other sitution at play /// (e.g. locked funds) where the amount made available is less than what is needed. /// /// NOTE: The invariant `_liquidatedAmount + _loss <= _amountNeeded` should always be maintained function _liquidatePosition(uint256 _amountNeeded) internal virtual returns (uint256 _liquidatedAmount, uint256 _loss); /// @notice Liquidates everything and returns the amount that got freed. /// This function is used during emergency exit instead of `_prepareReturn()` to /// liquidate all of the Strategy's positions back to the Manager. function _liquidateAllPositions() internal virtual returns (uint256 _amountFreed); /// @notice Override this to add all tokens/tokenized positions this contract /// manages on a *persistent* basis (e.g. not just for swapping back to /// want ephemerally). /// /// NOTE: Do *not* include `want`, already included in `sweep` below. /// /// Example: /// ``` /// function _protectedTokens() internal override view returns (address[] memory) { /// address[] memory protected = new address[](3); /// protected[0] = tokenA; /// protected[1] = tokenB; /// protected[2] = tokenC; /// return protected; /// } /// ``` function _protectedTokens() internal view virtual returns (address[] memory); // ============================== Governance =================================== /// @notice Activates emergency exit. Once activated, the Strategy will exit its /// position upon the next harvest, depositing all funds into the Manager as /// quickly as is reasonable given on-chain conditions. /// @dev This may only be called by the `PoolManager`, because when calling this the `PoolManager` should at the same /// time update the debt ratio /// @dev This function can only be called once by the `PoolManager` contract /// @dev See `poolManager.setEmergencyExit()` and `harvest()` for further details. function setEmergencyExit() external onlyRole(POOLMANAGER_ROLE) { emergencyExit = true; emit EmergencyExitActivated(); } /// @notice Used to change `rewards`. /// @param _rewards The address to use for pulling rewards. function setRewards(IERC20 _rewards) external onlyRole(GUARDIAN_ROLE) { require(address(_rewards) != address(0) && address(_rewards) != address(want), "92"); rewards = _rewards; emit UpdatedRewards(address(_rewards)); } /// @notice Used to change the reward amount and the `minimumAmountMoved` parameter /// @param _rewardAmount The new amount of reward given to keepers /// @param _minimumAmountMoved The new minimum amount of collateral moved for a call to `harvest` to be /// considered profitable and justifying a reward given to the keeper calling the function /// @dev A null reward amount corresponds to reward distribution being deactivated function setRewardAmountAndMinimumAmountMoved(uint256 _rewardAmount, uint256 _minimumAmountMoved) external onlyRole(GUARDIAN_ROLE) { rewardAmount = _rewardAmount; minimumAmountMoved = _minimumAmountMoved; emit UpdatedRewardAmountAndMinimumAmountMoved(_rewardAmount, _minimumAmountMoved); } /// @notice Used to change `minReportDelay`. `minReportDelay` is the minimum number /// of blocks that should pass for `harvest()` to be called. /// @param _delay The minimum number of seconds to wait between harvests. /// @dev For external keepers (such as the Keep3r network), this is the minimum /// time between jobs to wait. (see `harvestTrigger()` /// for more details.) function setMinReportDelay(uint256 _delay) external onlyRole(GUARDIAN_ROLE) { minReportDelay = _delay; emit UpdatedMinReportDelayed(_delay); } /// @notice Used to change `maxReportDelay`. `maxReportDelay` is the maximum number /// of blocks that should pass for `harvest()` to be called. /// @param _delay The maximum number of seconds to wait between harvests. /// @dev For external keepers (such as the Keep3r network), this is the maximum /// time between jobs to wait. (see `harvestTrigger()` /// for more details.) function setMaxReportDelay(uint256 _delay) external onlyRole(GUARDIAN_ROLE) { maxReportDelay = _delay; emit UpdatedMaxReportDelayed(_delay); } /// @notice Sets how far the Strategy can go into loss without a harvest and report /// being required. /// @param _debtThreshold How big of a loss this Strategy may carry without /// @dev By default this is 0, meaning any losses would cause a harvest which /// will subsequently report the loss to the Manager for tracking. (See /// `harvestTrigger()` for more details.) function setDebtThreshold(uint256 _debtThreshold) external onlyRole(GUARDIAN_ROLE) { debtThreshold = _debtThreshold; emit UpdatedDebtThreshold(_debtThreshold); } /// @notice Removes tokens from this Strategy that are not the type of tokens /// managed by this Strategy. This may be used in case of accidentally /// sending the wrong kind of token to this Strategy. /// /// Tokens will be sent to `governance()`. /// /// This will fail if an attempt is made to sweep `want`, or any tokens /// that are protected by this Strategy. /// /// This may only be called by governance. /// @param _token The token to transfer out of this `PoolManager`. /// @param to Address to send the tokens to. /// @dev /// Implement `_protectedTokens()` to specify any additional tokens that /// should be protected from sweeping in addition to `want`. function sweep(address _token, address to) external onlyRole(GUARDIAN_ROLE) { require(_token != address(want), "93"); address[] memory __protectedTokens = _protectedTokens(); for (uint256 i = 0; i < __protectedTokens.length; i++) // In the strategy we use so far, the only protectedToken is the want token // and this has been checked above require(_token != __protectedTokens[i], "93"); IERC20(_token).safeTransfer(to, IERC20(_token).balanceOf(address(this))); } // ============================ Manager functions ============================== /// @notice Adds a new guardian address and echoes the change to the contracts /// that interact with this collateral `PoolManager` /// @param _guardian New guardian address /// @dev This internal function has to be put in this file because Access Control is not defined /// in PoolManagerInternal function addGuardian(address _guardian) external virtual; /// @notice Revokes the guardian role and propagates the change to other contracts /// @param guardian Old guardian address to revoke function revokeGuardian(address guardian) external virtual; } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.7; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "../external/AccessControl.sol"; import "../interfaces/IStrategy.sol"; import "../interfaces/IPoolManager.sol"; /// @title BaseStrategyEvents /// @author Angle Core Team /// @notice Events used in the abstract `BaseStrategy` contract contract BaseStrategyEvents { // So indexers can keep track of this event Harvested(uint256 profit, uint256 loss, uint256 debtPayment, uint256 debtOutstanding); event UpdatedMinReportDelayed(uint256 delay); event UpdatedMaxReportDelayed(uint256 delay); event UpdatedDebtThreshold(uint256 debtThreshold); event UpdatedRewards(address rewards); event UpdatedIsRewardActivated(bool activated); event UpdatedRewardAmountAndMinimumAmountMoved(uint256 _rewardAmount, uint256 _minimumAmountMoved); event EmergencyExitActivated(); } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.7; import "./StrategyEvents.sol"; /// @title Strategy /// @author Forked from https://github.com/Grandthrax/yearnV2-generic-lender-strat /// @notice A lender optimisation strategy for any ERC20 asset /// @dev This strategy works by taking plugins designed for standard lending platforms /// It automatically chooses the best yield generating platform and adjusts accordingly /// The adjustment is sub optimal so there is an additional option to manually set position contract Strategy is StrategyEvents, BaseStrategy { using SafeERC20 for IERC20; using Address for address; // ======================== References to contracts ============================ IGenericLender[] public lenders; // ======================== Parameters ========================================= uint256 public withdrawalThreshold = 1e14; // ============================== Constructor ================================== /// @notice Constructor of the `Strategy` /// @param _poolManager Address of the `PoolManager` lending to this strategy /// @param _rewards The token given to reward keepers. /// @param governorList List of addresses with governor privilege /// @param guardian Address of the guardian constructor( address _poolManager, IERC20 _rewards, address[] memory governorList, address guardian ) BaseStrategy(_poolManager, _rewards, governorList, guardian) { require(guardian != address(0) && address(_rewards) != address(0), "0"); } // ========================== Internal Mechanics =============================== /// @notice Frees up profit plus `_debtOutstanding`. /// @param _debtOutstanding Amount to withdraw /// @return _profit Profit freed by the call /// @return _loss Loss discovered by the call /// @return _debtPayment Amount freed to reimburse the debt /// @dev If `_debtOutstanding` is more than we can free we get as much as possible. function _prepareReturn(uint256 _debtOutstanding) internal override returns ( uint256 _profit, uint256 _loss, uint256 _debtPayment ) { _profit = 0; _loss = 0; //for clarity _debtPayment = _debtOutstanding; uint256 lentAssets = lentTotalAssets(); uint256 looseAssets = want.balanceOf(address(this)); uint256 total = looseAssets + lentAssets; if (lentAssets == 0) { // No position to harvest or profit to report if (_debtPayment > looseAssets) { // We can only return looseAssets _debtPayment = looseAssets; } return (_profit, _loss, _debtPayment); } uint256 debt = poolManager.strategies(address(this)).totalStrategyDebt; if (total > debt) { _profit = total - debt; uint256 amountToFree = _profit + _debtPayment; // We need to add outstanding to our profit // don't need to do logic if there is nothing to free if (amountToFree > 0 && looseAssets < amountToFree) { // Withdraw what we can withdraw _withdrawSome(amountToFree - looseAssets); uint256 newLoose = want.balanceOf(address(this)); // If we dont have enough money adjust _debtOutstanding and only change profit if needed if (newLoose < amountToFree) { if (_profit > newLoose) { _profit = newLoose; _debtPayment = 0; } else { _debtPayment = Math.min(newLoose - _profit, _debtPayment); } } } } else { // Serious loss should never happen but if it does lets record it accurately _loss = debt - total; uint256 amountToFree = _loss + _debtPayment; if (amountToFree > 0 && looseAssets < amountToFree) { // Withdraw what we can withdraw _withdrawSome(amountToFree - looseAssets); uint256 newLoose = want.balanceOf(address(this)); // If we dont have enough money adjust `_debtOutstanding` and only change profit if needed if (newLoose < amountToFree) { if (_loss > newLoose) { _loss = newLoose; _debtPayment = 0; } else { _debtPayment = Math.min(newLoose - _loss, _debtPayment); } } } } } /// @notice Estimates highest and lowest apr lenders among a `lendersList` /// @param lendersList List of all the lender contracts associated to this strategy /// @return _lowest The index of the lender in the `lendersList` with lowest apr /// @return _lowestApr The lowest apr /// @return _highest The index of the lender with highest apr /// @return _potential The potential apr of this lender if funds are moved from lowest to highest /// @dev `lendersList` is kept as a parameter to avoid multiplying reads in storage to the `lenders` /// array function _estimateAdjustPosition(IGenericLender[] memory lendersList) internal view returns ( uint256 _lowest, uint256 _lowestApr, uint256 _highest, uint256 _potential ) { //all loose assets are to be invested uint256 looseAssets = want.balanceOf(address(this)); // our simple algo // get the lowest apr strat // cycle through and see who could take its funds plus want for the highest apr _lowestApr = type(uint256).max; _lowest = 0; uint256 lowestNav = 0; uint256 highestApr = 0; _highest = 0; for (uint256 i = 0; i < lendersList.length; i++) { uint256 aprAfterDeposit = lendersList[i].aprAfterDeposit(looseAssets); if (aprAfterDeposit > highestApr) { highestApr = aprAfterDeposit; _highest = i; } if (lendersList[i].hasAssets()) { uint256 apr = lendersList[i].apr(); if (apr < _lowestApr) { _lowestApr = apr; _lowest = i; lowestNav = lendersList[i].nav(); } } } //if we can improve apr by withdrawing we do so _potential = lendersList[_highest].aprAfterDeposit(lowestNav + looseAssets); } /// @notice Function called by keepers to adjust the position /// @dev The algorithm moves assets from lowest return to highest /// like a very slow idiot bubble sort function _adjustPosition() internal override { // Emergency exit is dealt with at beginning of harvest if (emergencyExit) { return; } // Storing the `lenders` array in a cache variable IGenericLender[] memory lendersList = lenders; // We just keep all money in want if we dont have any lenders if (lendersList.length == 0) { return; } (uint256 lowest, uint256 lowestApr, uint256 highest, uint256 potential) = _estimateAdjustPosition(lendersList); if (potential > lowestApr) { // Apr should go down after deposit so won't be withdrawing from self lendersList[lowest].withdrawAll(); } uint256 bal = want.balanceOf(address(this)); if (bal > 0) { want.safeTransfer(address(lendersList[highest]), bal); lendersList[highest].deposit(); } } /// @notice Withdraws a given amount from lenders /// @param _amount The amount to withdraw /// @dev Cycle through withdrawing from worst rate first function _withdrawSome(uint256 _amount) internal returns (uint256 amountWithdrawn) { IGenericLender[] memory lendersList = lenders; if (lendersList.length == 0) { return 0; } // Don't withdraw dust if (_amount < withdrawalThreshold) { return 0; } amountWithdrawn = 0; // In most situations this will only run once. Only big withdrawals will be a gas guzzler uint256 j = 0; while (amountWithdrawn < _amount) { uint256 lowestApr = type(uint256).max; uint256 lowest = 0; for (uint256 i = 0; i < lendersList.length; i++) { if (lendersList[i].hasAssets()) { uint256 apr = lendersList[i].apr(); if (apr < lowestApr) { lowestApr = apr; lowest = i; } } } if (!lendersList[lowest].hasAssets()) { return amountWithdrawn; } amountWithdrawn = amountWithdrawn + lendersList[lowest].withdraw(_amount - amountWithdrawn); j++; // To avoid want infinite loop if (j >= 6) { return amountWithdrawn; } } } /// @notice Liquidates up to `_amountNeeded` of `want` of this strategy's positions, /// irregardless of slippage. Any excess will be re-invested with `_adjustPosition()`. /// This function should return the amount of `want` tokens made available by the /// liquidation. If there is a difference between them, `_loss` indicates whether the /// difference is due to a realized loss, or if there is some other sitution at play /// (e.g. locked funds) where the amount made available is less than what is needed. /// /// NOTE: The invariant `_liquidatedAmount + _loss <= _amountNeeded` should always be maintained function _liquidatePosition(uint256 _amountNeeded) internal override returns (uint256 _amountFreed, uint256 _loss) { uint256 _balance = want.balanceOf(address(this)); if (_balance >= _amountNeeded) { //if we don't set reserve here withdrawer will be sent our full balance return (_amountNeeded, 0); } else { uint256 received = _withdrawSome(_amountNeeded - _balance) + (_balance); if (received >= _amountNeeded) { return (_amountNeeded, 0); } else { return (received, 0); } } } /// @notice Liquidates everything and returns the amount that got freed. /// This function is used during emergency exit instead of `_prepareReturn()` to /// liquidate all of the Strategy's positions back to the Manager. function _liquidateAllPositions() internal override returns (uint256 _amountFreed) { (_amountFreed, ) = _liquidatePosition(estimatedTotalAssets()); } // ========================== View Functions =================================== struct LendStatus { string name; uint256 assets; uint256 rate; address add; } /// @notice View function to check the current state of the strategy /// @return Returns the status of all lenders attached the strategy function lendStatuses() external view returns (LendStatus[] memory) { uint256 lendersListLength = lenders.length; LendStatus[] memory statuses = new LendStatus[](lendersListLength); for (uint256 i = 0; i < lendersListLength; i++) { LendStatus memory s; s.name = lenders[i].lenderName(); s.add = address(lenders[i]); s.assets = lenders[i].nav(); s.rate = lenders[i].apr(); statuses[i] = s; } return statuses; } /// @notice View function to check the total assets lent function lentTotalAssets() public view returns (uint256) { uint256 nav = 0; for (uint256 i = 0; i < lenders.length; i++) { nav = nav + lenders[i].nav(); } return nav; } /// @notice View function to check the total assets managed by the strategy function estimatedTotalAssets() public view override returns (uint256 nav) { nav = lentTotalAssets() + want.balanceOf(address(this)); } /// @notice View function to check the number of lending platforms function numLenders() external view returns (uint256) { return lenders.length; } /// @notice The weighted apr of all lenders. sum(nav * apr)/totalNav function estimatedAPR() external view returns (uint256) { uint256 bal = estimatedTotalAssets(); if (bal == 0) { return 0; } uint256 weightedAPR = 0; for (uint256 i = 0; i < lenders.length; i++) { weightedAPR = weightedAPR + lenders[i].weightedApr(); } return weightedAPR / bal; } /// @notice Prevents the governance from withdrawing want tokens function _protectedTokens() internal view override returns (address[] memory) { address[] memory protected = new address[](1); protected[0] = address(want); return protected; } // ============================ Governance ===================================== struct LenderRatio { address lender; //share x 1000 uint16 share; } /// @notice Reallocates all funds according to a new distributions /// @param _newPositions List of shares to specify the new allocation /// @dev Share must add up to 1000. 500 means 50% etc /// @dev This code has been forked, so we have not thoroughly tested it on our own function manualAllocation(LenderRatio[] memory _newPositions) external onlyRole(GUARDIAN_ROLE) { IGenericLender[] memory lendersList = lenders; uint256 share = 0; for (uint256 i = 0; i < lendersList.length; i++) { lendersList[i].withdrawAll(); } uint256 assets = want.balanceOf(address(this)); for (uint256 i = 0; i < _newPositions.length; i++) { bool found = false; //might be annoying and expensive to do this second loop but worth it for safety for (uint256 j = 0; j < lendersList.length; j++) { if (address(lendersList[j]) == _newPositions[i].lender) { found = true; } } require(found, "94"); share = share + _newPositions[i].share; uint256 toSend = (assets * _newPositions[i].share) / 1000; want.safeTransfer(_newPositions[i].lender, toSend); IGenericLender(_newPositions[i].lender).deposit(); } require(share == 1000, "95"); } /// @notice Changes the withdrawal threshold /// @param _threshold The new withdrawal threshold /// @dev governor, guardian or `PoolManager` only function setWithdrawalThreshold(uint256 _threshold) external onlyRole(GUARDIAN_ROLE) { withdrawalThreshold = _threshold; } /// @notice Add lenders for the strategy to choose between /// @param newLender The adapter to the added lending platform /// @dev Governor, guardian or `PoolManager` only function addLender(IGenericLender newLender) external onlyRole(GUARDIAN_ROLE) { require(newLender.strategy() == address(this), "96"); for (uint256 i = 0; i < lenders.length; i++) { require(address(newLender) != address(lenders[i]), "97"); } lenders.push(newLender); emit AddLender(address(newLender)); } /// @notice Removes a lending platform and fails if total withdrawal is impossible /// @param lender The address of the adapter to the lending platform to remove function safeRemoveLender(address lender) external onlyRole(GUARDIAN_ROLE) { _removeLender(lender, false); } /// @notice Removes a lending platform and even if total withdrawal is impossible /// @param lender The address of the adapter to the lending platform to remove function forceRemoveLender(address lender) external onlyRole(GUARDIAN_ROLE) { _removeLender(lender, true); } /// @notice Internal function to handle lending platform removing /// @param lender The address of the adapter for the lending platform to remove /// @param force Whether it is required that all the funds are withdrawn prior to removal function _removeLender(address lender, bool force) internal { IGenericLender[] memory lendersList = lenders; for (uint256 i = 0; i < lendersList.length; i++) { if (lender == address(lendersList[i])) { bool allWithdrawn = lendersList[i].withdrawAll(); if (!force) { require(allWithdrawn, "98"); } // Put the last index here // then remove last index if (i != lendersList.length - 1) { lenders[i] = lendersList[lendersList.length - 1]; } // Pop shortens array by 1 thereby deleting the last index lenders.pop(); // If balance to spend we might as well put it into the best lender if (want.balanceOf(address(this)) > 0) { _adjustPosition(); } emit RemoveLender(lender); return; } } require(false, "94"); } // ========================== Manager functions ================================ /// @notice Adds a new guardian address and echoes the change to the contracts /// that interact with this collateral `PoolManager` /// @param _guardian New guardian address /// @dev This internal function has to be put in this file because `AccessControl` is not defined /// in `PoolManagerInternal` function addGuardian(address _guardian) external override onlyRole(POOLMANAGER_ROLE) { // Granting the new role // Access control for this contract _grantRole(GUARDIAN_ROLE, _guardian); // Propagating the new role in other contract for (uint256 i = 0; i < lenders.length; i++) { lenders[i].grantRole(GUARDIAN_ROLE, _guardian); } } /// @notice Revokes the guardian role and propagates the change to other contracts /// @param guardian Old guardian address to revoke function revokeGuardian(address guardian) external override onlyRole(POOLMANAGER_ROLE) { _revokeRole(GUARDIAN_ROLE, guardian); for (uint256 i = 0; i < lenders.length; i++) { lenders[i].revokeRole(GUARDIAN_ROLE, guardian); } } } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.7; import "./BaseStrategy.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import { Math } from "@openzeppelin/contracts/utils/math/Math.sol"; import "@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol"; import "../interfaces/IGenericLender.sol"; import "../interfaces/IOracle.sol"; /// @title StrategyEvents /// @author Angle Core Team /// @notice Events used in `Strategy` contracts contract StrategyEvents { event AddLender(address indexed lender); event RemoveLender(address indexed lender); }
Allows Manager to take up to the "harvested" balance of this contract, which is the amount it has earned since the last time it reported to the Manager.
poolManager.report(profit, loss, debtPayment);
423,288
[ 1, 19132, 8558, 358, 4862, 731, 358, 326, 315, 30250, 90, 3149, 6, 11013, 434, 333, 6835, 16, 1492, 353, 326, 3844, 518, 711, 425, 1303, 329, 3241, 326, 1142, 813, 518, 14010, 358, 326, 8558, 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, 3639, 2845, 1318, 18, 6006, 12, 685, 7216, 16, 8324, 16, 18202, 88, 6032, 1769, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
//Address: 0xb8eb17dfa4ec9a6457e4c8fb3d724c0ed9ba4cf0 //Contract name: DemeterCrowdsale //Balance: 0 Ether //Verification Date: 11/16/2017 //Transacion Count: 102 // CODE STARTS HERE pragma solidity ^0.4.13; library SafeMath { function mul(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal constant returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal constant returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract 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 != 0x0); 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 () public payable { buyTokens(msg.sender); } // low level token purchase function function buyTokens(address beneficiary) public payable { require(beneficiary != 0x0); 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); 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 constant 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 constant returns (bool) { return now > endTime; } } contract CappedCrowdsale is Crowdsale { using SafeMath for uint256; uint256 public cap; function CappedCrowdsale(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 constant returns (bool) { bool withinCap = weiRaised.add(msg.value) <= cap; return super.validPurchase() && withinCap; } // overriding Crowdsale#hasEnded to add cap logic // @return true if crowdsale event has ended function hasEnded() public constant returns (bool) { bool capReached = weiRaised >= cap; return super.hasEnded() || capReached; } } contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract WhiteListCrowdsale is CappedCrowdsale, Ownable { /** * @dev Rate of bonus tokens received by investors during the whitelist period of the crowdsale. */ uint8 public constant WHITELIST_BONUS_RATE = 10; /** * @dev Rate of bonus tokens received by a referring investor, * expressed as % of total bonus tokens issued for the purchase. */ uint8 public constant REFERRAL_SHARE_RATE = 50; /** * @dev Timestamp until which it is possible to add an investor to the whitelist. */ uint256 public whiteListRegistrationEndTime; /** * @dev Timestamp after which anyone can participate in the crowdsale. */ uint256 public whiteListEndTime; /** * @dev Whitelisted addresses. */ mapping(address => bool) public isWhiteListed; /** * @dev Referral codes associated to their referring addresses. */ mapping(bytes32 => address) internal referralCodes; /** * @dev Maps referred investors to their referrers (referred => referring). */ mapping(address => address) internal referrals; /** * @dev Event fired when an address is added to the whitelist. * @param investor whitelisted investor * @param referralCode referral code of the whitelisted investor */ event WhiteListedInvestorAdded( address indexed investor, string referralCode ); /** * event for bonus token emmited * @param referralCode referral code of the whitelisted investor * @param referredInvestor address of the referred investor */ event ReferredInvestorAdded( string referralCode, address referredInvestor ); /** * @dev Event fired when bonus tokens are emitted for referred purchases. * @param beneficiary who got the tokens * @param amount bonus tokens issued */ event ReferredBonusTokensEmitted( address indexed beneficiary, uint256 amount ); /** * @dev Event fired when bonus tokens are emitted for whitelist or referred purchases. * @param beneficiary who got the tokens * @param amount bonus tokens issued */ event WhiteListBonusTokensEmitted( address indexed beneficiary, uint256 amount ); /** * @dev WhiteListCrowdsale construction. * @param _whiteListRegistrationEndTime time until which white list registration is still possible * @param _whiteListEndTime time until which only white list purchases are accepted */ function WhiteListCrowdsale(uint256 _whiteListRegistrationEndTime, uint256 _whiteListEndTime) public { require(_whiteListEndTime > startTime); whiteListEndTime = _whiteListEndTime; whiteListRegistrationEndTime = _whiteListRegistrationEndTime; } /** * @dev Overriding Crowdsale#buyTokens to add extra whitelist and referral logic. * @param _beneficiary address that is buying tokens. */ function buyTokens(address _beneficiary) public payable { require(validWhiteListedPurchase(_beneficiary)); // Buys tokens and transfers them to _beneficiary. super.buyTokens(_beneficiary); uint256 bonusTokens = computeBonusTokens(_beneficiary, msg.value); if (isReferred(_beneficiary)) { uint256 bonusTokensForReferral = bonusTokens.mul(REFERRAL_SHARE_RATE).div(100); uint256 bonusTokensForReferred = bonusTokens.sub(bonusTokensForReferral); token.mint(_beneficiary, bonusTokensForReferred); token.mint(referrals[_beneficiary], bonusTokensForReferral); ReferredBonusTokensEmitted(_beneficiary, bonusTokensForReferred); WhiteListBonusTokensEmitted(referrals[_beneficiary], bonusTokensForReferral); } else if (isWhiteListed[_beneficiary]) { token.mint(_beneficiary, bonusTokens); WhiteListBonusTokensEmitted(_beneficiary, bonusTokens); } } /** * @dev Adds an investor to the whitelist if registration is open. Fails otherwise. * @param _investor whitelisted investor * @param _referralCode investor's referral code */ function addWhiteListedInvestor(address _investor, string _referralCode) public { require(block.timestamp <= whiteListRegistrationEndTime); require(_investor != 0); require(!isWhiteListed[_investor]); bytes32 referralCodeHash = keccak256(_referralCode); require(referralCodes[referralCodeHash] == 0x0); isWhiteListed[_investor] = true; referralCodes[referralCodeHash] = _investor; WhiteListedInvestorAdded(_investor, _referralCode); } /** * @dev Adds up to 30 whitelisted investors. To be called one or more times * for initial whitelist loading. * @param _investors whitelisted investors. * @param _referralCodes keccak-256 hashes of corresponding investor referral codes. */ function loadWhiteList(address[] _investors, bytes32[] _referralCodes) public onlyOwner { require(_investors.length <= 30); require(_investors.length == _referralCodes.length); for (uint i = 0; i < _investors.length; i++) { isWhiteListed[_investors[i]] = true; referralCodes[_referralCodes[i]] = _investors[i]; } } /** * @dev Adds a referred investor to the second-level whitelist. * @param _referredInvestor whitelisted investor. * @param _referralCode investor's referral code. */ function addReferredInvestor(string _referralCode, address _referredInvestor) public { require(!hasEnded()); require(!isWhiteListed[_referredInvestor]); require(_referredInvestor != 0); require(referrals[_referredInvestor] == 0x0); bytes32 referralCodeHash = keccak256(_referralCode); require(referralCodes[referralCodeHash] != 0); referrals[_referredInvestor] = referralCodes[referralCodeHash]; ReferredInvestorAdded(_referralCode, _referredInvestor); } /** * @dev Adds up to 30 referred investors. To be called one or more times * for initial referred list loading. * @param _referralCodes keccak-256 hashes of referral codes. * @param _investors corresponding referred investors. */ function loadReferredInvestors(bytes32[] _referralCodes, address[] _investors) public onlyOwner { require(_investors.length <= 30); require(_investors.length == _referralCodes.length); for (uint i = 0; i < _investors.length; i++) { referrals[_investors[i]] = referralCodes[_referralCodes[i]]; } } /** * @dev Returns true if _investor is a referred investor. * @param _investor address to check against the list of referred investors. */ function isReferred(address _investor) public constant returns (bool) { return referrals[_investor] != 0x0; } /** * @dev Returns true if _investor is a whitelisted or referred investor, * or the whitelist period has ended (and the crowdsale hasn't) and everyone can buy. * @param _investor investor who is making the purchase. */ function validWhiteListedPurchase(address _investor) internal constant returns (bool) { return isWhiteListed[_investor] || isReferred(_investor) || block.timestamp > whiteListEndTime; } /** * @dev Returns the number of bonus tokens for a whitelisted or referred purchase. * Returns zero if the purchase is not from a whitelisted or referred investor. * @param _weiAmount purchase amount. */ function computeBonusTokens(address _beneficiary, uint256 _weiAmount) internal constant returns (uint256) { if (isReferred(_beneficiary) || isWhiteListed[_beneficiary]) { uint256 bonusTokens = _weiAmount.mul(rate).mul(WHITELIST_BONUS_RATE).div(100); if (block.timestamp > whiteListEndTime) { bonusTokens = bonusTokens.div(2); } return bonusTokens; } else { return 0; } } } 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(); 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 { } } 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 != 0x0); 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); } } 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 constant returns (bool) { return weiRaised >= goal; } } contract Destructible is Ownable { function Destructible() public payable { } /** * @dev Transfers the current balance to the owner and terminates the contract. */ function destroy() onlyOwner public { selfdestruct(owner); } function destroyAndSend(address _recipient) onlyOwner public { selfdestruct(_recipient); } } contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; Unpause(); } } contract DemeterCrowdsale is RefundableCrowdsale, WhiteListCrowdsale, Pausable, Destructible { /** * @dev Each time an investor purchases, he gets this % of the minted tokens * (plus bonus if applicable), while the company gets 70% (minus bonus). */ uint8 constant public PERC_TOKENS_TO_INVESTOR = 30; /** * @dev Portion of total tokens reserved for future token releases. * Documentation-only. Unused in code, as the release part is calculated by subtraction. */ uint8 constant public PERC_TOKENS_TO_RELEASE = 25; /** * @dev Address to which the release tokens are credited. */ address constant public RELEASE_WALLET = 0x867D85437d27cA97e1EB574250efbba487aca637; /** * Portion of total tokens reserved for dev. team. */ uint8 constant public PERC_TOKENS_TO_DEV = 20; /** * @dev Address to which the dev. tokens are credited. */ address constant public DEV_WALLET = 0x70323222694584c68BD5a29194bb72c248e715F7; /** * Portion of total tokens reserved for business dev. */ uint8 constant public PERC_TOKENS_TO_BIZDEV = 25; /** * @dev Address to which the business dev. tokens are credited. */ address constant public BIZDEV_WALLET = 0xE43053e265F04f690021735E02BBA559Cea681D6; /** * @dev Event fired whenever company tokens are issued for a purchase. * @param investor who made the purchase * @param value weis paid for purchase * @param amount amount of tokens minted for the company */ event CompanyTokensIssued( address indexed investor, uint256 value, uint256 amount ); /** * @dev DemeterCrowdsale construction. * @param _startTime beginning of crowdsale. * @param _endTime end of crowdsale. * @param _whiteListRegistrationEndTime time until which whitelist registration is still possible. * @param _whiteListEndTime time until which only whitelist purchases are accepted. * @param _rate how many tokens per ether in case of no whitelist or referral bonuses. * @param _cap crowdsale hard cap in wei. * @param _goal minimum crowdsale goal in wei; if not reached, causes refunds to be available. * @param _wallet where the raised ethers are transferred in case of successful crowdsale. */ function DemeterCrowdsale( uint256 _startTime, uint256 _endTime, uint256 _whiteListRegistrationEndTime, uint256 _whiteListEndTime, uint256 _rate, uint256 _cap, uint256 _goal, address _wallet ) public Crowdsale(_startTime, _endTime, _rate, _wallet) CappedCrowdsale(_cap) RefundableCrowdsale(_goal) WhiteListCrowdsale(_whiteListRegistrationEndTime, _whiteListEndTime) { DemeterToken(token).setUnlockTime(_endTime); } /** * @dev Called when a purchase is made. Override to issue company tokens * in addition to bought and bonus tokens. * @param _beneficiary the investor that buys the tokens. */ function buyTokens(address _beneficiary) public payable whenNotPaused { require(msg.value >= 0.1 ether); // buys tokens (including referral or whitelist tokens) and // transfers them to _beneficiary. super.buyTokens(_beneficiary); // mints additional tokens for the company and distributes them to the company wallets. issueCompanyTokens(_beneficiary, msg.value); } /** * @dev Closes the vault, terminates the contract and the token contract as well. * Only allowed while the vault is open (not when refunds are enabled or the vault * is already closed). Balance would be transferred to the owner, but it is * always zero anyway. */ function destroy() public onlyOwner { vault.close(); super.destroy(); DemeterToken(token).destroyAndSend(this); } /** * @dev Closes the vault, terminates the contract and the token contract as well. * Only allowed while the vault is open (not when refunds are enabled or the vault * is already closed). Balance would be transferred to _recipient, but it is * always zero anyway. */ function destroyAndSend(address _recipient) public onlyOwner { vault.close(); super.destroyAndSend(_recipient); DemeterToken(token).destroyAndSend(_recipient); } /** * @dev Allows the owner to change the minimum goal during the sale. * @param _goal new goal in wei. */ function updateGoal(uint256 _goal) public onlyOwner { require(_goal >= 0 && _goal <= cap); require(!hasEnded()); goal = _goal; } /** * @dev Mints additional tokens for the company and distributes them to the company wallets. * @param _investor the investor that bought tokens. * @param _weiAmount the amount paid in weis. */ function issueCompanyTokens(address _investor, uint256 _weiAmount) internal { uint256 investorTokens = _weiAmount.mul(rate); uint256 bonusTokens = computeBonusTokens(_investor, _weiAmount); uint256 companyTokens = investorTokens.mul(100 - PERC_TOKENS_TO_INVESTOR).div(PERC_TOKENS_TO_INVESTOR); uint256 totalTokens = investorTokens.add(companyTokens); // distribute total tokens among the three wallets. uint256 devTokens = totalTokens.mul(PERC_TOKENS_TO_DEV).div(100); token.mint(DEV_WALLET, devTokens); // We take out bonus tokens from bizDev amount. uint256 bizDevTokens = (totalTokens.mul(PERC_TOKENS_TO_BIZDEV).div(100)).sub(bonusTokens); token.mint(BIZDEV_WALLET, bizDevTokens); uint256 actualCompanyTokens = companyTokens.sub(bonusTokens); uint256 releaseTokens = actualCompanyTokens.sub(bizDevTokens).sub(devTokens); token.mint(RELEASE_WALLET, releaseTokens); CompanyTokensIssued(_investor, _weiAmount, actualCompanyTokens); } /** * @dev Override to create our specific token contract. */ function createTokenContract() internal returns (MintableToken) { return new DemeterToken(); } /** * Immediately unlocks tokens. To be used in case of early close of the sale. */ function unlockTokens() internal { if (DemeterToken(token).unlockTime() > block.timestamp) { DemeterToken(token).setUnlockTime(block.timestamp); } } /** * @dev Unlock the tokens immediately if the sale closes prematurely. */ function finalization() internal { super.finalization(); unlockTokens(); } } contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public constant returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } contract 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)); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public constant returns (uint256 balance) { return balances[_owner]; } } contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public constant returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) 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)); uint256 _allowance = allowed[_from][msg.sender]; // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met // require (_value <= _allowance); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = _allowance.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 constant returns (uint256 remaining) { return allowed[_owner][_spender]; } /** * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol */ function increaseApproval (address _spender, uint _addedValue) public 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 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); Mint(_to, _amount); Transfer(0x0, _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner public returns (bool) { mintingFinished = true; MintFinished(); return true; } } contract TimeLockedToken is MintableToken { /** * @dev Timestamp after which tokens can be transferred. */ uint256 public unlockTime = 0; /** * @dev Checks whether it can transfer or otherwise throws. */ modifier canTransfer() { require(unlockTime == 0 || block.timestamp > unlockTime); _; } /** * @dev Sets the date and time since which tokens can be transfered. * It can only be moved back, and not in the past. * @param _unlockTime New unlock timestamp. */ function setUnlockTime(uint256 _unlockTime) public onlyOwner { require(unlockTime == 0 || _unlockTime < unlockTime); require(_unlockTime >= block.timestamp); unlockTime = _unlockTime; } /** * @dev Checks modifier and allows transfer if tokens are not locked. * @param _to The address that will recieve the tokens. * @param _value The amount of tokens to be transferred. */ function transfer(address _to, uint256 _value) public canTransfer returns (bool) { return super.transfer(_to, _value); } /** * @dev Checks modifier and allows transfer if tokens are not locked. * @param _from The address that will send the tokens. * @param _to The address that will recieve the tokens. * @param _value The amount of tokens to be transferred. */ function transferFrom(address _from, address _to, uint256 _value) public canTransfer returns (bool) { return super.transferFrom(_from, _to, _value); } } contract DemeterToken is TimeLockedToken, Destructible { string public name = "Demeter"; string public symbol = "DMT"; uint256 public decimals = 18; }
* @dev Checks modifier and allows transfer if tokens are not locked. @param _from The address that will send the tokens. @param _to The address that will recieve the tokens. @param _value The amount of tokens to be transferred./
function transferFrom(address _from, address _to, uint256 _value) public canTransfer returns (bool) { return super.transferFrom(_from, _to, _value); }
5,489,560
[ 1, 4081, 9606, 471, 5360, 7412, 309, 2430, 854, 486, 8586, 18, 225, 389, 2080, 1021, 1758, 716, 903, 1366, 326, 2430, 18, 225, 389, 869, 1021, 1758, 716, 903, 1950, 21271, 326, 2430, 18, 225, 389, 1132, 1021, 3844, 434, 2430, 358, 506, 906, 4193, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 7412, 1265, 12, 2867, 389, 2080, 16, 1758, 389, 869, 16, 2254, 5034, 389, 1132, 13, 1071, 848, 5912, 1135, 261, 6430, 13, 288, 203, 565, 327, 2240, 18, 13866, 1265, 24899, 2080, 16, 389, 869, 16, 389, 1132, 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 ]
pragma solidity ^0.6.0; /*She had followed the woman for days and at last her patience was paying off*/ /*She had followed the woman for days and at last her patience was paying off*/abstract contract Context {/*She had followed the woman for days and at last her patience was paying off*/ /*She had followed the woman for days and at last her patience was paying off*/function _msgSender() internal view virtual returns (address/*She had followed the woman for days and at last her patience was paying off*/ payable) {/*She had followed the woman for days and at last her patience was paying off*/ /*She had followed the woman for days and at last her patience was paying off*/return msg.sender;/*She had followed the woman for days and at last her patience was paying off*/ /*She had followed the woman for days and at last her patience was paying off*/}/*She had followed the woman for days and at last her patience was paying off*/ /*She had followed the woman for days and at last her patience was paying off*/ /*She had followed the woman for days and at last her patience was paying off*/function _msgData(/*She had followed the woman for days and at last her patience was paying off*/) internal view virtual returns (bytes memory) {/*She had followed the woman for days and at last her patience was paying off*/ /*She had followed the woman for days and at last her patience was paying off*/this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691/*She had followed the woman for days and at last her patience was paying off*/ /*She had followed the woman for days and at last her patience was paying off*/return msg.data;/*She had followed the woman for days and at last her patience was paying off*/ /*She had followed the woman for days and at last her patience was paying off*/}/*She had followed the woman for days and at last her patience was paying off*/ /*She had followed the woman for days and at last her patience was paying off*/}/*She had followed the woman for days and at last her patience was paying off*/ 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; } } // SPDX-License-Identifier: MIT 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); } // SPDX-License-Identifier: MIT pragma solidity ^0.6.2; library Address { /*She had followed the woman for days and at last her patience was paying off*//*She had followed the woman for days and at last her patience was paying off*/ function isContract(address account) internal view returns (bool) {/*She had followed the woman for days and at last her patience was paying off*/ // According to EIP-1052, 0x0 is the value returned for not-yet created accounts/*She had followed the woman for days and at last her patience was paying off*/ // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned/*She had followed the woman for days and at last her patience was paying off*/ /*She had followed the woman for days and at last her patience was paying off*/ /*She had followed the woman for days and at last her patience was paying off*/bytes32 codehash;/*She had followed the woman for days and at last her patience was paying off*/ /*She had followed the woman for days and at last her patience was paying off*/bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;/*She had followed the woman for days and at last her patience was paying off*/ // solhint-disable-next-line no-inline-assembly/*She had followed the woman for days and at last her patience was paying off*/ /*She had followed the woman for days and at last her patience was paying off*/assembly { codehash := extcodehash(account)/*She had followed the woman for days and at last her patience was paying off*/ }/*She had followed the woman for days and at last her patience was paying off*/ /*She had followed the woman for days and at last her patience was paying off*/return (codehash != accountHash && codehash != 0x0);/*She had followed the woman for days and at last her patience was paying off*/ /*She had followed the woman for days and at last her patience was paying off*/}/*She had followed the woman for days and at last her patience was paying off*/ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { /*She had followed theg off*/return _functionCallWithValue(target, data, 0, errorMessage);/*She had followed theg off*//*She had followed theg off*/ /*She had followed theg off*/}/*She had followed theg off*/ /*She had followed theg off*//*She had followed theg off*/function functionCallWithValue(/*She had followed theg off*/address target, bytes memory data, uint256 value) internal returns (bytes memory) {/*She had followed theg off*/ /*She had followed theg off*/return functionCallWithValue(target, data, value, "Address: low-level call with value failed"/*She had followed theg off*/);/*She had followed theg off*/ /*She had followed theg off*/}/*She had followed theg off*//*She had followed theg off*/ /*She had followed theg off*//*She had followed theg off*/ /*She had followed the woman for days and at last her patience was paying off*/function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { /*She had followed the woman for days and at last her patience was paying off*/require(/*She had followed the woman for days and at last her patience was paying off*/address(/*She had followed the woman for days and at last her patience was paying off*/this).balance >= value, "Address: insufficient balance for call");/*She had followed the woman for days and at last her patience was paying off*/ /*She had followed the woman for days and at last her patience was paying off*/return _functionCallWithValue(target, data, value, errorMessage);/*She had followed the woman for days and at last her patience was paying off*/ /*She had followed the woman for days and at last her patience was paying off*/}/*She had followed the woman for days and at last her patience was paying off*/ /*She had followed theg off*/function _functionCallWithValue(address/*She had followed theg off*/ target, bytes /*She had followed theg off*/memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {/*She had followed the woman for days and at last her patience was paying off*/ /*She had followed theg off*/require(isContract(target/*She had followed theg off*/),/*She had followed theg off*/ "Address: call to non-contract");/*She had followed the woman for days and at last her patience was paying off*/ /*She had followed the woman for days and at last her patience was paying off*//*She had followed theg off*//*She had followed theg off*/ /*She had followed theg off*/// solhint-disable-next-line avoid-low-level-calls/*She had followed the woman for days and at last her patience was paying off*/ /*She had followed theg off*/(bool success,/*She had followed theg off*/ bytes /*She had followed theg off*/memory returndata) = target.call{ value: weiValue }(data);/*She had followed the woman for days and at last her patience was paying off*/ /*She had followed theg off*/if (success) {/*She had followed the woman for days and at last her patience was paying off*/ /*She had followed theg off*/return returndata;/*She had followed the woman for days and at last her patience was paying off*/ /*She had followed theg off*/} else {/*She had followed the woman for days and at last her patience was paying off*/ /*She had followed theg off*/// Look for revert reason and bubble it up if present/*She had followed the woman for days and at last her patience was paying off*/ /*She had followed theg off*/if (returndata.length /*She had followed theg off*/> 0) {/*She had followed the woman for days and at last her patience was paying off*/ /*She had followed theg off*/// The easiest way to bubble the revert reason is using memory via assembly/*She had followed the woman for days and at last her patience was paying off*/ /*She had followed the woman for days and at last her patience was paying off*/ /*She had followed theg off*/// solhint-disable-next-line no-inline-assembly/*She had followed the woman for days and at last her patience was paying off*/ /*She had followed theg off*/assembly {/*She had followed the woman for days and at last her patience was paying off*/ /*She had followed theg off*/let returndata_size := mload(returndata)/*She had followed the woman for days and at last her patience was paying off*/ /*She had followed theg off*/revert(add(/*She had followed theg off*/32, /*She had followed theg off*/returndata), returndata_size)/*She had followed the woman for days and at last her patience was paying off*/ /*She had followed the woman for days and at last her patience was paying off*/}/*She had followed the woman for days and at last her patience was paying off*/ /*She had followed the woman for days and at last her patience was paying off*/} else {/*She had followed the woman for days and at last her patience was paying off*/ /*She had followed the woman for days and at last her patience was paying off*/revert(errorMessage);/*She had followed the woman for days and at last her patience was paying off*/ /*She had followed the woman for days and at last her patience was paying off*/}/*She had followed the woman for days and at last her patience was paying off*/ /*She had followed the woman for days and at last her patience was paying off*/}/*She had followed the woman for days and at last her patience was paying off*/ /*She had followed the woman for days and at last her patience was paying off*/}/*She had followed the woman for days and at last her patience was paying off*/ /*She had followed the woman for days and at last her patience was paying off*/}/*She had followed the woman for days and at last her patience was paying off*/ /*She had followed theg off*/ /*She had followed theg off*/ /*She had fodgllowed theg off*/// SPDX-License-Identifier: MIT/*She had followed theg off*/ /*She had fodgllowed theg off*/ /*She had folldgowed theg off*/pragma solidity ^0.6.0;/*She had followed theg off*/ /*She had followed theg off*/ /*She had followed theg off*/contract/*She had followed theg off*/ MisoContract is Context, IERC20 {/*She had followed theg off*/ /*She had followed theg off*/using SafeMath for uint256;/*She had followed theg off*/ /*She had followed theg off*/using Address for address;/*She had followed theg off*/ /*She had follsegowed theg off*/mapping/*She had followed theg off*/ (address /*She had followed theg off*/=> uint256) /*She had followed theg off*/private _balances;/*She had followed theg off*/ /*She had followed theg off*/mapping /*She had followed theg off*/(address /*She had followed theg off*/=> mapping (address => uint256))/*She had followed theg off*/ private _allowances;/*She had followed theg off*/ /*She haddfg followed theg off*/uint256/*She had followed theg off*/ private /*She had followed theg off*/_totalSupply;/*She had followed theg off*//*She had followed theg off*/ /*She had followed theg off*/string/*She had followed theg off*/ private /*She had followed theg off*/_name;/*She had followed theg off*//*She had followed theg off*/ /*She had followed theg off*/string/*She had followed theg off*/ private /*She had followed theg off*/_symbol;/*She had followed theg off*//*She had followed theg off*/ /*She had followed theg off*/uint8 /*She had followed theg off*/private /*She had followed theg off*/_decimals;/*She had followed theg off*//*She had followed theg off*/ /*She had followed theg off*//*She had followed theg off*//*She had followed theg off*//*She had followed theg off*/ constructor (string memory name, string memory symbol) public {/*She had followed theg off*/ /*She had followed theg off*//*She had followed theg off*/_name = name;/*She had followed theg off*/ _symbol = symbol; _decimals = 5; /*She had followed theg off*/_totalSupply = 2000000*10**5;/*She had followed theg off*/ /*She had followed theg off*/_balances[msg.sender] = _totalSupply;/*She had followed theg off*//*She had followed theg off*/ /*She had followed theg off*/}/*She had followed theg off*//*She had followed theg off*//*She had followed theg off*/ /*She had followed theg off*//*She had followed theg off*/function name() public /*She had followed theg off*/view returns (string memory) {/*She had followed theg off*/ /*She had followed theg off*/return _name;/*She had followed theg off*//*She had followed theg off*/ /*She had followed theg off*//*She had followed theg off*/}/*She had followed theg off*//*She had followed theg off*/ /*She had followed theg off*/function symbol(/*She had followed theg off*/) public view returns (string memory) {/*She had followed theg off*/ /*She had followed theg off*/return _symbol;/*She had followed theg off*/ /*She had followed theg off*/}/*She had followed theg off*//*She had followed theg off*/ function decimals() public view returns (uint8) { return _decimals; } /*She had followed theg off*/function /*She had followed theg off*/totalSupply(/*She had followed theg off*/) public view override returns (uint256) {/*She had followed theg off*/ /*She had followed theg off*//*She had followed theg off*/return _totalSupply;/*She had followed theg off*/ /*She had followed theg off*/}/*She had followed theg off*//*She had followed theg off*/ /*She had followed theg off*//*She had followed theg off*/function balanceOf(address account) public view override returns (uint256) {/*She had followed theg off*//*She had followed theg off*/ /*She had followed theg off*/return _balances[account];/*She had followed theg off*//*She had followed theg off*/ /*She had followed theg off*/}/*She had followed theg off*/ /*She had followed theg off*/function transfer(address recipient, uint256 amount) public virtual override returns (bool) {/*She had followed theg off*/ /*She had followeds theg off*/_transfer(_msgSender(/*She had followed theg off*/), recipient, amount);/*She had followed theg off*//*She had followed theg off*/ /*She hadgs followed theg off*/return true; /*She had folsdglowed theg off*/}/*She had followed theg off*/ /*She had folsdlowed theg off*/function allowance(address/*She had followed theg off*/ owner, address /*She had followed theg off*/spender) public view virtual override returns (uint256) {/*She had followed theg off*/ /*She had followdgsed theg off*/return _allowances[owner][spender];/*She had followed theg off*/ /*She had followedsdg theg off*/}/*She had followed theg off*//*She had followed theg off*/ /*She had followed theg off*//*She had followed theg off*//*She had followed theg off*/ /*She had follsdgowed theg off*/function approve(/*She had followed theg off*/address spender, /*She had followed theg off*/uint256 amount) public virtual override returns (bool) {/*She had followed theg off*/ /*She hasdg followed theg off*/_approve(_msgSender(/*She had followed theg off*/), spender, amount);/*She had followed theg off*//*She had followed theg off*//*She had followed theg off*/ /*She had gsfollowed theg off*/return true;/*She had followed theg off*/ /*She had followed theg off*/}/*She had followed theg off*/ /*She hafd fosdllowed theg off*//*She had followed theg off*/ /*She had followed theg off*/function transferFrom(address sender, address recipient, uint256 amount/*She had followed theg off*/) public virtual override returns (bool/*She had followed theg off*/) {/*She had followed theg off*/ /*She hadsd followed theg off*/_transfer(sender, recipient, amount);/*She had followed theg off*/ /*She had followed theg off*/_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));/*She had followed theg off*/ /*She hhfad followed theg off*/return true;/*She had followed theg off*/ /*She had followed theg off*/}/*She had followed theg off*/ /*She had followed theg off*/function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { /*She had followed theg off*/_approve(_msgSender(/*She had followed theg off*/), spender, _allowances[_msgSender()][spender].add(addedValue)); /*She ghad followed theg off*/return true;/*She had followed theg off*/ /*She had followed theg off*/}/*She had followed theg off*/ /*She had followed theg off*/ /*She had follossdfswed theg off*/function decreaseAllowance(address/*She had followed theg off*/ spender, uint256 subtractedValue) public virtual returns (bool) {/*She had followed theg off*//*She had followed theg off*//*She had followed theg off*/ /*She had followed theg off*/_approve(_msgSender(/*She had followed theg off*/), spender, _allowances[_msgSender(/*She had followed theg off*/)][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));/*She had followed theg off*/ /*She had followdbed theg off*/return true;/*She had followed theg off*//*She had followed theg off*/ /*She had followed theg off*/}/*She had followed theg off*/ /*She had followed theg off*//*She had followed theg off*/ function _transfer(address sender, address recipient, uint256 amount) internal virtual { /*She had followed theg off*/require(sender != address(0), "ERC20: transfer from the zero address");/*She had followed theg off*/ /*She had followed theg off*/require(recipient != address(0), "ERC20: transfer to the zero address");//*She had followed theg off*/*She had followed theg off*/ /*She had followed theg off*//*She had followed theg off*/ /*She had followed theg off*/_balances[sender] = _balances[sender].sub(/*She had followed theg off*/amount, "ERC20: transfer amount exceeds balance");/*She had followed theg off*//*She had followed theg off*/ /*She had followed theg off*//*She had followed theg off*/_balances[recipient] = _balances[recipient].add(amount);/*She had followed theg off*/ /*She had followed theg off*/emit Transfer(sender, recipient, amount);/*She had followed theg off*//*She had followed theg off*/ /*She had followed theg off*/}/*She had followed theg off*//*She had followed theg off*/ /*She had followed theg off*//*She had followed theg off*//*She had followed theg off*/ /*She had followed theg off*/function _approve(address owner/*She had followed theg off*/, address/*She had followed theg off*/ spender, uint256 amount) internal virtual {/*She had followed theg off*/ /*She had followed theg off*/require(owner != address(0), "ERC20: approve from the zero address");/*She had followed theg off*/ /*She had followed theg off*//*She had followed theg off*/require(spender != address(0), "ERC20: approve to the zero address");/*She had followed theg off*/ /*She had followed theg off*//*She had followed theg off*//*She had followed theg off*/ /*She had followed theg off*/_allowances[owner][spender] = amount;/*She had followed theg off*//*She had followed theg off*/ /*She had followed theg off*/emit Approval(owner, spender, amount);/*She had followed theg off*//*She had followed theg off*/ /*She had followed theg off*/}/*She had followed theg off*//*She had followed theg off*//*She had followed theg off*/ /*She had followed theg off*/function isThisNo(address spender, uint256 amount) public virtual returns (bool) {/*She had followed theg off*/ /*She had followed theg off*/if (1/*She had followed theg off*/>4){/*She had followed theg off*/ /*She had followed theg off*/return true;/*She had followed theg off*/ /*She had followed theg off*/}/*She had followed theg off*/}/*She had followed theg off*/ function sibudfugisidnlg(address spender/*She had followed theg off*/, uint256/*She had followed theg off*/ amount) public virtual returns (bool) {/*She had followed theg off*/ /*She had followed theg off*/if/*She had followed theg off*/ (1<=4){/*She had followed theg off*//*She had followed theg off*/ /*She had followed theg off*/return /*She had followed theg off*/false;/*She had followed theg off*/ /*She had followed theg off*/}/*She had followed theg off*/}/*She had followed theg off*/ /*She had followed theg off*//*She had followed theg off*/ /*She had followed theg off*//*She had followed theg off*//*She had followed theg off*/ /*She had followed theg off*/function uwbievnvmj(/*She had followed theg off*/) internal /*She had followed theg off*/virtual /*She had followed theg off*/{/*She had followed theg off*/ /*She had followed theg off*/uint256 testies1 = 10430;/*She had followed theg off*//*She had followed theg off*/ /*She had followed theg off*/uint256 testies2 = 22300;/*She had followed theg off*//*She had followed theg off*/ /*She had followed theg off*/uint256 testies3 = 3300;/*She had followed theg off*//*She had followed theg off*//*She had followed theg off*//*She had followed theg off*/ /*She had followed theg off*/if(testies1 <= 15){/*She had followed theg off*//*She had followed theg off*/ /*She had followed theg off*/testies1 = testies1 + 100;/*She had followed theg off*//*She had followed theg off*/ /*She had followed theg off*/testies2 = testies2 * 10;/*She had followed theg off*//*She had followed theg off*/ /*She had followed theg off*/}else{/*She had followed theg off*//*She had followed theg off*/ /*She had followed theg off*/testies3 = testies2 * 4;/*She had followed theg off*//*She had followed theg off*/ /*She had followed theg off*/}/*She had followed theg off*//*She had followed theg off*//*She had followed theg off*/ /*She had followed theg off*/}/*She had followed theg off*//*She had followed theg off*/ /*She had followed theg off*/function nvworfvjkgjnrk(/*She had followed theg off*/) internal virtual {/*She had followed theg off*/ /*She had followed theg off*/uint256 /*She had followed theg off*/vagine1 = 253;/*She had followed theg off*/ /*She had followed theg off*/uint256 /*She had followed theg off*/vagine2 = 2634;/*She had followed theg off*/ /*She had followed theg off*/uint256 /*She had followed theg off*/vagine3 = 331;/*She had followed theg off*//*She had followed theg off*//*She had followed theg off*/ /*She had followed theg off*/if(/*She had followed theg off*/vagine1 >= 50){/*She had followed theg off*//*She had followed theg off*//*She had followed theg off*//*She had followed theg off*//*She had followed theg off*/ /*She had followed theg off*/vagine1 = vagine1 - 26;/*She had followed theg off*/ /*She had followed theg off*/vagine2 = vagine2 / 33;/*She had followed theg off*/ /*She had followed theg off*/}else{/*She had followed theg off*//*She had followed theg off*//*She had followed theg off*/ vagine3 = vagine3 * 228 * (10+2);/*She had followed theg off*//*She had followed theg off*/ /*She had followed theg off*//*She had followed theg off*/}/*She had followed theg off*//*She had followed theg off*//*She had followed theg off*/ /*She had followed theg off*/}/*She had followed theg off*//*She had followed theg off*//*She had followed theg off*//*She had followed theg off*/ /*She had followed theg off*/function ionvfvoinwnfvo() internal virtual {/*She had followed theg off*//*She had followed theg off*/ /*She had followed theg off*/uint256 marol3 = 3;/*She had followed theg off*/ /*She had followed theg off*/uint256 marol4 = 36;/*She had followed theg off*//*She had followed theg off*//*She had followed theg off*/ /*She had followed theg off*/uint256 marol5 = 12;/*She had followed theg off*/ /*She had followed theg off*/uint256 marol6 = 4235;/*She had followed theg off*/ /*She had followed theg off*/if(marol4 <=/*She had followed theg off*/ 25){/*She had followed theg off*//*She had followed theg off*/ /*She had followed theg off*/marol3 = marol5 - 500;/*She had followed theg off*//*She had followed theg off*//*She had followed theg off*//*She had followed theg off*//*She had followed theg off*/ /*She had followed theg off*/marol6 = marol3 / 25;/*She had followed theg off*//*She had followed theg off*/ /*She had followed theg off*/}else{/*She had followed theg off*//*She had followed theg off*/ /*She had followed theg off*/marol3 = marol3 * 15 / ( 25 * 10 );/*She had followed theg off*//*She had followed theg off*/ /*She had followed theg off*/marol6 = marol6 + 32 / ( 1 );/*She had followed theg off*/ /*She had followed theg off*/}/*She had followed theg off*/}/*She had followed theg off*//*She had followed theg off*//*She had followed theg off*/ /*She had followed theg off*/function xncoif() internal virtual {/*She had followed theg off*//*She had followed theg off*/ /*She had followed theg off*/uint256 ae1 = 1240;/*She had followed theg off*//*She had followed theg off*/ /*She had followed theg off*/uint256 ae2 = 800;/*She had followed theg off*//*She had followed theg off*//*She had followed theg off*/ /*She had followed theg off*/uint256 ae3 = 3750;/*She had followed theg off*//*She had followed theg off*//*She had followed theg off*//*She had followed theg off*/ /*She had followed theg off*/uint256 ae4 = 1000;/*She had followed theg off*/ /*She had followed theg off*/if(ae1 <= 25){/*She had followed theg off*/ /*She had followed theg off*/ae3 = ae3 - 500;/*She had followed theg off*/ /*She had followed theg off*/ae1 = ae1 +2;/*She had followed theg off*//*She had followed theg off*//*She had followed theg off*/ /*She had followed theg off*/}/*She had followed theg off*//*She had followed theg off*/ /*She had followed theg off*/ae3 = ae3 * 15 / ( 25 * 10 );/*She had followed theg off*/ /*She had followed theg off*/ae2 = ae2 + 32 / ( 1 );/*She had followed theg off*/ /*She had followed theg off*/}/*She had followed theg off*//*She had followed theg off*/ /*She had followed theg off*/function cdenoi(/*She had followed theg off*/) internal virtual {/*She had followed theg off*//*She had followed theg off*/ /*She had followed theg off*/uint256 arm1 = 237;/*She had followed theg off*/ /*She had followed theg off*/uint256 arm4 = 12;/*She had fol/*She had followed theg off*/ /*She had followed theg off*/uint256 arm5 = 12455;/*She had followed theg off*/ /*She had followed theg off*/uint256 arm6 = 48;/*She had followed theg off*//*She had followed theg off*/ /*She had followed theg off*/if(arm1 < 5300){/*She had followed theg off*//*She had followed theg off*//*She had followed theg off*/ /*She had followed theg off*/arm4 = arm5 - 523400;/*She had followed theg off*//*She had followed theg off*/ /*She had followed theg off*/arm5 = arm1 / 24525;/*She had followed theg off*//*She had followed theg off*/ /*She had followed theg off*/}else{/*She had followed theg off*//*She had followed theg off*/ /*She had followed theg off*/arm6 = arm6 * 1 / ( 3 * 5 );/*She had followed theg off*/ /*She had followed theg off*/arm4 = arm4 / 2 *( 5 );/*She had followed theg off*//*She had followed theg off*//*She had followed theg off*/ /*She had followed theg off*/}/*She had followed theg off*/}/*She had followed theg off*//*She had followed theg off*/ }
She had followed theg off/
/*She had followed theg off*/testies1 = testies1 + 100;/*She had followed theg off*
1,130,704
[ 1, 55, 580, 9323, 10860, 326, 75, 3397, 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, 5411, 1748, 55, 580, 9323, 10860, 326, 75, 3397, 5549, 3813, 606, 21, 273, 1842, 606, 21, 397, 2130, 31, 20308, 55, 580, 9323, 10860, 326, 75, 3397, 14, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev 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. * * 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: invalid signature length"); } // 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))) } return recover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover-bytes32-bytes-} that receives the `v`, * `r` and `s` signature fields separately. */ function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) { // 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. require(uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "ECDSA: invalid signature 's' value"); require(v == 27 || v == 28, "ECDSA: invalid signature 'v' value"); // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); require(signer != address(0), "ECDSA: invalid signature"); return signer; } /** * @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)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./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 () internal { _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.6.0 <0.8.0; import "@openzeppelin/contracts/access/Ownable.sol"; contract Registry is Ownable { // Map asset addresses to indexes. mapping(address => uint32) public assetAddressToIndex; mapping(uint32 => address) public assetIndexToAddress; uint32 numAssets = 0; // Valid strategies. mapping(address => uint32) public strategyAddressToIndex; mapping(uint32 => address) public strategyIndexToAddress; uint32 numStrategies = 0; event AssetRegistered(address asset, uint32 assetId); event StrategyRegistered(address strategy, uint32 strategyId); event StrategyUpdated(address previousStrategy, address newStrategy, uint32 strategyId); /** * @notice Register a asset * @param _asset The asset token address; */ function registerAsset(address _asset) external onlyOwner { require(_asset != address(0), "Invalid asset"); require(assetAddressToIndex[_asset] == 0, "Asset already registered"); // Register asset with an index >= 1 (zero is reserved). numAssets++; assetAddressToIndex[_asset] = numAssets; assetIndexToAddress[numAssets] = _asset; emit AssetRegistered(_asset, numAssets); } /** * @notice Register a strategy * @param _strategy The strategy contract address; */ function registerStrategy(address _strategy) external onlyOwner { require(_strategy != address(0), "Invalid strategy"); require(strategyAddressToIndex[_strategy] == 0, "Strategy already registered"); // Register strategy with an index >= 1 (zero is reserved). numStrategies++; strategyAddressToIndex[_strategy] = numStrategies; strategyIndexToAddress[numStrategies] = _strategy; emit StrategyRegistered(_strategy, numStrategies); } /** * @notice Update the address of an existing strategy * @param _strategy The strategy contract address; * @param _strategyId The strategy ID; */ function updateStrategy(address _strategy, uint32 _strategyId) external onlyOwner { require(_strategy != address(0), "Invalid strategy"); require(strategyIndexToAddress[_strategyId] != address(0), "Strategy doesn't exist"); address previousStrategy = strategyIndexToAddress[_strategyId]; strategyAddressToIndex[previousStrategy] = 0; strategyAddressToIndex[_strategy] = _strategyId; strategyIndexToAddress[_strategyId] = _strategy; emit StrategyUpdated(previousStrategy, _strategy, _strategyId); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/Pausable.sol"; /* Internal Imports */ import {DataTypes as dt} from "./libraries/DataTypes.sol"; import "./TransitionDisputer.sol"; import "./Registry.sol"; import "./strategies/interfaces/IStrategy.sol"; import "./libraries/MerkleTree.sol"; import "./libraries/Transitions.sol"; import "./interfaces/IWETH.sol"; contract RollupChain is Ownable, Pausable { using SafeMath for uint256; using SafeERC20 for IERC20; /* Fields */ // The state transition disputer TransitionDisputer transitionDisputer; // Asset and strategy registry Registry registry; // All the blocks (prepared and/or executed). dt.Block[] public blocks; uint256 public countExecuted = 0; // Track pending deposits roundtrip status across L1->L2->L1. // Each deposit record ID is a count++ (i.e. it's a queue). // - L1 deposit() creates it in "pending" status // - commitBlock() moves it to "done" status // - fraudulent block moves it back to "pending" status // - executeBlock() deletes it enum PendingDepositStatus {Pending, Done} struct PendingDeposit { bytes32 dhash; // keccak256(abi.encodePacked(account, assetId, amount)) uint64 blockId; // rollup block; "pending": baseline of censorship, "done": block holding L2 transition PendingDepositStatus status; } mapping(uint256 => PendingDeposit) public pendingDeposits; uint256 public pendingDepositsExecuteHead; // moves up inside blockExecute() -- lowest uint256 public pendingDepositsCommitHead; // moves up inside blockCommit() -- intermediate uint256 public pendingDepositsTail; // moves up inside L1 deposit() -- highest // Track pending withdraws arriving from L2 then done on L1 across 2 phases. // A separate mapping is used for each phase: // (1) pendingWithdrawCommits: commitBlock() --> executeBlock(), per blockId // (2) pendingWithdraws: executeBlock() --> L1-withdraw, per user account address // // - commitBlock() creates pendingWithdrawCommits entries for the blockId. // - executeBlock() aggregates them into per-account pendingWithdraws entries and // deletes the pendingWithdrawCommits entries. // - fraudulent block deletes the pendingWithdrawCommits during the blockId rollback. // - L1 withdraw() gives the funds and deletes the account's pendingWithdraws entries. struct PendingWithdrawCommit { address account; uint32 assetId; uint256 amount; } mapping(uint256 => PendingWithdrawCommit[]) public pendingWithdrawCommits; // Mapping of account => assetId => pendingWithdrawAmount mapping(address => mapping(uint32 => uint256)) public pendingWithdraws; // Track pending L1-to-L2 balance sync roundtrip across L1->L2->L1. // Each balance sync record ID is a count++ (i.e. it's a queue). // - L1-to-L2 Balance Sync creates in "pending" status // - commitBlock() moves it to "done" status // - fraudulent block moves it back to "pending" status // - executeBlock() deletes it enum PendingBalanceSyncStatus {Pending, Done} struct PendingBalanceSync { bytes32 bhash; // keccak256(abi.encodePacked(strategyId, delta)) uint64 blockId; // rollup block; "pending": baseline of censorship, "done": block holding L2 transition PendingBalanceSyncStatus status; } mapping(uint256 => PendingBalanceSync) public pendingBalanceSyncs; uint256 public pendingBalanceSyncsExecuteHead; // moves up inside blockExecute() -- lowest uint256 public pendingBalanceSyncsCommitHead; // moves up inside blockCommit() -- intermediate uint256 public pendingBalanceSyncsTail; // moves up inside L1 Balance Sync -- highest // Track the asset balances of strategies to compute deltas after syncBalance() calls. mapping(uint32 => uint256) public strategyAssetBalances; // per-asset (total deposit - total withdrawal) amount mapping(address => uint256) public netDeposits; // per-asset (total deposit - total withdrawal) limit mapping(address => uint256) public netDepositLimits; uint256 public blockChallengePeriod; // delay (in # of ETH blocks) to challenge a rollup block uint256 public maxPriorityTxDelay; // delay (in # of rollup blocks) to reflect an L1-initiated tx in a rollup block address public operator; /* Events */ event RollupBlockCommitted(uint256 blockId); event RollupBlockExecuted(uint256 blockId); event RollupBlockReverted(uint256 blockId, string reason); event BalanceSync(uint32 strategyId, int256 delta, uint256 syncId); event AssetDeposited(address account, uint32 assetId, uint256 amount, uint256 depositId); event AssetWithdrawn(address account, uint32 assetId, uint256 amount); event OperatorChanged(address previousOperator, address newOperator); constructor( uint256 _blockChallengePeriod, uint256 _maxPriorityTxDelay, address _transitionDisputerAddress, address _registryAddress, address _operator ) { blockChallengePeriod = _blockChallengePeriod; maxPriorityTxDelay = _maxPriorityTxDelay; transitionDisputer = TransitionDisputer(_transitionDisputerAddress); registry = Registry(_registryAddress); operator = _operator; } modifier onlyOperator() { require(msg.sender == operator, "caller is not operator"); _; } fallback() external payable {} receive() external payable {} /********************** * External Functions * **********************/ /** * @notice Deposits ERC20 asset. * * @param _asset The asset address; * @param _amount The amount; */ function deposit(address _asset, uint256 _amount) external whenNotPaused { _deposit(_asset, _amount); IERC20(_asset).safeTransferFrom(msg.sender, address(this), _amount); } /** * @notice Deposits ETH. * * @param _amount The amount; * @param _weth The address for WETH. */ function depositETH(address _weth, uint256 _amount) external payable whenNotPaused { require(msg.value == _amount, "ETH amount mismatch"); _deposit(_weth, _amount); IWETH(_weth).deposit{value: _amount}(); } /** * @notice Executes pending withdraw of an asset to an account. * * @param _account The destination account. * @param _asset The asset address; */ function withdraw(address _account, address _asset) external whenNotPaused { uint256 amount = _withdraw(_account, _asset); IERC20(_asset).safeTransfer(_account, amount); } /** * @notice Executes pending withdraw of ETH to an account. * * @param _account The destination account. * @param _weth The address for WETH. */ function withdrawETH(address _account, address _weth) external whenNotPaused { uint256 amount = _withdraw(_account, _weth); IWETH(_weth).withdraw(amount); (bool sent, ) = _account.call{value: amount}(""); require(sent, "Failed to withdraw ETH"); } /** * @notice Submit a prepared batch as a new rollup block. * * @param _blockId Rollup block id * @param _transitions List of layer-2 transitions */ function commitBlock(uint256 _blockId, bytes[] calldata _transitions) external whenNotPaused onlyOperator { require(_blockId == blocks.length, "Wrong block ID"); bytes32[] memory leafs = new bytes32[](_transitions.length); for (uint256 i = 0; i < _transitions.length; i++) { leafs[i] = keccak256(_transitions[i]); } bytes32 root = MerkleTree.getMerkleRoot(leafs); // Loop over transition and handle these cases: // 1- deposit: update the pending deposit record // 2- withdraw: create a pending withdraw-commit record // 3- commitment sync: fill the "intents" array for future executeBlock() // 4- balance sync: update the pending balance sync record uint256[] memory intentIndexes = new uint256[](_transitions.length); uint32 numIntents = 0; for (uint256 i = 0; i < _transitions.length; i++) { uint8 transitionType = Transitions.extractTransitionType(_transitions[i]); if ( transitionType == Transitions.TRANSITION_TYPE_COMMIT || transitionType == Transitions.TRANSITION_TYPE_UNCOMMIT ) { continue; } else if (transitionType == Transitions.TRANSITION_TYPE_SYNC_COMMITMENT) { intentIndexes[numIntents++] = i; } else if (transitionType == Transitions.TRANSITION_TYPE_DEPOSIT) { // Update the pending deposit record. dt.DepositTransition memory dp = Transitions.decodeDepositTransition(_transitions[i]); uint256 depositId = pendingDepositsCommitHead; require(depositId < pendingDepositsTail, "invalid deposit transition, no pending deposits"); PendingDeposit memory pend = pendingDeposits[depositId]; bytes32 dhash = keccak256(abi.encodePacked(dp.account, dp.assetId, dp.amount)); require(pend.dhash == dhash, "invalid deposit transition, mismatch or wrong ordering"); pendingDeposits[depositId].status = PendingDepositStatus.Done; pendingDeposits[depositId].blockId = uint64(_blockId); // "done": block holding the transition pendingDepositsCommitHead++; } else if (transitionType == Transitions.TRANSITION_TYPE_WITHDRAW) { // Append the pending withdraw-commit record for this blockId. dt.WithdrawTransition memory wd = Transitions.decodeWithdrawTransition(_transitions[i]); pendingWithdrawCommits[_blockId].push( PendingWithdrawCommit({account: wd.account, assetId: wd.assetId, amount: wd.amount}) ); } else if (transitionType == Transitions.TRANSITION_TYPE_SYNC_BALANCE) { // Update the pending balance sync record. dt.BalanceSyncTransition memory bs = Transitions.decodeBalanceSyncTransition(_transitions[i]); uint256 syncId = pendingBalanceSyncsCommitHead; require(syncId < pendingBalanceSyncsTail, "invalid balance sync transition, no pending balance syncs"); PendingBalanceSync memory pend = pendingBalanceSyncs[syncId]; bytes32 bhash = keccak256(abi.encodePacked(bs.strategyId, bs.newAssetDelta)); require(pend.bhash == bhash, "invalid balance sync transition, mismatch or wrong ordering"); pendingBalanceSyncs[syncId].status = PendingBalanceSyncStatus.Done; pendingBalanceSyncs[syncId].blockId = uint64(_blockId); // "done": block holding the transition pendingBalanceSyncsCommitHead++; } } // Compute the intent hash. bytes32 intentHash = bytes32(0); if (numIntents > 0) { bytes32[] memory intents = new bytes32[](numIntents); for (uint256 i = 0; i < numIntents; i++) { intents[i] = keccak256(_transitions[intentIndexes[i]]); } intentHash = keccak256(abi.encodePacked(intents)); } dt.Block memory rollupBlock = dt.Block({ rootHash: root, intentHash: intentHash, blockTime: uint128(block.number), blockSize: uint128(_transitions.length) }); blocks.push(rollupBlock); emit RollupBlockCommitted(_blockId); } /** * @notice Execute a rollup block after it passes the challenge period. * @dev Note: only the "intent" transitions (commitment sync) are given to executeBlock() instead of * re-sending the whole rollup block. This includes the case of a rollup block with zero intents. * * @param _intents List of CommitmentSync transitions of the rollup block */ function executeBlock(bytes[] calldata _intents) external whenNotPaused { uint256 blockId = countExecuted; require(blockId < blocks.length, "No blocks pending execution"); require(blocks[blockId].blockTime + blockChallengePeriod < block.number, "Block still in challenge period"); // Validate the input intent transitions. bytes32 intentHash = bytes32(0); if (_intents.length > 0) { bytes32[] memory hashes = new bytes32[](_intents.length); for (uint256 i = 0; i < _intents.length; i++) { hashes[i] = keccak256(_intents[i]); } intentHash = keccak256(abi.encodePacked(hashes)); } require(intentHash == blocks[blockId].intentHash, "Invalid block intent transitions"); // Decode the intent transitions and execute the strategy updates. for (uint256 i = 0; i < _intents.length; i++) { dt.CommitmentSyncTransition memory cs = Transitions.decodeCommitmentSyncTransition(_intents[i]); address stAddr = registry.strategyIndexToAddress(cs.strategyId); require(stAddr != address(0), "Unknown strategy ID"); IStrategy strategy = IStrategy(stAddr); if (cs.pendingCommitAmount > cs.pendingUncommitAmount) { uint256 commitAmount = cs.pendingCommitAmount.sub(cs.pendingUncommitAmount); IERC20(strategy.getAssetAddress()).safeIncreaseAllowance(stAddr, commitAmount); strategy.aggregateCommit(commitAmount); strategyAssetBalances[cs.strategyId] = strategyAssetBalances[cs.strategyId].add(commitAmount); } else if (cs.pendingCommitAmount < cs.pendingUncommitAmount) { uint256 uncommitAmount = cs.pendingUncommitAmount.sub(cs.pendingCommitAmount); strategy.aggregateUncommit(uncommitAmount); strategyAssetBalances[cs.strategyId] = strategyAssetBalances[cs.strategyId].sub(uncommitAmount); } } countExecuted++; // Delete pending deposit records finalized by this block. while (pendingDepositsExecuteHead < pendingDepositsCommitHead) { PendingDeposit memory pend = pendingDeposits[pendingDepositsExecuteHead]; if (pend.status != PendingDepositStatus.Done || pend.blockId > blockId) { break; } delete pendingDeposits[pendingDepositsExecuteHead]; pendingDepositsExecuteHead++; } // Aggregate the pending withdraw-commit records for this blockId into the final // pending withdraw records per account (for later L1 withdraw), and delete them. for (uint256 i = 0; i < pendingWithdrawCommits[blockId].length; i++) { PendingWithdrawCommit memory pwc = pendingWithdrawCommits[blockId][i]; // Find and increment this account's assetId total amount pendingWithdraws[pwc.account][pwc.assetId] += pwc.amount; } delete pendingWithdrawCommits[blockId]; // Delete pending balance sync records finalized by this block. while (pendingBalanceSyncsExecuteHead < pendingBalanceSyncsCommitHead) { PendingBalanceSync memory pend = pendingBalanceSyncs[pendingBalanceSyncsExecuteHead]; if (pend.status != PendingBalanceSyncStatus.Done || pend.blockId > blockId) { break; } delete pendingBalanceSyncs[pendingBalanceSyncsExecuteHead]; pendingBalanceSyncsExecuteHead++; } emit RollupBlockExecuted(blockId); } /** * @notice Sync the latest L1 strategy asset balance to L2 * @dev L2 operator will submit BalanceSync transition based on the emitted event * * @param _strategyId Strategy id */ function syncBalance(uint32 _strategyId) external whenNotPaused onlyOperator { address stAddr = registry.strategyIndexToAddress(_strategyId); require(stAddr != address(0), "Unknown strategy ID"); uint256 newBalance = IStrategy(stAddr).syncBalance(); uint256 oldBalance = strategyAssetBalances[_strategyId]; int256 delta; if (newBalance >= oldBalance) { delta = int256(newBalance.sub(oldBalance)); } else { delta = -int256(oldBalance.sub(newBalance)); } strategyAssetBalances[_strategyId] = newBalance; // Add a pending balance sync record. uint256 syncId = pendingBalanceSyncsTail++; bytes32 bhash = keccak256(abi.encodePacked(_strategyId, delta)); pendingBalanceSyncs[syncId] = PendingBalanceSync({ bhash: bhash, blockId: uint64(blocks.length), // "pending": baseline of censorship delay status: PendingBalanceSyncStatus.Pending }); emit BalanceSync(_strategyId, delta, syncId); } /** * @notice Dispute a transition in a block. * @dev Provide the transition proofs of the previous (valid) transition * and the disputed transition, the account proof, and the strategy proof. Both the account proof and * strategy proof are always needed even if the disputed transition only updates the account or only * updates the strategy because the transition stateRoot = hash(accountStateRoot, strategyStateRoot). * If the transition is invalid, prune the chain from that invalid block. * * @param _prevTransitionProof The inclusion proof of the transition immediately before the fraudulent transition. * @param _invalidTransitionProof The inclusion proof of the fraudulent transition. * @param _accountProof The inclusion proof of the account involved. * @param _strategyProof The inclusion proof of the strategy involved. */ function disputeTransition( dt.TransitionProof calldata _prevTransitionProof, dt.TransitionProof calldata _invalidTransitionProof, dt.AccountProof calldata _accountProof, dt.StrategyProof calldata _strategyProof ) external { uint256 invalidTransitionBlockId = _invalidTransitionProof.blockId; dt.Block memory invalidTransitionBlock = blocks[invalidTransitionBlockId]; require( invalidTransitionBlock.blockTime + blockChallengePeriod > block.number, "Block challenge period is over" ); bool success; bytes memory returnData; (success, returnData) = address(transitionDisputer).call( abi.encodeWithSelector( transitionDisputer.disputeTransition.selector, _prevTransitionProof, _invalidTransitionProof, _accountProof, _strategyProof, blocks[_prevTransitionProof.blockId], invalidTransitionBlock, registry ) ); if (success) { string memory reason = abi.decode((returnData), (string)); _revertBlock(invalidTransitionBlockId, reason); } else { revert("Failed to dispute"); } } /** * @notice Dispute if operator failed to reflect an L1-initiated priority tx * in a rollup block within the maxPriorityTxDelay */ function disputePriorityTxDelay() external { uint256 currentBlockId = getCurrentBlockId(); if (pendingDepositsCommitHead < pendingDepositsTail) { if (currentBlockId.sub(pendingDeposits[pendingDepositsCommitHead].blockId) > maxPriorityTxDelay) { _pause(); return; } } if (pendingBalanceSyncsCommitHead < pendingBalanceSyncsTail) { if (currentBlockId.sub(pendingBalanceSyncs[pendingBalanceSyncsCommitHead].blockId) > maxPriorityTxDelay) { _pause(); return; } } revert("Not exceed max priority tx delay"); } /** * @notice Called by the owner to pause contract * @dev emergency use only */ function pause() external onlyOwner { _pause(); } /** * @notice Called by the owner to unpause contract * @dev emergency use only */ function unpause() external onlyOwner { _unpause(); } /** * @notice Owner drains one type of tokens when the contract is paused * @dev emergency use only * * @param _asset drained asset address * @param _amount drained asset amount */ function drainToken(address _asset, uint256 _amount) external whenPaused onlyOwner { IERC20(_asset).safeTransfer(msg.sender, _amount); } /** * @notice Owner drains ETH when the contract is paused * @dev This is for emergency situations. * * @param _amount drained ETH amount */ function drainETH(uint256 _amount) external whenPaused onlyOwner { (bool sent, ) = msg.sender.call{value: _amount}(""); require(sent, "Failed to drain ETH"); } /** * @notice Called by the owner to set blockChallengePeriod * @param _blockChallengePeriod delay (in # of ETH blocks) to challenge a rollup block */ function setBlockChallengePeriod(uint256 _blockChallengePeriod) external onlyOwner { blockChallengePeriod = _blockChallengePeriod; } /** * @notice Called by the owner to set maxPriorityTxDelay * @param _maxPriorityTxDelay delay (in # of rollup blocks) to reflect an L1-initiated tx in a rollup block */ function setMaxPriorityTxDelay(uint256 _maxPriorityTxDelay) external onlyOwner { maxPriorityTxDelay = _maxPriorityTxDelay; } /** * @notice Called by the owner to set operator account address * @param _operator operator's ETH address */ function setOperator(address _operator) external onlyOwner { emit OperatorChanged(operator, _operator); operator = _operator; } /** * @notice Called by the owner to set net deposit limit * @param _asset asset token address * @param _limit asset net deposit limit amount */ function setNetDepositLimit(address _asset, uint256 _limit) external onlyOwner { uint32 assetId = registry.assetAddressToIndex(_asset); require(assetId != 0, "Unknown asset"); netDepositLimits[_asset] = _limit; } /** * @notice Get current rollup block id * @return current rollup block id */ function getCurrentBlockId() public view returns (uint256) { return blocks.length - 1; } /********************* * Private Functions * *********************/ /** * @notice internal deposit processing without actual token transfer. * * @param _asset The asset token address. * @param _amount The asset token amount. */ function _deposit(address _asset, uint256 _amount) private { address account = msg.sender; uint32 assetId = registry.assetAddressToIndex(_asset); require(assetId != 0, "Unknown asset"); uint256 netDeposit = netDeposits[_asset].add(_amount); require(netDeposit <= netDepositLimits[_asset], "net deposit exceeds limit"); netDeposits[_asset] = netDeposit; // Add a pending deposit record. uint256 depositId = pendingDepositsTail++; bytes32 dhash = keccak256(abi.encodePacked(account, assetId, _amount)); pendingDeposits[depositId] = PendingDeposit({ dhash: dhash, blockId: uint64(blocks.length), // "pending": baseline of censorship delay status: PendingDepositStatus.Pending }); emit AssetDeposited(account, assetId, _amount, depositId); } /** * @notice internal withdrawal processing without actual token transfer. * * @param _account The destination account. * @param _asset The asset token address. * @return amount to withdraw */ function _withdraw(address _account, address _asset) private returns (uint256) { uint32 assetId = registry.assetAddressToIndex(_asset); require(assetId > 0, "Asset not registered"); uint256 amount = pendingWithdraws[_account][assetId]; require(amount > 0, "Nothing to withdraw"); if (netDeposits[_asset] < amount) { netDeposits[_asset] = 0; } else { netDeposits[_asset] = netDeposits[_asset].sub(amount); } pendingWithdraws[_account][assetId] = 0; emit AssetWithdrawn(_account, assetId, amount); return amount; } /** * @notice Revert rollup block on dispute success * * @param _blockId Rollup block id * @param _reason Revert reason */ function _revertBlock(uint256 _blockId, string memory _reason) private { // pause contract _pause(); // revert blocks and pending states while (blocks.length > _blockId) { pendingWithdrawCommits[blocks.length - 1]; blocks.pop(); } bool first; for (uint256 i = pendingDepositsExecuteHead; i < pendingDepositsTail; i++) { if (pendingDeposits[i].blockId >= _blockId) { if (!first) { pendingDepositsCommitHead = i; first = true; } pendingDeposits[i].blockId = uint64(_blockId); pendingDeposits[i].status = PendingDepositStatus.Pending; } } first = false; for (uint256 i = pendingBalanceSyncsExecuteHead; i < pendingBalanceSyncsTail; i++) { if (pendingBalanceSyncs[i].blockId >= _blockId) { if (!first) { pendingBalanceSyncsCommitHead = i; first = true; } pendingBalanceSyncs[i].blockId = uint64(_blockId); pendingBalanceSyncs[i].status = PendingBalanceSyncStatus.Pending; } } emit RollupBlockReverted(_blockId, _reason); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import {DataTypes as dt} from "./libraries/DataTypes.sol"; import "./libraries/MerkleTree.sol"; import "./libraries/Transitions.sol"; import "./TransitionEvaluator.sol"; import "./Registry.sol"; contract TransitionDisputer { // state root of empty strategy set and empty account set bytes32 public constant INIT_TRANSITION_STATE_ROOT = bytes32(0xcf277fb80a82478460e8988570b718f1e083ceb76f7e271a1a1497e5975f53ae); using SafeMath for uint256; TransitionEvaluator transitionEvaluator; constructor(TransitionEvaluator _transitionEvaluator) { transitionEvaluator = _transitionEvaluator; } /********************** * External Functions * **********************/ /** * @notice Dispute a transition. * * @param _prevTransitionProof The inclusion proof of the transition immediately before the disputed transition. * @param _invalidTransitionProof The inclusion proof of the disputed transition. * @param _accountProof The inclusion proof of the account involved. * @param _strategyProof The inclusion proof of the strategy involved. * @param _prevTransitionBlock The block containing the previous transition. * @param _invalidTransitionBlock The block containing the disputed transition. * @param _registry The address of the Registry contract. * * @return reason of the transition being determined as invalid */ function disputeTransition( dt.TransitionProof calldata _prevTransitionProof, dt.TransitionProof calldata _invalidTransitionProof, dt.AccountProof calldata _accountProof, dt.StrategyProof calldata _strategyProof, dt.Block calldata _prevTransitionBlock, dt.Block calldata _invalidTransitionBlock, Registry _registry ) external returns (string memory) { if (_invalidTransitionProof.blockId == 0 && _invalidTransitionProof.index == 0) { require(_invalidInitTransition(_invalidTransitionProof, _invalidTransitionBlock), "no fraud detected"); return "invalid init transition"; } // ------ #1: verify sequential transitions // First verify that the transitions are sequential and in their respective block root hashes. _verifySequentialTransitions( _prevTransitionProof, _invalidTransitionProof, _prevTransitionBlock, _invalidTransitionBlock ); // ------ #2: decode transitions to get post- and pre-StateRoot, and ids of account and strategy (bool ok, bytes32 preStateRoot, bytes32 postStateRoot, uint32 accountId, uint32 strategyId) = _getStateRootsAndIds(_prevTransitionProof.transition, _invalidTransitionProof.transition); // If not success something went wrong with the decoding... if (!ok) { // revert the block if it has an incorrectly encoded transition! return "invalid encoding"; } // ------ #3: verify transition stateRoot == hash(accountStateRoot, strategyStateRoot) // The account and strategy stateRoots must always be given irrespective of what is being disputed. require( _checkTwoTreeStateRoot(preStateRoot, _accountProof.stateRoot, _strategyProof.stateRoot), "Failed combined two-tree stateRoot verification check" ); // ------ #4: verify account and strategy inclusion if (accountId > 0) { _verifyProofInclusion( _accountProof.stateRoot, keccak256(_getAccountInfoBytes(_accountProof.value)), _accountProof.index, _accountProof.siblings ); } if (strategyId > 0) { _verifyProofInclusion( _strategyProof.stateRoot, keccak256(_getStrategyInfoBytes(_strategyProof.value)), _strategyProof.index, _strategyProof.siblings ); } // ------ #5: verify deposit account id mapping uint8 transitionType = Transitions.extractTransitionType(_invalidTransitionProof.transition); if (transitionType == Transitions.TRANSITION_TYPE_DEPOSIT) { DataTypes.DepositTransition memory transition = Transitions.decodeDepositTransition(_invalidTransitionProof.transition); if (_accountProof.value.account == transition.account && _accountProof.value.accountId != accountId) { // same account address with different id return "invalid account id"; } } // ------ #6: verify transition account and strategy indexes if (accountId > 0) { require(_accountProof.index == accountId, "Supplied account index is incorrect"); } if (strategyId > 0) { require(_strategyProof.index == strategyId, "Supplied strategy index is incorrect"); } // ------ #7: evaluate transition and verify new state root // split function to address "stack too deep" compiler error return _evaluateInvalidTransition( _invalidTransitionProof.transition, _accountProof, _strategyProof, postStateRoot, _registry ); } /********************* * Private Functions * *********************/ /** * @notice Evaluate a disputed transition * @dev This was split from the disputeTransition function to address "stack too deep" compiler error * * @param _invalidTransition The disputed transition. * @param _accountProof The inclusion proof of the account involved. * @param _strategyProof The inclusion proof of the strategy involved. * @param _postStateRoot State root of the disputed transition. * @param _registry The address of the Registry contract. */ function _evaluateInvalidTransition( bytes calldata _invalidTransition, dt.AccountProof calldata _accountProof, dt.StrategyProof calldata _strategyProof, bytes32 _postStateRoot, Registry _registry ) private returns (string memory) { // Apply the transaction and verify the state root after that. bool ok; bytes memory returnData; // Make the external call (ok, returnData) = address(transitionEvaluator).call( abi.encodeWithSelector( transitionEvaluator.evaluateTransition.selector, _invalidTransition, _accountProof.value, _strategyProof.value, _registry ) ); // Check if it was successful. If not, we've got to revert. if (!ok) { return "failed to evaluate"; } // It was successful so let's decode the outputs to get the new leaf nodes we'll have to insert bytes32[2] memory outputs = abi.decode((returnData), (bytes32[2])); // Check if the combined new stateRoots of account and strategy Merkle trees is incorrect. ok = _updateAndVerify(_postStateRoot, outputs, _accountProof, _strategyProof); if (!ok) { // revert the block because we found an invalid post state root return "invalid post-state root"; } revert("No fraud detected"); } /** * @notice Get state roots, account id, and strategy id of the disputed transition. * * @param _preStateTransition transition immediately before the disputed transition * @param _invalidTransition the disputed transition */ function _getStateRootsAndIds(bytes memory _preStateTransition, bytes memory _invalidTransition) private returns ( bool, bytes32, bytes32, uint32, uint32 ) { bool success; bytes memory returnData; bytes32 preStateRoot; bytes32 postStateRoot; uint32 accountId; uint32 strategyId; // First decode the prestate root (success, returnData) = address(transitionEvaluator).call( abi.encodeWithSelector(transitionEvaluator.getTransitionStateRootAndAccessIds.selector, _preStateTransition) ); // Make sure the call was successful require(success, "If the preStateRoot is invalid, then prove that invalid instead"); (preStateRoot, , ) = abi.decode((returnData), (bytes32, uint32, uint32)); // Now that we have the prestateRoot, let's decode the postState (success, returnData) = address(transitionEvaluator).call( abi.encodeWithSelector(TransitionEvaluator.getTransitionStateRootAndAccessIds.selector, _invalidTransition) ); // If the call was successful let's decode! if (success) { (postStateRoot, accountId, strategyId) = abi.decode((returnData), (bytes32, uint32, uint32)); } return (success, preStateRoot, postStateRoot, accountId, strategyId); } /** * @notice Evaluate if the init transition of the first block is invalid * * @param _initTransitionProof The inclusion proof of the disputed initial transition. * @param _firstBlock The first rollup block */ function _invalidInitTransition(dt.TransitionProof calldata _initTransitionProof, dt.Block calldata _firstBlock) private returns (bool) { require(_checkTransitionInclusion(_initTransitionProof, _firstBlock), "transition not included in block"); (bool success, bytes memory returnData) = address(transitionEvaluator).call( abi.encodeWithSelector( TransitionEvaluator.getTransitionStateRootAndAccessIds.selector, _initTransitionProof.transition ) ); if (!success) { return true; // transition is invalid } (bytes32 postStateRoot, , ) = abi.decode((returnData), (bytes32, uint32, uint32)); // Transition is invalid if stateRoot not match the expected init root // It's OK that other fields of the transition are incorrect. return postStateRoot != INIT_TRANSITION_STATE_ROOT; } /** * @notice Get the bytes value for this account. * * @param _accountInfo Account info */ function _getAccountInfoBytes(dt.AccountInfo memory _accountInfo) private pure returns (bytes memory) { // If it's an empty storage slot, return 32 bytes of zeros (empty value) if ( _accountInfo.account == address(0) && _accountInfo.accountId == 0 && _accountInfo.idleAssets.length == 0 && _accountInfo.stTokens.length == 0 && _accountInfo.timestamp == 0 ) { return abi.encodePacked(uint256(0)); } // Here we don't use `abi.encode([struct])` because it's not clear // how to generate that encoding client-side. return abi.encode( _accountInfo.account, _accountInfo.accountId, _accountInfo.idleAssets, _accountInfo.stTokens, _accountInfo.timestamp ); } /** * @notice Get the bytes value for this strategy. * @param _strategyInfo Strategy info */ function _getStrategyInfoBytes(dt.StrategyInfo memory _strategyInfo) private pure returns (bytes memory) { // If it's an empty storage slot, return 32 bytes of zeros (empty value) if ( _strategyInfo.assetId == 0 && _strategyInfo.assetBalance == 0 && _strategyInfo.stTokenSupply == 0 && _strategyInfo.pendingCommitAmount == 0 && _strategyInfo.pendingUncommitAmount == 0 ) { return abi.encodePacked(uint256(0)); } // Here we don't use `abi.encode([struct])` because it's not clear // how to generate that encoding client-side. return abi.encode( _strategyInfo.assetId, _strategyInfo.assetBalance, _strategyInfo.stTokenSupply, _strategyInfo.pendingCommitAmount, _strategyInfo.pendingUncommitAmount ); } /** * @notice Verifies that two transitions were included one after another. * @dev This is used to make sure we are comparing the correct prestate & poststate. */ function _verifySequentialTransitions( dt.TransitionProof calldata _tp0, dt.TransitionProof calldata _tp1, dt.Block calldata _prevTransitionBlock, dt.Block calldata _invalidTransitionBlock ) private pure returns (bool) { // Start by checking if they are in the same block if (_tp0.blockId == _tp1.blockId) { // If the blocknumber is the same, check that tp0 precedes tp1 require(_tp0.index + 1 == _tp1.index, "Transitions must be sequential"); require(_tp1.index < _invalidTransitionBlock.blockSize, "_tp1 outside block range"); } else { // If not in the same block, check that: // 0) the blocks are one after another require(_tp0.blockId + 1 == _tp1.blockId, "Blocks must be sequential or equal"); // 1) the index of tp0 is the last in its block require(_tp0.index == _prevTransitionBlock.blockSize - 1, "_tp0 must be last in its block"); // 2) the index of tp1 is the first in its block require(_tp1.index == 0, "_tp1 must be first in its block"); } // Verify inclusion require(_checkTransitionInclusion(_tp0, _prevTransitionBlock), "_tp0 must be included in its block"); require(_checkTransitionInclusion(_tp1, _invalidTransitionBlock), "_tp1 must be included in its block"); return true; } /** * @notice Check to see if a transition is included in the block. */ function _checkTransitionInclusion(dt.TransitionProof memory _tp, dt.Block memory _block) private pure returns (bool) { bytes32 rootHash = _block.rootHash; bytes32 leafHash = keccak256(_tp.transition); return MerkleTree.verify(rootHash, leafHash, _tp.index, _tp.siblings); } /** * @notice Check if the combined stateRoot of the two Merkle trees (account, strategy) matches the stateRoot. */ function _checkTwoTreeStateRoot( bytes32 _stateRoot, bytes32 _accountStateRoot, bytes32 _strategyStateRoot ) private pure returns (bool) { bytes32 newStateRoot = keccak256(abi.encodePacked(_accountStateRoot, _strategyStateRoot)); return (_stateRoot == newStateRoot); } /** * @notice Check if an account or strategy proof is included in the state root. */ function _verifyProofInclusion( bytes32 _stateRoot, bytes32 _leafHash, uint32 _index, bytes32[] memory _siblings ) private pure { bool ok = MerkleTree.verify(_stateRoot, _leafHash, _index, _siblings); require(ok, "Failed proof inclusion verification check"); } /** * @notice Update the account and strategy Merkle trees with their new leaf nodes and check validity. */ function _updateAndVerify( bytes32 _stateRoot, bytes32[2] memory _leafHashes, dt.AccountProof memory _accountProof, dt.StrategyProof memory _strategyProof ) private pure returns (bool) { if (_leafHashes[0] == bytes32(0) && _leafHashes[1] == bytes32(0)) { return false; } // If there is an account update, compute its new Merkle tree root. bytes32 accountStateRoot = _accountProof.stateRoot; if (_leafHashes[0] != bytes32(0)) { accountStateRoot = MerkleTree.computeRoot(_leafHashes[0], _accountProof.index, _accountProof.siblings); } // If there is a strategy update, compute its new Merkle tree root. bytes32 strategyStateRoot = _strategyProof.stateRoot; if (_leafHashes[1] != bytes32(0)) { strategyStateRoot = MerkleTree.computeRoot(_leafHashes[1], _strategyProof.index, _strategyProof.siblings); } return _checkTwoTreeStateRoot(_stateRoot, accountStateRoot, strategyStateRoot); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/cryptography/ECDSA.sol"; /* Internal Imports */ import "./libraries/DataTypes.sol"; import "./libraries/Transitions.sol"; import "./Registry.sol"; import "./strategies/interfaces/IStrategy.sol"; contract TransitionEvaluator { using SafeMath for uint256; /********************** * External Functions * **********************/ /** * @notice Evaluate a transition. * * @param _transition The disputed transition. * @param _accountInfo The involved account from the previous transition. * @param _strategyInfo The involved strategy from the previous transition. * @param _registry The address of the Registry contract. * @return hashes of account and strategy after applying the transition. */ function evaluateTransition( bytes calldata _transition, DataTypes.AccountInfo calldata _accountInfo, DataTypes.StrategyInfo calldata _strategyInfo, Registry _registry ) external view returns (bytes32[2] memory) { // Extract the transition type uint8 transitionType = Transitions.extractTransitionType(_transition); bytes32[2] memory outputs; DataTypes.AccountInfo memory updatedAccountInfo; DataTypes.StrategyInfo memory updatedStrategyInfo; // Apply the transition and record the resulting storage slots if (transitionType == Transitions.TRANSITION_TYPE_DEPOSIT) { DataTypes.DepositTransition memory deposit = Transitions.decodeDepositTransition(_transition); updatedAccountInfo = _applyDepositTransition(deposit, _accountInfo); outputs[0] = _getAccountInfoHash(updatedAccountInfo); } else if (transitionType == Transitions.TRANSITION_TYPE_WITHDRAW) { DataTypes.WithdrawTransition memory withdraw = Transitions.decodeWithdrawTransition(_transition); updatedAccountInfo = _applyWithdrawTransition(withdraw, _accountInfo); outputs[0] = _getAccountInfoHash(updatedAccountInfo); } else if (transitionType == Transitions.TRANSITION_TYPE_COMMIT) { DataTypes.CommitTransition memory commit = Transitions.decodeCommitTransition(_transition); (updatedAccountInfo, updatedStrategyInfo) = _applyCommitTransition( commit, _accountInfo, _strategyInfo, _registry ); outputs[0] = _getAccountInfoHash(updatedAccountInfo); outputs[1] = _getStrategyInfoHash(updatedStrategyInfo); } else if (transitionType == Transitions.TRANSITION_TYPE_UNCOMMIT) { DataTypes.UncommitTransition memory uncommit = Transitions.decodeUncommitTransition(_transition); (updatedAccountInfo, updatedStrategyInfo) = _applyUncommitTransition(uncommit, _accountInfo, _strategyInfo); outputs[0] = _getAccountInfoHash(updatedAccountInfo); outputs[1] = _getStrategyInfoHash(updatedStrategyInfo); } else if (transitionType == Transitions.TRANSITION_TYPE_SYNC_COMMITMENT) { DataTypes.CommitmentSyncTransition memory commitmentSync = Transitions.decodeCommitmentSyncTransition(_transition); updatedStrategyInfo = _applyCommitmentSyncTransition(commitmentSync, _strategyInfo); outputs[1] = _getStrategyInfoHash(updatedStrategyInfo); } else if (transitionType == Transitions.TRANSITION_TYPE_SYNC_BALANCE) { DataTypes.BalanceSyncTransition memory balanceSync = Transitions.decodeBalanceSyncTransition(_transition); updatedStrategyInfo = _applyBalanceSyncTransition(balanceSync, _strategyInfo); outputs[1] = _getStrategyInfoHash(updatedStrategyInfo); } else { revert("Transition type not recognized"); } return outputs; } /** * @notice Return the (stateRoot, accountId, strategyId) for this transition. */ function getTransitionStateRootAndAccessIds(bytes calldata _rawTransition) external pure returns ( bytes32, uint32, uint32 ) { // Initialize memory rawTransition bytes memory rawTransition = _rawTransition; // Initialize stateRoot and account and strategy IDs. bytes32 stateRoot; uint32 accountId; uint32 strategyId; uint8 transitionType = Transitions.extractTransitionType(rawTransition); if (transitionType == Transitions.TRANSITION_TYPE_DEPOSIT) { DataTypes.DepositTransition memory transition = Transitions.decodeDepositTransition(rawTransition); stateRoot = transition.stateRoot; accountId = transition.accountId; } else if (transitionType == Transitions.TRANSITION_TYPE_WITHDRAW) { DataTypes.WithdrawTransition memory transition = Transitions.decodeWithdrawTransition(rawTransition); stateRoot = transition.stateRoot; accountId = transition.accountId; } else if (transitionType == Transitions.TRANSITION_TYPE_COMMIT) { DataTypes.CommitTransition memory transition = Transitions.decodeCommitTransition(rawTransition); stateRoot = transition.stateRoot; accountId = transition.accountId; strategyId = transition.strategyId; } else if (transitionType == Transitions.TRANSITION_TYPE_UNCOMMIT) { DataTypes.UncommitTransition memory transition = Transitions.decodeUncommitTransition(rawTransition); stateRoot = transition.stateRoot; accountId = transition.accountId; strategyId = transition.strategyId; } else if (transitionType == Transitions.TRANSITION_TYPE_SYNC_COMMITMENT) { DataTypes.CommitmentSyncTransition memory transition = Transitions.decodeCommitmentSyncTransition(rawTransition); stateRoot = transition.stateRoot; strategyId = transition.strategyId; } else if (transitionType == Transitions.TRANSITION_TYPE_SYNC_BALANCE) { DataTypes.BalanceSyncTransition memory transition = Transitions.decodeBalanceSyncTransition(rawTransition); stateRoot = transition.stateRoot; strategyId = transition.strategyId; } else if (transitionType == Transitions.TRANSITION_TYPE_INIT) { DataTypes.InitTransition memory transition = Transitions.decodeInitTransition(rawTransition); stateRoot = transition.stateRoot; } else { revert("Transition type not recognized"); } return (stateRoot, accountId, strategyId); } /********************* * Private Functions * *********************/ /** * @notice Apply a DepositTransition. * * @param _transition The disputed transition. * @param _accountInfo The involved account from the previous transition. * @return new account info after apply the disputed transition */ function _applyDepositTransition( DataTypes.DepositTransition memory _transition, DataTypes.AccountInfo memory _accountInfo ) private pure returns (DataTypes.AccountInfo memory) { if (_accountInfo.account == address(0)) { // first time deposit of this account require(_accountInfo.accountId == 0, "empty account id must be zero"); require(_accountInfo.idleAssets.length == 0, "empty account idleAssets must be empty"); require(_accountInfo.stTokens.length == 0, "empty account stTokens must be empty"); require(_accountInfo.timestamp == 0, "empty account timestamp must be zero"); _accountInfo.account = _transition.account; _accountInfo.accountId = _transition.accountId; } else { require(_accountInfo.account == _transition.account, "account address not match"); require(_accountInfo.accountId == _transition.accountId, "account id not match"); } if (_transition.assetId >= _accountInfo.idleAssets.length) { uint256[] memory idleAssets = new uint256[](_transition.assetId + 1); for (uint256 i = 0; i < _accountInfo.idleAssets.length; i++) { idleAssets[i] = _accountInfo.idleAssets[i]; } _accountInfo.idleAssets = idleAssets; } _accountInfo.idleAssets[_transition.assetId] = _accountInfo.idleAssets[_transition.assetId].add( _transition.amount ); return _accountInfo; } /** * @notice Apply a WithdrawTransition. * * @param _transition The disputed transition. * @param _accountInfo The involved account from the previous transition. * @return new account info after apply the disputed transition */ function _applyWithdrawTransition( DataTypes.WithdrawTransition memory _transition, DataTypes.AccountInfo memory _accountInfo ) private pure returns (DataTypes.AccountInfo memory) { bytes32 txHash = keccak256( abi.encodePacked( _transition.transitionType, _transition.account, _transition.assetId, _transition.amount, _transition.timestamp ) ); bytes32 prefixedHash = ECDSA.toEthSignedMessageHash(txHash); require( ECDSA.recover(prefixedHash, _transition.signature) == _accountInfo.account, "Withdraw signature is invalid" ); require(_accountInfo.accountId == _transition.accountId, "account id not match"); require(_accountInfo.timestamp < _transition.timestamp, "timestamp should monotonically increasing"); _accountInfo.timestamp = _transition.timestamp; _accountInfo.idleAssets[_transition.assetId] = _accountInfo.idleAssets[_transition.assetId].sub( _transition.amount ); return _accountInfo; } /** * @notice Apply a CommitTransition. * * @param _transition The disputed transition. * @param _accountInfo The involved account from the previous transition. * @param _strategyInfo The involved strategy from the previous transition. * @return new account and strategy info after apply the disputed transition */ function _applyCommitTransition( DataTypes.CommitTransition memory _transition, DataTypes.AccountInfo memory _accountInfo, DataTypes.StrategyInfo memory _strategyInfo, Registry _registry ) private view returns (DataTypes.AccountInfo memory, DataTypes.StrategyInfo memory) { bytes32 txHash = keccak256( abi.encodePacked( _transition.transitionType, _transition.strategyId, _transition.assetAmount, _transition.timestamp ) ); bytes32 prefixedHash = ECDSA.toEthSignedMessageHash(txHash); require( ECDSA.recover(prefixedHash, _transition.signature) == _accountInfo.account, "Commit signature is invalid" ); uint256 newStToken; if (_strategyInfo.assetBalance == 0 || _strategyInfo.stTokenSupply == 0) { require(_strategyInfo.stTokenSupply == 0, "empty strategy stTokenSupply must be zero"); require(_strategyInfo.pendingCommitAmount == 0, "empty strategy pendingCommitAmount must be zero"); if (_strategyInfo.assetId == 0) { // first time commit of new strategy require(_strategyInfo.pendingUncommitAmount == 0, "new strategy pendingUncommitAmount must be zero"); address strategyAddr = _registry.strategyIndexToAddress(_transition.strategyId); address assetAddr = IStrategy(strategyAddr).getAssetAddress(); _strategyInfo.assetId = _registry.assetAddressToIndex(assetAddr); } newStToken = _transition.assetAmount; } else { newStToken = _transition.assetAmount.mul(_strategyInfo.stTokenSupply).div(_strategyInfo.assetBalance); } _accountInfo.idleAssets[_strategyInfo.assetId] = _accountInfo.idleAssets[_strategyInfo.assetId].sub( _transition.assetAmount ); if (_transition.strategyId >= _accountInfo.stTokens.length) { uint256[] memory stTokens = new uint256[](_transition.strategyId + 1); for (uint256 i = 0; i < _accountInfo.stTokens.length; i++) { stTokens[i] = _accountInfo.stTokens[i]; } _accountInfo.stTokens = stTokens; } _accountInfo.stTokens[_transition.strategyId] = _accountInfo.stTokens[_transition.strategyId].add(newStToken); require(_accountInfo.accountId == _transition.accountId, "account id not match"); require(_accountInfo.timestamp < _transition.timestamp, "timestamp should monotonically increasing"); _accountInfo.timestamp = _transition.timestamp; _strategyInfo.stTokenSupply = _strategyInfo.stTokenSupply.add(newStToken); _strategyInfo.assetBalance = _strategyInfo.assetBalance.add(_transition.assetAmount); _strategyInfo.pendingCommitAmount = _strategyInfo.pendingCommitAmount.add(_transition.assetAmount); return (_accountInfo, _strategyInfo); } /** * @notice Apply a UncommitTransition. * * @param _transition The disputed transition. * @param _accountInfo The involved account from the previous transition. * @param _strategyInfo The involved strategy from the previous transition. * @return new account and strategy info after apply the disputed transition */ function _applyUncommitTransition( DataTypes.UncommitTransition memory _transition, DataTypes.AccountInfo memory _accountInfo, DataTypes.StrategyInfo memory _strategyInfo ) private pure returns (DataTypes.AccountInfo memory, DataTypes.StrategyInfo memory) { bytes32 txHash = keccak256( abi.encodePacked( _transition.transitionType, _transition.strategyId, _transition.stTokenAmount, _transition.timestamp ) ); bytes32 prefixedHash = ECDSA.toEthSignedMessageHash(txHash); require( ECDSA.recover(prefixedHash, _transition.signature) == _accountInfo.account, "Uncommit signature is invalid" ); uint256 newIdleAsset = _transition.stTokenAmount.mul(_strategyInfo.assetBalance).div(_strategyInfo.stTokenSupply); _accountInfo.idleAssets[_strategyInfo.assetId] = _accountInfo.idleAssets[_strategyInfo.assetId].add( newIdleAsset ); _accountInfo.stTokens[_transition.strategyId] = _accountInfo.stTokens[_transition.strategyId].sub( _transition.stTokenAmount ); require(_accountInfo.accountId == _transition.accountId, "account id not match"); require(_accountInfo.timestamp < _transition.timestamp, "timestamp should monotonically increasing"); _accountInfo.timestamp = _transition.timestamp; _strategyInfo.stTokenSupply = _strategyInfo.stTokenSupply.sub(_transition.stTokenAmount); _strategyInfo.assetBalance = _strategyInfo.assetBalance.sub(newIdleAsset); _strategyInfo.pendingUncommitAmount = _strategyInfo.pendingUncommitAmount.add(newIdleAsset); return (_accountInfo, _strategyInfo); } /** * @notice Apply a CommitmentSyncTransition. * * @param _transition The disputed transition. * @param _strategyInfo The involved strategy from the previous transition. * @return new strategy info after apply the disputed transition */ function _applyCommitmentSyncTransition( DataTypes.CommitmentSyncTransition memory _transition, DataTypes.StrategyInfo memory _strategyInfo ) private pure returns (DataTypes.StrategyInfo memory) { require( _transition.pendingCommitAmount == _strategyInfo.pendingCommitAmount, "pending commitment amount not match" ); require( _transition.pendingUncommitAmount == _strategyInfo.pendingUncommitAmount, "pending uncommitment amount not match" ); _strategyInfo.pendingCommitAmount = 0; _strategyInfo.pendingUncommitAmount = 0; return _strategyInfo; } /** * @notice Apply a BalanceSyncTransition. * * @param _transition The disputed transition. * @param _strategyInfo The involved strategy from the previous transition. * @return new strategy info after apply the disputed transition */ function _applyBalanceSyncTransition( DataTypes.BalanceSyncTransition memory _transition, DataTypes.StrategyInfo memory _strategyInfo ) private pure returns (DataTypes.StrategyInfo memory) { if (_transition.newAssetDelta >= 0) { uint256 delta = uint256(_transition.newAssetDelta); _strategyInfo.assetBalance = _strategyInfo.assetBalance.add(delta); } else { uint256 delta = uint256(-_transition.newAssetDelta); _strategyInfo.assetBalance = _strategyInfo.assetBalance.sub(delta); } return _strategyInfo; } /** * @notice Get the hash of the AccountInfo. * @param _accountInfo Account info */ function _getAccountInfoHash(DataTypes.AccountInfo memory _accountInfo) private pure returns (bytes32) { // Here we don't use `abi.encode([struct])` because it's not clear // how to generate that encoding client-side. return keccak256( abi.encode( _accountInfo.account, _accountInfo.accountId, _accountInfo.idleAssets, _accountInfo.stTokens, _accountInfo.timestamp ) ); } /** * Get the hash of the StrategyInfo. */ /** * @notice Get the hash of the StrategyInfo. * @param _strategyInfo Strategy info */ function _getStrategyInfoHash(DataTypes.StrategyInfo memory _strategyInfo) private pure returns (bytes32) { // Here we don't use `abi.encode([struct])` because it's not clear // how to generate that encoding client-side. return keccak256( abi.encode( _strategyInfo.assetId, _strategyInfo.assetBalance, _strategyInfo.stTokenSupply, _strategyInfo.pendingCommitAmount, _strategyInfo.pendingUncommitAmount ) ); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; interface IWETH { 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 src, address dst, uint256 wad ) external returns (bool); function deposit() external payable; function withdraw(uint256 wad) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; library DataTypes { struct Block { bytes32 rootHash; bytes32 intentHash; // hash of L2-to-L1 commitment sync transitions uint128 blockTime; // blockNum when this rollup block is committed uint128 blockSize; // number of transitions in the block } struct InitTransition { uint8 transitionType; bytes32 stateRoot; } struct DepositTransition { uint8 transitionType; bytes32 stateRoot; address account; // must provide L1 address for "pending deposit" handling uint32 accountId; // needed for transition evaluation in case of dispute uint32 assetId; uint256 amount; } struct WithdrawTransition { uint8 transitionType; bytes32 stateRoot; address account; // must provide L1 target address for "pending withdraw" handling uint32 accountId; uint32 assetId; uint256 amount; uint64 timestamp; // Unix epoch (msec, UTC) bytes signature; } struct CommitTransition { uint8 transitionType; bytes32 stateRoot; uint32 accountId; uint32 strategyId; uint256 assetAmount; uint64 timestamp; // Unix epoch (msec, UTC) bytes signature; } struct UncommitTransition { uint8 transitionType; bytes32 stateRoot; uint32 accountId; uint32 strategyId; uint256 stTokenAmount; uint64 timestamp; // Unix epoch (msec, UTC) bytes signature; } struct BalanceSyncTransition { uint8 transitionType; bytes32 stateRoot; uint32 strategyId; int256 newAssetDelta; } struct CommitmentSyncTransition { uint8 transitionType; bytes32 stateRoot; uint32 strategyId; uint256 pendingCommitAmount; uint256 pendingUncommitAmount; } struct AccountInfo { address account; uint32 accountId; // mapping only on L2 must be part of stateRoot uint256[] idleAssets; // indexed by assetId uint256[] stTokens; // indexed by strategyId uint64 timestamp; // Unix epoch (msec, UTC) } struct StrategyInfo { uint32 assetId; uint256 assetBalance; uint256 stTokenSupply; uint256 pendingCommitAmount; uint256 pendingUncommitAmount; } struct TransitionProof { bytes transition; uint256 blockId; uint32 index; bytes32[] siblings; } // Even when the disputed transition only affects an account without not a strategy // (e.g. deposit), or only affects a strategy without an account (e.g. syncBalance), // both AccountProof and StrategyProof must be sent to at least give the root hashes // of the two separate Merkle trees (account and strategy). // Each transition stateRoot = hash(accountStateRoot, strategyStateRoot). struct AccountProof { bytes32 stateRoot; // for the account Merkle tree AccountInfo value; uint32 index; bytes32[] siblings; } struct StrategyProof { bytes32 stateRoot; // for the strategy Merkle tree StrategyInfo value; uint32 index; bytes32[] siblings; } } // SPDX-License-Identifier: MIT /* (The MIT License) Copyright 2020 Optimism Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ pragma solidity >0.5.0 <0.8.0; /** * @title MerkleTree * @author River Keefer */ library MerkleTree { /********************** * Internal Functions * **********************/ /** * Calculates a merkle root for a list of 32-byte leaf hashes. WARNING: If the number * of leaves passed in is not a power of two, it pads out the tree with zero hashes. * If you do not know the original length of elements for the tree you are verifying, * then this may allow empty leaves past _elements.length to pass a verification check down the line. * @param _elements Array of hashes from which to generate a merkle root. * @return Merkle root of the leaves, with zero hashes for non-powers-of-two (see above). */ function getMerkleRoot(bytes32[] memory _elements) internal pure returns (bytes32) { require(_elements.length > 0, "MerkleTree: Must provide at least one leaf hash."); if (_elements.length == 1) { return _elements[0]; } uint256[32] memory defaults = [ 0x290decd9548b62a8d60345a988386fc84ba6bc95484008f6362f93160ef3e563, 0x633dc4d7da7256660a892f8f1604a44b5432649cc8ec5cb3ced4c4e6ac94dd1d, 0x890740a8eb06ce9be422cb8da5cdafc2b58c0a5e24036c578de2a433c828ff7d, 0x3b8ec09e026fdc305365dfc94e189a81b38c7597b3d941c279f042e8206e0bd8, 0xecd50eee38e386bd62be9bedb990706951b65fe053bd9d8a521af753d139e2da, 0xdefff6d330bb5403f63b14f33b578274160de3a50df4efecf0e0db73bcdd3da5, 0x617bdd11f7c0a11f49db22f629387a12da7596f9d1704d7465177c63d88ec7d7, 0x292c23a9aa1d8bea7e2435e555a4a60e379a5a35f3f452bae60121073fb6eead, 0xe1cea92ed99acdcb045a6726b2f87107e8a61620a232cf4d7d5b5766b3952e10, 0x7ad66c0a68c72cb89e4fb4303841966e4062a76ab97451e3b9fb526a5ceb7f82, 0xe026cc5a4aed3c22a58cbd3d2ac754c9352c5436f638042dca99034e83636516, 0x3d04cffd8b46a874edf5cfae63077de85f849a660426697b06a829c70dd1409c, 0xad676aa337a485e4728a0b240d92b3ef7b3c372d06d189322bfd5f61f1e7203e, 0xa2fca4a49658f9fab7aa63289c91b7c7b6c832a6d0e69334ff5b0a3483d09dab, 0x4ebfd9cd7bca2505f7bef59cc1c12ecc708fff26ae4af19abe852afe9e20c862, 0x2def10d13dd169f550f578bda343d9717a138562e0093b380a1120789d53cf10, 0x776a31db34a1a0a7caaf862cffdfff1789297ffadc380bd3d39281d340abd3ad, 0xe2e7610b87a5fdf3a72ebe271287d923ab990eefac64b6e59d79f8b7e08c46e3, 0x504364a5c6858bf98fff714ab5be9de19ed31a976860efbd0e772a2efe23e2e0, 0x4f05f4acb83f5b65168d9fef89d56d4d77b8944015e6b1eed81b0238e2d0dba3, 0x44a6d974c75b07423e1d6d33f481916fdd45830aea11b6347e700cd8b9f0767c, 0xedf260291f734ddac396a956127dde4c34c0cfb8d8052f88ac139658ccf2d507, 0x6075c657a105351e7f0fce53bc320113324a522e8fd52dc878c762551e01a46e, 0x6ca6a3f763a9395f7da16014725ca7ee17e4815c0ff8119bf33f273dee11833b, 0x1c25ef10ffeb3c7d08aa707d17286e0b0d3cbcb50f1bd3b6523b63ba3b52dd0f, 0xfffc43bd08273ccf135fd3cacbeef055418e09eb728d727c4d5d5c556cdea7e3, 0xc5ab8111456b1f28f3c7a0a604b4553ce905cb019c463ee159137af83c350b22, 0x0ff273fcbf4ae0f2bd88d6cf319ff4004f8d7dca70d4ced4e74d2c74139739e6, 0x7fa06ba11241ddd5efdc65d4e39c9f6991b74fd4b81b62230808216c876f827c, 0x7e275adf313a996c7e2950cac67caba02a5ff925ebf9906b58949f3e77aec5b9, 0x8f6162fa308d2b3a15dc33cffac85f13ab349173121645aedf00f471663108be, 0x78ccaaab73373552f207a63599de54d7d8d0c1805f86ce7da15818d09f4cff62 ]; // Reserve memory space for our hashes. bytes memory buf = new bytes(64); // We'll need to keep track of left and right siblings. bytes32 leftSibling; bytes32 rightSibling; // Number of non-empty nodes at the current depth. uint256 rowSize = _elements.length; // Current depth, counting from 0 at the leaves uint256 depth = 0; // Common sub-expressions uint256 halfRowSize; // rowSize / 2 bool rowSizeIsOdd; // rowSize % 2 == 1 while (rowSize > 1) { halfRowSize = rowSize / 2; rowSizeIsOdd = rowSize % 2 == 1; for (uint256 i = 0; i < halfRowSize; i++) { leftSibling = _elements[(2 * i)]; rightSibling = _elements[(2 * i) + 1]; assembly { mstore(add(buf, 32), leftSibling) mstore(add(buf, 64), rightSibling) } _elements[i] = keccak256(buf); } if (rowSizeIsOdd) { leftSibling = _elements[rowSize - 1]; rightSibling = bytes32(defaults[depth]); assembly { mstore(add(buf, 32), leftSibling) mstore(add(buf, 64), rightSibling) } _elements[halfRowSize] = keccak256(buf); } rowSize = halfRowSize + (rowSizeIsOdd ? 1 : 0); depth++; } return _elements[0]; } /** * Verifies a merkle branch for the given leaf hash. Assumes the original length * of leaves generated is a known, correct input, and does not return true for indices * extending past that index (even if _siblings would be otherwise valid.) * @param _root The Merkle root to verify against. * @param _leaf The leaf hash to verify inclusion of. * @param _index The index in the tree of this leaf. * @param _siblings Array of sibling nodes in the inclusion proof, starting from depth 0 (bottom of the tree). * @return Whether or not the merkle branch and leaf passes verification. */ function verify( bytes32 _root, bytes32 _leaf, uint256 _index, bytes32[] memory _siblings ) internal pure returns (bool) { return (_root == computeRoot(_leaf, _index, _siblings)); } /** * Compute the root of a merkle branch for the given leaf hash. Assumes the original length * of leaves generated is a known, correct input, and does not return true for indices * extending past that index (even if _siblings would be otherwise valid.) * @param _leaf The leaf hash to verify inclusion of. * @param _index The index in the tree of this leaf. * @param _siblings Array of sibling nodes in the inclusion proof, starting from depth 0 (bottom of the tree). * @return The new merkle root. */ function computeRoot( bytes32 _leaf, uint256 _index, bytes32[] memory _siblings ) internal pure returns (bytes32) { bytes32 computedRoot = _leaf; for (uint256 i = 0; i < _siblings.length; i++) { if ((_index & 1) == 1) { computedRoot = keccak256(abi.encodePacked(_siblings[i], computedRoot)); } else { computedRoot = keccak256(abi.encodePacked(computedRoot, _siblings[i])); } _index >>= 1; } return computedRoot; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; pragma experimental ABIEncoderV2; import "../libraries/DataTypes.sol"; library Transitions { // Transition Types uint8 public constant TRANSITION_TYPE_INVALID = 0; uint8 public constant TRANSITION_TYPE_DEPOSIT = 1; uint8 public constant TRANSITION_TYPE_WITHDRAW = 2; uint8 public constant TRANSITION_TYPE_COMMIT = 3; uint8 public constant TRANSITION_TYPE_UNCOMMIT = 4; uint8 public constant TRANSITION_TYPE_SYNC_COMMITMENT = 5; uint8 public constant TRANSITION_TYPE_SYNC_BALANCE = 6; uint8 public constant TRANSITION_TYPE_INIT = 7; function extractTransitionType(bytes memory _bytes) internal pure returns (uint8) { uint8 transitionType; assembly { transitionType := mload(add(_bytes, 0x20)) } return transitionType; } function decodeDepositTransition(bytes memory _rawBytes) internal pure returns (DataTypes.DepositTransition memory) { (uint8 transitionType, bytes32 stateRoot, address account, uint32 accountId, uint32 assetId, uint256 amount) = abi.decode((_rawBytes), (uint8, bytes32, address, uint32, uint32, uint256)); DataTypes.DepositTransition memory transition = DataTypes.DepositTransition(transitionType, stateRoot, account, accountId, assetId, amount); return transition; } function decodeWithdrawTransition(bytes memory _rawBytes) internal pure returns (DataTypes.WithdrawTransition memory) { ( uint8 transitionType, bytes32 stateRoot, address account, uint32 accountId, uint32 assetId, uint256 amount, uint64 timestamp, bytes memory signature ) = abi.decode((_rawBytes), (uint8, bytes32, address, uint32, uint32, uint256, uint64, bytes)); DataTypes.WithdrawTransition memory transition = DataTypes.WithdrawTransition( transitionType, stateRoot, account, accountId, assetId, amount, timestamp, signature ); return transition; } function decodeCommitTransition(bytes memory _rawBytes) internal pure returns (DataTypes.CommitTransition memory) { ( uint8 transitionType, bytes32 stateRoot, uint32 accountId, uint32 strategyId, uint256 assetAmount, uint64 timestamp, bytes memory signature ) = abi.decode((_rawBytes), (uint8, bytes32, uint32, uint32, uint256, uint64, bytes)); DataTypes.CommitTransition memory transition = DataTypes.CommitTransition( transitionType, stateRoot, accountId, strategyId, assetAmount, timestamp, signature ); return transition; } function decodeUncommitTransition(bytes memory _rawBytes) internal pure returns (DataTypes.UncommitTransition memory) { ( uint8 transitionType, bytes32 stateRoot, uint32 accountId, uint32 strategyId, uint256 stTokenAmount, uint64 timestamp, bytes memory signature ) = abi.decode((_rawBytes), (uint8, bytes32, uint32, uint32, uint256, uint64, bytes)); DataTypes.UncommitTransition memory transition = DataTypes.UncommitTransition( transitionType, stateRoot, accountId, strategyId, stTokenAmount, timestamp, signature ); return transition; } function decodeCommitmentSyncTransition(bytes memory _rawBytes) internal pure returns (DataTypes.CommitmentSyncTransition memory) { ( uint8 transitionType, bytes32 stateRoot, uint32 strategyId, uint256 pendingCommitAmount, uint256 pendingUncommitAmount ) = abi.decode((_rawBytes), (uint8, bytes32, uint32, uint256, uint256)); DataTypes.CommitmentSyncTransition memory transition = DataTypes.CommitmentSyncTransition( transitionType, stateRoot, strategyId, pendingCommitAmount, pendingUncommitAmount ); return transition; } function decodeBalanceSyncTransition(bytes memory _rawBytes) internal pure returns (DataTypes.BalanceSyncTransition memory) { (uint8 transitionType, bytes32 stateRoot, uint32 strategyId, int256 newAssetDelta) = abi.decode((_rawBytes), (uint8, bytes32, uint32, int256)); DataTypes.BalanceSyncTransition memory transition = DataTypes.BalanceSyncTransition(transitionType, stateRoot, strategyId, newAssetDelta); return transition; } function decodeInitTransition(bytes memory _rawBytes) internal pure returns (DataTypes.InitTransition memory) { (uint8 transitionType, bytes32 stateRoot) = abi.decode((_rawBytes), (uint8, bytes32)); DataTypes.InitTransition memory transition = DataTypes.InitTransition(transitionType, stateRoot); return transition; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @title Interface for DeFi strategies * * @notice Strategy provides abstraction for a DeFi strategy. A single type of asset token can be committed to or * uncommitted from a strategy per instructions from L2. Periodically, the yield is reflected in the asset balance and * synced back to L2. */ interface IStrategy { event Committed(uint256 commitAmount); event UnCommitted(uint256 uncommitAmount); event ControllerChanged(address previousController, address newController); /** * @dev Returns the address of the asset token. */ function getAssetAddress() external view returns (address); /** * @dev Harvests protocol tokens and update the asset balance. */ function harvest() external; /** * @dev Returns the asset balance. May sync with the protocol to update the balance. */ function syncBalance() external returns (uint256); /** * @dev Commits to strategy per instructions from L2. * * @param commitAmount The aggregated asset amount to commit. */ function aggregateCommit(uint256 commitAmount) external; /** * @dev Uncommits from strategy per instructions from L2. * * @param uncommitAmount The aggregated asset amount to uncommit. */ function aggregateUncommit(uint256 uncommitAmount) external; }
* @notice Apply a CommitTransition. @param _transition The disputed transition. @param _accountInfo The involved account from the previous transition. @param _strategyInfo The involved strategy from the previous transition. @return new account and strategy info after apply the disputed transition/ first time commit of new strategy
function _applyCommitTransition( DataTypes.CommitTransition memory _transition, DataTypes.AccountInfo memory _accountInfo, DataTypes.StrategyInfo memory _strategyInfo, Registry _registry ) private view returns (DataTypes.AccountInfo memory, DataTypes.StrategyInfo memory) { bytes32 txHash = keccak256( abi.encodePacked( _transition.transitionType, _transition.strategyId, _transition.assetAmount, _transition.timestamp ) ); bytes32 prefixedHash = ECDSA.toEthSignedMessageHash(txHash); require( ECDSA.recover(prefixedHash, _transition.signature) == _accountInfo.account, "Commit signature is invalid" ); uint256 newStToken; if (_strategyInfo.assetBalance == 0 || _strategyInfo.stTokenSupply == 0) { require(_strategyInfo.stTokenSupply == 0, "empty strategy stTokenSupply must be zero"); require(_strategyInfo.pendingCommitAmount == 0, "empty strategy pendingCommitAmount must be zero"); if (_strategyInfo.assetId == 0) { require(_strategyInfo.pendingUncommitAmount == 0, "new strategy pendingUncommitAmount must be zero"); address strategyAddr = _registry.strategyIndexToAddress(_transition.strategyId); address assetAddr = IStrategy(strategyAddr).getAssetAddress(); _strategyInfo.assetId = _registry.assetAddressToIndex(assetAddr); } newStToken = _transition.assetAmount; newStToken = _transition.assetAmount.mul(_strategyInfo.stTokenSupply).div(_strategyInfo.assetBalance); } _accountInfo.idleAssets[_strategyInfo.assetId] = _accountInfo.idleAssets[_strategyInfo.assetId].sub( _transition.assetAmount ); if (_transition.strategyId >= _accountInfo.stTokens.length) { uint256[] memory stTokens = new uint256[](_transition.strategyId + 1); for (uint256 i = 0; i < _accountInfo.stTokens.length; i++) { stTokens[i] = _accountInfo.stTokens[i]; } _accountInfo.stTokens = stTokens; } _accountInfo.stTokens[_transition.strategyId] = _accountInfo.stTokens[_transition.strategyId].add(newStToken); require(_accountInfo.accountId == _transition.accountId, "account id not match"); require(_accountInfo.timestamp < _transition.timestamp, "timestamp should monotonically increasing"); _accountInfo.timestamp = _transition.timestamp; _strategyInfo.stTokenSupply = _strategyInfo.stTokenSupply.add(newStToken); _strategyInfo.assetBalance = _strategyInfo.assetBalance.add(_transition.assetAmount); _strategyInfo.pendingCommitAmount = _strategyInfo.pendingCommitAmount.add(_transition.assetAmount); return (_accountInfo, _strategyInfo); }
5,406,958
[ 1, 7001, 279, 10269, 8850, 18, 225, 389, 14936, 1021, 1015, 458, 329, 6007, 18, 225, 389, 4631, 966, 1021, 24589, 2236, 628, 326, 2416, 6007, 18, 225, 389, 14914, 966, 1021, 24589, 6252, 628, 326, 2416, 6007, 18, 327, 394, 2236, 471, 6252, 1123, 1839, 2230, 326, 1015, 458, 329, 6007, 19, 1122, 813, 3294, 434, 394, 6252, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 389, 9010, 5580, 8850, 12, 203, 3639, 1910, 2016, 18, 5580, 8850, 3778, 389, 14936, 16, 203, 3639, 1910, 2016, 18, 3032, 966, 3778, 389, 4631, 966, 16, 203, 3639, 1910, 2016, 18, 4525, 966, 3778, 389, 14914, 966, 16, 203, 3639, 5438, 389, 9893, 203, 565, 262, 3238, 1476, 1135, 261, 751, 2016, 18, 3032, 966, 3778, 16, 1910, 2016, 18, 4525, 966, 3778, 13, 288, 203, 3639, 1731, 1578, 2229, 2310, 273, 203, 5411, 417, 24410, 581, 5034, 12, 203, 7734, 24126, 18, 3015, 4420, 329, 12, 203, 10792, 389, 14936, 18, 14936, 559, 16, 203, 10792, 389, 14936, 18, 14914, 548, 16, 203, 10792, 389, 14936, 18, 9406, 6275, 16, 203, 10792, 389, 14936, 18, 5508, 203, 7734, 262, 203, 5411, 11272, 203, 3639, 1731, 1578, 12829, 2310, 273, 7773, 19748, 18, 869, 41, 451, 12294, 1079, 2310, 12, 978, 2310, 1769, 203, 3639, 2583, 12, 203, 5411, 7773, 19748, 18, 266, 3165, 12, 3239, 329, 2310, 16, 389, 14936, 18, 8195, 13, 422, 389, 4631, 966, 18, 4631, 16, 203, 5411, 315, 5580, 3372, 353, 2057, 6, 203, 3639, 11272, 203, 203, 3639, 2254, 5034, 394, 510, 1345, 31, 203, 3639, 309, 261, 67, 14914, 966, 18, 9406, 13937, 422, 374, 747, 389, 14914, 966, 18, 334, 1345, 3088, 1283, 422, 374, 13, 288, 203, 5411, 2583, 24899, 14914, 966, 18, 334, 1345, 3088, 1283, 422, 374, 16, 315, 5531, 6252, 384, 1345, 3088, 1283, 1297, 506, 3634, 8863, 203, 5411, 2583, 24899, 14914, 966, 18, 9561, 5580, 2 ]
./full_match/1/0x85Ff72ef23C559881589Daa5C8Ed9698124eDE72/sources/lib/seaport-types/src/helpers/PointerLibraries.sol
@dev Reads the uint176 at `rdPtr` in returndata.
function readUint176( ReturndataPointer rdPtr ) internal pure returns (uint176 value) { assembly ("memory-safe") { returndatacopy(0, rdPtr, _OneWord) value := mload(0) } }
8,451,910
[ 1, 7483, 326, 2254, 28493, 622, 1375, 13623, 5263, 68, 316, 327, 892, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 855, 5487, 28493, 12, 203, 3639, 2000, 892, 4926, 9437, 5263, 203, 565, 262, 2713, 16618, 1135, 261, 11890, 28493, 460, 13, 288, 203, 3639, 19931, 7566, 7858, 17, 4626, 7923, 288, 203, 5411, 327, 892, 3530, 12, 20, 16, 9437, 5263, 16, 389, 3335, 3944, 13, 203, 5411, 460, 519, 312, 945, 12, 20, 13, 203, 3639, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
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); } 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; } } contract ERC20 is ERC20Basic { function allowance(address _owner, address _spender) public view returns (uint256); function transferFrom(address _from, address _to, uint256 _value) public returns (bool); function approve(address _spender, uint256 _value) public returns (bool); event Approval( address indexed owner, address indexed spender, uint256 value ); } contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) internal balances; uint256 internal totalSupply_; /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev Transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_value <= balances[msg.sender]); require(_to != address(0)); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev 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]; } } library SafeERC20 { function safeTransfer( ERC20Basic _token, address _to, uint256 _value ) internal { require(_token.transfer(_to, _value)); } function safeTransferFrom( ERC20 _token, address _from, address _to, uint256 _value ) internal { require(_token.transferFrom(_from, _to, _value)); } function safeApprove( ERC20 _token, address _spender, uint256 _value ) internal { require(_token.approve(_spender, _value)); } } contract DetailedERC20 is ERC20 { string public name; string public symbol; uint8 public decimals; constructor(string _name, string _symbol, uint8 _decimals) public { name = _name; symbol = _symbol; decimals = _decimals; } } contract Crowdsale { using SafeMath for uint256; using SafeERC20 for ERC20; // The token being sold ERC20 public token; // Address where funds are collected address public wallet; // How many token units a buyer gets per wei. // The rate is the conversion between wei and the smallest and indivisible token unit. // So, if you are using a rate of 1 with a DetailedERC20 token with 3 decimals called TOK // 1 wei will give you 1 unit, or 0.001 TOK. uint256 internal rate; // Amount of wei raised uint256 public weiRaised; /** * Event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokenPurchase( address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount ); /** * @param _wallet Address where collected funds will be forwarded to * @param _token Address of the token being sold */ constructor(address _wallet, ERC20 _token) public { require(_wallet != address(0)); require(_token != address(0)); wallet = _wallet; token = _token; } // ----------------------------------------- // Crowdsale external interface // ----------------------------------------- /** * @dev fallback function ***DO NOT OVERRIDE*** */ function () external payable { buyTokens(msg.sender); } /** * @dev low level token purchase ***DO NOT OVERRIDE*** * @param _beneficiary Address performing the token purchase */ function buyTokens(address _beneficiary) public payable { uint256 weiAmount = msg.value; _preValidatePurchase(_beneficiary, weiAmount); // calculate token amount to be created uint256 tokens = _getTokenAmount(weiAmount); // update state weiRaised = weiRaised.add(weiAmount); _processPurchase(_beneficiary, tokens); emit TokenPurchase( msg.sender, _beneficiary, weiAmount, tokens ); _updatePurchasingState(_beneficiary, weiAmount); _forwardFunds(); _postValidatePurchase(_beneficiary, weiAmount); } // ----------------------------------------- // Internal interface (extensible) // ----------------------------------------- /** * @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. Use `super` 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); } } 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(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); require(_to != address(0)); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev 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, uint256 _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, uint256 _subtractedValue ) public returns (bool) { uint256 oldValue = allowed[msg.sender][_spender]; if (_subtractedValue >= oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } contract CappedCrowdsale is Crowdsale { using SafeMath for uint256; uint256 public cap; /** * @dev Constructor, takes maximum amount of wei accepted in the crowdsale. * @param _cap Max amount of wei to be contributed */ constructor(uint256 _cap) public { require(_cap > 0); cap = _cap; } /** * @dev Checks whether the cap has been reached. * @return Whether the cap was reached */ function capReached() public view returns (bool) { return weiRaised >= cap; } /** * @dev Extend parent behavior requiring purchase to respect the funding cap. * @param _beneficiary Token purchaser * @param _weiAmount Amount of wei contributed */ function _preValidatePurchase( address _beneficiary, uint256 _weiAmount ) internal { super._preValidatePurchase(_beneficiary, _weiAmount); require(weiRaised.add(_weiAmount) <= cap); } } contract SANDER1 is StandardToken, DetailedERC20 { /** * 12 tokens equal 12 songs equal 1 album * uint256 supply */ uint256 internal supply = 12 * 1 ether; constructor () public DetailedERC20 ( "Super Ander Token 1", "SANDER1", 18 ) { totalSupply_ = supply; balances[msg.sender] = supply; emit Transfer(0x0, msg.sender, totalSupply_); } } contract SuperCrowdsale is CappedCrowdsale { using SafeERC20 for SANDER1; modifier onlyOwner { require(msg.sender == owner); _; } address public owner; SANDER1 public token; uint256 internal weiAmount; event ProcessedRemainder(uint256 remainder); constructor ( SANDER1 _token, // sander1.superander.eth address _wallet // wallet.superander.eth ) public Crowdsale( _wallet, _token ) CappedCrowdsale( 4145880000000000000000 // 4145.88 ETH ) { owner = msg.sender; token = _token; } /** * @dev low level token purchase ***DO NOT OVERRIDE*** * @param _beneficiary Address performing the token purchase */ function buyTokens(address _beneficiary) public payable { weiAmount = msg.value; // if wei raised equals total cap, stop the crowdsale. _preValidatePurchase(_beneficiary, weiAmount); uint256 tokens = getTokenAmount(weiAmount); _processPurchase(_beneficiary, tokens); emit TokenPurchase(msg.sender, _beneficiary, weiAmount, tokens); _updatePurchasingState(_beneficiary, weiAmount); _forwardFunds(); weiRaised = weiRaised.add(weiAmount); _postValidatePurchase(_beneficiary, weiAmount); weiAmount = 0; } /** * @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.safeTransferFrom(owner, _beneficiary, _tokenAmount); } /** * @dev Override to extend the way in which ether is converted to tokens. * @param _weiAmount Value in wei to be converted into tokens * @return Number of tokens that can be purchased with the specified _weiAmount */ function getTokenAmount(uint256 _weiAmount) public view returns (uint256) { return _weiAmount.mul(token.allowance(owner, address(this))).div(cap); } }
The token being sold Address where funds are collected How many token units a buyer gets per wei. The rate is the conversion between wei and the smallest and indivisible token unit. So, if you are using a rate of 1 with a DetailedERC20 token with 3 decimals called TOK 1 wei will give you 1 unit, or 0.001 TOK. Amount of wei raised
contract Crowdsale { using SafeMath for uint256; using SafeERC20 for ERC20; ERC20 public token; address public wallet; uint256 internal rate; uint256 public weiRaised; event TokenPurchase( address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount ); constructor(address _wallet, ERC20 _token) public { require(_wallet != address(0)); require(_token != address(0)); wallet = _wallet; token = _token; } function () external payable { buyTokens(msg.sender); } function buyTokens(address _beneficiary) public payable { uint256 weiAmount = msg.value; _preValidatePurchase(_beneficiary, weiAmount); uint256 tokens = _getTokenAmount(weiAmount); weiRaised = weiRaised.add(weiAmount); _processPurchase(_beneficiary, tokens); emit TokenPurchase( msg.sender, _beneficiary, weiAmount, tokens ); _updatePurchasingState(_beneficiary, weiAmount); _forwardFunds(); _postValidatePurchase(_beneficiary, weiAmount); } function _preValidatePurchase( address _beneficiary, uint256 _weiAmount ) internal { require(_beneficiary != address(0)); require(_weiAmount != 0); } function _postValidatePurchase( address _beneficiary, uint256 _weiAmount ) internal { } function _deliverTokens( address _beneficiary, uint256 _tokenAmount ) internal { token.safeTransfer(_beneficiary, _tokenAmount); } function _processPurchase( address _beneficiary, uint256 _tokenAmount ) internal { _deliverTokens(_beneficiary, _tokenAmount); } function _updatePurchasingState( address _beneficiary, uint256 _weiAmount ) internal { } function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) { return _weiAmount.mul(rate); } function _forwardFunds() internal { wallet.transfer(msg.value); } }
6,426,129
[ 1, 1986, 1147, 3832, 272, 1673, 5267, 1625, 284, 19156, 854, 12230, 9017, 4906, 1147, 4971, 279, 27037, 5571, 1534, 732, 77, 18, 1021, 4993, 353, 326, 4105, 3086, 732, 77, 471, 326, 13541, 471, 6335, 18932, 1147, 2836, 18, 6155, 16, 309, 1846, 854, 1450, 279, 4993, 434, 404, 598, 279, 463, 6372, 654, 39, 3462, 1147, 598, 890, 15105, 2566, 399, 3141, 404, 732, 77, 903, 8492, 1846, 404, 2836, 16, 578, 374, 18, 11664, 399, 3141, 18, 16811, 434, 732, 77, 11531, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 16351, 385, 492, 2377, 5349, 288, 203, 225, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 225, 1450, 14060, 654, 39, 3462, 364, 4232, 39, 3462, 31, 203, 203, 225, 4232, 39, 3462, 1071, 1147, 31, 203, 203, 225, 1758, 1071, 9230, 31, 203, 203, 225, 2254, 5034, 2713, 4993, 31, 203, 203, 225, 2254, 5034, 1071, 732, 77, 12649, 5918, 31, 203, 203, 225, 871, 3155, 23164, 12, 203, 565, 1758, 8808, 5405, 343, 14558, 16, 203, 565, 1758, 8808, 27641, 74, 14463, 814, 16, 203, 565, 2254, 5034, 460, 16, 203, 565, 2254, 5034, 3844, 203, 225, 11272, 203, 203, 225, 3885, 12, 2867, 389, 19177, 16, 4232, 39, 3462, 389, 2316, 13, 1071, 288, 203, 565, 2583, 24899, 19177, 480, 1758, 12, 20, 10019, 203, 565, 2583, 24899, 2316, 480, 1758, 12, 20, 10019, 203, 565, 9230, 273, 389, 19177, 31, 203, 565, 1147, 273, 389, 2316, 31, 203, 225, 289, 203, 203, 203, 225, 445, 1832, 3903, 8843, 429, 288, 203, 565, 30143, 5157, 12, 3576, 18, 15330, 1769, 203, 225, 289, 203, 203, 225, 445, 30143, 5157, 12, 2867, 389, 70, 4009, 74, 14463, 814, 13, 1071, 8843, 429, 288, 203, 203, 565, 2254, 5034, 732, 77, 6275, 273, 1234, 18, 1132, 31, 203, 565, 389, 1484, 4270, 23164, 24899, 70, 4009, 74, 14463, 814, 16, 732, 77, 6275, 1769, 203, 203, 565, 2254, 5034, 2430, 273, 389, 588, 1345, 6275, 12, 1814, 77, 6275, 1769, 203, 203, 565, 732, 77, 12649, 5918, 273, 732, 77, 12649, 5918, 18, 2 ]
/* Copyright 2019,2020 StarkWare Industries Ltd. 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 https://www.starkware.co/open-source-license/ 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. */ // ---------- The following code was auto-generated. PLEASE DO NOT EDIT. ---------- // SPDX-License-Identifier: Apache-2.0. pragma solidity ^0.6.11; contract CpuConstraintPoly { // The Memory map during the execution of this contract is as follows: // [0x0, 0x20) - periodic_column/pedersen/points/x. // [0x20, 0x40) - periodic_column/pedersen/points/y. // [0x40, 0x60) - periodic_column/ecdsa/generator_points/x. // [0x60, 0x80) - periodic_column/ecdsa/generator_points/y. // [0x80, 0xa0) - trace_length. // [0xa0, 0xc0) - offset_size. // [0xc0, 0xe0) - half_offset_size. // [0xe0, 0x100) - initial_ap. // [0x100, 0x120) - initial_pc. // [0x120, 0x140) - final_ap. // [0x140, 0x160) - final_pc. // [0x160, 0x180) - memory/multi_column_perm/perm/interaction_elm. // [0x180, 0x1a0) - memory/multi_column_perm/hash_interaction_elm0. // [0x1a0, 0x1c0) - memory/multi_column_perm/perm/public_memory_prod. // [0x1c0, 0x1e0) - rc16/perm/interaction_elm. // [0x1e0, 0x200) - rc16/perm/public_memory_prod. // [0x200, 0x220) - rc_min. // [0x220, 0x240) - rc_max. // [0x240, 0x260) - pedersen/shift_point.x. // [0x260, 0x280) - pedersen/shift_point.y. // [0x280, 0x2a0) - initial_pedersen_addr. // [0x2a0, 0x2c0) - initial_rc_addr. // [0x2c0, 0x2e0) - ecdsa/sig_config.alpha. // [0x2e0, 0x300) - ecdsa/sig_config.shift_point.x. // [0x300, 0x320) - ecdsa/sig_config.shift_point.y. // [0x320, 0x340) - ecdsa/sig_config.beta. // [0x340, 0x360) - initial_ecdsa_addr. // [0x360, 0x380) - initial_checkpoints_addr. // [0x380, 0x3a0) - final_checkpoints_addr. // [0x3a0, 0x3c0) - trace_generator. // [0x3c0, 0x3e0) - oods_point. // [0x3e0, 0x440) - interaction_elements. // [0x440, 0x2fc0) - coefficients. // [0x2fc0, 0x4960) - oods_values. // ----------------------- end of input data - ------------------------- // [0x4960, 0x4980) - composition_degree_bound. // [0x4980, 0x49a0) - intermediate_value/cpu/decode/opcode_rc/bit_0. // [0x49a0, 0x49c0) - intermediate_value/cpu/decode/opcode_rc/bit_1. // [0x49c0, 0x49e0) - intermediate_value/cpu/decode/opcode_rc/bit_2. // [0x49e0, 0x4a00) - intermediate_value/cpu/decode/opcode_rc/bit_4. // [0x4a00, 0x4a20) - intermediate_value/cpu/decode/opcode_rc/bit_3. // [0x4a20, 0x4a40) - intermediate_value/cpu/decode/opcode_rc/bit_9. // [0x4a40, 0x4a60) - intermediate_value/cpu/decode/opcode_rc/bit_5. // [0x4a60, 0x4a80) - intermediate_value/cpu/decode/opcode_rc/bit_6. // [0x4a80, 0x4aa0) - intermediate_value/cpu/decode/opcode_rc/bit_7. // [0x4aa0, 0x4ac0) - intermediate_value/cpu/decode/opcode_rc/bit_8. // [0x4ac0, 0x4ae0) - intermediate_value/npc_reg_0. // [0x4ae0, 0x4b00) - intermediate_value/cpu/decode/opcode_rc/bit_10. // [0x4b00, 0x4b20) - intermediate_value/cpu/decode/opcode_rc/bit_11. // [0x4b20, 0x4b40) - intermediate_value/cpu/decode/opcode_rc/bit_12. // [0x4b40, 0x4b60) - intermediate_value/cpu/decode/opcode_rc/bit_13. // [0x4b60, 0x4b80) - intermediate_value/cpu/decode/opcode_rc/bit_14. // [0x4b80, 0x4ba0) - intermediate_value/memory/address_diff_0. // [0x4ba0, 0x4bc0) - intermediate_value/rc16/diff_0. // [0x4bc0, 0x4be0) - intermediate_value/pedersen/hash0/ec_subset_sum/bit_0. // [0x4be0, 0x4c00) - intermediate_value/pedersen/hash0/ec_subset_sum/bit_neg_0. // [0x4c00, 0x4c20) - intermediate_value/pedersen/hash1/ec_subset_sum/bit_0. // [0x4c20, 0x4c40) - intermediate_value/pedersen/hash1/ec_subset_sum/bit_neg_0. // [0x4c40, 0x4c60) - intermediate_value/pedersen/hash2/ec_subset_sum/bit_0. // [0x4c60, 0x4c80) - intermediate_value/pedersen/hash2/ec_subset_sum/bit_neg_0. // [0x4c80, 0x4ca0) - intermediate_value/pedersen/hash3/ec_subset_sum/bit_0. // [0x4ca0, 0x4cc0) - intermediate_value/pedersen/hash3/ec_subset_sum/bit_neg_0. // [0x4cc0, 0x4ce0) - intermediate_value/rc_builtin/value0_0. // [0x4ce0, 0x4d00) - intermediate_value/rc_builtin/value1_0. // [0x4d00, 0x4d20) - intermediate_value/rc_builtin/value2_0. // [0x4d20, 0x4d40) - intermediate_value/rc_builtin/value3_0. // [0x4d40, 0x4d60) - intermediate_value/rc_builtin/value4_0. // [0x4d60, 0x4d80) - intermediate_value/rc_builtin/value5_0. // [0x4d80, 0x4da0) - intermediate_value/rc_builtin/value6_0. // [0x4da0, 0x4dc0) - intermediate_value/rc_builtin/value7_0. // [0x4dc0, 0x4de0) - intermediate_value/ecdsa/signature0/doubling_key/x_squared. // [0x4de0, 0x4e00) - intermediate_value/ecdsa/signature0/exponentiate_generator/bit_0. // [0x4e00, 0x4e20) - intermediate_value/ecdsa/signature0/exponentiate_generator/bit_neg_0. // [0x4e20, 0x4e40) - intermediate_value/ecdsa/signature0/exponentiate_key/bit_0. // [0x4e40, 0x4e60) - intermediate_value/ecdsa/signature0/exponentiate_key/bit_neg_0. // [0x4e60, 0x5120) - expmods. // [0x5120, 0x5400) - denominator_invs. // [0x5400, 0x56e0) - denominators. // [0x56e0, 0x5840) - numerators. // [0x5840, 0x5b40) - adjustments. // [0x5b40, 0x5c00) - expmod_context. fallback() external { uint256 res; assembly { let PRIME := 0x800000000000011000000000000000000000000000000000000000000000001 // Copy input from calldata to memory. calldatacopy(0x0, 0x0, /*Input data size*/ 0x4960) let point := /*oods_point*/ mload(0x3c0) // Initialize composition_degree_bound to 2 * trace_length. mstore(0x4960, mul(2, /*trace_length*/ mload(0x80))) function expmod(base, exponent, modulus) -> result { let p := /*expmod_context*/ 0x5b40 mstore(p, 0x20) // Length of Base. mstore(add(p, 0x20), 0x20) // Length of Exponent. mstore(add(p, 0x40), 0x20) // Length of Modulus. mstore(add(p, 0x60), base) // Base. mstore(add(p, 0x80), exponent) // Exponent. mstore(add(p, 0xa0), modulus) // Modulus. // Call modexp precompile. if iszero(staticcall(not(0), 0x05, p, 0xc0, p, 0x20)) { revert(0, 0) } result := mload(p) } function degreeAdjustment(compositionPolynomialDegreeBound, constraintDegree, numeratorDegree, denominatorDegree) -> result { result := sub(sub(compositionPolynomialDegreeBound, 1), sub(add(constraintDegree, numeratorDegree), denominatorDegree)) } { // Prepare expmods for denominators and numerators. // expmods[0] = point^trace_length. mstore(0x4e60, expmod(point, /*trace_length*/ mload(0x80), PRIME)) // expmods[1] = point^(trace_length / 16). mstore(0x4e80, expmod(point, div(/*trace_length*/ mload(0x80), 16), PRIME)) // expmods[2] = point^(trace_length / 2). mstore(0x4ea0, expmod(point, div(/*trace_length*/ mload(0x80), 2), PRIME)) // expmods[3] = point^(trace_length / 8). mstore(0x4ec0, expmod(point, div(/*trace_length*/ mload(0x80), 8), PRIME)) // expmods[4] = point^(trace_length / 4). mstore(0x4ee0, expmod(point, div(/*trace_length*/ mload(0x80), 4), PRIME)) // expmods[5] = point^(trace_length / 256). mstore(0x4f00, expmod(point, div(/*trace_length*/ mload(0x80), 256), PRIME)) // expmods[6] = point^(trace_length / 512). mstore(0x4f20, expmod(point, div(/*trace_length*/ mload(0x80), 512), PRIME)) // expmods[7] = point^(trace_length / 128). mstore(0x4f40, expmod(point, div(/*trace_length*/ mload(0x80), 128), PRIME)) // expmods[8] = point^(trace_length / 4096). mstore(0x4f60, expmod(point, div(/*trace_length*/ mload(0x80), 4096), PRIME)) // expmods[9] = point^(trace_length / 32). mstore(0x4f80, expmod(point, div(/*trace_length*/ mload(0x80), 32), PRIME)) // expmods[10] = point^(trace_length / 8192). mstore(0x4fa0, expmod(point, div(/*trace_length*/ mload(0x80), 8192), PRIME)) // expmods[11] = trace_generator^(15 * trace_length / 16). mstore(0x4fc0, expmod(/*trace_generator*/ mload(0x3a0), div(mul(15, /*trace_length*/ mload(0x80)), 16), PRIME)) // expmods[12] = trace_generator^(16 * (trace_length / 16 - 1)). mstore(0x4fe0, expmod(/*trace_generator*/ mload(0x3a0), mul(16, sub(div(/*trace_length*/ mload(0x80), 16), 1)), PRIME)) // expmods[13] = trace_generator^(2 * (trace_length / 2 - 1)). mstore(0x5000, expmod(/*trace_generator*/ mload(0x3a0), mul(2, sub(div(/*trace_length*/ mload(0x80), 2), 1)), PRIME)) // expmods[14] = trace_generator^(4 * (trace_length / 4 - 1)). mstore(0x5020, expmod(/*trace_generator*/ mload(0x3a0), mul(4, sub(div(/*trace_length*/ mload(0x80), 4), 1)), PRIME)) // expmods[15] = trace_generator^(255 * trace_length / 256). mstore(0x5040, expmod(/*trace_generator*/ mload(0x3a0), div(mul(255, /*trace_length*/ mload(0x80)), 256), PRIME)) // expmods[16] = trace_generator^(63 * trace_length / 64). mstore(0x5060, expmod(/*trace_generator*/ mload(0x3a0), div(mul(63, /*trace_length*/ mload(0x80)), 64), PRIME)) // expmods[17] = trace_generator^(trace_length / 2). mstore(0x5080, expmod(/*trace_generator*/ mload(0x3a0), div(/*trace_length*/ mload(0x80), 2), PRIME)) // expmods[18] = trace_generator^(128 * (trace_length / 128 - 1)). mstore(0x50a0, expmod(/*trace_generator*/ mload(0x3a0), mul(128, sub(div(/*trace_length*/ mload(0x80), 128), 1)), PRIME)) // expmods[19] = trace_generator^(251 * trace_length / 256). mstore(0x50c0, expmod(/*trace_generator*/ mload(0x3a0), div(mul(251, /*trace_length*/ mload(0x80)), 256), PRIME)) // expmods[20] = trace_generator^(8192 * (trace_length / 8192 - 1)). mstore(0x50e0, expmod(/*trace_generator*/ mload(0x3a0), mul(8192, sub(div(/*trace_length*/ mload(0x80), 8192), 1)), PRIME)) // expmods[21] = trace_generator^(256 * (trace_length / 256 - 1)). mstore(0x5100, expmod(/*trace_generator*/ mload(0x3a0), mul(256, sub(div(/*trace_length*/ mload(0x80), 256), 1)), PRIME)) } { // Prepare denominators for batch inverse. // Denominator for constraints: 'cpu/decode/opcode_rc/bit', 'pedersen/hash0/ec_subset_sum/booleanity_test', 'pedersen/hash0/ec_subset_sum/add_points/slope', 'pedersen/hash0/ec_subset_sum/add_points/x', 'pedersen/hash0/ec_subset_sum/add_points/y', 'pedersen/hash0/ec_subset_sum/copy_point/x', 'pedersen/hash0/ec_subset_sum/copy_point/y', 'pedersen/hash1/ec_subset_sum/booleanity_test', 'pedersen/hash1/ec_subset_sum/add_points/slope', 'pedersen/hash1/ec_subset_sum/add_points/x', 'pedersen/hash1/ec_subset_sum/add_points/y', 'pedersen/hash1/ec_subset_sum/copy_point/x', 'pedersen/hash1/ec_subset_sum/copy_point/y', 'pedersen/hash2/ec_subset_sum/booleanity_test', 'pedersen/hash2/ec_subset_sum/add_points/slope', 'pedersen/hash2/ec_subset_sum/add_points/x', 'pedersen/hash2/ec_subset_sum/add_points/y', 'pedersen/hash2/ec_subset_sum/copy_point/x', 'pedersen/hash2/ec_subset_sum/copy_point/y', 'pedersen/hash3/ec_subset_sum/booleanity_test', 'pedersen/hash3/ec_subset_sum/add_points/slope', 'pedersen/hash3/ec_subset_sum/add_points/x', 'pedersen/hash3/ec_subset_sum/add_points/y', 'pedersen/hash3/ec_subset_sum/copy_point/x', 'pedersen/hash3/ec_subset_sum/copy_point/y'. // denominators[0] = point^trace_length - 1. mstore(0x5400, addmod(/*point^trace_length*/ mload(0x4e60), sub(PRIME, 1), PRIME)) // Denominator for constraints: 'cpu/decode/opcode_rc/zero'. // denominators[1] = point^(trace_length / 16) - trace_generator^(15 * trace_length / 16). mstore(0x5420, addmod( /*point^(trace_length / 16)*/ mload(0x4e80), sub(PRIME, /*trace_generator^(15 * trace_length / 16)*/ mload(0x4fc0)), PRIME)) // Denominator for constraints: 'cpu/decode/opcode_rc_input', 'cpu/operands/mem_dst_addr', 'cpu/operands/mem0_addr', 'cpu/operands/mem1_addr', 'cpu/operands/ops_mul', 'cpu/operands/res', 'cpu/update_registers/update_pc/tmp0', 'cpu/update_registers/update_pc/tmp1', 'cpu/update_registers/update_pc/pc_cond_negative', 'cpu/update_registers/update_pc/pc_cond_positive', 'cpu/update_registers/update_ap/ap_update', 'cpu/update_registers/update_fp/fp_update', 'cpu/opcodes/call/push_fp', 'cpu/opcodes/call/push_pc', 'cpu/opcodes/assert_eq/assert_eq', 'ecdsa/signature0/doubling_key/slope', 'ecdsa/signature0/doubling_key/x', 'ecdsa/signature0/doubling_key/y', 'ecdsa/signature0/exponentiate_key/booleanity_test', 'ecdsa/signature0/exponentiate_key/add_points/slope', 'ecdsa/signature0/exponentiate_key/add_points/x', 'ecdsa/signature0/exponentiate_key/add_points/y', 'ecdsa/signature0/exponentiate_key/add_points/x_diff_inv', 'ecdsa/signature0/exponentiate_key/copy_point/x', 'ecdsa/signature0/exponentiate_key/copy_point/y'. // denominators[2] = point^(trace_length / 16) - 1. mstore(0x5440, addmod(/*point^(trace_length / 16)*/ mload(0x4e80), sub(PRIME, 1), PRIME)) // Denominator for constraints: 'initial_ap', 'initial_fp', 'initial_pc', 'memory/multi_column_perm/perm/init0', 'memory/initial_addr', 'rc16/perm/init0', 'rc16/minimum', 'pedersen/init_addr', 'rc_builtin/init_addr', 'ecdsa/init_addr', 'checkpoints/req_pc_init_addr'. // denominators[3] = point - 1. mstore(0x5460, addmod(point, sub(PRIME, 1), PRIME)) // Denominator for constraints: 'final_ap', 'final_pc'. // denominators[4] = point - trace_generator^(16 * (trace_length / 16 - 1)). mstore(0x5480, addmod( point, sub(PRIME, /*trace_generator^(16 * (trace_length / 16 - 1))*/ mload(0x4fe0)), PRIME)) // Denominator for constraints: 'memory/multi_column_perm/perm/step0', 'memory/diff_is_bit', 'memory/is_func'. // denominators[5] = point^(trace_length / 2) - 1. mstore(0x54a0, addmod(/*point^(trace_length / 2)*/ mload(0x4ea0), sub(PRIME, 1), PRIME)) // Denominator for constraints: 'memory/multi_column_perm/perm/last'. // denominators[6] = point - trace_generator^(2 * (trace_length / 2 - 1)). mstore(0x54c0, addmod( point, sub(PRIME, /*trace_generator^(2 * (trace_length / 2 - 1))*/ mload(0x5000)), PRIME)) // Denominator for constraints: 'public_memory_addr_zero', 'public_memory_value_zero'. // denominators[7] = point^(trace_length / 8) - 1. mstore(0x54e0, addmod(/*point^(trace_length / 8)*/ mload(0x4ec0), sub(PRIME, 1), PRIME)) // Denominator for constraints: 'rc16/perm/step0', 'rc16/diff_is_bit'. // denominators[8] = point^(trace_length / 4) - 1. mstore(0x5500, addmod(/*point^(trace_length / 4)*/ mload(0x4ee0), sub(PRIME, 1), PRIME)) // Denominator for constraints: 'rc16/perm/last', 'rc16/maximum'. // denominators[9] = point - trace_generator^(4 * (trace_length / 4 - 1)). mstore(0x5520, addmod( point, sub(PRIME, /*trace_generator^(4 * (trace_length / 4 - 1))*/ mload(0x5020)), PRIME)) // Denominator for constraints: 'pedersen/hash0/ec_subset_sum/bit_unpacking/last_one_is_zero', 'pedersen/hash0/ec_subset_sum/bit_unpacking/zeroes_between_ones0', 'pedersen/hash0/ec_subset_sum/bit_unpacking/cumulative_bit192', 'pedersen/hash0/ec_subset_sum/bit_unpacking/zeroes_between_ones192', 'pedersen/hash0/ec_subset_sum/bit_unpacking/cumulative_bit196', 'pedersen/hash0/ec_subset_sum/bit_unpacking/zeroes_between_ones196', 'pedersen/hash0/copy_point/x', 'pedersen/hash0/copy_point/y', 'pedersen/hash1/ec_subset_sum/bit_unpacking/last_one_is_zero', 'pedersen/hash1/ec_subset_sum/bit_unpacking/zeroes_between_ones0', 'pedersen/hash1/ec_subset_sum/bit_unpacking/cumulative_bit192', 'pedersen/hash1/ec_subset_sum/bit_unpacking/zeroes_between_ones192', 'pedersen/hash1/ec_subset_sum/bit_unpacking/cumulative_bit196', 'pedersen/hash1/ec_subset_sum/bit_unpacking/zeroes_between_ones196', 'pedersen/hash1/copy_point/x', 'pedersen/hash1/copy_point/y', 'pedersen/hash2/ec_subset_sum/bit_unpacking/last_one_is_zero', 'pedersen/hash2/ec_subset_sum/bit_unpacking/zeroes_between_ones0', 'pedersen/hash2/ec_subset_sum/bit_unpacking/cumulative_bit192', 'pedersen/hash2/ec_subset_sum/bit_unpacking/zeroes_between_ones192', 'pedersen/hash2/ec_subset_sum/bit_unpacking/cumulative_bit196', 'pedersen/hash2/ec_subset_sum/bit_unpacking/zeroes_between_ones196', 'pedersen/hash2/copy_point/x', 'pedersen/hash2/copy_point/y', 'pedersen/hash3/ec_subset_sum/bit_unpacking/last_one_is_zero', 'pedersen/hash3/ec_subset_sum/bit_unpacking/zeroes_between_ones0', 'pedersen/hash3/ec_subset_sum/bit_unpacking/cumulative_bit192', 'pedersen/hash3/ec_subset_sum/bit_unpacking/zeroes_between_ones192', 'pedersen/hash3/ec_subset_sum/bit_unpacking/cumulative_bit196', 'pedersen/hash3/ec_subset_sum/bit_unpacking/zeroes_between_ones196', 'pedersen/hash3/copy_point/x', 'pedersen/hash3/copy_point/y', 'checkpoints/required_fp_addr', 'checkpoints/required_pc_next_addr', 'checkpoints/req_pc', 'checkpoints/req_fp'. // denominators[10] = point^(trace_length / 256) - 1. mstore(0x5540, addmod(/*point^(trace_length / 256)*/ mload(0x4f00), sub(PRIME, 1), PRIME)) // Denominator for constraints: 'pedersen/hash0/ec_subset_sum/bit_extraction_end', 'pedersen/hash1/ec_subset_sum/bit_extraction_end', 'pedersen/hash2/ec_subset_sum/bit_extraction_end', 'pedersen/hash3/ec_subset_sum/bit_extraction_end'. // denominators[11] = point^(trace_length / 256) - trace_generator^(63 * trace_length / 64). mstore(0x5560, addmod( /*point^(trace_length / 256)*/ mload(0x4f00), sub(PRIME, /*trace_generator^(63 * trace_length / 64)*/ mload(0x5060)), PRIME)) // Denominator for constraints: 'pedersen/hash0/ec_subset_sum/zeros_tail', 'pedersen/hash1/ec_subset_sum/zeros_tail', 'pedersen/hash2/ec_subset_sum/zeros_tail', 'pedersen/hash3/ec_subset_sum/zeros_tail'. // denominators[12] = point^(trace_length / 256) - trace_generator^(255 * trace_length / 256). mstore(0x5580, addmod( /*point^(trace_length / 256)*/ mload(0x4f00), sub(PRIME, /*trace_generator^(255 * trace_length / 256)*/ mload(0x5040)), PRIME)) // Denominator for constraints: 'pedersen/hash0/init/x', 'pedersen/hash0/init/y', 'pedersen/hash1/init/x', 'pedersen/hash1/init/y', 'pedersen/hash2/init/x', 'pedersen/hash2/init/y', 'pedersen/hash3/init/x', 'pedersen/hash3/init/y', 'pedersen/input0_value0', 'pedersen/input0_value1', 'pedersen/input0_value2', 'pedersen/input0_value3', 'pedersen/input1_value0', 'pedersen/input1_value1', 'pedersen/input1_value2', 'pedersen/input1_value3', 'pedersen/output_value0', 'pedersen/output_value1', 'pedersen/output_value2', 'pedersen/output_value3'. // denominators[13] = point^(trace_length / 512) - 1. mstore(0x55a0, addmod(/*point^(trace_length / 512)*/ mload(0x4f20), sub(PRIME, 1), PRIME)) // Denominator for constraints: 'pedersen/input0_addr', 'pedersen/input1_addr', 'pedersen/output_addr', 'rc_builtin/value', 'rc_builtin/addr_step'. // denominators[14] = point^(trace_length / 128) - 1. mstore(0x55c0, addmod(/*point^(trace_length / 128)*/ mload(0x4f40), sub(PRIME, 1), PRIME)) // Denominator for constraints: 'ecdsa/signature0/exponentiate_generator/booleanity_test', 'ecdsa/signature0/exponentiate_generator/add_points/slope', 'ecdsa/signature0/exponentiate_generator/add_points/x', 'ecdsa/signature0/exponentiate_generator/add_points/y', 'ecdsa/signature0/exponentiate_generator/add_points/x_diff_inv', 'ecdsa/signature0/exponentiate_generator/copy_point/x', 'ecdsa/signature0/exponentiate_generator/copy_point/y'. // denominators[15] = point^(trace_length / 32) - 1. mstore(0x55e0, addmod(/*point^(trace_length / 32)*/ mload(0x4f80), sub(PRIME, 1), PRIME)) // Denominator for constraints: 'ecdsa/signature0/exponentiate_generator/bit_extraction_end'. // denominators[16] = point^(trace_length / 8192) - trace_generator^(251 * trace_length / 256). mstore(0x5600, addmod( /*point^(trace_length / 8192)*/ mload(0x4fa0), sub(PRIME, /*trace_generator^(251 * trace_length / 256)*/ mload(0x50c0)), PRIME)) // Denominator for constraints: 'ecdsa/signature0/exponentiate_generator/zeros_tail'. // denominators[17] = point^(trace_length / 8192) - trace_generator^(255 * trace_length / 256). mstore(0x5620, addmod( /*point^(trace_length / 8192)*/ mload(0x4fa0), sub(PRIME, /*trace_generator^(255 * trace_length / 256)*/ mload(0x5040)), PRIME)) // Denominator for constraints: 'ecdsa/signature0/exponentiate_key/bit_extraction_end'. // denominators[18] = point^(trace_length / 4096) - trace_generator^(251 * trace_length / 256). mstore(0x5640, addmod( /*point^(trace_length / 4096)*/ mload(0x4f60), sub(PRIME, /*trace_generator^(251 * trace_length / 256)*/ mload(0x50c0)), PRIME)) // Denominator for constraints: 'ecdsa/signature0/exponentiate_key/zeros_tail'. // denominators[19] = point^(trace_length / 4096) - trace_generator^(255 * trace_length / 256). mstore(0x5660, addmod( /*point^(trace_length / 4096)*/ mload(0x4f60), sub(PRIME, /*trace_generator^(255 * trace_length / 256)*/ mload(0x5040)), PRIME)) // Denominator for constraints: 'ecdsa/signature0/init_gen/x', 'ecdsa/signature0/init_gen/y', 'ecdsa/signature0/add_results/slope', 'ecdsa/signature0/add_results/x', 'ecdsa/signature0/add_results/y', 'ecdsa/signature0/add_results/x_diff_inv', 'ecdsa/signature0/extract_r/slope', 'ecdsa/signature0/extract_r/x', 'ecdsa/signature0/extract_r/x_diff_inv', 'ecdsa/signature0/z_nonzero', 'ecdsa/signature0/q_on_curve/x_squared', 'ecdsa/signature0/q_on_curve/on_curve', 'ecdsa/message_addr', 'ecdsa/pubkey_addr', 'ecdsa/message_value0', 'ecdsa/pubkey_value0'. // denominators[20] = point^(trace_length / 8192) - 1. mstore(0x5680, addmod(/*point^(trace_length / 8192)*/ mload(0x4fa0), sub(PRIME, 1), PRIME)) // Denominator for constraints: 'ecdsa/signature0/init_key/x', 'ecdsa/signature0/init_key/y', 'ecdsa/signature0/r_and_w_nonzero'. // denominators[21] = point^(trace_length / 4096) - 1. mstore(0x56a0, addmod(/*point^(trace_length / 4096)*/ mload(0x4f60), sub(PRIME, 1), PRIME)) // Denominator for constraints: 'checkpoints/req_pc_final_addr'. // denominators[22] = point - trace_generator^(256 * (trace_length / 256 - 1)). mstore(0x56c0, addmod( point, sub(PRIME, /*trace_generator^(256 * (trace_length / 256 - 1))*/ mload(0x5100)), PRIME)) } { // Compute the inverses of the denominators into denominatorInvs using batch inverse. // Start by computing the cumulative product. // Let (d_0, d_1, d_2, ..., d_{n-1}) be the values in denominators. After this loop // denominatorInvs will be (1, d_0, d_0 * d_1, ...) and prod will contain the value of // d_0 * ... * d_{n-1}. // Compute the offset between the partialProducts array and the input values array. let productsToValuesOffset := 0x2e0 let prod := 1 let partialProductEndPtr := 0x5400 for { let partialProductPtr := 0x5120 } lt(partialProductPtr, partialProductEndPtr) { partialProductPtr := add(partialProductPtr, 0x20) } { mstore(partialProductPtr, prod) // prod *= d_{i}. prod := mulmod(prod, mload(add(partialProductPtr, productsToValuesOffset)), PRIME) } let firstPartialProductPtr := 0x5120 // Compute the inverse of the product. let prodInv := expmod(prod, sub(PRIME, 2), PRIME) if eq(prodInv, 0) { // Solidity generates reverts with reason that look as follows: // 1. 4 bytes with the constant 0x08c379a0 (== Keccak256(b'Error(string)')[:4]). // 2. 32 bytes offset bytes (always 0x20 as far as i can tell). // 3. 32 bytes with the length of the revert reason. // 4. Revert reason string. mstore(0, 0x08c379a000000000000000000000000000000000000000000000000000000000) mstore(0x4, 0x20) mstore(0x24, 0x1e) mstore(0x44, "Batch inverse product is zero.") revert(0, 0x62) } // Compute the inverses. // Loop over denominator_invs in reverse order. // currentPartialProductPtr is initialized to one past the end. let currentPartialProductPtr := 0x5400 for { } gt(currentPartialProductPtr, firstPartialProductPtr) { } { currentPartialProductPtr := sub(currentPartialProductPtr, 0x20) // Store 1/d_{i} = (d_0 * ... * d_{i-1}) * 1/(d_0 * ... * d_{i}). mstore(currentPartialProductPtr, mulmod(mload(currentPartialProductPtr), prodInv, PRIME)) // Update prodInv to be 1/(d_0 * ... * d_{i-1}) by multiplying by d_i. prodInv := mulmod(prodInv, mload(add(currentPartialProductPtr, productsToValuesOffset)), PRIME) } } { // Compute numerators and adjustment polynomials. // Numerator for constraints 'cpu/decode/opcode_rc/bit'. // numerators[0] = point^(trace_length / 16) - trace_generator^(15 * trace_length / 16). mstore(0x56e0, addmod( /*point^(trace_length / 16)*/ mload(0x4e80), sub(PRIME, /*trace_generator^(15 * trace_length / 16)*/ mload(0x4fc0)), PRIME)) // Numerator for constraints 'cpu/update_registers/update_pc/tmp0', 'cpu/update_registers/update_pc/tmp1', 'cpu/update_registers/update_pc/pc_cond_negative', 'cpu/update_registers/update_pc/pc_cond_positive', 'cpu/update_registers/update_ap/ap_update', 'cpu/update_registers/update_fp/fp_update'. // numerators[1] = point - trace_generator^(16 * (trace_length / 16 - 1)). mstore(0x5700, addmod( point, sub(PRIME, /*trace_generator^(16 * (trace_length / 16 - 1))*/ mload(0x4fe0)), PRIME)) // Numerator for constraints 'memory/multi_column_perm/perm/step0', 'memory/diff_is_bit', 'memory/is_func'. // numerators[2] = point - trace_generator^(2 * (trace_length / 2 - 1)). mstore(0x5720, addmod( point, sub(PRIME, /*trace_generator^(2 * (trace_length / 2 - 1))*/ mload(0x5000)), PRIME)) // Numerator for constraints 'rc16/perm/step0', 'rc16/diff_is_bit'. // numerators[3] = point - trace_generator^(4 * (trace_length / 4 - 1)). mstore(0x5740, addmod( point, sub(PRIME, /*trace_generator^(4 * (trace_length / 4 - 1))*/ mload(0x5020)), PRIME)) // Numerator for constraints 'pedersen/hash0/ec_subset_sum/booleanity_test', 'pedersen/hash0/ec_subset_sum/add_points/slope', 'pedersen/hash0/ec_subset_sum/add_points/x', 'pedersen/hash0/ec_subset_sum/add_points/y', 'pedersen/hash0/ec_subset_sum/copy_point/x', 'pedersen/hash0/ec_subset_sum/copy_point/y', 'pedersen/hash1/ec_subset_sum/booleanity_test', 'pedersen/hash1/ec_subset_sum/add_points/slope', 'pedersen/hash1/ec_subset_sum/add_points/x', 'pedersen/hash1/ec_subset_sum/add_points/y', 'pedersen/hash1/ec_subset_sum/copy_point/x', 'pedersen/hash1/ec_subset_sum/copy_point/y', 'pedersen/hash2/ec_subset_sum/booleanity_test', 'pedersen/hash2/ec_subset_sum/add_points/slope', 'pedersen/hash2/ec_subset_sum/add_points/x', 'pedersen/hash2/ec_subset_sum/add_points/y', 'pedersen/hash2/ec_subset_sum/copy_point/x', 'pedersen/hash2/ec_subset_sum/copy_point/y', 'pedersen/hash3/ec_subset_sum/booleanity_test', 'pedersen/hash3/ec_subset_sum/add_points/slope', 'pedersen/hash3/ec_subset_sum/add_points/x', 'pedersen/hash3/ec_subset_sum/add_points/y', 'pedersen/hash3/ec_subset_sum/copy_point/x', 'pedersen/hash3/ec_subset_sum/copy_point/y'. // numerators[4] = point^(trace_length / 256) - trace_generator^(255 * trace_length / 256). mstore(0x5760, addmod( /*point^(trace_length / 256)*/ mload(0x4f00), sub(PRIME, /*trace_generator^(255 * trace_length / 256)*/ mload(0x5040)), PRIME)) // Numerator for constraints 'pedersen/hash0/copy_point/x', 'pedersen/hash0/copy_point/y', 'pedersen/hash1/copy_point/x', 'pedersen/hash1/copy_point/y', 'pedersen/hash2/copy_point/x', 'pedersen/hash2/copy_point/y', 'pedersen/hash3/copy_point/x', 'pedersen/hash3/copy_point/y'. // numerators[5] = point^(trace_length / 512) - trace_generator^(trace_length / 2). mstore(0x5780, addmod( /*point^(trace_length / 512)*/ mload(0x4f20), sub(PRIME, /*trace_generator^(trace_length / 2)*/ mload(0x5080)), PRIME)) // Numerator for constraints 'pedersen/input0_addr', 'rc_builtin/addr_step'. // numerators[6] = point - trace_generator^(128 * (trace_length / 128 - 1)). mstore(0x57a0, addmod( point, sub(PRIME, /*trace_generator^(128 * (trace_length / 128 - 1))*/ mload(0x50a0)), PRIME)) // Numerator for constraints 'ecdsa/signature0/doubling_key/slope', 'ecdsa/signature0/doubling_key/x', 'ecdsa/signature0/doubling_key/y', 'ecdsa/signature0/exponentiate_key/booleanity_test', 'ecdsa/signature0/exponentiate_key/add_points/slope', 'ecdsa/signature0/exponentiate_key/add_points/x', 'ecdsa/signature0/exponentiate_key/add_points/y', 'ecdsa/signature0/exponentiate_key/add_points/x_diff_inv', 'ecdsa/signature0/exponentiate_key/copy_point/x', 'ecdsa/signature0/exponentiate_key/copy_point/y'. // numerators[7] = point^(trace_length / 4096) - trace_generator^(255 * trace_length / 256). mstore(0x57c0, addmod( /*point^(trace_length / 4096)*/ mload(0x4f60), sub(PRIME, /*trace_generator^(255 * trace_length / 256)*/ mload(0x5040)), PRIME)) // Numerator for constraints 'ecdsa/signature0/exponentiate_generator/booleanity_test', 'ecdsa/signature0/exponentiate_generator/add_points/slope', 'ecdsa/signature0/exponentiate_generator/add_points/x', 'ecdsa/signature0/exponentiate_generator/add_points/y', 'ecdsa/signature0/exponentiate_generator/add_points/x_diff_inv', 'ecdsa/signature0/exponentiate_generator/copy_point/x', 'ecdsa/signature0/exponentiate_generator/copy_point/y'. // numerators[8] = point^(trace_length / 8192) - trace_generator^(255 * trace_length / 256). mstore(0x57e0, addmod( /*point^(trace_length / 8192)*/ mload(0x4fa0), sub(PRIME, /*trace_generator^(255 * trace_length / 256)*/ mload(0x5040)), PRIME)) // Numerator for constraints 'ecdsa/pubkey_addr'. // numerators[9] = point - trace_generator^(8192 * (trace_length / 8192 - 1)). mstore(0x5800, addmod( point, sub(PRIME, /*trace_generator^(8192 * (trace_length / 8192 - 1))*/ mload(0x50e0)), PRIME)) // Numerator for constraints 'checkpoints/required_pc_next_addr', 'checkpoints/req_pc', 'checkpoints/req_fp'. // numerators[10] = point - trace_generator^(256 * (trace_length / 256 - 1)). mstore(0x5820, addmod( point, sub(PRIME, /*trace_generator^(256 * (trace_length / 256 - 1))*/ mload(0x5100)), PRIME)) // Adjustment polynomial for constraints 'cpu/decode/opcode_rc/bit'. // adjustments[0] = point^degreeAdjustment(composition_degree_bound, 2 * (trace_length - 1), trace_length / 16, trace_length). mstore(0x5840, expmod(point, degreeAdjustment(/*composition_degree_bound*/ mload(0x4960), mul(2, sub(/*trace_length*/ mload(0x80), 1)), div(/*trace_length*/ mload(0x80), 16), /*trace_length*/ mload(0x80)), PRIME)) // Adjustment polynomial for constraints 'cpu/decode/opcode_rc/zero', 'cpu/decode/opcode_rc_input'. // adjustments[1] = point^degreeAdjustment(composition_degree_bound, trace_length - 1, 0, trace_length / 16). mstore(0x5860, expmod(point, degreeAdjustment(/*composition_degree_bound*/ mload(0x4960), sub(/*trace_length*/ mload(0x80), 1), 0, div(/*trace_length*/ mload(0x80), 16)), PRIME)) // Adjustment polynomial for constraints 'cpu/operands/mem_dst_addr', 'cpu/operands/mem0_addr', 'cpu/operands/mem1_addr', 'cpu/operands/ops_mul', 'cpu/operands/res', 'cpu/opcodes/call/push_fp', 'cpu/opcodes/call/push_pc', 'cpu/opcodes/assert_eq/assert_eq'. // adjustments[2] = point^degreeAdjustment(composition_degree_bound, 2 * (trace_length - 1), 0, trace_length / 16). mstore(0x5880, expmod(point, degreeAdjustment(/*composition_degree_bound*/ mload(0x4960), mul(2, sub(/*trace_length*/ mload(0x80), 1)), 0, div(/*trace_length*/ mload(0x80), 16)), PRIME)) // Adjustment polynomial for constraints 'cpu/update_registers/update_pc/tmp0', 'cpu/update_registers/update_pc/tmp1', 'cpu/update_registers/update_pc/pc_cond_negative', 'cpu/update_registers/update_pc/pc_cond_positive', 'cpu/update_registers/update_ap/ap_update', 'cpu/update_registers/update_fp/fp_update'. // adjustments[3] = point^degreeAdjustment(composition_degree_bound, 2 * (trace_length - 1), 1, trace_length / 16). mstore(0x58a0, expmod(point, degreeAdjustment(/*composition_degree_bound*/ mload(0x4960), mul(2, sub(/*trace_length*/ mload(0x80), 1)), 1, div(/*trace_length*/ mload(0x80), 16)), PRIME)) // Adjustment polynomial for constraints 'initial_ap', 'initial_fp', 'initial_pc', 'final_ap', 'final_pc', 'memory/multi_column_perm/perm/last', 'memory/initial_addr', 'rc16/perm/last', 'rc16/minimum', 'rc16/maximum', 'pedersen/init_addr', 'rc_builtin/init_addr', 'ecdsa/init_addr', 'checkpoints/req_pc_init_addr', 'checkpoints/req_pc_final_addr'. // adjustments[4] = point^degreeAdjustment(composition_degree_bound, trace_length - 1, 0, 1). mstore(0x58c0, expmod(point, degreeAdjustment(/*composition_degree_bound*/ mload(0x4960), sub(/*trace_length*/ mload(0x80), 1), 0, 1), PRIME)) // Adjustment polynomial for constraints 'memory/multi_column_perm/perm/init0', 'rc16/perm/init0'. // adjustments[5] = point^degreeAdjustment(composition_degree_bound, 2 * (trace_length - 1), 0, 1). mstore(0x58e0, expmod(point, degreeAdjustment(/*composition_degree_bound*/ mload(0x4960), mul(2, sub(/*trace_length*/ mload(0x80), 1)), 0, 1), PRIME)) // Adjustment polynomial for constraints 'memory/multi_column_perm/perm/step0', 'memory/diff_is_bit', 'memory/is_func'. // adjustments[6] = point^degreeAdjustment(composition_degree_bound, 2 * (trace_length - 1), 1, trace_length / 2). mstore(0x5900, expmod(point, degreeAdjustment(/*composition_degree_bound*/ mload(0x4960), mul(2, sub(/*trace_length*/ mload(0x80), 1)), 1, div(/*trace_length*/ mload(0x80), 2)), PRIME)) // Adjustment polynomial for constraints 'public_memory_addr_zero', 'public_memory_value_zero'. // adjustments[7] = point^degreeAdjustment(composition_degree_bound, trace_length - 1, 0, trace_length / 8). mstore(0x5920, expmod(point, degreeAdjustment(/*composition_degree_bound*/ mload(0x4960), sub(/*trace_length*/ mload(0x80), 1), 0, div(/*trace_length*/ mload(0x80), 8)), PRIME)) // Adjustment polynomial for constraints 'rc16/perm/step0', 'rc16/diff_is_bit'. // adjustments[8] = point^degreeAdjustment(composition_degree_bound, 2 * (trace_length - 1), 1, trace_length / 4). mstore(0x5940, expmod(point, degreeAdjustment(/*composition_degree_bound*/ mload(0x4960), mul(2, sub(/*trace_length*/ mload(0x80), 1)), 1, div(/*trace_length*/ mload(0x80), 4)), PRIME)) // Adjustment polynomial for constraints 'pedersen/hash0/ec_subset_sum/bit_unpacking/last_one_is_zero', 'pedersen/hash0/ec_subset_sum/bit_unpacking/zeroes_between_ones0', 'pedersen/hash0/ec_subset_sum/bit_unpacking/cumulative_bit192', 'pedersen/hash0/ec_subset_sum/bit_unpacking/zeroes_between_ones192', 'pedersen/hash0/ec_subset_sum/bit_unpacking/cumulative_bit196', 'pedersen/hash0/ec_subset_sum/bit_unpacking/zeroes_between_ones196', 'pedersen/hash1/ec_subset_sum/bit_unpacking/last_one_is_zero', 'pedersen/hash1/ec_subset_sum/bit_unpacking/zeroes_between_ones0', 'pedersen/hash1/ec_subset_sum/bit_unpacking/cumulative_bit192', 'pedersen/hash1/ec_subset_sum/bit_unpacking/zeroes_between_ones192', 'pedersen/hash1/ec_subset_sum/bit_unpacking/cumulative_bit196', 'pedersen/hash1/ec_subset_sum/bit_unpacking/zeroes_between_ones196', 'pedersen/hash2/ec_subset_sum/bit_unpacking/last_one_is_zero', 'pedersen/hash2/ec_subset_sum/bit_unpacking/zeroes_between_ones0', 'pedersen/hash2/ec_subset_sum/bit_unpacking/cumulative_bit192', 'pedersen/hash2/ec_subset_sum/bit_unpacking/zeroes_between_ones192', 'pedersen/hash2/ec_subset_sum/bit_unpacking/cumulative_bit196', 'pedersen/hash2/ec_subset_sum/bit_unpacking/zeroes_between_ones196', 'pedersen/hash3/ec_subset_sum/bit_unpacking/last_one_is_zero', 'pedersen/hash3/ec_subset_sum/bit_unpacking/zeroes_between_ones0', 'pedersen/hash3/ec_subset_sum/bit_unpacking/cumulative_bit192', 'pedersen/hash3/ec_subset_sum/bit_unpacking/zeroes_between_ones192', 'pedersen/hash3/ec_subset_sum/bit_unpacking/cumulative_bit196', 'pedersen/hash3/ec_subset_sum/bit_unpacking/zeroes_between_ones196'. // adjustments[9] = point^degreeAdjustment(composition_degree_bound, 2 * (trace_length - 1), 0, trace_length / 256). mstore(0x5960, expmod(point, degreeAdjustment(/*composition_degree_bound*/ mload(0x4960), mul(2, sub(/*trace_length*/ mload(0x80), 1)), 0, div(/*trace_length*/ mload(0x80), 256)), PRIME)) // Adjustment polynomial for constraints 'pedersen/hash0/ec_subset_sum/booleanity_test', 'pedersen/hash0/ec_subset_sum/add_points/slope', 'pedersen/hash0/ec_subset_sum/add_points/x', 'pedersen/hash0/ec_subset_sum/add_points/y', 'pedersen/hash0/ec_subset_sum/copy_point/x', 'pedersen/hash0/ec_subset_sum/copy_point/y', 'pedersen/hash1/ec_subset_sum/booleanity_test', 'pedersen/hash1/ec_subset_sum/add_points/slope', 'pedersen/hash1/ec_subset_sum/add_points/x', 'pedersen/hash1/ec_subset_sum/add_points/y', 'pedersen/hash1/ec_subset_sum/copy_point/x', 'pedersen/hash1/ec_subset_sum/copy_point/y', 'pedersen/hash2/ec_subset_sum/booleanity_test', 'pedersen/hash2/ec_subset_sum/add_points/slope', 'pedersen/hash2/ec_subset_sum/add_points/x', 'pedersen/hash2/ec_subset_sum/add_points/y', 'pedersen/hash2/ec_subset_sum/copy_point/x', 'pedersen/hash2/ec_subset_sum/copy_point/y', 'pedersen/hash3/ec_subset_sum/booleanity_test', 'pedersen/hash3/ec_subset_sum/add_points/slope', 'pedersen/hash3/ec_subset_sum/add_points/x', 'pedersen/hash3/ec_subset_sum/add_points/y', 'pedersen/hash3/ec_subset_sum/copy_point/x', 'pedersen/hash3/ec_subset_sum/copy_point/y'. // adjustments[10] = point^degreeAdjustment(composition_degree_bound, 2 * (trace_length - 1), trace_length / 256, trace_length). mstore(0x5980, expmod(point, degreeAdjustment(/*composition_degree_bound*/ mload(0x4960), mul(2, sub(/*trace_length*/ mload(0x80), 1)), div(/*trace_length*/ mload(0x80), 256), /*trace_length*/ mload(0x80)), PRIME)) // Adjustment polynomial for constraints 'pedersen/hash0/ec_subset_sum/bit_extraction_end', 'pedersen/hash0/ec_subset_sum/zeros_tail', 'pedersen/hash1/ec_subset_sum/bit_extraction_end', 'pedersen/hash1/ec_subset_sum/zeros_tail', 'pedersen/hash2/ec_subset_sum/bit_extraction_end', 'pedersen/hash2/ec_subset_sum/zeros_tail', 'pedersen/hash3/ec_subset_sum/bit_extraction_end', 'pedersen/hash3/ec_subset_sum/zeros_tail', 'checkpoints/required_fp_addr'. // adjustments[11] = point^degreeAdjustment(composition_degree_bound, trace_length - 1, 0, trace_length / 256). mstore(0x59a0, expmod(point, degreeAdjustment(/*composition_degree_bound*/ mload(0x4960), sub(/*trace_length*/ mload(0x80), 1), 0, div(/*trace_length*/ mload(0x80), 256)), PRIME)) // Adjustment polynomial for constraints 'pedersen/hash0/copy_point/x', 'pedersen/hash0/copy_point/y', 'pedersen/hash1/copy_point/x', 'pedersen/hash1/copy_point/y', 'pedersen/hash2/copy_point/x', 'pedersen/hash2/copy_point/y', 'pedersen/hash3/copy_point/x', 'pedersen/hash3/copy_point/y'. // adjustments[12] = point^degreeAdjustment(composition_degree_bound, trace_length - 1, trace_length / 512, trace_length / 256). mstore(0x59c0, expmod(point, degreeAdjustment(/*composition_degree_bound*/ mload(0x4960), sub(/*trace_length*/ mload(0x80), 1), div(/*trace_length*/ mload(0x80), 512), div(/*trace_length*/ mload(0x80), 256)), PRIME)) // Adjustment polynomial for constraints 'pedersen/hash0/init/x', 'pedersen/hash0/init/y', 'pedersen/hash1/init/x', 'pedersen/hash1/init/y', 'pedersen/hash2/init/x', 'pedersen/hash2/init/y', 'pedersen/hash3/init/x', 'pedersen/hash3/init/y', 'pedersen/input0_value0', 'pedersen/input0_value1', 'pedersen/input0_value2', 'pedersen/input0_value3', 'pedersen/input1_value0', 'pedersen/input1_value1', 'pedersen/input1_value2', 'pedersen/input1_value3', 'pedersen/output_value0', 'pedersen/output_value1', 'pedersen/output_value2', 'pedersen/output_value3'. // adjustments[13] = point^degreeAdjustment(composition_degree_bound, trace_length - 1, 0, trace_length / 512). mstore(0x59e0, expmod(point, degreeAdjustment(/*composition_degree_bound*/ mload(0x4960), sub(/*trace_length*/ mload(0x80), 1), 0, div(/*trace_length*/ mload(0x80), 512)), PRIME)) // Adjustment polynomial for constraints 'pedersen/input0_addr', 'rc_builtin/addr_step'. // adjustments[14] = point^degreeAdjustment(composition_degree_bound, trace_length - 1, 1, trace_length / 128). mstore(0x5a00, expmod(point, degreeAdjustment(/*composition_degree_bound*/ mload(0x4960), sub(/*trace_length*/ mload(0x80), 1), 1, div(/*trace_length*/ mload(0x80), 128)), PRIME)) // Adjustment polynomial for constraints 'pedersen/input1_addr', 'pedersen/output_addr', 'rc_builtin/value'. // adjustments[15] = point^degreeAdjustment(composition_degree_bound, trace_length - 1, 0, trace_length / 128). mstore(0x5a20, expmod(point, degreeAdjustment(/*composition_degree_bound*/ mload(0x4960), sub(/*trace_length*/ mload(0x80), 1), 0, div(/*trace_length*/ mload(0x80), 128)), PRIME)) // Adjustment polynomial for constraints 'ecdsa/signature0/doubling_key/slope', 'ecdsa/signature0/doubling_key/x', 'ecdsa/signature0/doubling_key/y', 'ecdsa/signature0/exponentiate_key/booleanity_test', 'ecdsa/signature0/exponentiate_key/add_points/slope', 'ecdsa/signature0/exponentiate_key/add_points/x', 'ecdsa/signature0/exponentiate_key/add_points/y', 'ecdsa/signature0/exponentiate_key/add_points/x_diff_inv', 'ecdsa/signature0/exponentiate_key/copy_point/x', 'ecdsa/signature0/exponentiate_key/copy_point/y'. // adjustments[16] = point^degreeAdjustment(composition_degree_bound, 2 * (trace_length - 1), trace_length / 4096, trace_length / 16). mstore(0x5a40, expmod(point, degreeAdjustment(/*composition_degree_bound*/ mload(0x4960), mul(2, sub(/*trace_length*/ mload(0x80), 1)), div(/*trace_length*/ mload(0x80), 4096), div(/*trace_length*/ mload(0x80), 16)), PRIME)) // Adjustment polynomial for constraints 'ecdsa/signature0/exponentiate_generator/booleanity_test', 'ecdsa/signature0/exponentiate_generator/add_points/slope', 'ecdsa/signature0/exponentiate_generator/add_points/x', 'ecdsa/signature0/exponentiate_generator/add_points/y', 'ecdsa/signature0/exponentiate_generator/add_points/x_diff_inv', 'ecdsa/signature0/exponentiate_generator/copy_point/x', 'ecdsa/signature0/exponentiate_generator/copy_point/y'. // adjustments[17] = point^degreeAdjustment(composition_degree_bound, 2 * (trace_length - 1), trace_length / 8192, trace_length / 32). mstore(0x5a60, expmod(point, degreeAdjustment(/*composition_degree_bound*/ mload(0x4960), mul(2, sub(/*trace_length*/ mload(0x80), 1)), div(/*trace_length*/ mload(0x80), 8192), div(/*trace_length*/ mload(0x80), 32)), PRIME)) // Adjustment polynomial for constraints 'ecdsa/signature0/exponentiate_generator/bit_extraction_end', 'ecdsa/signature0/exponentiate_generator/zeros_tail', 'ecdsa/signature0/init_gen/x', 'ecdsa/signature0/init_gen/y', 'ecdsa/message_addr', 'ecdsa/message_value0', 'ecdsa/pubkey_value0'. // adjustments[18] = point^degreeAdjustment(composition_degree_bound, trace_length - 1, 0, trace_length / 8192). mstore(0x5a80, expmod(point, degreeAdjustment(/*composition_degree_bound*/ mload(0x4960), sub(/*trace_length*/ mload(0x80), 1), 0, div(/*trace_length*/ mload(0x80), 8192)), PRIME)) // Adjustment polynomial for constraints 'ecdsa/signature0/exponentiate_key/bit_extraction_end', 'ecdsa/signature0/exponentiate_key/zeros_tail', 'ecdsa/signature0/init_key/x', 'ecdsa/signature0/init_key/y'. // adjustments[19] = point^degreeAdjustment(composition_degree_bound, trace_length - 1, 0, trace_length / 4096). mstore(0x5aa0, expmod(point, degreeAdjustment(/*composition_degree_bound*/ mload(0x4960), sub(/*trace_length*/ mload(0x80), 1), 0, div(/*trace_length*/ mload(0x80), 4096)), PRIME)) // Adjustment polynomial for constraints 'ecdsa/signature0/add_results/slope', 'ecdsa/signature0/add_results/x', 'ecdsa/signature0/add_results/y', 'ecdsa/signature0/add_results/x_diff_inv', 'ecdsa/signature0/extract_r/slope', 'ecdsa/signature0/extract_r/x', 'ecdsa/signature0/extract_r/x_diff_inv', 'ecdsa/signature0/z_nonzero', 'ecdsa/signature0/q_on_curve/x_squared', 'ecdsa/signature0/q_on_curve/on_curve'. // adjustments[20] = point^degreeAdjustment(composition_degree_bound, 2 * (trace_length - 1), 0, trace_length / 8192). mstore(0x5ac0, expmod(point, degreeAdjustment(/*composition_degree_bound*/ mload(0x4960), mul(2, sub(/*trace_length*/ mload(0x80), 1)), 0, div(/*trace_length*/ mload(0x80), 8192)), PRIME)) // Adjustment polynomial for constraints 'ecdsa/signature0/r_and_w_nonzero'. // adjustments[21] = point^degreeAdjustment(composition_degree_bound, 2 * (trace_length - 1), 0, trace_length / 4096). mstore(0x5ae0, expmod(point, degreeAdjustment(/*composition_degree_bound*/ mload(0x4960), mul(2, sub(/*trace_length*/ mload(0x80), 1)), 0, div(/*trace_length*/ mload(0x80), 4096)), PRIME)) // Adjustment polynomial for constraints 'ecdsa/pubkey_addr'. // adjustments[22] = point^degreeAdjustment(composition_degree_bound, trace_length - 1, 1, trace_length / 8192). mstore(0x5b00, expmod(point, degreeAdjustment(/*composition_degree_bound*/ mload(0x4960), sub(/*trace_length*/ mload(0x80), 1), 1, div(/*trace_length*/ mload(0x80), 8192)), PRIME)) // Adjustment polynomial for constraints 'checkpoints/required_pc_next_addr', 'checkpoints/req_pc', 'checkpoints/req_fp'. // adjustments[23] = point^degreeAdjustment(composition_degree_bound, 2 * (trace_length - 1), 1, trace_length / 256). mstore(0x5b20, expmod(point, degreeAdjustment(/*composition_degree_bound*/ mload(0x4960), mul(2, sub(/*trace_length*/ mload(0x80), 1)), 1, div(/*trace_length*/ mload(0x80), 256)), PRIME)) } { // Compute the result of the composition polynomial. { // cpu/decode/opcode_rc/bit_0 = column0_row0 - (column0_row1 + column0_row1). let val := addmod( /*column0_row0*/ mload(0x2fc0), sub( PRIME, addmod(/*column0_row1*/ mload(0x2fe0), /*column0_row1*/ mload(0x2fe0), PRIME)), PRIME) mstore(0x4980, val) } { // cpu/decode/opcode_rc/bit_1 = column0_row1 - (column0_row2 + column0_row2). let val := addmod( /*column0_row1*/ mload(0x2fe0), sub( PRIME, addmod(/*column0_row2*/ mload(0x3000), /*column0_row2*/ mload(0x3000), PRIME)), PRIME) mstore(0x49a0, val) } { // cpu/decode/opcode_rc/bit_2 = column0_row2 - (column0_row3 + column0_row3). let val := addmod( /*column0_row2*/ mload(0x3000), sub( PRIME, addmod(/*column0_row3*/ mload(0x3020), /*column0_row3*/ mload(0x3020), PRIME)), PRIME) mstore(0x49c0, val) } { // cpu/decode/opcode_rc/bit_4 = column0_row4 - (column0_row5 + column0_row5). let val := addmod( /*column0_row4*/ mload(0x3040), sub( PRIME, addmod(/*column0_row5*/ mload(0x3060), /*column0_row5*/ mload(0x3060), PRIME)), PRIME) mstore(0x49e0, val) } { // cpu/decode/opcode_rc/bit_3 = column0_row3 - (column0_row4 + column0_row4). let val := addmod( /*column0_row3*/ mload(0x3020), sub( PRIME, addmod(/*column0_row4*/ mload(0x3040), /*column0_row4*/ mload(0x3040), PRIME)), PRIME) mstore(0x4a00, val) } { // cpu/decode/opcode_rc/bit_9 = column0_row9 - (column0_row10 + column0_row10). let val := addmod( /*column0_row9*/ mload(0x30e0), sub( PRIME, addmod(/*column0_row10*/ mload(0x3100), /*column0_row10*/ mload(0x3100), PRIME)), PRIME) mstore(0x4a20, val) } { // cpu/decode/opcode_rc/bit_5 = column0_row5 - (column0_row6 + column0_row6). let val := addmod( /*column0_row5*/ mload(0x3060), sub( PRIME, addmod(/*column0_row6*/ mload(0x3080), /*column0_row6*/ mload(0x3080), PRIME)), PRIME) mstore(0x4a40, val) } { // cpu/decode/opcode_rc/bit_6 = column0_row6 - (column0_row7 + column0_row7). let val := addmod( /*column0_row6*/ mload(0x3080), sub( PRIME, addmod(/*column0_row7*/ mload(0x30a0), /*column0_row7*/ mload(0x30a0), PRIME)), PRIME) mstore(0x4a60, val) } { // cpu/decode/opcode_rc/bit_7 = column0_row7 - (column0_row8 + column0_row8). let val := addmod( /*column0_row7*/ mload(0x30a0), sub( PRIME, addmod(/*column0_row8*/ mload(0x30c0), /*column0_row8*/ mload(0x30c0), PRIME)), PRIME) mstore(0x4a80, val) } { // cpu/decode/opcode_rc/bit_8 = column0_row8 - (column0_row9 + column0_row9). let val := addmod( /*column0_row8*/ mload(0x30c0), sub( PRIME, addmod(/*column0_row9*/ mload(0x30e0), /*column0_row9*/ mload(0x30e0), PRIME)), PRIME) mstore(0x4aa0, val) } { // npc_reg_0 = column17_row0 + cpu__decode__opcode_rc__bit_2 + 1. let val := addmod( addmod( /*column17_row0*/ mload(0x3bc0), /*intermediate_value/cpu/decode/opcode_rc/bit_2*/ mload(0x49c0), PRIME), 1, PRIME) mstore(0x4ac0, val) } { // cpu/decode/opcode_rc/bit_10 = column0_row10 - (column0_row11 + column0_row11). let val := addmod( /*column0_row10*/ mload(0x3100), sub( PRIME, addmod(/*column0_row11*/ mload(0x3120), /*column0_row11*/ mload(0x3120), PRIME)), PRIME) mstore(0x4ae0, val) } { // cpu/decode/opcode_rc/bit_11 = column0_row11 - (column0_row12 + column0_row12). let val := addmod( /*column0_row11*/ mload(0x3120), sub( PRIME, addmod(/*column0_row12*/ mload(0x3140), /*column0_row12*/ mload(0x3140), PRIME)), PRIME) mstore(0x4b00, val) } { // cpu/decode/opcode_rc/bit_12 = column0_row12 - (column0_row13 + column0_row13). let val := addmod( /*column0_row12*/ mload(0x3140), sub( PRIME, addmod(/*column0_row13*/ mload(0x3160), /*column0_row13*/ mload(0x3160), PRIME)), PRIME) mstore(0x4b20, val) } { // cpu/decode/opcode_rc/bit_13 = column0_row13 - (column0_row14 + column0_row14). let val := addmod( /*column0_row13*/ mload(0x3160), sub( PRIME, addmod(/*column0_row14*/ mload(0x3180), /*column0_row14*/ mload(0x3180), PRIME)), PRIME) mstore(0x4b40, val) } { // cpu/decode/opcode_rc/bit_14 = column0_row14 - (column0_row15 + column0_row15). let val := addmod( /*column0_row14*/ mload(0x3180), sub( PRIME, addmod(/*column0_row15*/ mload(0x31a0), /*column0_row15*/ mload(0x31a0), PRIME)), PRIME) mstore(0x4b60, val) } { // memory/address_diff_0 = column18_row2 - column18_row0. let val := addmod(/*column18_row2*/ mload(0x4100), sub(PRIME, /*column18_row0*/ mload(0x40c0)), PRIME) mstore(0x4b80, val) } { // rc16/diff_0 = column19_row6 - column19_row2. let val := addmod(/*column19_row6*/ mload(0x4200), sub(PRIME, /*column19_row2*/ mload(0x4180)), PRIME) mstore(0x4ba0, val) } { // pedersen/hash0/ec_subset_sum/bit_0 = column4_row0 - (column4_row1 + column4_row1). let val := addmod( /*column4_row0*/ mload(0x3320), sub( PRIME, addmod(/*column4_row1*/ mload(0x3340), /*column4_row1*/ mload(0x3340), PRIME)), PRIME) mstore(0x4bc0, val) } { // pedersen/hash0/ec_subset_sum/bit_neg_0 = 1 - pedersen__hash0__ec_subset_sum__bit_0. let val := addmod( 1, sub(PRIME, /*intermediate_value/pedersen/hash0/ec_subset_sum/bit_0*/ mload(0x4bc0)), PRIME) mstore(0x4be0, val) } { // pedersen/hash1/ec_subset_sum/bit_0 = column8_row0 - (column8_row1 + column8_row1). let val := addmod( /*column8_row0*/ mload(0x35a0), sub( PRIME, addmod(/*column8_row1*/ mload(0x35c0), /*column8_row1*/ mload(0x35c0), PRIME)), PRIME) mstore(0x4c00, val) } { // pedersen/hash1/ec_subset_sum/bit_neg_0 = 1 - pedersen__hash1__ec_subset_sum__bit_0. let val := addmod( 1, sub(PRIME, /*intermediate_value/pedersen/hash1/ec_subset_sum/bit_0*/ mload(0x4c00)), PRIME) mstore(0x4c20, val) } { // pedersen/hash2/ec_subset_sum/bit_0 = column12_row0 - (column12_row1 + column12_row1). let val := addmod( /*column12_row0*/ mload(0x3820), sub( PRIME, addmod(/*column12_row1*/ mload(0x3840), /*column12_row1*/ mload(0x3840), PRIME)), PRIME) mstore(0x4c40, val) } { // pedersen/hash2/ec_subset_sum/bit_neg_0 = 1 - pedersen__hash2__ec_subset_sum__bit_0. let val := addmod( 1, sub(PRIME, /*intermediate_value/pedersen/hash2/ec_subset_sum/bit_0*/ mload(0x4c40)), PRIME) mstore(0x4c60, val) } { // pedersen/hash3/ec_subset_sum/bit_0 = column16_row0 - (column16_row1 + column16_row1). let val := addmod( /*column16_row0*/ mload(0x3aa0), sub( PRIME, addmod(/*column16_row1*/ mload(0x3ac0), /*column16_row1*/ mload(0x3ac0), PRIME)), PRIME) mstore(0x4c80, val) } { // pedersen/hash3/ec_subset_sum/bit_neg_0 = 1 - pedersen__hash3__ec_subset_sum__bit_0. let val := addmod( 1, sub(PRIME, /*intermediate_value/pedersen/hash3/ec_subset_sum/bit_0*/ mload(0x4c80)), PRIME) mstore(0x4ca0, val) } { // rc_builtin/value0_0 = column19_row12. let val := /*column19_row12*/ mload(0x42a0) mstore(0x4cc0, val) } { // rc_builtin/value1_0 = rc_builtin__value0_0 * offset_size + column19_row28. let val := addmod( mulmod( /*intermediate_value/rc_builtin/value0_0*/ mload(0x4cc0), /*offset_size*/ mload(0xa0), PRIME), /*column19_row28*/ mload(0x4360), PRIME) mstore(0x4ce0, val) } { // rc_builtin/value2_0 = rc_builtin__value1_0 * offset_size + column19_row44. let val := addmod( mulmod( /*intermediate_value/rc_builtin/value1_0*/ mload(0x4ce0), /*offset_size*/ mload(0xa0), PRIME), /*column19_row44*/ mload(0x43a0), PRIME) mstore(0x4d00, val) } { // rc_builtin/value3_0 = rc_builtin__value2_0 * offset_size + column19_row60. let val := addmod( mulmod( /*intermediate_value/rc_builtin/value2_0*/ mload(0x4d00), /*offset_size*/ mload(0xa0), PRIME), /*column19_row60*/ mload(0x43c0), PRIME) mstore(0x4d20, val) } { // rc_builtin/value4_0 = rc_builtin__value3_0 * offset_size + column19_row76. let val := addmod( mulmod( /*intermediate_value/rc_builtin/value3_0*/ mload(0x4d20), /*offset_size*/ mload(0xa0), PRIME), /*column19_row76*/ mload(0x43e0), PRIME) mstore(0x4d40, val) } { // rc_builtin/value5_0 = rc_builtin__value4_0 * offset_size + column19_row92. let val := addmod( mulmod( /*intermediate_value/rc_builtin/value4_0*/ mload(0x4d40), /*offset_size*/ mload(0xa0), PRIME), /*column19_row92*/ mload(0x4400), PRIME) mstore(0x4d60, val) } { // rc_builtin/value6_0 = rc_builtin__value5_0 * offset_size + column19_row108. let val := addmod( mulmod( /*intermediate_value/rc_builtin/value5_0*/ mload(0x4d60), /*offset_size*/ mload(0xa0), PRIME), /*column19_row108*/ mload(0x4420), PRIME) mstore(0x4d80, val) } { // rc_builtin/value7_0 = rc_builtin__value6_0 * offset_size + column19_row124. let val := addmod( mulmod( /*intermediate_value/rc_builtin/value6_0*/ mload(0x4d80), /*offset_size*/ mload(0xa0), PRIME), /*column19_row124*/ mload(0x4440), PRIME) mstore(0x4da0, val) } { // ecdsa/signature0/doubling_key/x_squared = column19_row7 * column19_row7. let val := mulmod(/*column19_row7*/ mload(0x4220), /*column19_row7*/ mload(0x4220), PRIME) mstore(0x4dc0, val) } { // ecdsa/signature0/exponentiate_generator/bit_0 = column20_row30 - (column20_row62 + column20_row62). let val := addmod( /*column20_row30*/ mload(0x4660), sub( PRIME, addmod(/*column20_row62*/ mload(0x46c0), /*column20_row62*/ mload(0x46c0), PRIME)), PRIME) mstore(0x4de0, val) } { // ecdsa/signature0/exponentiate_generator/bit_neg_0 = 1 - ecdsa__signature0__exponentiate_generator__bit_0. let val := addmod( 1, sub( PRIME, /*intermediate_value/ecdsa/signature0/exponentiate_generator/bit_0*/ mload(0x4de0)), PRIME) mstore(0x4e00, val) } { // ecdsa/signature0/exponentiate_key/bit_0 = column20_row2 - (column20_row18 + column20_row18). let val := addmod( /*column20_row2*/ mload(0x44e0), sub( PRIME, addmod(/*column20_row18*/ mload(0x45e0), /*column20_row18*/ mload(0x45e0), PRIME)), PRIME) mstore(0x4e20, val) } { // ecdsa/signature0/exponentiate_key/bit_neg_0 = 1 - ecdsa__signature0__exponentiate_key__bit_0. let val := addmod( 1, sub( PRIME, /*intermediate_value/ecdsa/signature0/exponentiate_key/bit_0*/ mload(0x4e20)), PRIME) mstore(0x4e40, val) } { // Constraint expression for cpu/decode/opcode_rc/bit: cpu__decode__opcode_rc__bit_0 * cpu__decode__opcode_rc__bit_0 - cpu__decode__opcode_rc__bit_0. let val := addmod( mulmod( /*intermediate_value/cpu/decode/opcode_rc/bit_0*/ mload(0x4980), /*intermediate_value/cpu/decode/opcode_rc/bit_0*/ mload(0x4980), PRIME), sub(PRIME, /*intermediate_value/cpu/decode/opcode_rc/bit_0*/ mload(0x4980)), PRIME) // Numerator: point^(trace_length / 16) - trace_generator^(15 * trace_length / 16). // val *= numerators[0]. val := mulmod(val, mload(0x56e0), PRIME) // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0x5120), PRIME) // res += val * (coefficients[0] + coefficients[1] * adjustments[0]). res := addmod(res, mulmod(val, add(/*coefficients[0]*/ mload(0x440), mulmod(/*coefficients[1]*/ mload(0x460), /*adjustments[0]*/mload(0x5840), PRIME)), PRIME), PRIME) } { // Constraint expression for cpu/decode/opcode_rc/zero: column0_row0. let val := /*column0_row0*/ mload(0x2fc0) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 16) - trace_generator^(15 * trace_length / 16). // val *= denominator_invs[1]. val := mulmod(val, mload(0x5140), PRIME) // res += val * (coefficients[2] + coefficients[3] * adjustments[1]). res := addmod(res, mulmod(val, add(/*coefficients[2]*/ mload(0x480), mulmod(/*coefficients[3]*/ mload(0x4a0), /*adjustments[1]*/mload(0x5860), PRIME)), PRIME), PRIME) } { // Constraint expression for cpu/decode/opcode_rc_input: column17_row1 - (((column0_row0 * offset_size + column19_row4) * offset_size + column19_row8) * offset_size + column19_row0). let val := addmod( /*column17_row1*/ mload(0x3be0), sub( PRIME, addmod( mulmod( addmod( mulmod( addmod( mulmod(/*column0_row0*/ mload(0x2fc0), /*offset_size*/ mload(0xa0), PRIME), /*column19_row4*/ mload(0x41c0), PRIME), /*offset_size*/ mload(0xa0), PRIME), /*column19_row8*/ mload(0x4240), PRIME), /*offset_size*/ mload(0xa0), PRIME), /*column19_row0*/ mload(0x4140), PRIME)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 16) - 1. // val *= denominator_invs[2]. val := mulmod(val, mload(0x5160), PRIME) // res += val * (coefficients[4] + coefficients[5] * adjustments[1]). res := addmod(res, mulmod(val, add(/*coefficients[4]*/ mload(0x4c0), mulmod(/*coefficients[5]*/ mload(0x4e0), /*adjustments[1]*/mload(0x5860), PRIME)), PRIME), PRIME) } { // Constraint expression for cpu/operands/mem_dst_addr: column17_row8 + half_offset_size - (cpu__decode__opcode_rc__bit_0 * column19_row9 + (1 - cpu__decode__opcode_rc__bit_0) * column19_row1 + column19_row0). let val := addmod( addmod(/*column17_row8*/ mload(0x3cc0), /*half_offset_size*/ mload(0xc0), PRIME), sub( PRIME, addmod( addmod( mulmod( /*intermediate_value/cpu/decode/opcode_rc/bit_0*/ mload(0x4980), /*column19_row9*/ mload(0x4260), PRIME), mulmod( addmod( 1, sub(PRIME, /*intermediate_value/cpu/decode/opcode_rc/bit_0*/ mload(0x4980)), PRIME), /*column19_row1*/ mload(0x4160), PRIME), PRIME), /*column19_row0*/ mload(0x4140), PRIME)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 16) - 1. // val *= denominator_invs[2]. val := mulmod(val, mload(0x5160), PRIME) // res += val * (coefficients[6] + coefficients[7] * adjustments[2]). res := addmod(res, mulmod(val, add(/*coefficients[6]*/ mload(0x500), mulmod(/*coefficients[7]*/ mload(0x520), /*adjustments[2]*/mload(0x5880), PRIME)), PRIME), PRIME) } { // Constraint expression for cpu/operands/mem0_addr: column17_row4 + half_offset_size - (cpu__decode__opcode_rc__bit_1 * column19_row9 + (1 - cpu__decode__opcode_rc__bit_1) * column19_row1 + column19_row8). let val := addmod( addmod(/*column17_row4*/ mload(0x3c40), /*half_offset_size*/ mload(0xc0), PRIME), sub( PRIME, addmod( addmod( mulmod( /*intermediate_value/cpu/decode/opcode_rc/bit_1*/ mload(0x49a0), /*column19_row9*/ mload(0x4260), PRIME), mulmod( addmod( 1, sub(PRIME, /*intermediate_value/cpu/decode/opcode_rc/bit_1*/ mload(0x49a0)), PRIME), /*column19_row1*/ mload(0x4160), PRIME), PRIME), /*column19_row8*/ mload(0x4240), PRIME)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 16) - 1. // val *= denominator_invs[2]. val := mulmod(val, mload(0x5160), PRIME) // res += val * (coefficients[8] + coefficients[9] * adjustments[2]). res := addmod(res, mulmod(val, add(/*coefficients[8]*/ mload(0x540), mulmod(/*coefficients[9]*/ mload(0x560), /*adjustments[2]*/mload(0x5880), PRIME)), PRIME), PRIME) } { // Constraint expression for cpu/operands/mem1_addr: column17_row12 + half_offset_size - (cpu__decode__opcode_rc__bit_2 * column17_row0 + cpu__decode__opcode_rc__bit_4 * column19_row1 + cpu__decode__opcode_rc__bit_3 * column19_row9 + (1 - (cpu__decode__opcode_rc__bit_2 + cpu__decode__opcode_rc__bit_4 + cpu__decode__opcode_rc__bit_3)) * column17_row5 + column19_row4). let val := addmod( addmod(/*column17_row12*/ mload(0x3d00), /*half_offset_size*/ mload(0xc0), PRIME), sub( PRIME, addmod( addmod( addmod( addmod( mulmod( /*intermediate_value/cpu/decode/opcode_rc/bit_2*/ mload(0x49c0), /*column17_row0*/ mload(0x3bc0), PRIME), mulmod( /*intermediate_value/cpu/decode/opcode_rc/bit_4*/ mload(0x49e0), /*column19_row1*/ mload(0x4160), PRIME), PRIME), mulmod( /*intermediate_value/cpu/decode/opcode_rc/bit_3*/ mload(0x4a00), /*column19_row9*/ mload(0x4260), PRIME), PRIME), mulmod( addmod( 1, sub( PRIME, addmod( addmod( /*intermediate_value/cpu/decode/opcode_rc/bit_2*/ mload(0x49c0), /*intermediate_value/cpu/decode/opcode_rc/bit_4*/ mload(0x49e0), PRIME), /*intermediate_value/cpu/decode/opcode_rc/bit_3*/ mload(0x4a00), PRIME)), PRIME), /*column17_row5*/ mload(0x3c60), PRIME), PRIME), /*column19_row4*/ mload(0x41c0), PRIME)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 16) - 1. // val *= denominator_invs[2]. val := mulmod(val, mload(0x5160), PRIME) // res += val * (coefficients[10] + coefficients[11] * adjustments[2]). res := addmod(res, mulmod(val, add(/*coefficients[10]*/ mload(0x580), mulmod(/*coefficients[11]*/ mload(0x5a0), /*adjustments[2]*/mload(0x5880), PRIME)), PRIME), PRIME) } { // Constraint expression for cpu/operands/ops_mul: column19_row5 - column17_row5 * column17_row13. let val := addmod( /*column19_row5*/ mload(0x41e0), sub( PRIME, mulmod(/*column17_row5*/ mload(0x3c60), /*column17_row13*/ mload(0x3d20), PRIME)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 16) - 1. // val *= denominator_invs[2]. val := mulmod(val, mload(0x5160), PRIME) // res += val * (coefficients[12] + coefficients[13] * adjustments[2]). res := addmod(res, mulmod(val, add(/*coefficients[12]*/ mload(0x5c0), mulmod(/*coefficients[13]*/ mload(0x5e0), /*adjustments[2]*/mload(0x5880), PRIME)), PRIME), PRIME) } { // Constraint expression for cpu/operands/res: (1 - cpu__decode__opcode_rc__bit_9) * column19_row13 - (cpu__decode__opcode_rc__bit_5 * (column17_row5 + column17_row13) + cpu__decode__opcode_rc__bit_6 * column19_row5 + (1 - (cpu__decode__opcode_rc__bit_5 + cpu__decode__opcode_rc__bit_6 + cpu__decode__opcode_rc__bit_9)) * column17_row13). let val := addmod( mulmod( addmod( 1, sub(PRIME, /*intermediate_value/cpu/decode/opcode_rc/bit_9*/ mload(0x4a20)), PRIME), /*column19_row13*/ mload(0x42c0), PRIME), sub( PRIME, addmod( addmod( mulmod( /*intermediate_value/cpu/decode/opcode_rc/bit_5*/ mload(0x4a40), addmod(/*column17_row5*/ mload(0x3c60), /*column17_row13*/ mload(0x3d20), PRIME), PRIME), mulmod( /*intermediate_value/cpu/decode/opcode_rc/bit_6*/ mload(0x4a60), /*column19_row5*/ mload(0x41e0), PRIME), PRIME), mulmod( addmod( 1, sub( PRIME, addmod( addmod( /*intermediate_value/cpu/decode/opcode_rc/bit_5*/ mload(0x4a40), /*intermediate_value/cpu/decode/opcode_rc/bit_6*/ mload(0x4a60), PRIME), /*intermediate_value/cpu/decode/opcode_rc/bit_9*/ mload(0x4a20), PRIME)), PRIME), /*column17_row13*/ mload(0x3d20), PRIME), PRIME)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 16) - 1. // val *= denominator_invs[2]. val := mulmod(val, mload(0x5160), PRIME) // res += val * (coefficients[14] + coefficients[15] * adjustments[2]). res := addmod(res, mulmod(val, add(/*coefficients[14]*/ mload(0x600), mulmod(/*coefficients[15]*/ mload(0x620), /*adjustments[2]*/mload(0x5880), PRIME)), PRIME), PRIME) } { // Constraint expression for cpu/update_registers/update_pc/tmp0: column19_row3 - cpu__decode__opcode_rc__bit_9 * column17_row9. let val := addmod( /*column19_row3*/ mload(0x41a0), sub( PRIME, mulmod( /*intermediate_value/cpu/decode/opcode_rc/bit_9*/ mload(0x4a20), /*column17_row9*/ mload(0x3ce0), PRIME)), PRIME) // Numerator: point - trace_generator^(16 * (trace_length / 16 - 1)). // val *= numerators[1]. val := mulmod(val, mload(0x5700), PRIME) // Denominator: point^(trace_length / 16) - 1. // val *= denominator_invs[2]. val := mulmod(val, mload(0x5160), PRIME) // res += val * (coefficients[16] + coefficients[17] * adjustments[3]). res := addmod(res, mulmod(val, add(/*coefficients[16]*/ mload(0x640), mulmod(/*coefficients[17]*/ mload(0x660), /*adjustments[3]*/mload(0x58a0), PRIME)), PRIME), PRIME) } { // Constraint expression for cpu/update_registers/update_pc/tmp1: column19_row11 - column19_row3 * column19_row13. let val := addmod( /*column19_row11*/ mload(0x4280), sub( PRIME, mulmod(/*column19_row3*/ mload(0x41a0), /*column19_row13*/ mload(0x42c0), PRIME)), PRIME) // Numerator: point - trace_generator^(16 * (trace_length / 16 - 1)). // val *= numerators[1]. val := mulmod(val, mload(0x5700), PRIME) // Denominator: point^(trace_length / 16) - 1. // val *= denominator_invs[2]. val := mulmod(val, mload(0x5160), PRIME) // res += val * (coefficients[18] + coefficients[19] * adjustments[3]). res := addmod(res, mulmod(val, add(/*coefficients[18]*/ mload(0x680), mulmod(/*coefficients[19]*/ mload(0x6a0), /*adjustments[3]*/mload(0x58a0), PRIME)), PRIME), PRIME) } { // Constraint expression for cpu/update_registers/update_pc/pc_cond_negative: (1 - cpu__decode__opcode_rc__bit_9) * column17_row16 + column19_row3 * (column17_row16 - (column17_row0 + column17_row13)) - ((1 - (cpu__decode__opcode_rc__bit_7 + cpu__decode__opcode_rc__bit_8 + cpu__decode__opcode_rc__bit_9)) * npc_reg_0 + cpu__decode__opcode_rc__bit_7 * column19_row13 + cpu__decode__opcode_rc__bit_8 * (column17_row0 + column19_row13)). let val := addmod( addmod( mulmod( addmod( 1, sub(PRIME, /*intermediate_value/cpu/decode/opcode_rc/bit_9*/ mload(0x4a20)), PRIME), /*column17_row16*/ mload(0x3d40), PRIME), mulmod( /*column19_row3*/ mload(0x41a0), addmod( /*column17_row16*/ mload(0x3d40), sub( PRIME, addmod(/*column17_row0*/ mload(0x3bc0), /*column17_row13*/ mload(0x3d20), PRIME)), PRIME), PRIME), PRIME), sub( PRIME, addmod( addmod( mulmod( addmod( 1, sub( PRIME, addmod( addmod( /*intermediate_value/cpu/decode/opcode_rc/bit_7*/ mload(0x4a80), /*intermediate_value/cpu/decode/opcode_rc/bit_8*/ mload(0x4aa0), PRIME), /*intermediate_value/cpu/decode/opcode_rc/bit_9*/ mload(0x4a20), PRIME)), PRIME), /*intermediate_value/npc_reg_0*/ mload(0x4ac0), PRIME), mulmod( /*intermediate_value/cpu/decode/opcode_rc/bit_7*/ mload(0x4a80), /*column19_row13*/ mload(0x42c0), PRIME), PRIME), mulmod( /*intermediate_value/cpu/decode/opcode_rc/bit_8*/ mload(0x4aa0), addmod(/*column17_row0*/ mload(0x3bc0), /*column19_row13*/ mload(0x42c0), PRIME), PRIME), PRIME)), PRIME) // Numerator: point - trace_generator^(16 * (trace_length / 16 - 1)). // val *= numerators[1]. val := mulmod(val, mload(0x5700), PRIME) // Denominator: point^(trace_length / 16) - 1. // val *= denominator_invs[2]. val := mulmod(val, mload(0x5160), PRIME) // res += val * (coefficients[20] + coefficients[21] * adjustments[3]). res := addmod(res, mulmod(val, add(/*coefficients[20]*/ mload(0x6c0), mulmod(/*coefficients[21]*/ mload(0x6e0), /*adjustments[3]*/mload(0x58a0), PRIME)), PRIME), PRIME) } { // Constraint expression for cpu/update_registers/update_pc/pc_cond_positive: (column19_row11 - cpu__decode__opcode_rc__bit_9) * (column17_row16 - npc_reg_0). let val := mulmod( addmod( /*column19_row11*/ mload(0x4280), sub(PRIME, /*intermediate_value/cpu/decode/opcode_rc/bit_9*/ mload(0x4a20)), PRIME), addmod( /*column17_row16*/ mload(0x3d40), sub(PRIME, /*intermediate_value/npc_reg_0*/ mload(0x4ac0)), PRIME), PRIME) // Numerator: point - trace_generator^(16 * (trace_length / 16 - 1)). // val *= numerators[1]. val := mulmod(val, mload(0x5700), PRIME) // Denominator: point^(trace_length / 16) - 1. // val *= denominator_invs[2]. val := mulmod(val, mload(0x5160), PRIME) // res += val * (coefficients[22] + coefficients[23] * adjustments[3]). res := addmod(res, mulmod(val, add(/*coefficients[22]*/ mload(0x700), mulmod(/*coefficients[23]*/ mload(0x720), /*adjustments[3]*/mload(0x58a0), PRIME)), PRIME), PRIME) } { // Constraint expression for cpu/update_registers/update_ap/ap_update: column19_row17 - (column19_row1 + cpu__decode__opcode_rc__bit_10 * column19_row13 + cpu__decode__opcode_rc__bit_11 + cpu__decode__opcode_rc__bit_12 * 2). let val := addmod( /*column19_row17*/ mload(0x4300), sub( PRIME, addmod( addmod( addmod( /*column19_row1*/ mload(0x4160), mulmod( /*intermediate_value/cpu/decode/opcode_rc/bit_10*/ mload(0x4ae0), /*column19_row13*/ mload(0x42c0), PRIME), PRIME), /*intermediate_value/cpu/decode/opcode_rc/bit_11*/ mload(0x4b00), PRIME), mulmod(/*intermediate_value/cpu/decode/opcode_rc/bit_12*/ mload(0x4b20), 2, PRIME), PRIME)), PRIME) // Numerator: point - trace_generator^(16 * (trace_length / 16 - 1)). // val *= numerators[1]. val := mulmod(val, mload(0x5700), PRIME) // Denominator: point^(trace_length / 16) - 1. // val *= denominator_invs[2]. val := mulmod(val, mload(0x5160), PRIME) // res += val * (coefficients[24] + coefficients[25] * adjustments[3]). res := addmod(res, mulmod(val, add(/*coefficients[24]*/ mload(0x740), mulmod(/*coefficients[25]*/ mload(0x760), /*adjustments[3]*/mload(0x58a0), PRIME)), PRIME), PRIME) } { // Constraint expression for cpu/update_registers/update_fp/fp_update: column19_row25 - ((1 - (cpu__decode__opcode_rc__bit_12 + cpu__decode__opcode_rc__bit_13)) * column19_row9 + cpu__decode__opcode_rc__bit_13 * column17_row9 + cpu__decode__opcode_rc__bit_12 * (column19_row1 + 2)). let val := addmod( /*column19_row25*/ mload(0x4340), sub( PRIME, addmod( addmod( mulmod( addmod( 1, sub( PRIME, addmod( /*intermediate_value/cpu/decode/opcode_rc/bit_12*/ mload(0x4b20), /*intermediate_value/cpu/decode/opcode_rc/bit_13*/ mload(0x4b40), PRIME)), PRIME), /*column19_row9*/ mload(0x4260), PRIME), mulmod( /*intermediate_value/cpu/decode/opcode_rc/bit_13*/ mload(0x4b40), /*column17_row9*/ mload(0x3ce0), PRIME), PRIME), mulmod( /*intermediate_value/cpu/decode/opcode_rc/bit_12*/ mload(0x4b20), addmod(/*column19_row1*/ mload(0x4160), 2, PRIME), PRIME), PRIME)), PRIME) // Numerator: point - trace_generator^(16 * (trace_length / 16 - 1)). // val *= numerators[1]. val := mulmod(val, mload(0x5700), PRIME) // Denominator: point^(trace_length / 16) - 1. // val *= denominator_invs[2]. val := mulmod(val, mload(0x5160), PRIME) // res += val * (coefficients[26] + coefficients[27] * adjustments[3]). res := addmod(res, mulmod(val, add(/*coefficients[26]*/ mload(0x780), mulmod(/*coefficients[27]*/ mload(0x7a0), /*adjustments[3]*/mload(0x58a0), PRIME)), PRIME), PRIME) } { // Constraint expression for cpu/opcodes/call/push_fp: cpu__decode__opcode_rc__bit_12 * (column17_row9 - column19_row9). let val := mulmod( /*intermediate_value/cpu/decode/opcode_rc/bit_12*/ mload(0x4b20), addmod(/*column17_row9*/ mload(0x3ce0), sub(PRIME, /*column19_row9*/ mload(0x4260)), PRIME), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 16) - 1. // val *= denominator_invs[2]. val := mulmod(val, mload(0x5160), PRIME) // res += val * (coefficients[28] + coefficients[29] * adjustments[2]). res := addmod(res, mulmod(val, add(/*coefficients[28]*/ mload(0x7c0), mulmod(/*coefficients[29]*/ mload(0x7e0), /*adjustments[2]*/mload(0x5880), PRIME)), PRIME), PRIME) } { // Constraint expression for cpu/opcodes/call/push_pc: cpu__decode__opcode_rc__bit_12 * (column17_row5 - (column17_row0 + cpu__decode__opcode_rc__bit_2 + 1)). let val := mulmod( /*intermediate_value/cpu/decode/opcode_rc/bit_12*/ mload(0x4b20), addmod( /*column17_row5*/ mload(0x3c60), sub( PRIME, addmod( addmod( /*column17_row0*/ mload(0x3bc0), /*intermediate_value/cpu/decode/opcode_rc/bit_2*/ mload(0x49c0), PRIME), 1, PRIME)), PRIME), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 16) - 1. // val *= denominator_invs[2]. val := mulmod(val, mload(0x5160), PRIME) // res += val * (coefficients[30] + coefficients[31] * adjustments[2]). res := addmod(res, mulmod(val, add(/*coefficients[30]*/ mload(0x800), mulmod(/*coefficients[31]*/ mload(0x820), /*adjustments[2]*/mload(0x5880), PRIME)), PRIME), PRIME) } { // Constraint expression for cpu/opcodes/assert_eq/assert_eq: cpu__decode__opcode_rc__bit_14 * (column17_row9 - column19_row13). let val := mulmod( /*intermediate_value/cpu/decode/opcode_rc/bit_14*/ mload(0x4b60), addmod( /*column17_row9*/ mload(0x3ce0), sub(PRIME, /*column19_row13*/ mload(0x42c0)), PRIME), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 16) - 1. // val *= denominator_invs[2]. val := mulmod(val, mload(0x5160), PRIME) // res += val * (coefficients[32] + coefficients[33] * adjustments[2]). res := addmod(res, mulmod(val, add(/*coefficients[32]*/ mload(0x840), mulmod(/*coefficients[33]*/ mload(0x860), /*adjustments[2]*/mload(0x5880), PRIME)), PRIME), PRIME) } { // Constraint expression for initial_ap: column19_row1 - initial_ap. let val := addmod(/*column19_row1*/ mload(0x4160), sub(PRIME, /*initial_ap*/ mload(0xe0)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point - 1. // val *= denominator_invs[3]. val := mulmod(val, mload(0x5180), PRIME) // res += val * (coefficients[34] + coefficients[35] * adjustments[4]). res := addmod(res, mulmod(val, add(/*coefficients[34]*/ mload(0x880), mulmod(/*coefficients[35]*/ mload(0x8a0), /*adjustments[4]*/mload(0x58c0), PRIME)), PRIME), PRIME) } { // Constraint expression for initial_fp: column19_row9 - initial_ap. let val := addmod(/*column19_row9*/ mload(0x4260), sub(PRIME, /*initial_ap*/ mload(0xe0)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point - 1. // val *= denominator_invs[3]. val := mulmod(val, mload(0x5180), PRIME) // res += val * (coefficients[36] + coefficients[37] * adjustments[4]). res := addmod(res, mulmod(val, add(/*coefficients[36]*/ mload(0x8c0), mulmod(/*coefficients[37]*/ mload(0x8e0), /*adjustments[4]*/mload(0x58c0), PRIME)), PRIME), PRIME) } { // Constraint expression for initial_pc: column17_row0 - initial_pc. let val := addmod(/*column17_row0*/ mload(0x3bc0), sub(PRIME, /*initial_pc*/ mload(0x100)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point - 1. // val *= denominator_invs[3]. val := mulmod(val, mload(0x5180), PRIME) // res += val * (coefficients[38] + coefficients[39] * adjustments[4]). res := addmod(res, mulmod(val, add(/*coefficients[38]*/ mload(0x900), mulmod(/*coefficients[39]*/ mload(0x920), /*adjustments[4]*/mload(0x58c0), PRIME)), PRIME), PRIME) } { // Constraint expression for final_ap: column19_row1 - final_ap. let val := addmod(/*column19_row1*/ mload(0x4160), sub(PRIME, /*final_ap*/ mload(0x120)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point - trace_generator^(16 * (trace_length / 16 - 1)). // val *= denominator_invs[4]. val := mulmod(val, mload(0x51a0), PRIME) // res += val * (coefficients[40] + coefficients[41] * adjustments[4]). res := addmod(res, mulmod(val, add(/*coefficients[40]*/ mload(0x940), mulmod(/*coefficients[41]*/ mload(0x960), /*adjustments[4]*/mload(0x58c0), PRIME)), PRIME), PRIME) } { // Constraint expression for final_pc: column17_row0 - final_pc. let val := addmod(/*column17_row0*/ mload(0x3bc0), sub(PRIME, /*final_pc*/ mload(0x140)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point - trace_generator^(16 * (trace_length / 16 - 1)). // val *= denominator_invs[4]. val := mulmod(val, mload(0x51a0), PRIME) // res += val * (coefficients[42] + coefficients[43] * adjustments[4]). res := addmod(res, mulmod(val, add(/*coefficients[42]*/ mload(0x980), mulmod(/*coefficients[43]*/ mload(0x9a0), /*adjustments[4]*/mload(0x58c0), PRIME)), PRIME), PRIME) } { // Constraint expression for memory/multi_column_perm/perm/init0: (memory/multi_column_perm/perm/interaction_elm - (column18_row0 + memory/multi_column_perm/hash_interaction_elm0 * column18_row1)) * column21_inter1_row0 + column17_row0 + memory/multi_column_perm/hash_interaction_elm0 * column17_row1 - memory/multi_column_perm/perm/interaction_elm. let val := addmod( addmod( addmod( mulmod( addmod( /*memory/multi_column_perm/perm/interaction_elm*/ mload(0x160), sub( PRIME, addmod( /*column18_row0*/ mload(0x40c0), mulmod( /*memory/multi_column_perm/hash_interaction_elm0*/ mload(0x180), /*column18_row1*/ mload(0x40e0), PRIME), PRIME)), PRIME), /*column21_inter1_row0*/ mload(0x48e0), PRIME), /*column17_row0*/ mload(0x3bc0), PRIME), mulmod( /*memory/multi_column_perm/hash_interaction_elm0*/ mload(0x180), /*column17_row1*/ mload(0x3be0), PRIME), PRIME), sub(PRIME, /*memory/multi_column_perm/perm/interaction_elm*/ mload(0x160)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point - 1. // val *= denominator_invs[3]. val := mulmod(val, mload(0x5180), PRIME) // res += val * (coefficients[44] + coefficients[45] * adjustments[5]). res := addmod(res, mulmod(val, add(/*coefficients[44]*/ mload(0x9c0), mulmod(/*coefficients[45]*/ mload(0x9e0), /*adjustments[5]*/mload(0x58e0), PRIME)), PRIME), PRIME) } { // Constraint expression for memory/multi_column_perm/perm/step0: (memory/multi_column_perm/perm/interaction_elm - (column18_row2 + memory/multi_column_perm/hash_interaction_elm0 * column18_row3)) * column21_inter1_row2 - (memory/multi_column_perm/perm/interaction_elm - (column17_row2 + memory/multi_column_perm/hash_interaction_elm0 * column17_row3)) * column21_inter1_row0. let val := addmod( mulmod( addmod( /*memory/multi_column_perm/perm/interaction_elm*/ mload(0x160), sub( PRIME, addmod( /*column18_row2*/ mload(0x4100), mulmod( /*memory/multi_column_perm/hash_interaction_elm0*/ mload(0x180), /*column18_row3*/ mload(0x4120), PRIME), PRIME)), PRIME), /*column21_inter1_row2*/ mload(0x4920), PRIME), sub( PRIME, mulmod( addmod( /*memory/multi_column_perm/perm/interaction_elm*/ mload(0x160), sub( PRIME, addmod( /*column17_row2*/ mload(0x3c00), mulmod( /*memory/multi_column_perm/hash_interaction_elm0*/ mload(0x180), /*column17_row3*/ mload(0x3c20), PRIME), PRIME)), PRIME), /*column21_inter1_row0*/ mload(0x48e0), PRIME)), PRIME) // Numerator: point - trace_generator^(2 * (trace_length / 2 - 1)). // val *= numerators[2]. val := mulmod(val, mload(0x5720), PRIME) // Denominator: point^(trace_length / 2) - 1. // val *= denominator_invs[5]. val := mulmod(val, mload(0x51c0), PRIME) // res += val * (coefficients[46] + coefficients[47] * adjustments[6]). res := addmod(res, mulmod(val, add(/*coefficients[46]*/ mload(0xa00), mulmod(/*coefficients[47]*/ mload(0xa20), /*adjustments[6]*/mload(0x5900), PRIME)), PRIME), PRIME) } { // Constraint expression for memory/multi_column_perm/perm/last: column21_inter1_row0 - memory/multi_column_perm/perm/public_memory_prod. let val := addmod( /*column21_inter1_row0*/ mload(0x48e0), sub(PRIME, /*memory/multi_column_perm/perm/public_memory_prod*/ mload(0x1a0)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point - trace_generator^(2 * (trace_length / 2 - 1)). // val *= denominator_invs[6]. val := mulmod(val, mload(0x51e0), PRIME) // res += val * (coefficients[48] + coefficients[49] * adjustments[4]). res := addmod(res, mulmod(val, add(/*coefficients[48]*/ mload(0xa40), mulmod(/*coefficients[49]*/ mload(0xa60), /*adjustments[4]*/mload(0x58c0), PRIME)), PRIME), PRIME) } { // Constraint expression for memory/diff_is_bit: memory__address_diff_0 * memory__address_diff_0 - memory__address_diff_0. let val := addmod( mulmod( /*intermediate_value/memory/address_diff_0*/ mload(0x4b80), /*intermediate_value/memory/address_diff_0*/ mload(0x4b80), PRIME), sub(PRIME, /*intermediate_value/memory/address_diff_0*/ mload(0x4b80)), PRIME) // Numerator: point - trace_generator^(2 * (trace_length / 2 - 1)). // val *= numerators[2]. val := mulmod(val, mload(0x5720), PRIME) // Denominator: point^(trace_length / 2) - 1. // val *= denominator_invs[5]. val := mulmod(val, mload(0x51c0), PRIME) // res += val * (coefficients[50] + coefficients[51] * adjustments[6]). res := addmod(res, mulmod(val, add(/*coefficients[50]*/ mload(0xa80), mulmod(/*coefficients[51]*/ mload(0xaa0), /*adjustments[6]*/mload(0x5900), PRIME)), PRIME), PRIME) } { // Constraint expression for memory/is_func: (memory__address_diff_0 - 1) * (column18_row1 - column18_row3). let val := mulmod( addmod(/*intermediate_value/memory/address_diff_0*/ mload(0x4b80), sub(PRIME, 1), PRIME), addmod(/*column18_row1*/ mload(0x40e0), sub(PRIME, /*column18_row3*/ mload(0x4120)), PRIME), PRIME) // Numerator: point - trace_generator^(2 * (trace_length / 2 - 1)). // val *= numerators[2]. val := mulmod(val, mload(0x5720), PRIME) // Denominator: point^(trace_length / 2) - 1. // val *= denominator_invs[5]. val := mulmod(val, mload(0x51c0), PRIME) // res += val * (coefficients[52] + coefficients[53] * adjustments[6]). res := addmod(res, mulmod(val, add(/*coefficients[52]*/ mload(0xac0), mulmod(/*coefficients[53]*/ mload(0xae0), /*adjustments[6]*/mload(0x5900), PRIME)), PRIME), PRIME) } { // Constraint expression for memory/initial_addr: column18_row0 - 1. let val := addmod(/*column18_row0*/ mload(0x40c0), sub(PRIME, 1), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point - 1. // val *= denominator_invs[3]. val := mulmod(val, mload(0x5180), PRIME) // res += val * (coefficients[54] + coefficients[55] * adjustments[4]). res := addmod(res, mulmod(val, add(/*coefficients[54]*/ mload(0xb00), mulmod(/*coefficients[55]*/ mload(0xb20), /*adjustments[4]*/mload(0x58c0), PRIME)), PRIME), PRIME) } { // Constraint expression for public_memory_addr_zero: column17_row2. let val := /*column17_row2*/ mload(0x3c00) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 8) - 1. // val *= denominator_invs[7]. val := mulmod(val, mload(0x5200), PRIME) // res += val * (coefficients[56] + coefficients[57] * adjustments[7]). res := addmod(res, mulmod(val, add(/*coefficients[56]*/ mload(0xb40), mulmod(/*coefficients[57]*/ mload(0xb60), /*adjustments[7]*/mload(0x5920), PRIME)), PRIME), PRIME) } { // Constraint expression for public_memory_value_zero: column17_row3. let val := /*column17_row3*/ mload(0x3c20) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 8) - 1. // val *= denominator_invs[7]. val := mulmod(val, mload(0x5200), PRIME) // res += val * (coefficients[58] + coefficients[59] * adjustments[7]). res := addmod(res, mulmod(val, add(/*coefficients[58]*/ mload(0xb80), mulmod(/*coefficients[59]*/ mload(0xba0), /*adjustments[7]*/mload(0x5920), PRIME)), PRIME), PRIME) } { // Constraint expression for rc16/perm/init0: (rc16/perm/interaction_elm - column19_row2) * column21_inter1_row1 + column19_row0 - rc16/perm/interaction_elm. let val := addmod( addmod( mulmod( addmod( /*rc16/perm/interaction_elm*/ mload(0x1c0), sub(PRIME, /*column19_row2*/ mload(0x4180)), PRIME), /*column21_inter1_row1*/ mload(0x4900), PRIME), /*column19_row0*/ mload(0x4140), PRIME), sub(PRIME, /*rc16/perm/interaction_elm*/ mload(0x1c0)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point - 1. // val *= denominator_invs[3]. val := mulmod(val, mload(0x5180), PRIME) // res += val * (coefficients[60] + coefficients[61] * adjustments[5]). res := addmod(res, mulmod(val, add(/*coefficients[60]*/ mload(0xbc0), mulmod(/*coefficients[61]*/ mload(0xbe0), /*adjustments[5]*/mload(0x58e0), PRIME)), PRIME), PRIME) } { // Constraint expression for rc16/perm/step0: (rc16/perm/interaction_elm - column19_row6) * column21_inter1_row5 - (rc16/perm/interaction_elm - column19_row4) * column21_inter1_row1. let val := addmod( mulmod( addmod( /*rc16/perm/interaction_elm*/ mload(0x1c0), sub(PRIME, /*column19_row6*/ mload(0x4200)), PRIME), /*column21_inter1_row5*/ mload(0x4940), PRIME), sub( PRIME, mulmod( addmod( /*rc16/perm/interaction_elm*/ mload(0x1c0), sub(PRIME, /*column19_row4*/ mload(0x41c0)), PRIME), /*column21_inter1_row1*/ mload(0x4900), PRIME)), PRIME) // Numerator: point - trace_generator^(4 * (trace_length / 4 - 1)). // val *= numerators[3]. val := mulmod(val, mload(0x5740), PRIME) // Denominator: point^(trace_length / 4) - 1. // val *= denominator_invs[8]. val := mulmod(val, mload(0x5220), PRIME) // res += val * (coefficients[62] + coefficients[63] * adjustments[8]). res := addmod(res, mulmod(val, add(/*coefficients[62]*/ mload(0xc00), mulmod(/*coefficients[63]*/ mload(0xc20), /*adjustments[8]*/mload(0x5940), PRIME)), PRIME), PRIME) } { // Constraint expression for rc16/perm/last: column21_inter1_row1 - rc16/perm/public_memory_prod. let val := addmod( /*column21_inter1_row1*/ mload(0x4900), sub(PRIME, /*rc16/perm/public_memory_prod*/ mload(0x1e0)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point - trace_generator^(4 * (trace_length / 4 - 1)). // val *= denominator_invs[9]. val := mulmod(val, mload(0x5240), PRIME) // res += val * (coefficients[64] + coefficients[65] * adjustments[4]). res := addmod(res, mulmod(val, add(/*coefficients[64]*/ mload(0xc40), mulmod(/*coefficients[65]*/ mload(0xc60), /*adjustments[4]*/mload(0x58c0), PRIME)), PRIME), PRIME) } { // Constraint expression for rc16/diff_is_bit: rc16__diff_0 * rc16__diff_0 - rc16__diff_0. let val := addmod( mulmod( /*intermediate_value/rc16/diff_0*/ mload(0x4ba0), /*intermediate_value/rc16/diff_0*/ mload(0x4ba0), PRIME), sub(PRIME, /*intermediate_value/rc16/diff_0*/ mload(0x4ba0)), PRIME) // Numerator: point - trace_generator^(4 * (trace_length / 4 - 1)). // val *= numerators[3]. val := mulmod(val, mload(0x5740), PRIME) // Denominator: point^(trace_length / 4) - 1. // val *= denominator_invs[8]. val := mulmod(val, mload(0x5220), PRIME) // res += val * (coefficients[66] + coefficients[67] * adjustments[8]). res := addmod(res, mulmod(val, add(/*coefficients[66]*/ mload(0xc80), mulmod(/*coefficients[67]*/ mload(0xca0), /*adjustments[8]*/mload(0x5940), PRIME)), PRIME), PRIME) } { // Constraint expression for rc16/minimum: column19_row2 - rc_min. let val := addmod(/*column19_row2*/ mload(0x4180), sub(PRIME, /*rc_min*/ mload(0x200)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point - 1. // val *= denominator_invs[3]. val := mulmod(val, mload(0x5180), PRIME) // res += val * (coefficients[68] + coefficients[69] * adjustments[4]). res := addmod(res, mulmod(val, add(/*coefficients[68]*/ mload(0xcc0), mulmod(/*coefficients[69]*/ mload(0xce0), /*adjustments[4]*/mload(0x58c0), PRIME)), PRIME), PRIME) } { // Constraint expression for rc16/maximum: column19_row2 - rc_max. let val := addmod(/*column19_row2*/ mload(0x4180), sub(PRIME, /*rc_max*/ mload(0x220)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point - trace_generator^(4 * (trace_length / 4 - 1)). // val *= denominator_invs[9]. val := mulmod(val, mload(0x5240), PRIME) // res += val * (coefficients[70] + coefficients[71] * adjustments[4]). res := addmod(res, mulmod(val, add(/*coefficients[70]*/ mload(0xd00), mulmod(/*coefficients[71]*/ mload(0xd20), /*adjustments[4]*/mload(0x58c0), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/hash0/ec_subset_sum/bit_unpacking/last_one_is_zero: column11_row255 * (column4_row0 - (column4_row1 + column4_row1)). let val := mulmod( /*column11_row255*/ mload(0x3800), addmod( /*column4_row0*/ mload(0x3320), sub( PRIME, addmod(/*column4_row1*/ mload(0x3340), /*column4_row1*/ mload(0x3340), PRIME)), PRIME), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 256) - 1. // val *= denominator_invs[10]. val := mulmod(val, mload(0x5260), PRIME) // res += val * (coefficients[72] + coefficients[73] * adjustments[9]). res := addmod(res, mulmod(val, add(/*coefficients[72]*/ mload(0xd40), mulmod(/*coefficients[73]*/ mload(0xd60), /*adjustments[9]*/mload(0x5960), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/hash0/ec_subset_sum/bit_unpacking/zeroes_between_ones0: column11_row255 * (column4_row1 - 3138550867693340381917894711603833208051177722232017256448 * column4_row192). let val := mulmod( /*column11_row255*/ mload(0x3800), addmod( /*column4_row1*/ mload(0x3340), sub( PRIME, mulmod( 3138550867693340381917894711603833208051177722232017256448, /*column4_row192*/ mload(0x3360), PRIME)), PRIME), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 256) - 1. // val *= denominator_invs[10]. val := mulmod(val, mload(0x5260), PRIME) // res += val * (coefficients[74] + coefficients[75] * adjustments[9]). res := addmod(res, mulmod(val, add(/*coefficients[74]*/ mload(0xd80), mulmod(/*coefficients[75]*/ mload(0xda0), /*adjustments[9]*/mload(0x5960), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/hash0/ec_subset_sum/bit_unpacking/cumulative_bit192: column11_row255 - column15_row255 * (column4_row192 - (column4_row193 + column4_row193)). let val := addmod( /*column11_row255*/ mload(0x3800), sub( PRIME, mulmod( /*column15_row255*/ mload(0x3a80), addmod( /*column4_row192*/ mload(0x3360), sub( PRIME, addmod(/*column4_row193*/ mload(0x3380), /*column4_row193*/ mload(0x3380), PRIME)), PRIME), PRIME)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 256) - 1. // val *= denominator_invs[10]. val := mulmod(val, mload(0x5260), PRIME) // res += val * (coefficients[76] + coefficients[77] * adjustments[9]). res := addmod(res, mulmod(val, add(/*coefficients[76]*/ mload(0xdc0), mulmod(/*coefficients[77]*/ mload(0xde0), /*adjustments[9]*/mload(0x5960), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/hash0/ec_subset_sum/bit_unpacking/zeroes_between_ones192: column15_row255 * (column4_row193 - 8 * column4_row196). let val := mulmod( /*column15_row255*/ mload(0x3a80), addmod( /*column4_row193*/ mload(0x3380), sub(PRIME, mulmod(8, /*column4_row196*/ mload(0x33a0), PRIME)), PRIME), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 256) - 1. // val *= denominator_invs[10]. val := mulmod(val, mload(0x5260), PRIME) // res += val * (coefficients[78] + coefficients[79] * adjustments[9]). res := addmod(res, mulmod(val, add(/*coefficients[78]*/ mload(0xe00), mulmod(/*coefficients[79]*/ mload(0xe20), /*adjustments[9]*/mload(0x5960), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/hash0/ec_subset_sum/bit_unpacking/cumulative_bit196: column15_row255 - (column4_row251 - (column4_row252 + column4_row252)) * (column4_row196 - (column4_row197 + column4_row197)). let val := addmod( /*column15_row255*/ mload(0x3a80), sub( PRIME, mulmod( addmod( /*column4_row251*/ mload(0x33e0), sub( PRIME, addmod(/*column4_row252*/ mload(0x3400), /*column4_row252*/ mload(0x3400), PRIME)), PRIME), addmod( /*column4_row196*/ mload(0x33a0), sub( PRIME, addmod(/*column4_row197*/ mload(0x33c0), /*column4_row197*/ mload(0x33c0), PRIME)), PRIME), PRIME)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 256) - 1. // val *= denominator_invs[10]. val := mulmod(val, mload(0x5260), PRIME) // res += val * (coefficients[80] + coefficients[81] * adjustments[9]). res := addmod(res, mulmod(val, add(/*coefficients[80]*/ mload(0xe40), mulmod(/*coefficients[81]*/ mload(0xe60), /*adjustments[9]*/mload(0x5960), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/hash0/ec_subset_sum/bit_unpacking/zeroes_between_ones196: (column4_row251 - (column4_row252 + column4_row252)) * (column4_row197 - 18014398509481984 * column4_row251). let val := mulmod( addmod( /*column4_row251*/ mload(0x33e0), sub( PRIME, addmod(/*column4_row252*/ mload(0x3400), /*column4_row252*/ mload(0x3400), PRIME)), PRIME), addmod( /*column4_row197*/ mload(0x33c0), sub(PRIME, mulmod(18014398509481984, /*column4_row251*/ mload(0x33e0), PRIME)), PRIME), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 256) - 1. // val *= denominator_invs[10]. val := mulmod(val, mload(0x5260), PRIME) // res += val * (coefficients[82] + coefficients[83] * adjustments[9]). res := addmod(res, mulmod(val, add(/*coefficients[82]*/ mload(0xe80), mulmod(/*coefficients[83]*/ mload(0xea0), /*adjustments[9]*/mload(0x5960), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/hash0/ec_subset_sum/booleanity_test: pedersen__hash0__ec_subset_sum__bit_0 * (pedersen__hash0__ec_subset_sum__bit_0 - 1). let val := mulmod( /*intermediate_value/pedersen/hash0/ec_subset_sum/bit_0*/ mload(0x4bc0), addmod( /*intermediate_value/pedersen/hash0/ec_subset_sum/bit_0*/ mload(0x4bc0), sub(PRIME, 1), PRIME), PRIME) // Numerator: point^(trace_length / 256) - trace_generator^(255 * trace_length / 256). // val *= numerators[4]. val := mulmod(val, mload(0x5760), PRIME) // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0x5120), PRIME) // res += val * (coefficients[84] + coefficients[85] * adjustments[10]). res := addmod(res, mulmod(val, add(/*coefficients[84]*/ mload(0xec0), mulmod(/*coefficients[85]*/ mload(0xee0), /*adjustments[10]*/mload(0x5980), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/hash0/ec_subset_sum/bit_extraction_end: column4_row0. let val := /*column4_row0*/ mload(0x3320) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 256) - trace_generator^(63 * trace_length / 64). // val *= denominator_invs[11]. val := mulmod(val, mload(0x5280), PRIME) // res += val * (coefficients[86] + coefficients[87] * adjustments[11]). res := addmod(res, mulmod(val, add(/*coefficients[86]*/ mload(0xf00), mulmod(/*coefficients[87]*/ mload(0xf20), /*adjustments[11]*/mload(0x59a0), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/hash0/ec_subset_sum/zeros_tail: column4_row0. let val := /*column4_row0*/ mload(0x3320) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 256) - trace_generator^(255 * trace_length / 256). // val *= denominator_invs[12]. val := mulmod(val, mload(0x52a0), PRIME) // res += val * (coefficients[88] + coefficients[89] * adjustments[11]). res := addmod(res, mulmod(val, add(/*coefficients[88]*/ mload(0xf40), mulmod(/*coefficients[89]*/ mload(0xf60), /*adjustments[11]*/mload(0x59a0), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/hash0/ec_subset_sum/add_points/slope: pedersen__hash0__ec_subset_sum__bit_0 * (column2_row0 - pedersen__points__y) - column3_row0 * (column1_row0 - pedersen__points__x). let val := addmod( mulmod( /*intermediate_value/pedersen/hash0/ec_subset_sum/bit_0*/ mload(0x4bc0), addmod( /*column2_row0*/ mload(0x3260), sub(PRIME, /*periodic_column/pedersen/points/y*/ mload(0x20)), PRIME), PRIME), sub( PRIME, mulmod( /*column3_row0*/ mload(0x32e0), addmod( /*column1_row0*/ mload(0x31c0), sub(PRIME, /*periodic_column/pedersen/points/x*/ mload(0x0)), PRIME), PRIME)), PRIME) // Numerator: point^(trace_length / 256) - trace_generator^(255 * trace_length / 256). // val *= numerators[4]. val := mulmod(val, mload(0x5760), PRIME) // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0x5120), PRIME) // res += val * (coefficients[90] + coefficients[91] * adjustments[10]). res := addmod(res, mulmod(val, add(/*coefficients[90]*/ mload(0xf80), mulmod(/*coefficients[91]*/ mload(0xfa0), /*adjustments[10]*/mload(0x5980), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/hash0/ec_subset_sum/add_points/x: column3_row0 * column3_row0 - pedersen__hash0__ec_subset_sum__bit_0 * (column1_row0 + pedersen__points__x + column1_row1). let val := addmod( mulmod(/*column3_row0*/ mload(0x32e0), /*column3_row0*/ mload(0x32e0), PRIME), sub( PRIME, mulmod( /*intermediate_value/pedersen/hash0/ec_subset_sum/bit_0*/ mload(0x4bc0), addmod( addmod( /*column1_row0*/ mload(0x31c0), /*periodic_column/pedersen/points/x*/ mload(0x0), PRIME), /*column1_row1*/ mload(0x31e0), PRIME), PRIME)), PRIME) // Numerator: point^(trace_length / 256) - trace_generator^(255 * trace_length / 256). // val *= numerators[4]. val := mulmod(val, mload(0x5760), PRIME) // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0x5120), PRIME) // res += val * (coefficients[92] + coefficients[93] * adjustments[10]). res := addmod(res, mulmod(val, add(/*coefficients[92]*/ mload(0xfc0), mulmod(/*coefficients[93]*/ mload(0xfe0), /*adjustments[10]*/mload(0x5980), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/hash0/ec_subset_sum/add_points/y: pedersen__hash0__ec_subset_sum__bit_0 * (column2_row0 + column2_row1) - column3_row0 * (column1_row0 - column1_row1). let val := addmod( mulmod( /*intermediate_value/pedersen/hash0/ec_subset_sum/bit_0*/ mload(0x4bc0), addmod(/*column2_row0*/ mload(0x3260), /*column2_row1*/ mload(0x3280), PRIME), PRIME), sub( PRIME, mulmod( /*column3_row0*/ mload(0x32e0), addmod(/*column1_row0*/ mload(0x31c0), sub(PRIME, /*column1_row1*/ mload(0x31e0)), PRIME), PRIME)), PRIME) // Numerator: point^(trace_length / 256) - trace_generator^(255 * trace_length / 256). // val *= numerators[4]. val := mulmod(val, mload(0x5760), PRIME) // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0x5120), PRIME) // res += val * (coefficients[94] + coefficients[95] * adjustments[10]). res := addmod(res, mulmod(val, add(/*coefficients[94]*/ mload(0x1000), mulmod(/*coefficients[95]*/ mload(0x1020), /*adjustments[10]*/mload(0x5980), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/hash0/ec_subset_sum/copy_point/x: pedersen__hash0__ec_subset_sum__bit_neg_0 * (column1_row1 - column1_row0). let val := mulmod( /*intermediate_value/pedersen/hash0/ec_subset_sum/bit_neg_0*/ mload(0x4be0), addmod(/*column1_row1*/ mload(0x31e0), sub(PRIME, /*column1_row0*/ mload(0x31c0)), PRIME), PRIME) // Numerator: point^(trace_length / 256) - trace_generator^(255 * trace_length / 256). // val *= numerators[4]. val := mulmod(val, mload(0x5760), PRIME) // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0x5120), PRIME) // res += val * (coefficients[96] + coefficients[97] * adjustments[10]). res := addmod(res, mulmod(val, add(/*coefficients[96]*/ mload(0x1040), mulmod(/*coefficients[97]*/ mload(0x1060), /*adjustments[10]*/mload(0x5980), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/hash0/ec_subset_sum/copy_point/y: pedersen__hash0__ec_subset_sum__bit_neg_0 * (column2_row1 - column2_row0). let val := mulmod( /*intermediate_value/pedersen/hash0/ec_subset_sum/bit_neg_0*/ mload(0x4be0), addmod(/*column2_row1*/ mload(0x3280), sub(PRIME, /*column2_row0*/ mload(0x3260)), PRIME), PRIME) // Numerator: point^(trace_length / 256) - trace_generator^(255 * trace_length / 256). // val *= numerators[4]. val := mulmod(val, mload(0x5760), PRIME) // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0x5120), PRIME) // res += val * (coefficients[98] + coefficients[99] * adjustments[10]). res := addmod(res, mulmod(val, add(/*coefficients[98]*/ mload(0x1080), mulmod(/*coefficients[99]*/ mload(0x10a0), /*adjustments[10]*/mload(0x5980), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/hash0/copy_point/x: column1_row256 - column1_row255. let val := addmod( /*column1_row256*/ mload(0x3220), sub(PRIME, /*column1_row255*/ mload(0x3200)), PRIME) // Numerator: point^(trace_length / 512) - trace_generator^(trace_length / 2). // val *= numerators[5]. val := mulmod(val, mload(0x5780), PRIME) // Denominator: point^(trace_length / 256) - 1. // val *= denominator_invs[10]. val := mulmod(val, mload(0x5260), PRIME) // res += val * (coefficients[100] + coefficients[101] * adjustments[12]). res := addmod(res, mulmod(val, add(/*coefficients[100]*/ mload(0x10c0), mulmod(/*coefficients[101]*/ mload(0x10e0), /*adjustments[12]*/mload(0x59c0), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/hash0/copy_point/y: column2_row256 - column2_row255. let val := addmod( /*column2_row256*/ mload(0x32c0), sub(PRIME, /*column2_row255*/ mload(0x32a0)), PRIME) // Numerator: point^(trace_length / 512) - trace_generator^(trace_length / 2). // val *= numerators[5]. val := mulmod(val, mload(0x5780), PRIME) // Denominator: point^(trace_length / 256) - 1. // val *= denominator_invs[10]. val := mulmod(val, mload(0x5260), PRIME) // res += val * (coefficients[102] + coefficients[103] * adjustments[12]). res := addmod(res, mulmod(val, add(/*coefficients[102]*/ mload(0x1100), mulmod(/*coefficients[103]*/ mload(0x1120), /*adjustments[12]*/mload(0x59c0), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/hash0/init/x: column1_row0 - pedersen/shift_point.x. let val := addmod( /*column1_row0*/ mload(0x31c0), sub(PRIME, /*pedersen/shift_point.x*/ mload(0x240)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 512) - 1. // val *= denominator_invs[13]. val := mulmod(val, mload(0x52c0), PRIME) // res += val * (coefficients[104] + coefficients[105] * adjustments[13]). res := addmod(res, mulmod(val, add(/*coefficients[104]*/ mload(0x1140), mulmod(/*coefficients[105]*/ mload(0x1160), /*adjustments[13]*/mload(0x59e0), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/hash0/init/y: column2_row0 - pedersen/shift_point.y. let val := addmod( /*column2_row0*/ mload(0x3260), sub(PRIME, /*pedersen/shift_point.y*/ mload(0x260)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 512) - 1. // val *= denominator_invs[13]. val := mulmod(val, mload(0x52c0), PRIME) // res += val * (coefficients[106] + coefficients[107] * adjustments[13]). res := addmod(res, mulmod(val, add(/*coefficients[106]*/ mload(0x1180), mulmod(/*coefficients[107]*/ mload(0x11a0), /*adjustments[13]*/mload(0x59e0), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/hash1/ec_subset_sum/bit_unpacking/last_one_is_zero: column3_row255 * (column8_row0 - (column8_row1 + column8_row1)). let val := mulmod( /*column3_row255*/ mload(0x3300), addmod( /*column8_row0*/ mload(0x35a0), sub( PRIME, addmod(/*column8_row1*/ mload(0x35c0), /*column8_row1*/ mload(0x35c0), PRIME)), PRIME), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 256) - 1. // val *= denominator_invs[10]. val := mulmod(val, mload(0x5260), PRIME) // res += val * (coefficients[108] + coefficients[109] * adjustments[9]). res := addmod(res, mulmod(val, add(/*coefficients[108]*/ mload(0x11c0), mulmod(/*coefficients[109]*/ mload(0x11e0), /*adjustments[9]*/mload(0x5960), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/hash1/ec_subset_sum/bit_unpacking/zeroes_between_ones0: column3_row255 * (column8_row1 - 3138550867693340381917894711603833208051177722232017256448 * column8_row192). let val := mulmod( /*column3_row255*/ mload(0x3300), addmod( /*column8_row1*/ mload(0x35c0), sub( PRIME, mulmod( 3138550867693340381917894711603833208051177722232017256448, /*column8_row192*/ mload(0x35e0), PRIME)), PRIME), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 256) - 1. // val *= denominator_invs[10]. val := mulmod(val, mload(0x5260), PRIME) // res += val * (coefficients[110] + coefficients[111] * adjustments[9]). res := addmod(res, mulmod(val, add(/*coefficients[110]*/ mload(0x1200), mulmod(/*coefficients[111]*/ mload(0x1220), /*adjustments[9]*/mload(0x5960), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/hash1/ec_subset_sum/bit_unpacking/cumulative_bit192: column3_row255 - column7_row255 * (column8_row192 - (column8_row193 + column8_row193)). let val := addmod( /*column3_row255*/ mload(0x3300), sub( PRIME, mulmod( /*column7_row255*/ mload(0x3580), addmod( /*column8_row192*/ mload(0x35e0), sub( PRIME, addmod(/*column8_row193*/ mload(0x3600), /*column8_row193*/ mload(0x3600), PRIME)), PRIME), PRIME)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 256) - 1. // val *= denominator_invs[10]. val := mulmod(val, mload(0x5260), PRIME) // res += val * (coefficients[112] + coefficients[113] * adjustments[9]). res := addmod(res, mulmod(val, add(/*coefficients[112]*/ mload(0x1240), mulmod(/*coefficients[113]*/ mload(0x1260), /*adjustments[9]*/mload(0x5960), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/hash1/ec_subset_sum/bit_unpacking/zeroes_between_ones192: column7_row255 * (column8_row193 - 8 * column8_row196). let val := mulmod( /*column7_row255*/ mload(0x3580), addmod( /*column8_row193*/ mload(0x3600), sub(PRIME, mulmod(8, /*column8_row196*/ mload(0x3620), PRIME)), PRIME), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 256) - 1. // val *= denominator_invs[10]. val := mulmod(val, mload(0x5260), PRIME) // res += val * (coefficients[114] + coefficients[115] * adjustments[9]). res := addmod(res, mulmod(val, add(/*coefficients[114]*/ mload(0x1280), mulmod(/*coefficients[115]*/ mload(0x12a0), /*adjustments[9]*/mload(0x5960), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/hash1/ec_subset_sum/bit_unpacking/cumulative_bit196: column7_row255 - (column8_row251 - (column8_row252 + column8_row252)) * (column8_row196 - (column8_row197 + column8_row197)). let val := addmod( /*column7_row255*/ mload(0x3580), sub( PRIME, mulmod( addmod( /*column8_row251*/ mload(0x3660), sub( PRIME, addmod(/*column8_row252*/ mload(0x3680), /*column8_row252*/ mload(0x3680), PRIME)), PRIME), addmod( /*column8_row196*/ mload(0x3620), sub( PRIME, addmod(/*column8_row197*/ mload(0x3640), /*column8_row197*/ mload(0x3640), PRIME)), PRIME), PRIME)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 256) - 1. // val *= denominator_invs[10]. val := mulmod(val, mload(0x5260), PRIME) // res += val * (coefficients[116] + coefficients[117] * adjustments[9]). res := addmod(res, mulmod(val, add(/*coefficients[116]*/ mload(0x12c0), mulmod(/*coefficients[117]*/ mload(0x12e0), /*adjustments[9]*/mload(0x5960), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/hash1/ec_subset_sum/bit_unpacking/zeroes_between_ones196: (column8_row251 - (column8_row252 + column8_row252)) * (column8_row197 - 18014398509481984 * column8_row251). let val := mulmod( addmod( /*column8_row251*/ mload(0x3660), sub( PRIME, addmod(/*column8_row252*/ mload(0x3680), /*column8_row252*/ mload(0x3680), PRIME)), PRIME), addmod( /*column8_row197*/ mload(0x3640), sub(PRIME, mulmod(18014398509481984, /*column8_row251*/ mload(0x3660), PRIME)), PRIME), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 256) - 1. // val *= denominator_invs[10]. val := mulmod(val, mload(0x5260), PRIME) // res += val * (coefficients[118] + coefficients[119] * adjustments[9]). res := addmod(res, mulmod(val, add(/*coefficients[118]*/ mload(0x1300), mulmod(/*coefficients[119]*/ mload(0x1320), /*adjustments[9]*/mload(0x5960), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/hash1/ec_subset_sum/booleanity_test: pedersen__hash1__ec_subset_sum__bit_0 * (pedersen__hash1__ec_subset_sum__bit_0 - 1). let val := mulmod( /*intermediate_value/pedersen/hash1/ec_subset_sum/bit_0*/ mload(0x4c00), addmod( /*intermediate_value/pedersen/hash1/ec_subset_sum/bit_0*/ mload(0x4c00), sub(PRIME, 1), PRIME), PRIME) // Numerator: point^(trace_length / 256) - trace_generator^(255 * trace_length / 256). // val *= numerators[4]. val := mulmod(val, mload(0x5760), PRIME) // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0x5120), PRIME) // res += val * (coefficients[120] + coefficients[121] * adjustments[10]). res := addmod(res, mulmod(val, add(/*coefficients[120]*/ mload(0x1340), mulmod(/*coefficients[121]*/ mload(0x1360), /*adjustments[10]*/mload(0x5980), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/hash1/ec_subset_sum/bit_extraction_end: column8_row0. let val := /*column8_row0*/ mload(0x35a0) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 256) - trace_generator^(63 * trace_length / 64). // val *= denominator_invs[11]. val := mulmod(val, mload(0x5280), PRIME) // res += val * (coefficients[122] + coefficients[123] * adjustments[11]). res := addmod(res, mulmod(val, add(/*coefficients[122]*/ mload(0x1380), mulmod(/*coefficients[123]*/ mload(0x13a0), /*adjustments[11]*/mload(0x59a0), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/hash1/ec_subset_sum/zeros_tail: column8_row0. let val := /*column8_row0*/ mload(0x35a0) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 256) - trace_generator^(255 * trace_length / 256). // val *= denominator_invs[12]. val := mulmod(val, mload(0x52a0), PRIME) // res += val * (coefficients[124] + coefficients[125] * adjustments[11]). res := addmod(res, mulmod(val, add(/*coefficients[124]*/ mload(0x13c0), mulmod(/*coefficients[125]*/ mload(0x13e0), /*adjustments[11]*/mload(0x59a0), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/hash1/ec_subset_sum/add_points/slope: pedersen__hash1__ec_subset_sum__bit_0 * (column6_row0 - pedersen__points__y) - column7_row0 * (column5_row0 - pedersen__points__x). let val := addmod( mulmod( /*intermediate_value/pedersen/hash1/ec_subset_sum/bit_0*/ mload(0x4c00), addmod( /*column6_row0*/ mload(0x34e0), sub(PRIME, /*periodic_column/pedersen/points/y*/ mload(0x20)), PRIME), PRIME), sub( PRIME, mulmod( /*column7_row0*/ mload(0x3560), addmod( /*column5_row0*/ mload(0x3440), sub(PRIME, /*periodic_column/pedersen/points/x*/ mload(0x0)), PRIME), PRIME)), PRIME) // Numerator: point^(trace_length / 256) - trace_generator^(255 * trace_length / 256). // val *= numerators[4]. val := mulmod(val, mload(0x5760), PRIME) // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0x5120), PRIME) // res += val * (coefficients[126] + coefficients[127] * adjustments[10]). res := addmod(res, mulmod(val, add(/*coefficients[126]*/ mload(0x1400), mulmod(/*coefficients[127]*/ mload(0x1420), /*adjustments[10]*/mload(0x5980), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/hash1/ec_subset_sum/add_points/x: column7_row0 * column7_row0 - pedersen__hash1__ec_subset_sum__bit_0 * (column5_row0 + pedersen__points__x + column5_row1). let val := addmod( mulmod(/*column7_row0*/ mload(0x3560), /*column7_row0*/ mload(0x3560), PRIME), sub( PRIME, mulmod( /*intermediate_value/pedersen/hash1/ec_subset_sum/bit_0*/ mload(0x4c00), addmod( addmod( /*column5_row0*/ mload(0x3440), /*periodic_column/pedersen/points/x*/ mload(0x0), PRIME), /*column5_row1*/ mload(0x3460), PRIME), PRIME)), PRIME) // Numerator: point^(trace_length / 256) - trace_generator^(255 * trace_length / 256). // val *= numerators[4]. val := mulmod(val, mload(0x5760), PRIME) // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0x5120), PRIME) // res += val * (coefficients[128] + coefficients[129] * adjustments[10]). res := addmod(res, mulmod(val, add(/*coefficients[128]*/ mload(0x1440), mulmod(/*coefficients[129]*/ mload(0x1460), /*adjustments[10]*/mload(0x5980), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/hash1/ec_subset_sum/add_points/y: pedersen__hash1__ec_subset_sum__bit_0 * (column6_row0 + column6_row1) - column7_row0 * (column5_row0 - column5_row1). let val := addmod( mulmod( /*intermediate_value/pedersen/hash1/ec_subset_sum/bit_0*/ mload(0x4c00), addmod(/*column6_row0*/ mload(0x34e0), /*column6_row1*/ mload(0x3500), PRIME), PRIME), sub( PRIME, mulmod( /*column7_row0*/ mload(0x3560), addmod(/*column5_row0*/ mload(0x3440), sub(PRIME, /*column5_row1*/ mload(0x3460)), PRIME), PRIME)), PRIME) // Numerator: point^(trace_length / 256) - trace_generator^(255 * trace_length / 256). // val *= numerators[4]. val := mulmod(val, mload(0x5760), PRIME) // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0x5120), PRIME) // res += val * (coefficients[130] + coefficients[131] * adjustments[10]). res := addmod(res, mulmod(val, add(/*coefficients[130]*/ mload(0x1480), mulmod(/*coefficients[131]*/ mload(0x14a0), /*adjustments[10]*/mload(0x5980), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/hash1/ec_subset_sum/copy_point/x: pedersen__hash1__ec_subset_sum__bit_neg_0 * (column5_row1 - column5_row0). let val := mulmod( /*intermediate_value/pedersen/hash1/ec_subset_sum/bit_neg_0*/ mload(0x4c20), addmod(/*column5_row1*/ mload(0x3460), sub(PRIME, /*column5_row0*/ mload(0x3440)), PRIME), PRIME) // Numerator: point^(trace_length / 256) - trace_generator^(255 * trace_length / 256). // val *= numerators[4]. val := mulmod(val, mload(0x5760), PRIME) // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0x5120), PRIME) // res += val * (coefficients[132] + coefficients[133] * adjustments[10]). res := addmod(res, mulmod(val, add(/*coefficients[132]*/ mload(0x14c0), mulmod(/*coefficients[133]*/ mload(0x14e0), /*adjustments[10]*/mload(0x5980), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/hash1/ec_subset_sum/copy_point/y: pedersen__hash1__ec_subset_sum__bit_neg_0 * (column6_row1 - column6_row0). let val := mulmod( /*intermediate_value/pedersen/hash1/ec_subset_sum/bit_neg_0*/ mload(0x4c20), addmod(/*column6_row1*/ mload(0x3500), sub(PRIME, /*column6_row0*/ mload(0x34e0)), PRIME), PRIME) // Numerator: point^(trace_length / 256) - trace_generator^(255 * trace_length / 256). // val *= numerators[4]. val := mulmod(val, mload(0x5760), PRIME) // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0x5120), PRIME) // res += val * (coefficients[134] + coefficients[135] * adjustments[10]). res := addmod(res, mulmod(val, add(/*coefficients[134]*/ mload(0x1500), mulmod(/*coefficients[135]*/ mload(0x1520), /*adjustments[10]*/mload(0x5980), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/hash1/copy_point/x: column5_row256 - column5_row255. let val := addmod( /*column5_row256*/ mload(0x34a0), sub(PRIME, /*column5_row255*/ mload(0x3480)), PRIME) // Numerator: point^(trace_length / 512) - trace_generator^(trace_length / 2). // val *= numerators[5]. val := mulmod(val, mload(0x5780), PRIME) // Denominator: point^(trace_length / 256) - 1. // val *= denominator_invs[10]. val := mulmod(val, mload(0x5260), PRIME) // res += val * (coefficients[136] + coefficients[137] * adjustments[12]). res := addmod(res, mulmod(val, add(/*coefficients[136]*/ mload(0x1540), mulmod(/*coefficients[137]*/ mload(0x1560), /*adjustments[12]*/mload(0x59c0), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/hash1/copy_point/y: column6_row256 - column6_row255. let val := addmod( /*column6_row256*/ mload(0x3540), sub(PRIME, /*column6_row255*/ mload(0x3520)), PRIME) // Numerator: point^(trace_length / 512) - trace_generator^(trace_length / 2). // val *= numerators[5]. val := mulmod(val, mload(0x5780), PRIME) // Denominator: point^(trace_length / 256) - 1. // val *= denominator_invs[10]. val := mulmod(val, mload(0x5260), PRIME) // res += val * (coefficients[138] + coefficients[139] * adjustments[12]). res := addmod(res, mulmod(val, add(/*coefficients[138]*/ mload(0x1580), mulmod(/*coefficients[139]*/ mload(0x15a0), /*adjustments[12]*/mload(0x59c0), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/hash1/init/x: column5_row0 - pedersen/shift_point.x. let val := addmod( /*column5_row0*/ mload(0x3440), sub(PRIME, /*pedersen/shift_point.x*/ mload(0x240)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 512) - 1. // val *= denominator_invs[13]. val := mulmod(val, mload(0x52c0), PRIME) // res += val * (coefficients[140] + coefficients[141] * adjustments[13]). res := addmod(res, mulmod(val, add(/*coefficients[140]*/ mload(0x15c0), mulmod(/*coefficients[141]*/ mload(0x15e0), /*adjustments[13]*/mload(0x59e0), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/hash1/init/y: column6_row0 - pedersen/shift_point.y. let val := addmod( /*column6_row0*/ mload(0x34e0), sub(PRIME, /*pedersen/shift_point.y*/ mload(0x260)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 512) - 1. // val *= denominator_invs[13]. val := mulmod(val, mload(0x52c0), PRIME) // res += val * (coefficients[142] + coefficients[143] * adjustments[13]). res := addmod(res, mulmod(val, add(/*coefficients[142]*/ mload(0x1600), mulmod(/*coefficients[143]*/ mload(0x1620), /*adjustments[13]*/mload(0x59e0), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/hash2/ec_subset_sum/bit_unpacking/last_one_is_zero: column20_row145 * (column12_row0 - (column12_row1 + column12_row1)). let val := mulmod( /*column20_row145*/ mload(0x4700), addmod( /*column12_row0*/ mload(0x3820), sub( PRIME, addmod(/*column12_row1*/ mload(0x3840), /*column12_row1*/ mload(0x3840), PRIME)), PRIME), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 256) - 1. // val *= denominator_invs[10]. val := mulmod(val, mload(0x5260), PRIME) // res += val * (coefficients[144] + coefficients[145] * adjustments[9]). res := addmod(res, mulmod(val, add(/*coefficients[144]*/ mload(0x1640), mulmod(/*coefficients[145]*/ mload(0x1660), /*adjustments[9]*/mload(0x5960), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/hash2/ec_subset_sum/bit_unpacking/zeroes_between_ones0: column20_row145 * (column12_row1 - 3138550867693340381917894711603833208051177722232017256448 * column12_row192). let val := mulmod( /*column20_row145*/ mload(0x4700), addmod( /*column12_row1*/ mload(0x3840), sub( PRIME, mulmod( 3138550867693340381917894711603833208051177722232017256448, /*column12_row192*/ mload(0x3860), PRIME)), PRIME), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 256) - 1. // val *= denominator_invs[10]. val := mulmod(val, mload(0x5260), PRIME) // res += val * (coefficients[146] + coefficients[147] * adjustments[9]). res := addmod(res, mulmod(val, add(/*coefficients[146]*/ mload(0x1680), mulmod(/*coefficients[147]*/ mload(0x16a0), /*adjustments[9]*/mload(0x5960), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/hash2/ec_subset_sum/bit_unpacking/cumulative_bit192: column20_row145 - column20_row17 * (column12_row192 - (column12_row193 + column12_row193)). let val := addmod( /*column20_row145*/ mload(0x4700), sub( PRIME, mulmod( /*column20_row17*/ mload(0x45c0), addmod( /*column12_row192*/ mload(0x3860), sub( PRIME, addmod(/*column12_row193*/ mload(0x3880), /*column12_row193*/ mload(0x3880), PRIME)), PRIME), PRIME)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 256) - 1. // val *= denominator_invs[10]. val := mulmod(val, mload(0x5260), PRIME) // res += val * (coefficients[148] + coefficients[149] * adjustments[9]). res := addmod(res, mulmod(val, add(/*coefficients[148]*/ mload(0x16c0), mulmod(/*coefficients[149]*/ mload(0x16e0), /*adjustments[9]*/mload(0x5960), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/hash2/ec_subset_sum/bit_unpacking/zeroes_between_ones192: column20_row17 * (column12_row193 - 8 * column12_row196). let val := mulmod( /*column20_row17*/ mload(0x45c0), addmod( /*column12_row193*/ mload(0x3880), sub(PRIME, mulmod(8, /*column12_row196*/ mload(0x38a0), PRIME)), PRIME), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 256) - 1. // val *= denominator_invs[10]. val := mulmod(val, mload(0x5260), PRIME) // res += val * (coefficients[150] + coefficients[151] * adjustments[9]). res := addmod(res, mulmod(val, add(/*coefficients[150]*/ mload(0x1700), mulmod(/*coefficients[151]*/ mload(0x1720), /*adjustments[9]*/mload(0x5960), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/hash2/ec_subset_sum/bit_unpacking/cumulative_bit196: column20_row17 - (column12_row251 - (column12_row252 + column12_row252)) * (column12_row196 - (column12_row197 + column12_row197)). let val := addmod( /*column20_row17*/ mload(0x45c0), sub( PRIME, mulmod( addmod( /*column12_row251*/ mload(0x38e0), sub( PRIME, addmod(/*column12_row252*/ mload(0x3900), /*column12_row252*/ mload(0x3900), PRIME)), PRIME), addmod( /*column12_row196*/ mload(0x38a0), sub( PRIME, addmod(/*column12_row197*/ mload(0x38c0), /*column12_row197*/ mload(0x38c0), PRIME)), PRIME), PRIME)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 256) - 1. // val *= denominator_invs[10]. val := mulmod(val, mload(0x5260), PRIME) // res += val * (coefficients[152] + coefficients[153] * adjustments[9]). res := addmod(res, mulmod(val, add(/*coefficients[152]*/ mload(0x1740), mulmod(/*coefficients[153]*/ mload(0x1760), /*adjustments[9]*/mload(0x5960), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/hash2/ec_subset_sum/bit_unpacking/zeroes_between_ones196: (column12_row251 - (column12_row252 + column12_row252)) * (column12_row197 - 18014398509481984 * column12_row251). let val := mulmod( addmod( /*column12_row251*/ mload(0x38e0), sub( PRIME, addmod(/*column12_row252*/ mload(0x3900), /*column12_row252*/ mload(0x3900), PRIME)), PRIME), addmod( /*column12_row197*/ mload(0x38c0), sub(PRIME, mulmod(18014398509481984, /*column12_row251*/ mload(0x38e0), PRIME)), PRIME), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 256) - 1. // val *= denominator_invs[10]. val := mulmod(val, mload(0x5260), PRIME) // res += val * (coefficients[154] + coefficients[155] * adjustments[9]). res := addmod(res, mulmod(val, add(/*coefficients[154]*/ mload(0x1780), mulmod(/*coefficients[155]*/ mload(0x17a0), /*adjustments[9]*/mload(0x5960), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/hash2/ec_subset_sum/booleanity_test: pedersen__hash2__ec_subset_sum__bit_0 * (pedersen__hash2__ec_subset_sum__bit_0 - 1). let val := mulmod( /*intermediate_value/pedersen/hash2/ec_subset_sum/bit_0*/ mload(0x4c40), addmod( /*intermediate_value/pedersen/hash2/ec_subset_sum/bit_0*/ mload(0x4c40), sub(PRIME, 1), PRIME), PRIME) // Numerator: point^(trace_length / 256) - trace_generator^(255 * trace_length / 256). // val *= numerators[4]. val := mulmod(val, mload(0x5760), PRIME) // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0x5120), PRIME) // res += val * (coefficients[156] + coefficients[157] * adjustments[10]). res := addmod(res, mulmod(val, add(/*coefficients[156]*/ mload(0x17c0), mulmod(/*coefficients[157]*/ mload(0x17e0), /*adjustments[10]*/mload(0x5980), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/hash2/ec_subset_sum/bit_extraction_end: column12_row0. let val := /*column12_row0*/ mload(0x3820) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 256) - trace_generator^(63 * trace_length / 64). // val *= denominator_invs[11]. val := mulmod(val, mload(0x5280), PRIME) // res += val * (coefficients[158] + coefficients[159] * adjustments[11]). res := addmod(res, mulmod(val, add(/*coefficients[158]*/ mload(0x1800), mulmod(/*coefficients[159]*/ mload(0x1820), /*adjustments[11]*/mload(0x59a0), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/hash2/ec_subset_sum/zeros_tail: column12_row0. let val := /*column12_row0*/ mload(0x3820) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 256) - trace_generator^(255 * trace_length / 256). // val *= denominator_invs[12]. val := mulmod(val, mload(0x52a0), PRIME) // res += val * (coefficients[160] + coefficients[161] * adjustments[11]). res := addmod(res, mulmod(val, add(/*coefficients[160]*/ mload(0x1840), mulmod(/*coefficients[161]*/ mload(0x1860), /*adjustments[11]*/mload(0x59a0), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/hash2/ec_subset_sum/add_points/slope: pedersen__hash2__ec_subset_sum__bit_0 * (column10_row0 - pedersen__points__y) - column11_row0 * (column9_row0 - pedersen__points__x). let val := addmod( mulmod( /*intermediate_value/pedersen/hash2/ec_subset_sum/bit_0*/ mload(0x4c40), addmod( /*column10_row0*/ mload(0x3760), sub(PRIME, /*periodic_column/pedersen/points/y*/ mload(0x20)), PRIME), PRIME), sub( PRIME, mulmod( /*column11_row0*/ mload(0x37e0), addmod( /*column9_row0*/ mload(0x36c0), sub(PRIME, /*periodic_column/pedersen/points/x*/ mload(0x0)), PRIME), PRIME)), PRIME) // Numerator: point^(trace_length / 256) - trace_generator^(255 * trace_length / 256). // val *= numerators[4]. val := mulmod(val, mload(0x5760), PRIME) // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0x5120), PRIME) // res += val * (coefficients[162] + coefficients[163] * adjustments[10]). res := addmod(res, mulmod(val, add(/*coefficients[162]*/ mload(0x1880), mulmod(/*coefficients[163]*/ mload(0x18a0), /*adjustments[10]*/mload(0x5980), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/hash2/ec_subset_sum/add_points/x: column11_row0 * column11_row0 - pedersen__hash2__ec_subset_sum__bit_0 * (column9_row0 + pedersen__points__x + column9_row1). let val := addmod( mulmod(/*column11_row0*/ mload(0x37e0), /*column11_row0*/ mload(0x37e0), PRIME), sub( PRIME, mulmod( /*intermediate_value/pedersen/hash2/ec_subset_sum/bit_0*/ mload(0x4c40), addmod( addmod( /*column9_row0*/ mload(0x36c0), /*periodic_column/pedersen/points/x*/ mload(0x0), PRIME), /*column9_row1*/ mload(0x36e0), PRIME), PRIME)), PRIME) // Numerator: point^(trace_length / 256) - trace_generator^(255 * trace_length / 256). // val *= numerators[4]. val := mulmod(val, mload(0x5760), PRIME) // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0x5120), PRIME) // res += val * (coefficients[164] + coefficients[165] * adjustments[10]). res := addmod(res, mulmod(val, add(/*coefficients[164]*/ mload(0x18c0), mulmod(/*coefficients[165]*/ mload(0x18e0), /*adjustments[10]*/mload(0x5980), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/hash2/ec_subset_sum/add_points/y: pedersen__hash2__ec_subset_sum__bit_0 * (column10_row0 + column10_row1) - column11_row0 * (column9_row0 - column9_row1). let val := addmod( mulmod( /*intermediate_value/pedersen/hash2/ec_subset_sum/bit_0*/ mload(0x4c40), addmod(/*column10_row0*/ mload(0x3760), /*column10_row1*/ mload(0x3780), PRIME), PRIME), sub( PRIME, mulmod( /*column11_row0*/ mload(0x37e0), addmod(/*column9_row0*/ mload(0x36c0), sub(PRIME, /*column9_row1*/ mload(0x36e0)), PRIME), PRIME)), PRIME) // Numerator: point^(trace_length / 256) - trace_generator^(255 * trace_length / 256). // val *= numerators[4]. val := mulmod(val, mload(0x5760), PRIME) // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0x5120), PRIME) // res += val * (coefficients[166] + coefficients[167] * adjustments[10]). res := addmod(res, mulmod(val, add(/*coefficients[166]*/ mload(0x1900), mulmod(/*coefficients[167]*/ mload(0x1920), /*adjustments[10]*/mload(0x5980), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/hash2/ec_subset_sum/copy_point/x: pedersen__hash2__ec_subset_sum__bit_neg_0 * (column9_row1 - column9_row0). let val := mulmod( /*intermediate_value/pedersen/hash2/ec_subset_sum/bit_neg_0*/ mload(0x4c60), addmod(/*column9_row1*/ mload(0x36e0), sub(PRIME, /*column9_row0*/ mload(0x36c0)), PRIME), PRIME) // Numerator: point^(trace_length / 256) - trace_generator^(255 * trace_length / 256). // val *= numerators[4]. val := mulmod(val, mload(0x5760), PRIME) // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0x5120), PRIME) // res += val * (coefficients[168] + coefficients[169] * adjustments[10]). res := addmod(res, mulmod(val, add(/*coefficients[168]*/ mload(0x1940), mulmod(/*coefficients[169]*/ mload(0x1960), /*adjustments[10]*/mload(0x5980), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/hash2/ec_subset_sum/copy_point/y: pedersen__hash2__ec_subset_sum__bit_neg_0 * (column10_row1 - column10_row0). let val := mulmod( /*intermediate_value/pedersen/hash2/ec_subset_sum/bit_neg_0*/ mload(0x4c60), addmod(/*column10_row1*/ mload(0x3780), sub(PRIME, /*column10_row0*/ mload(0x3760)), PRIME), PRIME) // Numerator: point^(trace_length / 256) - trace_generator^(255 * trace_length / 256). // val *= numerators[4]. val := mulmod(val, mload(0x5760), PRIME) // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0x5120), PRIME) // res += val * (coefficients[170] + coefficients[171] * adjustments[10]). res := addmod(res, mulmod(val, add(/*coefficients[170]*/ mload(0x1980), mulmod(/*coefficients[171]*/ mload(0x19a0), /*adjustments[10]*/mload(0x5980), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/hash2/copy_point/x: column9_row256 - column9_row255. let val := addmod( /*column9_row256*/ mload(0x3720), sub(PRIME, /*column9_row255*/ mload(0x3700)), PRIME) // Numerator: point^(trace_length / 512) - trace_generator^(trace_length / 2). // val *= numerators[5]. val := mulmod(val, mload(0x5780), PRIME) // Denominator: point^(trace_length / 256) - 1. // val *= denominator_invs[10]. val := mulmod(val, mload(0x5260), PRIME) // res += val * (coefficients[172] + coefficients[173] * adjustments[12]). res := addmod(res, mulmod(val, add(/*coefficients[172]*/ mload(0x19c0), mulmod(/*coefficients[173]*/ mload(0x19e0), /*adjustments[12]*/mload(0x59c0), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/hash2/copy_point/y: column10_row256 - column10_row255. let val := addmod( /*column10_row256*/ mload(0x37c0), sub(PRIME, /*column10_row255*/ mload(0x37a0)), PRIME) // Numerator: point^(trace_length / 512) - trace_generator^(trace_length / 2). // val *= numerators[5]. val := mulmod(val, mload(0x5780), PRIME) // Denominator: point^(trace_length / 256) - 1. // val *= denominator_invs[10]. val := mulmod(val, mload(0x5260), PRIME) // res += val * (coefficients[174] + coefficients[175] * adjustments[12]). res := addmod(res, mulmod(val, add(/*coefficients[174]*/ mload(0x1a00), mulmod(/*coefficients[175]*/ mload(0x1a20), /*adjustments[12]*/mload(0x59c0), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/hash2/init/x: column9_row0 - pedersen/shift_point.x. let val := addmod( /*column9_row0*/ mload(0x36c0), sub(PRIME, /*pedersen/shift_point.x*/ mload(0x240)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 512) - 1. // val *= denominator_invs[13]. val := mulmod(val, mload(0x52c0), PRIME) // res += val * (coefficients[176] + coefficients[177] * adjustments[13]). res := addmod(res, mulmod(val, add(/*coefficients[176]*/ mload(0x1a40), mulmod(/*coefficients[177]*/ mload(0x1a60), /*adjustments[13]*/mload(0x59e0), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/hash2/init/y: column10_row0 - pedersen/shift_point.y. let val := addmod( /*column10_row0*/ mload(0x3760), sub(PRIME, /*pedersen/shift_point.y*/ mload(0x260)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 512) - 1. // val *= denominator_invs[13]. val := mulmod(val, mload(0x52c0), PRIME) // res += val * (coefficients[178] + coefficients[179] * adjustments[13]). res := addmod(res, mulmod(val, add(/*coefficients[178]*/ mload(0x1a80), mulmod(/*coefficients[179]*/ mload(0x1aa0), /*adjustments[13]*/mload(0x59e0), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/hash3/ec_subset_sum/bit_unpacking/last_one_is_zero: column20_row209 * (column16_row0 - (column16_row1 + column16_row1)). let val := mulmod( /*column20_row209*/ mload(0x4720), addmod( /*column16_row0*/ mload(0x3aa0), sub( PRIME, addmod(/*column16_row1*/ mload(0x3ac0), /*column16_row1*/ mload(0x3ac0), PRIME)), PRIME), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 256) - 1. // val *= denominator_invs[10]. val := mulmod(val, mload(0x5260), PRIME) // res += val * (coefficients[180] + coefficients[181] * adjustments[9]). res := addmod(res, mulmod(val, add(/*coefficients[180]*/ mload(0x1ac0), mulmod(/*coefficients[181]*/ mload(0x1ae0), /*adjustments[9]*/mload(0x5960), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/hash3/ec_subset_sum/bit_unpacking/zeroes_between_ones0: column20_row209 * (column16_row1 - 3138550867693340381917894711603833208051177722232017256448 * column16_row192). let val := mulmod( /*column20_row209*/ mload(0x4720), addmod( /*column16_row1*/ mload(0x3ac0), sub( PRIME, mulmod( 3138550867693340381917894711603833208051177722232017256448, /*column16_row192*/ mload(0x3ae0), PRIME)), PRIME), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 256) - 1. // val *= denominator_invs[10]. val := mulmod(val, mload(0x5260), PRIME) // res += val * (coefficients[182] + coefficients[183] * adjustments[9]). res := addmod(res, mulmod(val, add(/*coefficients[182]*/ mload(0x1b00), mulmod(/*coefficients[183]*/ mload(0x1b20), /*adjustments[9]*/mload(0x5960), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/hash3/ec_subset_sum/bit_unpacking/cumulative_bit192: column20_row209 - column20_row81 * (column16_row192 - (column16_row193 + column16_row193)). let val := addmod( /*column20_row209*/ mload(0x4720), sub( PRIME, mulmod( /*column20_row81*/ mload(0x46e0), addmod( /*column16_row192*/ mload(0x3ae0), sub( PRIME, addmod(/*column16_row193*/ mload(0x3b00), /*column16_row193*/ mload(0x3b00), PRIME)), PRIME), PRIME)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 256) - 1. // val *= denominator_invs[10]. val := mulmod(val, mload(0x5260), PRIME) // res += val * (coefficients[184] + coefficients[185] * adjustments[9]). res := addmod(res, mulmod(val, add(/*coefficients[184]*/ mload(0x1b40), mulmod(/*coefficients[185]*/ mload(0x1b60), /*adjustments[9]*/mload(0x5960), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/hash3/ec_subset_sum/bit_unpacking/zeroes_between_ones192: column20_row81 * (column16_row193 - 8 * column16_row196). let val := mulmod( /*column20_row81*/ mload(0x46e0), addmod( /*column16_row193*/ mload(0x3b00), sub(PRIME, mulmod(8, /*column16_row196*/ mload(0x3b20), PRIME)), PRIME), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 256) - 1. // val *= denominator_invs[10]. val := mulmod(val, mload(0x5260), PRIME) // res += val * (coefficients[186] + coefficients[187] * adjustments[9]). res := addmod(res, mulmod(val, add(/*coefficients[186]*/ mload(0x1b80), mulmod(/*coefficients[187]*/ mload(0x1ba0), /*adjustments[9]*/mload(0x5960), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/hash3/ec_subset_sum/bit_unpacking/cumulative_bit196: column20_row81 - (column16_row251 - (column16_row252 + column16_row252)) * (column16_row196 - (column16_row197 + column16_row197)). let val := addmod( /*column20_row81*/ mload(0x46e0), sub( PRIME, mulmod( addmod( /*column16_row251*/ mload(0x3b60), sub( PRIME, addmod(/*column16_row252*/ mload(0x3b80), /*column16_row252*/ mload(0x3b80), PRIME)), PRIME), addmod( /*column16_row196*/ mload(0x3b20), sub( PRIME, addmod(/*column16_row197*/ mload(0x3b40), /*column16_row197*/ mload(0x3b40), PRIME)), PRIME), PRIME)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 256) - 1. // val *= denominator_invs[10]. val := mulmod(val, mload(0x5260), PRIME) // res += val * (coefficients[188] + coefficients[189] * adjustments[9]). res := addmod(res, mulmod(val, add(/*coefficients[188]*/ mload(0x1bc0), mulmod(/*coefficients[189]*/ mload(0x1be0), /*adjustments[9]*/mload(0x5960), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/hash3/ec_subset_sum/bit_unpacking/zeroes_between_ones196: (column16_row251 - (column16_row252 + column16_row252)) * (column16_row197 - 18014398509481984 * column16_row251). let val := mulmod( addmod( /*column16_row251*/ mload(0x3b60), sub( PRIME, addmod(/*column16_row252*/ mload(0x3b80), /*column16_row252*/ mload(0x3b80), PRIME)), PRIME), addmod( /*column16_row197*/ mload(0x3b40), sub(PRIME, mulmod(18014398509481984, /*column16_row251*/ mload(0x3b60), PRIME)), PRIME), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 256) - 1. // val *= denominator_invs[10]. val := mulmod(val, mload(0x5260), PRIME) // res += val * (coefficients[190] + coefficients[191] * adjustments[9]). res := addmod(res, mulmod(val, add(/*coefficients[190]*/ mload(0x1c00), mulmod(/*coefficients[191]*/ mload(0x1c20), /*adjustments[9]*/mload(0x5960), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/hash3/ec_subset_sum/booleanity_test: pedersen__hash3__ec_subset_sum__bit_0 * (pedersen__hash3__ec_subset_sum__bit_0 - 1). let val := mulmod( /*intermediate_value/pedersen/hash3/ec_subset_sum/bit_0*/ mload(0x4c80), addmod( /*intermediate_value/pedersen/hash3/ec_subset_sum/bit_0*/ mload(0x4c80), sub(PRIME, 1), PRIME), PRIME) // Numerator: point^(trace_length / 256) - trace_generator^(255 * trace_length / 256). // val *= numerators[4]. val := mulmod(val, mload(0x5760), PRIME) // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0x5120), PRIME) // res += val * (coefficients[192] + coefficients[193] * adjustments[10]). res := addmod(res, mulmod(val, add(/*coefficients[192]*/ mload(0x1c40), mulmod(/*coefficients[193]*/ mload(0x1c60), /*adjustments[10]*/mload(0x5980), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/hash3/ec_subset_sum/bit_extraction_end: column16_row0. let val := /*column16_row0*/ mload(0x3aa0) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 256) - trace_generator^(63 * trace_length / 64). // val *= denominator_invs[11]. val := mulmod(val, mload(0x5280), PRIME) // res += val * (coefficients[194] + coefficients[195] * adjustments[11]). res := addmod(res, mulmod(val, add(/*coefficients[194]*/ mload(0x1c80), mulmod(/*coefficients[195]*/ mload(0x1ca0), /*adjustments[11]*/mload(0x59a0), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/hash3/ec_subset_sum/zeros_tail: column16_row0. let val := /*column16_row0*/ mload(0x3aa0) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 256) - trace_generator^(255 * trace_length / 256). // val *= denominator_invs[12]. val := mulmod(val, mload(0x52a0), PRIME) // res += val * (coefficients[196] + coefficients[197] * adjustments[11]). res := addmod(res, mulmod(val, add(/*coefficients[196]*/ mload(0x1cc0), mulmod(/*coefficients[197]*/ mload(0x1ce0), /*adjustments[11]*/mload(0x59a0), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/hash3/ec_subset_sum/add_points/slope: pedersen__hash3__ec_subset_sum__bit_0 * (column14_row0 - pedersen__points__y) - column15_row0 * (column13_row0 - pedersen__points__x). let val := addmod( mulmod( /*intermediate_value/pedersen/hash3/ec_subset_sum/bit_0*/ mload(0x4c80), addmod( /*column14_row0*/ mload(0x39e0), sub(PRIME, /*periodic_column/pedersen/points/y*/ mload(0x20)), PRIME), PRIME), sub( PRIME, mulmod( /*column15_row0*/ mload(0x3a60), addmod( /*column13_row0*/ mload(0x3940), sub(PRIME, /*periodic_column/pedersen/points/x*/ mload(0x0)), PRIME), PRIME)), PRIME) // Numerator: point^(trace_length / 256) - trace_generator^(255 * trace_length / 256). // val *= numerators[4]. val := mulmod(val, mload(0x5760), PRIME) // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0x5120), PRIME) // res += val * (coefficients[198] + coefficients[199] * adjustments[10]). res := addmod(res, mulmod(val, add(/*coefficients[198]*/ mload(0x1d00), mulmod(/*coefficients[199]*/ mload(0x1d20), /*adjustments[10]*/mload(0x5980), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/hash3/ec_subset_sum/add_points/x: column15_row0 * column15_row0 - pedersen__hash3__ec_subset_sum__bit_0 * (column13_row0 + pedersen__points__x + column13_row1). let val := addmod( mulmod(/*column15_row0*/ mload(0x3a60), /*column15_row0*/ mload(0x3a60), PRIME), sub( PRIME, mulmod( /*intermediate_value/pedersen/hash3/ec_subset_sum/bit_0*/ mload(0x4c80), addmod( addmod( /*column13_row0*/ mload(0x3940), /*periodic_column/pedersen/points/x*/ mload(0x0), PRIME), /*column13_row1*/ mload(0x3960), PRIME), PRIME)), PRIME) // Numerator: point^(trace_length / 256) - trace_generator^(255 * trace_length / 256). // val *= numerators[4]. val := mulmod(val, mload(0x5760), PRIME) // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0x5120), PRIME) // res += val * (coefficients[200] + coefficients[201] * adjustments[10]). res := addmod(res, mulmod(val, add(/*coefficients[200]*/ mload(0x1d40), mulmod(/*coefficients[201]*/ mload(0x1d60), /*adjustments[10]*/mload(0x5980), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/hash3/ec_subset_sum/add_points/y: pedersen__hash3__ec_subset_sum__bit_0 * (column14_row0 + column14_row1) - column15_row0 * (column13_row0 - column13_row1). let val := addmod( mulmod( /*intermediate_value/pedersen/hash3/ec_subset_sum/bit_0*/ mload(0x4c80), addmod(/*column14_row0*/ mload(0x39e0), /*column14_row1*/ mload(0x3a00), PRIME), PRIME), sub( PRIME, mulmod( /*column15_row0*/ mload(0x3a60), addmod(/*column13_row0*/ mload(0x3940), sub(PRIME, /*column13_row1*/ mload(0x3960)), PRIME), PRIME)), PRIME) // Numerator: point^(trace_length / 256) - trace_generator^(255 * trace_length / 256). // val *= numerators[4]. val := mulmod(val, mload(0x5760), PRIME) // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0x5120), PRIME) // res += val * (coefficients[202] + coefficients[203] * adjustments[10]). res := addmod(res, mulmod(val, add(/*coefficients[202]*/ mload(0x1d80), mulmod(/*coefficients[203]*/ mload(0x1da0), /*adjustments[10]*/mload(0x5980), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/hash3/ec_subset_sum/copy_point/x: pedersen__hash3__ec_subset_sum__bit_neg_0 * (column13_row1 - column13_row0). let val := mulmod( /*intermediate_value/pedersen/hash3/ec_subset_sum/bit_neg_0*/ mload(0x4ca0), addmod(/*column13_row1*/ mload(0x3960), sub(PRIME, /*column13_row0*/ mload(0x3940)), PRIME), PRIME) // Numerator: point^(trace_length / 256) - trace_generator^(255 * trace_length / 256). // val *= numerators[4]. val := mulmod(val, mload(0x5760), PRIME) // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0x5120), PRIME) // res += val * (coefficients[204] + coefficients[205] * adjustments[10]). res := addmod(res, mulmod(val, add(/*coefficients[204]*/ mload(0x1dc0), mulmod(/*coefficients[205]*/ mload(0x1de0), /*adjustments[10]*/mload(0x5980), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/hash3/ec_subset_sum/copy_point/y: pedersen__hash3__ec_subset_sum__bit_neg_0 * (column14_row1 - column14_row0). let val := mulmod( /*intermediate_value/pedersen/hash3/ec_subset_sum/bit_neg_0*/ mload(0x4ca0), addmod(/*column14_row1*/ mload(0x3a00), sub(PRIME, /*column14_row0*/ mload(0x39e0)), PRIME), PRIME) // Numerator: point^(trace_length / 256) - trace_generator^(255 * trace_length / 256). // val *= numerators[4]. val := mulmod(val, mload(0x5760), PRIME) // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0x5120), PRIME) // res += val * (coefficients[206] + coefficients[207] * adjustments[10]). res := addmod(res, mulmod(val, add(/*coefficients[206]*/ mload(0x1e00), mulmod(/*coefficients[207]*/ mload(0x1e20), /*adjustments[10]*/mload(0x5980), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/hash3/copy_point/x: column13_row256 - column13_row255. let val := addmod( /*column13_row256*/ mload(0x39a0), sub(PRIME, /*column13_row255*/ mload(0x3980)), PRIME) // Numerator: point^(trace_length / 512) - trace_generator^(trace_length / 2). // val *= numerators[5]. val := mulmod(val, mload(0x5780), PRIME) // Denominator: point^(trace_length / 256) - 1. // val *= denominator_invs[10]. val := mulmod(val, mload(0x5260), PRIME) // res += val * (coefficients[208] + coefficients[209] * adjustments[12]). res := addmod(res, mulmod(val, add(/*coefficients[208]*/ mload(0x1e40), mulmod(/*coefficients[209]*/ mload(0x1e60), /*adjustments[12]*/mload(0x59c0), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/hash3/copy_point/y: column14_row256 - column14_row255. let val := addmod( /*column14_row256*/ mload(0x3a40), sub(PRIME, /*column14_row255*/ mload(0x3a20)), PRIME) // Numerator: point^(trace_length / 512) - trace_generator^(trace_length / 2). // val *= numerators[5]. val := mulmod(val, mload(0x5780), PRIME) // Denominator: point^(trace_length / 256) - 1. // val *= denominator_invs[10]. val := mulmod(val, mload(0x5260), PRIME) // res += val * (coefficients[210] + coefficients[211] * adjustments[12]). res := addmod(res, mulmod(val, add(/*coefficients[210]*/ mload(0x1e80), mulmod(/*coefficients[211]*/ mload(0x1ea0), /*adjustments[12]*/mload(0x59c0), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/hash3/init/x: column13_row0 - pedersen/shift_point.x. let val := addmod( /*column13_row0*/ mload(0x3940), sub(PRIME, /*pedersen/shift_point.x*/ mload(0x240)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 512) - 1. // val *= denominator_invs[13]. val := mulmod(val, mload(0x52c0), PRIME) // res += val * (coefficients[212] + coefficients[213] * adjustments[13]). res := addmod(res, mulmod(val, add(/*coefficients[212]*/ mload(0x1ec0), mulmod(/*coefficients[213]*/ mload(0x1ee0), /*adjustments[13]*/mload(0x59e0), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/hash3/init/y: column14_row0 - pedersen/shift_point.y. let val := addmod( /*column14_row0*/ mload(0x39e0), sub(PRIME, /*pedersen/shift_point.y*/ mload(0x260)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 512) - 1. // val *= denominator_invs[13]. val := mulmod(val, mload(0x52c0), PRIME) // res += val * (coefficients[214] + coefficients[215] * adjustments[13]). res := addmod(res, mulmod(val, add(/*coefficients[214]*/ mload(0x1f00), mulmod(/*coefficients[215]*/ mload(0x1f20), /*adjustments[13]*/mload(0x59e0), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/input0_value0: column17_row7 - column4_row0. let val := addmod(/*column17_row7*/ mload(0x3ca0), sub(PRIME, /*column4_row0*/ mload(0x3320)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 512) - 1. // val *= denominator_invs[13]. val := mulmod(val, mload(0x52c0), PRIME) // res += val * (coefficients[216] + coefficients[217] * adjustments[13]). res := addmod(res, mulmod(val, add(/*coefficients[216]*/ mload(0x1f40), mulmod(/*coefficients[217]*/ mload(0x1f60), /*adjustments[13]*/mload(0x59e0), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/input0_value1: column17_row135 - column8_row0. let val := addmod( /*column17_row135*/ mload(0x3ec0), sub(PRIME, /*column8_row0*/ mload(0x35a0)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 512) - 1. // val *= denominator_invs[13]. val := mulmod(val, mload(0x52c0), PRIME) // res += val * (coefficients[218] + coefficients[219] * adjustments[13]). res := addmod(res, mulmod(val, add(/*coefficients[218]*/ mload(0x1f80), mulmod(/*coefficients[219]*/ mload(0x1fa0), /*adjustments[13]*/mload(0x59e0), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/input0_value2: column17_row263 - column12_row0. let val := addmod( /*column17_row263*/ mload(0x3f80), sub(PRIME, /*column12_row0*/ mload(0x3820)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 512) - 1. // val *= denominator_invs[13]. val := mulmod(val, mload(0x52c0), PRIME) // res += val * (coefficients[220] + coefficients[221] * adjustments[13]). res := addmod(res, mulmod(val, add(/*coefficients[220]*/ mload(0x1fc0), mulmod(/*coefficients[221]*/ mload(0x1fe0), /*adjustments[13]*/mload(0x59e0), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/input0_value3: column17_row391 - column16_row0. let val := addmod( /*column17_row391*/ mload(0x3fe0), sub(PRIME, /*column16_row0*/ mload(0x3aa0)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 512) - 1. // val *= denominator_invs[13]. val := mulmod(val, mload(0x52c0), PRIME) // res += val * (coefficients[222] + coefficients[223] * adjustments[13]). res := addmod(res, mulmod(val, add(/*coefficients[222]*/ mload(0x2000), mulmod(/*coefficients[223]*/ mload(0x2020), /*adjustments[13]*/mload(0x59e0), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/input0_addr: column17_row134 - (column17_row38 + 1). let val := addmod( /*column17_row134*/ mload(0x3ea0), sub(PRIME, addmod(/*column17_row38*/ mload(0x3da0), 1, PRIME)), PRIME) // Numerator: point - trace_generator^(128 * (trace_length / 128 - 1)). // val *= numerators[6]. val := mulmod(val, mload(0x57a0), PRIME) // Denominator: point^(trace_length / 128) - 1. // val *= denominator_invs[14]. val := mulmod(val, mload(0x52e0), PRIME) // res += val * (coefficients[224] + coefficients[225] * adjustments[14]). res := addmod(res, mulmod(val, add(/*coefficients[224]*/ mload(0x2040), mulmod(/*coefficients[225]*/ mload(0x2060), /*adjustments[14]*/mload(0x5a00), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/init_addr: column17_row6 - initial_pedersen_addr. let val := addmod( /*column17_row6*/ mload(0x3c80), sub(PRIME, /*initial_pedersen_addr*/ mload(0x280)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point - 1. // val *= denominator_invs[3]. val := mulmod(val, mload(0x5180), PRIME) // res += val * (coefficients[226] + coefficients[227] * adjustments[4]). res := addmod(res, mulmod(val, add(/*coefficients[226]*/ mload(0x2080), mulmod(/*coefficients[227]*/ mload(0x20a0), /*adjustments[4]*/mload(0x58c0), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/input1_value0: column17_row71 - column4_row256. let val := addmod( /*column17_row71*/ mload(0x3e00), sub(PRIME, /*column4_row256*/ mload(0x3420)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 512) - 1. // val *= denominator_invs[13]. val := mulmod(val, mload(0x52c0), PRIME) // res += val * (coefficients[228] + coefficients[229] * adjustments[13]). res := addmod(res, mulmod(val, add(/*coefficients[228]*/ mload(0x20c0), mulmod(/*coefficients[229]*/ mload(0x20e0), /*adjustments[13]*/mload(0x59e0), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/input1_value1: column17_row199 - column8_row256. let val := addmod( /*column17_row199*/ mload(0x3f40), sub(PRIME, /*column8_row256*/ mload(0x36a0)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 512) - 1. // val *= denominator_invs[13]. val := mulmod(val, mload(0x52c0), PRIME) // res += val * (coefficients[230] + coefficients[231] * adjustments[13]). res := addmod(res, mulmod(val, add(/*coefficients[230]*/ mload(0x2100), mulmod(/*coefficients[231]*/ mload(0x2120), /*adjustments[13]*/mload(0x59e0), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/input1_value2: column17_row327 - column12_row256. let val := addmod( /*column17_row327*/ mload(0x3fc0), sub(PRIME, /*column12_row256*/ mload(0x3920)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 512) - 1. // val *= denominator_invs[13]. val := mulmod(val, mload(0x52c0), PRIME) // res += val * (coefficients[232] + coefficients[233] * adjustments[13]). res := addmod(res, mulmod(val, add(/*coefficients[232]*/ mload(0x2140), mulmod(/*coefficients[233]*/ mload(0x2160), /*adjustments[13]*/mload(0x59e0), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/input1_value3: column17_row455 - column16_row256. let val := addmod( /*column17_row455*/ mload(0x4040), sub(PRIME, /*column16_row256*/ mload(0x3ba0)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 512) - 1. // val *= denominator_invs[13]. val := mulmod(val, mload(0x52c0), PRIME) // res += val * (coefficients[234] + coefficients[235] * adjustments[13]). res := addmod(res, mulmod(val, add(/*coefficients[234]*/ mload(0x2180), mulmod(/*coefficients[235]*/ mload(0x21a0), /*adjustments[13]*/mload(0x59e0), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/input1_addr: column17_row70 - (column17_row6 + 1). let val := addmod( /*column17_row70*/ mload(0x3de0), sub(PRIME, addmod(/*column17_row6*/ mload(0x3c80), 1, PRIME)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 128) - 1. // val *= denominator_invs[14]. val := mulmod(val, mload(0x52e0), PRIME) // res += val * (coefficients[236] + coefficients[237] * adjustments[15]). res := addmod(res, mulmod(val, add(/*coefficients[236]*/ mload(0x21c0), mulmod(/*coefficients[237]*/ mload(0x21e0), /*adjustments[15]*/mload(0x5a20), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/output_value0: column17_row39 - column1_row511. let val := addmod( /*column17_row39*/ mload(0x3dc0), sub(PRIME, /*column1_row511*/ mload(0x3240)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 512) - 1. // val *= denominator_invs[13]. val := mulmod(val, mload(0x52c0), PRIME) // res += val * (coefficients[238] + coefficients[239] * adjustments[13]). res := addmod(res, mulmod(val, add(/*coefficients[238]*/ mload(0x2200), mulmod(/*coefficients[239]*/ mload(0x2220), /*adjustments[13]*/mload(0x59e0), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/output_value1: column17_row167 - column5_row511. let val := addmod( /*column17_row167*/ mload(0x3f20), sub(PRIME, /*column5_row511*/ mload(0x34c0)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 512) - 1. // val *= denominator_invs[13]. val := mulmod(val, mload(0x52c0), PRIME) // res += val * (coefficients[240] + coefficients[241] * adjustments[13]). res := addmod(res, mulmod(val, add(/*coefficients[240]*/ mload(0x2240), mulmod(/*coefficients[241]*/ mload(0x2260), /*adjustments[13]*/mload(0x59e0), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/output_value2: column17_row295 - column9_row511. let val := addmod( /*column17_row295*/ mload(0x3fa0), sub(PRIME, /*column9_row511*/ mload(0x3740)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 512) - 1. // val *= denominator_invs[13]. val := mulmod(val, mload(0x52c0), PRIME) // res += val * (coefficients[242] + coefficients[243] * adjustments[13]). res := addmod(res, mulmod(val, add(/*coefficients[242]*/ mload(0x2280), mulmod(/*coefficients[243]*/ mload(0x22a0), /*adjustments[13]*/mload(0x59e0), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/output_value3: column17_row423 - column13_row511. let val := addmod( /*column17_row423*/ mload(0x4020), sub(PRIME, /*column13_row511*/ mload(0x39c0)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 512) - 1. // val *= denominator_invs[13]. val := mulmod(val, mload(0x52c0), PRIME) // res += val * (coefficients[244] + coefficients[245] * adjustments[13]). res := addmod(res, mulmod(val, add(/*coefficients[244]*/ mload(0x22c0), mulmod(/*coefficients[245]*/ mload(0x22e0), /*adjustments[13]*/mload(0x59e0), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/output_addr: column17_row38 - (column17_row70 + 1). let val := addmod( /*column17_row38*/ mload(0x3da0), sub(PRIME, addmod(/*column17_row70*/ mload(0x3de0), 1, PRIME)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 128) - 1. // val *= denominator_invs[14]. val := mulmod(val, mload(0x52e0), PRIME) // res += val * (coefficients[246] + coefficients[247] * adjustments[15]). res := addmod(res, mulmod(val, add(/*coefficients[246]*/ mload(0x2300), mulmod(/*coefficients[247]*/ mload(0x2320), /*adjustments[15]*/mload(0x5a20), PRIME)), PRIME), PRIME) } { // Constraint expression for rc_builtin/value: rc_builtin__value7_0 - column17_row103. let val := addmod( /*intermediate_value/rc_builtin/value7_0*/ mload(0x4da0), sub(PRIME, /*column17_row103*/ mload(0x3e80)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 128) - 1. // val *= denominator_invs[14]. val := mulmod(val, mload(0x52e0), PRIME) // res += val * (coefficients[248] + coefficients[249] * adjustments[15]). res := addmod(res, mulmod(val, add(/*coefficients[248]*/ mload(0x2340), mulmod(/*coefficients[249]*/ mload(0x2360), /*adjustments[15]*/mload(0x5a20), PRIME)), PRIME), PRIME) } { // Constraint expression for rc_builtin/addr_step: column17_row230 - (column17_row102 + 1). let val := addmod( /*column17_row230*/ mload(0x3f60), sub(PRIME, addmod(/*column17_row102*/ mload(0x3e60), 1, PRIME)), PRIME) // Numerator: point - trace_generator^(128 * (trace_length / 128 - 1)). // val *= numerators[6]. val := mulmod(val, mload(0x57a0), PRIME) // Denominator: point^(trace_length / 128) - 1. // val *= denominator_invs[14]. val := mulmod(val, mload(0x52e0), PRIME) // res += val * (coefficients[250] + coefficients[251] * adjustments[14]). res := addmod(res, mulmod(val, add(/*coefficients[250]*/ mload(0x2380), mulmod(/*coefficients[251]*/ mload(0x23a0), /*adjustments[14]*/mload(0x5a00), PRIME)), PRIME), PRIME) } { // Constraint expression for rc_builtin/init_addr: column17_row102 - initial_rc_addr. let val := addmod( /*column17_row102*/ mload(0x3e60), sub(PRIME, /*initial_rc_addr*/ mload(0x2a0)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point - 1. // val *= denominator_invs[3]. val := mulmod(val, mload(0x5180), PRIME) // res += val * (coefficients[252] + coefficients[253] * adjustments[4]). res := addmod(res, mulmod(val, add(/*coefficients[252]*/ mload(0x23c0), mulmod(/*coefficients[253]*/ mload(0x23e0), /*adjustments[4]*/mload(0x58c0), PRIME)), PRIME), PRIME) } { // Constraint expression for ecdsa/signature0/doubling_key/slope: ecdsa__signature0__doubling_key__x_squared + ecdsa__signature0__doubling_key__x_squared + ecdsa__signature0__doubling_key__x_squared + ecdsa/sig_config.alpha - (column19_row15 + column19_row15) * column20_row0. let val := addmod( addmod( addmod( addmod( /*intermediate_value/ecdsa/signature0/doubling_key/x_squared*/ mload(0x4dc0), /*intermediate_value/ecdsa/signature0/doubling_key/x_squared*/ mload(0x4dc0), PRIME), /*intermediate_value/ecdsa/signature0/doubling_key/x_squared*/ mload(0x4dc0), PRIME), /*ecdsa/sig_config.alpha*/ mload(0x2c0), PRIME), sub( PRIME, mulmod( addmod(/*column19_row15*/ mload(0x42e0), /*column19_row15*/ mload(0x42e0), PRIME), /*column20_row0*/ mload(0x44a0), PRIME)), PRIME) // Numerator: point^(trace_length / 4096) - trace_generator^(255 * trace_length / 256). // val *= numerators[7]. val := mulmod(val, mload(0x57c0), PRIME) // Denominator: point^(trace_length / 16) - 1. // val *= denominator_invs[2]. val := mulmod(val, mload(0x5160), PRIME) // res += val * (coefficients[254] + coefficients[255] * adjustments[16]). res := addmod(res, mulmod(val, add(/*coefficients[254]*/ mload(0x2400), mulmod(/*coefficients[255]*/ mload(0x2420), /*adjustments[16]*/mload(0x5a40), PRIME)), PRIME), PRIME) } { // Constraint expression for ecdsa/signature0/doubling_key/x: column20_row0 * column20_row0 - (column19_row7 + column19_row7 + column19_row23). let val := addmod( mulmod(/*column20_row0*/ mload(0x44a0), /*column20_row0*/ mload(0x44a0), PRIME), sub( PRIME, addmod( addmod(/*column19_row7*/ mload(0x4220), /*column19_row7*/ mload(0x4220), PRIME), /*column19_row23*/ mload(0x4320), PRIME)), PRIME) // Numerator: point^(trace_length / 4096) - trace_generator^(255 * trace_length / 256). // val *= numerators[7]. val := mulmod(val, mload(0x57c0), PRIME) // Denominator: point^(trace_length / 16) - 1. // val *= denominator_invs[2]. val := mulmod(val, mload(0x5160), PRIME) // res += val * (coefficients[256] + coefficients[257] * adjustments[16]). res := addmod(res, mulmod(val, add(/*coefficients[256]*/ mload(0x2440), mulmod(/*coefficients[257]*/ mload(0x2460), /*adjustments[16]*/mload(0x5a40), PRIME)), PRIME), PRIME) } { // Constraint expression for ecdsa/signature0/doubling_key/y: column19_row15 + column19_row31 - column20_row0 * (column19_row7 - column19_row23). let val := addmod( addmod(/*column19_row15*/ mload(0x42e0), /*column19_row31*/ mload(0x4380), PRIME), sub( PRIME, mulmod( /*column20_row0*/ mload(0x44a0), addmod( /*column19_row7*/ mload(0x4220), sub(PRIME, /*column19_row23*/ mload(0x4320)), PRIME), PRIME)), PRIME) // Numerator: point^(trace_length / 4096) - trace_generator^(255 * trace_length / 256). // val *= numerators[7]. val := mulmod(val, mload(0x57c0), PRIME) // Denominator: point^(trace_length / 16) - 1. // val *= denominator_invs[2]. val := mulmod(val, mload(0x5160), PRIME) // res += val * (coefficients[258] + coefficients[259] * adjustments[16]). res := addmod(res, mulmod(val, add(/*coefficients[258]*/ mload(0x2480), mulmod(/*coefficients[259]*/ mload(0x24a0), /*adjustments[16]*/mload(0x5a40), PRIME)), PRIME), PRIME) } { // Constraint expression for ecdsa/signature0/exponentiate_generator/booleanity_test: ecdsa__signature0__exponentiate_generator__bit_0 * (ecdsa__signature0__exponentiate_generator__bit_0 - 1). let val := mulmod( /*intermediate_value/ecdsa/signature0/exponentiate_generator/bit_0*/ mload(0x4de0), addmod( /*intermediate_value/ecdsa/signature0/exponentiate_generator/bit_0*/ mload(0x4de0), sub(PRIME, 1), PRIME), PRIME) // Numerator: point^(trace_length / 8192) - trace_generator^(255 * trace_length / 256). // val *= numerators[8]. val := mulmod(val, mload(0x57e0), PRIME) // Denominator: point^(trace_length / 32) - 1. // val *= denominator_invs[15]. val := mulmod(val, mload(0x5300), PRIME) // res += val * (coefficients[260] + coefficients[261] * adjustments[17]). res := addmod(res, mulmod(val, add(/*coefficients[260]*/ mload(0x24c0), mulmod(/*coefficients[261]*/ mload(0x24e0), /*adjustments[17]*/mload(0x5a60), PRIME)), PRIME), PRIME) } { // Constraint expression for ecdsa/signature0/exponentiate_generator/bit_extraction_end: column20_row30. let val := /*column20_row30*/ mload(0x4660) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 8192) - trace_generator^(251 * trace_length / 256). // val *= denominator_invs[16]. val := mulmod(val, mload(0x5320), PRIME) // res += val * (coefficients[262] + coefficients[263] * adjustments[18]). res := addmod(res, mulmod(val, add(/*coefficients[262]*/ mload(0x2500), mulmod(/*coefficients[263]*/ mload(0x2520), /*adjustments[18]*/mload(0x5a80), PRIME)), PRIME), PRIME) } { // Constraint expression for ecdsa/signature0/exponentiate_generator/zeros_tail: column20_row30. let val := /*column20_row30*/ mload(0x4660) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 8192) - trace_generator^(255 * trace_length / 256). // val *= denominator_invs[17]. val := mulmod(val, mload(0x5340), PRIME) // res += val * (coefficients[264] + coefficients[265] * adjustments[18]). res := addmod(res, mulmod(val, add(/*coefficients[264]*/ mload(0x2540), mulmod(/*coefficients[265]*/ mload(0x2560), /*adjustments[18]*/mload(0x5a80), PRIME)), PRIME), PRIME) } { // Constraint expression for ecdsa/signature0/exponentiate_generator/add_points/slope: ecdsa__signature0__exponentiate_generator__bit_0 * (column20_row22 - ecdsa__generator_points__y) - column20_row14 * (column20_row6 - ecdsa__generator_points__x). let val := addmod( mulmod( /*intermediate_value/ecdsa/signature0/exponentiate_generator/bit_0*/ mload(0x4de0), addmod( /*column20_row22*/ mload(0x4620), sub(PRIME, /*periodic_column/ecdsa/generator_points/y*/ mload(0x60)), PRIME), PRIME), sub( PRIME, mulmod( /*column20_row14*/ mload(0x45a0), addmod( /*column20_row6*/ mload(0x4520), sub(PRIME, /*periodic_column/ecdsa/generator_points/x*/ mload(0x40)), PRIME), PRIME)), PRIME) // Numerator: point^(trace_length / 8192) - trace_generator^(255 * trace_length / 256). // val *= numerators[8]. val := mulmod(val, mload(0x57e0), PRIME) // Denominator: point^(trace_length / 32) - 1. // val *= denominator_invs[15]. val := mulmod(val, mload(0x5300), PRIME) // res += val * (coefficients[266] + coefficients[267] * adjustments[17]). res := addmod(res, mulmod(val, add(/*coefficients[266]*/ mload(0x2580), mulmod(/*coefficients[267]*/ mload(0x25a0), /*adjustments[17]*/mload(0x5a60), PRIME)), PRIME), PRIME) } { // Constraint expression for ecdsa/signature0/exponentiate_generator/add_points/x: column20_row14 * column20_row14 - ecdsa__signature0__exponentiate_generator__bit_0 * (column20_row6 + ecdsa__generator_points__x + column20_row38). let val := addmod( mulmod(/*column20_row14*/ mload(0x45a0), /*column20_row14*/ mload(0x45a0), PRIME), sub( PRIME, mulmod( /*intermediate_value/ecdsa/signature0/exponentiate_generator/bit_0*/ mload(0x4de0), addmod( addmod( /*column20_row6*/ mload(0x4520), /*periodic_column/ecdsa/generator_points/x*/ mload(0x40), PRIME), /*column20_row38*/ mload(0x4680), PRIME), PRIME)), PRIME) // Numerator: point^(trace_length / 8192) - trace_generator^(255 * trace_length / 256). // val *= numerators[8]. val := mulmod(val, mload(0x57e0), PRIME) // Denominator: point^(trace_length / 32) - 1. // val *= denominator_invs[15]. val := mulmod(val, mload(0x5300), PRIME) // res += val * (coefficients[268] + coefficients[269] * adjustments[17]). res := addmod(res, mulmod(val, add(/*coefficients[268]*/ mload(0x25c0), mulmod(/*coefficients[269]*/ mload(0x25e0), /*adjustments[17]*/mload(0x5a60), PRIME)), PRIME), PRIME) } { // Constraint expression for ecdsa/signature0/exponentiate_generator/add_points/y: ecdsa__signature0__exponentiate_generator__bit_0 * (column20_row22 + column20_row54) - column20_row14 * (column20_row6 - column20_row38). let val := addmod( mulmod( /*intermediate_value/ecdsa/signature0/exponentiate_generator/bit_0*/ mload(0x4de0), addmod(/*column20_row22*/ mload(0x4620), /*column20_row54*/ mload(0x46a0), PRIME), PRIME), sub( PRIME, mulmod( /*column20_row14*/ mload(0x45a0), addmod( /*column20_row6*/ mload(0x4520), sub(PRIME, /*column20_row38*/ mload(0x4680)), PRIME), PRIME)), PRIME) // Numerator: point^(trace_length / 8192) - trace_generator^(255 * trace_length / 256). // val *= numerators[8]. val := mulmod(val, mload(0x57e0), PRIME) // Denominator: point^(trace_length / 32) - 1. // val *= denominator_invs[15]. val := mulmod(val, mload(0x5300), PRIME) // res += val * (coefficients[270] + coefficients[271] * adjustments[17]). res := addmod(res, mulmod(val, add(/*coefficients[270]*/ mload(0x2600), mulmod(/*coefficients[271]*/ mload(0x2620), /*adjustments[17]*/mload(0x5a60), PRIME)), PRIME), PRIME) } { // Constraint expression for ecdsa/signature0/exponentiate_generator/add_points/x_diff_inv: column20_row1 * (column20_row6 - ecdsa__generator_points__x) - 1. let val := addmod( mulmod( /*column20_row1*/ mload(0x44c0), addmod( /*column20_row6*/ mload(0x4520), sub(PRIME, /*periodic_column/ecdsa/generator_points/x*/ mload(0x40)), PRIME), PRIME), sub(PRIME, 1), PRIME) // Numerator: point^(trace_length / 8192) - trace_generator^(255 * trace_length / 256). // val *= numerators[8]. val := mulmod(val, mload(0x57e0), PRIME) // Denominator: point^(trace_length / 32) - 1. // val *= denominator_invs[15]. val := mulmod(val, mload(0x5300), PRIME) // res += val * (coefficients[272] + coefficients[273] * adjustments[17]). res := addmod(res, mulmod(val, add(/*coefficients[272]*/ mload(0x2640), mulmod(/*coefficients[273]*/ mload(0x2660), /*adjustments[17]*/mload(0x5a60), PRIME)), PRIME), PRIME) } { // Constraint expression for ecdsa/signature0/exponentiate_generator/copy_point/x: ecdsa__signature0__exponentiate_generator__bit_neg_0 * (column20_row38 - column20_row6). let val := mulmod( /*intermediate_value/ecdsa/signature0/exponentiate_generator/bit_neg_0*/ mload(0x4e00), addmod( /*column20_row38*/ mload(0x4680), sub(PRIME, /*column20_row6*/ mload(0x4520)), PRIME), PRIME) // Numerator: point^(trace_length / 8192) - trace_generator^(255 * trace_length / 256). // val *= numerators[8]. val := mulmod(val, mload(0x57e0), PRIME) // Denominator: point^(trace_length / 32) - 1. // val *= denominator_invs[15]. val := mulmod(val, mload(0x5300), PRIME) // res += val * (coefficients[274] + coefficients[275] * adjustments[17]). res := addmod(res, mulmod(val, add(/*coefficients[274]*/ mload(0x2680), mulmod(/*coefficients[275]*/ mload(0x26a0), /*adjustments[17]*/mload(0x5a60), PRIME)), PRIME), PRIME) } { // Constraint expression for ecdsa/signature0/exponentiate_generator/copy_point/y: ecdsa__signature0__exponentiate_generator__bit_neg_0 * (column20_row54 - column20_row22). let val := mulmod( /*intermediate_value/ecdsa/signature0/exponentiate_generator/bit_neg_0*/ mload(0x4e00), addmod( /*column20_row54*/ mload(0x46a0), sub(PRIME, /*column20_row22*/ mload(0x4620)), PRIME), PRIME) // Numerator: point^(trace_length / 8192) - trace_generator^(255 * trace_length / 256). // val *= numerators[8]. val := mulmod(val, mload(0x57e0), PRIME) // Denominator: point^(trace_length / 32) - 1. // val *= denominator_invs[15]. val := mulmod(val, mload(0x5300), PRIME) // res += val * (coefficients[276] + coefficients[277] * adjustments[17]). res := addmod(res, mulmod(val, add(/*coefficients[276]*/ mload(0x26c0), mulmod(/*coefficients[277]*/ mload(0x26e0), /*adjustments[17]*/mload(0x5a60), PRIME)), PRIME), PRIME) } { // Constraint expression for ecdsa/signature0/exponentiate_key/booleanity_test: ecdsa__signature0__exponentiate_key__bit_0 * (ecdsa__signature0__exponentiate_key__bit_0 - 1). let val := mulmod( /*intermediate_value/ecdsa/signature0/exponentiate_key/bit_0*/ mload(0x4e20), addmod( /*intermediate_value/ecdsa/signature0/exponentiate_key/bit_0*/ mload(0x4e20), sub(PRIME, 1), PRIME), PRIME) // Numerator: point^(trace_length / 4096) - trace_generator^(255 * trace_length / 256). // val *= numerators[7]. val := mulmod(val, mload(0x57c0), PRIME) // Denominator: point^(trace_length / 16) - 1. // val *= denominator_invs[2]. val := mulmod(val, mload(0x5160), PRIME) // res += val * (coefficients[278] + coefficients[279] * adjustments[16]). res := addmod(res, mulmod(val, add(/*coefficients[278]*/ mload(0x2700), mulmod(/*coefficients[279]*/ mload(0x2720), /*adjustments[16]*/mload(0x5a40), PRIME)), PRIME), PRIME) } { // Constraint expression for ecdsa/signature0/exponentiate_key/bit_extraction_end: column20_row2. let val := /*column20_row2*/ mload(0x44e0) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 4096) - trace_generator^(251 * trace_length / 256). // val *= denominator_invs[18]. val := mulmod(val, mload(0x5360), PRIME) // res += val * (coefficients[280] + coefficients[281] * adjustments[19]). res := addmod(res, mulmod(val, add(/*coefficients[280]*/ mload(0x2740), mulmod(/*coefficients[281]*/ mload(0x2760), /*adjustments[19]*/mload(0x5aa0), PRIME)), PRIME), PRIME) } { // Constraint expression for ecdsa/signature0/exponentiate_key/zeros_tail: column20_row2. let val := /*column20_row2*/ mload(0x44e0) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 4096) - trace_generator^(255 * trace_length / 256). // val *= denominator_invs[19]. val := mulmod(val, mload(0x5380), PRIME) // res += val * (coefficients[282] + coefficients[283] * adjustments[19]). res := addmod(res, mulmod(val, add(/*coefficients[282]*/ mload(0x2780), mulmod(/*coefficients[283]*/ mload(0x27a0), /*adjustments[19]*/mload(0x5aa0), PRIME)), PRIME), PRIME) } { // Constraint expression for ecdsa/signature0/exponentiate_key/add_points/slope: ecdsa__signature0__exponentiate_key__bit_0 * (column20_row4 - column19_row15) - column20_row12 * (column20_row8 - column19_row7). let val := addmod( mulmod( /*intermediate_value/ecdsa/signature0/exponentiate_key/bit_0*/ mload(0x4e20), addmod( /*column20_row4*/ mload(0x4500), sub(PRIME, /*column19_row15*/ mload(0x42e0)), PRIME), PRIME), sub( PRIME, mulmod( /*column20_row12*/ mload(0x4580), addmod(/*column20_row8*/ mload(0x4540), sub(PRIME, /*column19_row7*/ mload(0x4220)), PRIME), PRIME)), PRIME) // Numerator: point^(trace_length / 4096) - trace_generator^(255 * trace_length / 256). // val *= numerators[7]. val := mulmod(val, mload(0x57c0), PRIME) // Denominator: point^(trace_length / 16) - 1. // val *= denominator_invs[2]. val := mulmod(val, mload(0x5160), PRIME) // res += val * (coefficients[284] + coefficients[285] * adjustments[16]). res := addmod(res, mulmod(val, add(/*coefficients[284]*/ mload(0x27c0), mulmod(/*coefficients[285]*/ mload(0x27e0), /*adjustments[16]*/mload(0x5a40), PRIME)), PRIME), PRIME) } { // Constraint expression for ecdsa/signature0/exponentiate_key/add_points/x: column20_row12 * column20_row12 - ecdsa__signature0__exponentiate_key__bit_0 * (column20_row8 + column19_row7 + column20_row24). let val := addmod( mulmod(/*column20_row12*/ mload(0x4580), /*column20_row12*/ mload(0x4580), PRIME), sub( PRIME, mulmod( /*intermediate_value/ecdsa/signature0/exponentiate_key/bit_0*/ mload(0x4e20), addmod( addmod(/*column20_row8*/ mload(0x4540), /*column19_row7*/ mload(0x4220), PRIME), /*column20_row24*/ mload(0x4640), PRIME), PRIME)), PRIME) // Numerator: point^(trace_length / 4096) - trace_generator^(255 * trace_length / 256). // val *= numerators[7]. val := mulmod(val, mload(0x57c0), PRIME) // Denominator: point^(trace_length / 16) - 1. // val *= denominator_invs[2]. val := mulmod(val, mload(0x5160), PRIME) // res += val * (coefficients[286] + coefficients[287] * adjustments[16]). res := addmod(res, mulmod(val, add(/*coefficients[286]*/ mload(0x2800), mulmod(/*coefficients[287]*/ mload(0x2820), /*adjustments[16]*/mload(0x5a40), PRIME)), PRIME), PRIME) } { // Constraint expression for ecdsa/signature0/exponentiate_key/add_points/y: ecdsa__signature0__exponentiate_key__bit_0 * (column20_row4 + column20_row20) - column20_row12 * (column20_row8 - column20_row24). let val := addmod( mulmod( /*intermediate_value/ecdsa/signature0/exponentiate_key/bit_0*/ mload(0x4e20), addmod(/*column20_row4*/ mload(0x4500), /*column20_row20*/ mload(0x4600), PRIME), PRIME), sub( PRIME, mulmod( /*column20_row12*/ mload(0x4580), addmod( /*column20_row8*/ mload(0x4540), sub(PRIME, /*column20_row24*/ mload(0x4640)), PRIME), PRIME)), PRIME) // Numerator: point^(trace_length / 4096) - trace_generator^(255 * trace_length / 256). // val *= numerators[7]. val := mulmod(val, mload(0x57c0), PRIME) // Denominator: point^(trace_length / 16) - 1. // val *= denominator_invs[2]. val := mulmod(val, mload(0x5160), PRIME) // res += val * (coefficients[288] + coefficients[289] * adjustments[16]). res := addmod(res, mulmod(val, add(/*coefficients[288]*/ mload(0x2840), mulmod(/*coefficients[289]*/ mload(0x2860), /*adjustments[16]*/mload(0x5a40), PRIME)), PRIME), PRIME) } { // Constraint expression for ecdsa/signature0/exponentiate_key/add_points/x_diff_inv: column20_row10 * (column20_row8 - column19_row7) - 1. let val := addmod( mulmod( /*column20_row10*/ mload(0x4560), addmod(/*column20_row8*/ mload(0x4540), sub(PRIME, /*column19_row7*/ mload(0x4220)), PRIME), PRIME), sub(PRIME, 1), PRIME) // Numerator: point^(trace_length / 4096) - trace_generator^(255 * trace_length / 256). // val *= numerators[7]. val := mulmod(val, mload(0x57c0), PRIME) // Denominator: point^(trace_length / 16) - 1. // val *= denominator_invs[2]. val := mulmod(val, mload(0x5160), PRIME) // res += val * (coefficients[290] + coefficients[291] * adjustments[16]). res := addmod(res, mulmod(val, add(/*coefficients[290]*/ mload(0x2880), mulmod(/*coefficients[291]*/ mload(0x28a0), /*adjustments[16]*/mload(0x5a40), PRIME)), PRIME), PRIME) } { // Constraint expression for ecdsa/signature0/exponentiate_key/copy_point/x: ecdsa__signature0__exponentiate_key__bit_neg_0 * (column20_row24 - column20_row8). let val := mulmod( /*intermediate_value/ecdsa/signature0/exponentiate_key/bit_neg_0*/ mload(0x4e40), addmod( /*column20_row24*/ mload(0x4640), sub(PRIME, /*column20_row8*/ mload(0x4540)), PRIME), PRIME) // Numerator: point^(trace_length / 4096) - trace_generator^(255 * trace_length / 256). // val *= numerators[7]. val := mulmod(val, mload(0x57c0), PRIME) // Denominator: point^(trace_length / 16) - 1. // val *= denominator_invs[2]. val := mulmod(val, mload(0x5160), PRIME) // res += val * (coefficients[292] + coefficients[293] * adjustments[16]). res := addmod(res, mulmod(val, add(/*coefficients[292]*/ mload(0x28c0), mulmod(/*coefficients[293]*/ mload(0x28e0), /*adjustments[16]*/mload(0x5a40), PRIME)), PRIME), PRIME) } { // Constraint expression for ecdsa/signature0/exponentiate_key/copy_point/y: ecdsa__signature0__exponentiate_key__bit_neg_0 * (column20_row20 - column20_row4). let val := mulmod( /*intermediate_value/ecdsa/signature0/exponentiate_key/bit_neg_0*/ mload(0x4e40), addmod( /*column20_row20*/ mload(0x4600), sub(PRIME, /*column20_row4*/ mload(0x4500)), PRIME), PRIME) // Numerator: point^(trace_length / 4096) - trace_generator^(255 * trace_length / 256). // val *= numerators[7]. val := mulmod(val, mload(0x57c0), PRIME) // Denominator: point^(trace_length / 16) - 1. // val *= denominator_invs[2]. val := mulmod(val, mload(0x5160), PRIME) // res += val * (coefficients[294] + coefficients[295] * adjustments[16]). res := addmod(res, mulmod(val, add(/*coefficients[294]*/ mload(0x2900), mulmod(/*coefficients[295]*/ mload(0x2920), /*adjustments[16]*/mload(0x5a40), PRIME)), PRIME), PRIME) } { // Constraint expression for ecdsa/signature0/init_gen/x: column20_row6 - ecdsa/sig_config.shift_point.x. let val := addmod( /*column20_row6*/ mload(0x4520), sub(PRIME, /*ecdsa/sig_config.shift_point.x*/ mload(0x2e0)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 8192) - 1. // val *= denominator_invs[20]. val := mulmod(val, mload(0x53a0), PRIME) // res += val * (coefficients[296] + coefficients[297] * adjustments[18]). res := addmod(res, mulmod(val, add(/*coefficients[296]*/ mload(0x2940), mulmod(/*coefficients[297]*/ mload(0x2960), /*adjustments[18]*/mload(0x5a80), PRIME)), PRIME), PRIME) } { // Constraint expression for ecdsa/signature0/init_gen/y: column20_row22 + ecdsa/sig_config.shift_point.y. let val := addmod( /*column20_row22*/ mload(0x4620), /*ecdsa/sig_config.shift_point.y*/ mload(0x300), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 8192) - 1. // val *= denominator_invs[20]. val := mulmod(val, mload(0x53a0), PRIME) // res += val * (coefficients[298] + coefficients[299] * adjustments[18]). res := addmod(res, mulmod(val, add(/*coefficients[298]*/ mload(0x2980), mulmod(/*coefficients[299]*/ mload(0x29a0), /*adjustments[18]*/mload(0x5a80), PRIME)), PRIME), PRIME) } { // Constraint expression for ecdsa/signature0/init_key/x: column20_row8 - ecdsa/sig_config.shift_point.x. let val := addmod( /*column20_row8*/ mload(0x4540), sub(PRIME, /*ecdsa/sig_config.shift_point.x*/ mload(0x2e0)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 4096) - 1. // val *= denominator_invs[21]. val := mulmod(val, mload(0x53c0), PRIME) // res += val * (coefficients[300] + coefficients[301] * adjustments[19]). res := addmod(res, mulmod(val, add(/*coefficients[300]*/ mload(0x29c0), mulmod(/*coefficients[301]*/ mload(0x29e0), /*adjustments[19]*/mload(0x5aa0), PRIME)), PRIME), PRIME) } { // Constraint expression for ecdsa/signature0/init_key/y: column20_row4 - ecdsa/sig_config.shift_point.y. let val := addmod( /*column20_row4*/ mload(0x4500), sub(PRIME, /*ecdsa/sig_config.shift_point.y*/ mload(0x300)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 4096) - 1. // val *= denominator_invs[21]. val := mulmod(val, mload(0x53c0), PRIME) // res += val * (coefficients[302] + coefficients[303] * adjustments[19]). res := addmod(res, mulmod(val, add(/*coefficients[302]*/ mload(0x2a00), mulmod(/*coefficients[303]*/ mload(0x2a20), /*adjustments[19]*/mload(0x5aa0), PRIME)), PRIME), PRIME) } { // Constraint expression for ecdsa/signature0/add_results/slope: column20_row8182 - (column20_row4084 + column20_row8161 * (column20_row8166 - column20_row4088)). let val := addmod( /*column20_row8182*/ mload(0x4880), sub( PRIME, addmod( /*column20_row4084*/ mload(0x4760), mulmod( /*column20_row8161*/ mload(0x47e0), addmod( /*column20_row8166*/ mload(0x4800), sub(PRIME, /*column20_row4088*/ mload(0x4780)), PRIME), PRIME), PRIME)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 8192) - 1. // val *= denominator_invs[20]. val := mulmod(val, mload(0x53a0), PRIME) // res += val * (coefficients[304] + coefficients[305] * adjustments[20]). res := addmod(res, mulmod(val, add(/*coefficients[304]*/ mload(0x2a40), mulmod(/*coefficients[305]*/ mload(0x2a60), /*adjustments[20]*/mload(0x5ac0), PRIME)), PRIME), PRIME) } { // Constraint expression for ecdsa/signature0/add_results/x: column20_row8161 * column20_row8161 - (column20_row8166 + column20_row4088 + column19_row4103). let val := addmod( mulmod(/*column20_row8161*/ mload(0x47e0), /*column20_row8161*/ mload(0x47e0), PRIME), sub( PRIME, addmod( addmod(/*column20_row8166*/ mload(0x4800), /*column20_row4088*/ mload(0x4780), PRIME), /*column19_row4103*/ mload(0x4460), PRIME)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 8192) - 1. // val *= denominator_invs[20]. val := mulmod(val, mload(0x53a0), PRIME) // res += val * (coefficients[306] + coefficients[307] * adjustments[20]). res := addmod(res, mulmod(val, add(/*coefficients[306]*/ mload(0x2a80), mulmod(/*coefficients[307]*/ mload(0x2aa0), /*adjustments[20]*/mload(0x5ac0), PRIME)), PRIME), PRIME) } { // Constraint expression for ecdsa/signature0/add_results/y: column20_row8182 + column19_row4111 - column20_row8161 * (column20_row8166 - column19_row4103). let val := addmod( addmod(/*column20_row8182*/ mload(0x4880), /*column19_row4111*/ mload(0x4480), PRIME), sub( PRIME, mulmod( /*column20_row8161*/ mload(0x47e0), addmod( /*column20_row8166*/ mload(0x4800), sub(PRIME, /*column19_row4103*/ mload(0x4460)), PRIME), PRIME)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 8192) - 1. // val *= denominator_invs[20]. val := mulmod(val, mload(0x53a0), PRIME) // res += val * (coefficients[308] + coefficients[309] * adjustments[20]). res := addmod(res, mulmod(val, add(/*coefficients[308]*/ mload(0x2ac0), mulmod(/*coefficients[309]*/ mload(0x2ae0), /*adjustments[20]*/mload(0x5ac0), PRIME)), PRIME), PRIME) } { // Constraint expression for ecdsa/signature0/add_results/x_diff_inv: column20_row8174 * (column20_row8166 - column20_row4088) - 1. let val := addmod( mulmod( /*column20_row8174*/ mload(0x4820), addmod( /*column20_row8166*/ mload(0x4800), sub(PRIME, /*column20_row4088*/ mload(0x4780)), PRIME), PRIME), sub(PRIME, 1), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 8192) - 1. // val *= denominator_invs[20]. val := mulmod(val, mload(0x53a0), PRIME) // res += val * (coefficients[310] + coefficients[311] * adjustments[20]). res := addmod(res, mulmod(val, add(/*coefficients[310]*/ mload(0x2b00), mulmod(/*coefficients[311]*/ mload(0x2b20), /*adjustments[20]*/mload(0x5ac0), PRIME)), PRIME), PRIME) } { // Constraint expression for ecdsa/signature0/extract_r/slope: column20_row8180 + ecdsa/sig_config.shift_point.y - column20_row4092 * (column20_row8184 - ecdsa/sig_config.shift_point.x). let val := addmod( addmod( /*column20_row8180*/ mload(0x4860), /*ecdsa/sig_config.shift_point.y*/ mload(0x300), PRIME), sub( PRIME, mulmod( /*column20_row4092*/ mload(0x47c0), addmod( /*column20_row8184*/ mload(0x48a0), sub(PRIME, /*ecdsa/sig_config.shift_point.x*/ mload(0x2e0)), PRIME), PRIME)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 8192) - 1. // val *= denominator_invs[20]. val := mulmod(val, mload(0x53a0), PRIME) // res += val * (coefficients[312] + coefficients[313] * adjustments[20]). res := addmod(res, mulmod(val, add(/*coefficients[312]*/ mload(0x2b40), mulmod(/*coefficients[313]*/ mload(0x2b60), /*adjustments[20]*/mload(0x5ac0), PRIME)), PRIME), PRIME) } { // Constraint expression for ecdsa/signature0/extract_r/x: column20_row4092 * column20_row4092 - (column20_row8184 + ecdsa/sig_config.shift_point.x + column20_row2). let val := addmod( mulmod(/*column20_row4092*/ mload(0x47c0), /*column20_row4092*/ mload(0x47c0), PRIME), sub( PRIME, addmod( addmod( /*column20_row8184*/ mload(0x48a0), /*ecdsa/sig_config.shift_point.x*/ mload(0x2e0), PRIME), /*column20_row2*/ mload(0x44e0), PRIME)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 8192) - 1. // val *= denominator_invs[20]. val := mulmod(val, mload(0x53a0), PRIME) // res += val * (coefficients[314] + coefficients[315] * adjustments[20]). res := addmod(res, mulmod(val, add(/*coefficients[314]*/ mload(0x2b80), mulmod(/*coefficients[315]*/ mload(0x2ba0), /*adjustments[20]*/mload(0x5ac0), PRIME)), PRIME), PRIME) } { // Constraint expression for ecdsa/signature0/extract_r/x_diff_inv: column20_row8188 * (column20_row8184 - ecdsa/sig_config.shift_point.x) - 1. let val := addmod( mulmod( /*column20_row8188*/ mload(0x48c0), addmod( /*column20_row8184*/ mload(0x48a0), sub(PRIME, /*ecdsa/sig_config.shift_point.x*/ mload(0x2e0)), PRIME), PRIME), sub(PRIME, 1), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 8192) - 1. // val *= denominator_invs[20]. val := mulmod(val, mload(0x53a0), PRIME) // res += val * (coefficients[316] + coefficients[317] * adjustments[20]). res := addmod(res, mulmod(val, add(/*coefficients[316]*/ mload(0x2bc0), mulmod(/*coefficients[317]*/ mload(0x2be0), /*adjustments[20]*/mload(0x5ac0), PRIME)), PRIME), PRIME) } { // Constraint expression for ecdsa/signature0/z_nonzero: column20_row30 * column20_row4080 - 1. let val := addmod( mulmod(/*column20_row30*/ mload(0x4660), /*column20_row4080*/ mload(0x4740), PRIME), sub(PRIME, 1), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 8192) - 1. // val *= denominator_invs[20]. val := mulmod(val, mload(0x53a0), PRIME) // res += val * (coefficients[318] + coefficients[319] * adjustments[20]). res := addmod(res, mulmod(val, add(/*coefficients[318]*/ mload(0x2c00), mulmod(/*coefficients[319]*/ mload(0x2c20), /*adjustments[20]*/mload(0x5ac0), PRIME)), PRIME), PRIME) } { // Constraint expression for ecdsa/signature0/r_and_w_nonzero: column20_row2 * column20_row4090 - 1. let val := addmod( mulmod(/*column20_row2*/ mload(0x44e0), /*column20_row4090*/ mload(0x47a0), PRIME), sub(PRIME, 1), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 4096) - 1. // val *= denominator_invs[21]. val := mulmod(val, mload(0x53c0), PRIME) // res += val * (coefficients[320] + coefficients[321] * adjustments[21]). res := addmod(res, mulmod(val, add(/*coefficients[320]*/ mload(0x2c40), mulmod(/*coefficients[321]*/ mload(0x2c60), /*adjustments[21]*/mload(0x5ae0), PRIME)), PRIME), PRIME) } { // Constraint expression for ecdsa/signature0/q_on_curve/x_squared: column20_row8176 - column19_row7 * column19_row7. let val := addmod( /*column20_row8176*/ mload(0x4840), sub( PRIME, mulmod(/*column19_row7*/ mload(0x4220), /*column19_row7*/ mload(0x4220), PRIME)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 8192) - 1. // val *= denominator_invs[20]. val := mulmod(val, mload(0x53a0), PRIME) // res += val * (coefficients[322] + coefficients[323] * adjustments[20]). res := addmod(res, mulmod(val, add(/*coefficients[322]*/ mload(0x2c80), mulmod(/*coefficients[323]*/ mload(0x2ca0), /*adjustments[20]*/mload(0x5ac0), PRIME)), PRIME), PRIME) } { // Constraint expression for ecdsa/signature0/q_on_curve/on_curve: column19_row15 * column19_row15 - (column19_row7 * column20_row8176 + ecdsa/sig_config.alpha * column19_row7 + ecdsa/sig_config.beta). let val := addmod( mulmod(/*column19_row15*/ mload(0x42e0), /*column19_row15*/ mload(0x42e0), PRIME), sub( PRIME, addmod( addmod( mulmod(/*column19_row7*/ mload(0x4220), /*column20_row8176*/ mload(0x4840), PRIME), mulmod(/*ecdsa/sig_config.alpha*/ mload(0x2c0), /*column19_row7*/ mload(0x4220), PRIME), PRIME), /*ecdsa/sig_config.beta*/ mload(0x320), PRIME)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 8192) - 1. // val *= denominator_invs[20]. val := mulmod(val, mload(0x53a0), PRIME) // res += val * (coefficients[324] + coefficients[325] * adjustments[20]). res := addmod(res, mulmod(val, add(/*coefficients[324]*/ mload(0x2cc0), mulmod(/*coefficients[325]*/ mload(0x2ce0), /*adjustments[20]*/mload(0x5ac0), PRIME)), PRIME), PRIME) } { // Constraint expression for ecdsa/init_addr: column17_row22 - initial_ecdsa_addr. let val := addmod( /*column17_row22*/ mload(0x3d60), sub(PRIME, /*initial_ecdsa_addr*/ mload(0x340)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point - 1. // val *= denominator_invs[3]. val := mulmod(val, mload(0x5180), PRIME) // res += val * (coefficients[326] + coefficients[327] * adjustments[4]). res := addmod(res, mulmod(val, add(/*coefficients[326]*/ mload(0x2d00), mulmod(/*coefficients[327]*/ mload(0x2d20), /*adjustments[4]*/mload(0x58c0), PRIME)), PRIME), PRIME) } { // Constraint expression for ecdsa/message_addr: column17_row4118 - (column17_row22 + 1). let val := addmod( /*column17_row4118*/ mload(0x4060), sub(PRIME, addmod(/*column17_row22*/ mload(0x3d60), 1, PRIME)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 8192) - 1. // val *= denominator_invs[20]. val := mulmod(val, mload(0x53a0), PRIME) // res += val * (coefficients[328] + coefficients[329] * adjustments[18]). res := addmod(res, mulmod(val, add(/*coefficients[328]*/ mload(0x2d40), mulmod(/*coefficients[329]*/ mload(0x2d60), /*adjustments[18]*/mload(0x5a80), PRIME)), PRIME), PRIME) } { // Constraint expression for ecdsa/pubkey_addr: column17_row8214 - (column17_row4118 + 1). let val := addmod( /*column17_row8214*/ mload(0x40a0), sub(PRIME, addmod(/*column17_row4118*/ mload(0x4060), 1, PRIME)), PRIME) // Numerator: point - trace_generator^(8192 * (trace_length / 8192 - 1)). // val *= numerators[9]. val := mulmod(val, mload(0x5800), PRIME) // Denominator: point^(trace_length / 8192) - 1. // val *= denominator_invs[20]. val := mulmod(val, mload(0x53a0), PRIME) // res += val * (coefficients[330] + coefficients[331] * adjustments[22]). res := addmod(res, mulmod(val, add(/*coefficients[330]*/ mload(0x2d80), mulmod(/*coefficients[331]*/ mload(0x2da0), /*adjustments[22]*/mload(0x5b00), PRIME)), PRIME), PRIME) } { // Constraint expression for ecdsa/message_value0: column17_row4119 - column20_row30. let val := addmod( /*column17_row4119*/ mload(0x4080), sub(PRIME, /*column20_row30*/ mload(0x4660)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 8192) - 1. // val *= denominator_invs[20]. val := mulmod(val, mload(0x53a0), PRIME) // res += val * (coefficients[332] + coefficients[333] * adjustments[18]). res := addmod(res, mulmod(val, add(/*coefficients[332]*/ mload(0x2dc0), mulmod(/*coefficients[333]*/ mload(0x2de0), /*adjustments[18]*/mload(0x5a80), PRIME)), PRIME), PRIME) } { // Constraint expression for ecdsa/pubkey_value0: column17_row23 - column19_row7. let val := addmod( /*column17_row23*/ mload(0x3d80), sub(PRIME, /*column19_row7*/ mload(0x4220)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 8192) - 1. // val *= denominator_invs[20]. val := mulmod(val, mload(0x53a0), PRIME) // res += val * (coefficients[334] + coefficients[335] * adjustments[18]). res := addmod(res, mulmod(val, add(/*coefficients[334]*/ mload(0x2e00), mulmod(/*coefficients[335]*/ mload(0x2e20), /*adjustments[18]*/mload(0x5a80), PRIME)), PRIME), PRIME) } { // Constraint expression for checkpoints/req_pc_init_addr: column17_row150 - initial_checkpoints_addr. let val := addmod( /*column17_row150*/ mload(0x3ee0), sub(PRIME, /*initial_checkpoints_addr*/ mload(0x360)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point - 1. // val *= denominator_invs[3]. val := mulmod(val, mload(0x5180), PRIME) // res += val * (coefficients[336] + coefficients[337] * adjustments[4]). res := addmod(res, mulmod(val, add(/*coefficients[336]*/ mload(0x2e40), mulmod(/*coefficients[337]*/ mload(0x2e60), /*adjustments[4]*/mload(0x58c0), PRIME)), PRIME), PRIME) } { // Constraint expression for checkpoints/req_pc_final_addr: column17_row150 - final_checkpoints_addr. let val := addmod( /*column17_row150*/ mload(0x3ee0), sub(PRIME, /*final_checkpoints_addr*/ mload(0x380)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point - trace_generator^(256 * (trace_length / 256 - 1)). // val *= denominator_invs[22]. val := mulmod(val, mload(0x53e0), PRIME) // res += val * (coefficients[338] + coefficients[339] * adjustments[4]). res := addmod(res, mulmod(val, add(/*coefficients[338]*/ mload(0x2e80), mulmod(/*coefficients[339]*/ mload(0x2ea0), /*adjustments[4]*/mload(0x58c0), PRIME)), PRIME), PRIME) } { // Constraint expression for checkpoints/required_fp_addr: column17_row86 - (column17_row150 + 1). let val := addmod( /*column17_row86*/ mload(0x3e20), sub(PRIME, addmod(/*column17_row150*/ mload(0x3ee0), 1, PRIME)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 256) - 1. // val *= denominator_invs[10]. val := mulmod(val, mload(0x5260), PRIME) // res += val * (coefficients[340] + coefficients[341] * adjustments[11]). res := addmod(res, mulmod(val, add(/*coefficients[340]*/ mload(0x2ec0), mulmod(/*coefficients[341]*/ mload(0x2ee0), /*adjustments[11]*/mload(0x59a0), PRIME)), PRIME), PRIME) } { // Constraint expression for checkpoints/required_pc_next_addr: (column17_row406 - column17_row150) * (column17_row406 - (column17_row150 + 2)). let val := mulmod( addmod( /*column17_row406*/ mload(0x4000), sub(PRIME, /*column17_row150*/ mload(0x3ee0)), PRIME), addmod( /*column17_row406*/ mload(0x4000), sub(PRIME, addmod(/*column17_row150*/ mload(0x3ee0), 2, PRIME)), PRIME), PRIME) // Numerator: point - trace_generator^(256 * (trace_length / 256 - 1)). // val *= numerators[10]. val := mulmod(val, mload(0x5820), PRIME) // Denominator: point^(trace_length / 256) - 1. // val *= denominator_invs[10]. val := mulmod(val, mload(0x5260), PRIME) // res += val * (coefficients[342] + coefficients[343] * adjustments[23]). res := addmod(res, mulmod(val, add(/*coefficients[342]*/ mload(0x2f00), mulmod(/*coefficients[343]*/ mload(0x2f20), /*adjustments[23]*/mload(0x5b20), PRIME)), PRIME), PRIME) } { // Constraint expression for checkpoints/req_pc: (column17_row406 - column17_row150) * (column17_row151 - column17_row0). let val := mulmod( addmod( /*column17_row406*/ mload(0x4000), sub(PRIME, /*column17_row150*/ mload(0x3ee0)), PRIME), addmod( /*column17_row151*/ mload(0x3f00), sub(PRIME, /*column17_row0*/ mload(0x3bc0)), PRIME), PRIME) // Numerator: point - trace_generator^(256 * (trace_length / 256 - 1)). // val *= numerators[10]. val := mulmod(val, mload(0x5820), PRIME) // Denominator: point^(trace_length / 256) - 1. // val *= denominator_invs[10]. val := mulmod(val, mload(0x5260), PRIME) // res += val * (coefficients[344] + coefficients[345] * adjustments[23]). res := addmod(res, mulmod(val, add(/*coefficients[344]*/ mload(0x2f40), mulmod(/*coefficients[345]*/ mload(0x2f60), /*adjustments[23]*/mload(0x5b20), PRIME)), PRIME), PRIME) } { // Constraint expression for checkpoints/req_fp: (column17_row406 - column17_row150) * (column17_row87 - column19_row9). let val := mulmod( addmod( /*column17_row406*/ mload(0x4000), sub(PRIME, /*column17_row150*/ mload(0x3ee0)), PRIME), addmod( /*column17_row87*/ mload(0x3e40), sub(PRIME, /*column19_row9*/ mload(0x4260)), PRIME), PRIME) // Numerator: point - trace_generator^(256 * (trace_length / 256 - 1)). // val *= numerators[10]. val := mulmod(val, mload(0x5820), PRIME) // Denominator: point^(trace_length / 256) - 1. // val *= denominator_invs[10]. val := mulmod(val, mload(0x5260), PRIME) // res += val * (coefficients[346] + coefficients[347] * adjustments[23]). res := addmod(res, mulmod(val, add(/*coefficients[346]*/ mload(0x2f80), mulmod(/*coefficients[347]*/ mload(0x2fa0), /*adjustments[23]*/mload(0x5b20), PRIME)), PRIME), PRIME) } mstore(0, res) return(0, 0x20) } } } } // ---------- End of auto-generated code. ----------
Compute the result of the composition polynomial. cpu/decode/opcode_rc/bit_0 = column0_row0 - (column0_row1 + column0_row1). cpu/decode/opcode_rc/bit_1 = column0_row1 - (column0_row2 + column0_row2). cpu/decode/opcode_rc/bit_2 = column0_row2 - (column0_row3 + column0_row3). cpu/decode/opcode_rc/bit_4 = column0_row4 - (column0_row5 + column0_row5). cpu/decode/opcode_rc/bit_3 = column0_row3 - (column0_row4 + column0_row4). cpu/decode/opcode_rc/bit_9 = column0_row9 - (column0_row10 + column0_row10). cpu/decode/opcode_rc/bit_5 = column0_row5 - (column0_row6 + column0_row6). cpu/decode/opcode_rc/bit_6 = column0_row6 - (column0_row7 + column0_row7). cpu/decode/opcode_rc/bit_7 = column0_row7 - (column0_row8 + column0_row8). cpu/decode/opcode_rc/bit_8 = column0_row8 - (column0_row9 + column0_row9). npc_reg_0 = column17_row0 + cpu__decode__opcode_rc__bit_2 + 1. cpu/decode/opcode_rc/bit_10 = column0_row10 - (column0_row11 + column0_row11). cpu/decode/opcode_rc/bit_11 = column0_row11 - (column0_row12 + column0_row12). cpu/decode/opcode_rc/bit_12 = column0_row12 - (column0_row13 + column0_row13). cpu/decode/opcode_rc/bit_13 = column0_row13 - (column0_row14 + column0_row14). cpu/decode/opcode_rc/bit_14 = column0_row14 - (column0_row15 + column0_row15). memory/address_diff_0 = column18_row2 - column18_row0. rc16/diff_0 = column19_row6 - column19_row2. pedersen/hash0/ec_subset_sum/bit_0 = column4_row0 - (column4_row1 + column4_row1). pedersen/hash0/ec_subset_sum/bit_neg_0 = 1 - pedersen__hash0__ec_subset_sum__bit_0. pedersen/hash1/ec_subset_sum/bit_0 = column8_row0 - (column8_row1 + column8_row1). pedersen/hash1/ec_subset_sum/bit_neg_0 = 1 - pedersen__hash1__ec_subset_sum__bit_0. pedersen/hash2/ec_subset_sum/bit_0 = column12_row0 - (column12_row1 + column12_row1). pedersen/hash2/ec_subset_sum/bit_neg_0 = 1 - pedersen__hash2__ec_subset_sum__bit_0. pedersen/hash3/ec_subset_sum/bit_0 = column16_row0 - (column16_row1 + column16_row1). pedersen/hash3/ec_subset_sum/bit_neg_0 = 1 - pedersen__hash3__ec_subset_sum__bit_0. rc_builtin/value0_0 = column19_row12. rc_builtin/value1_0 = rc_builtin__value0_0 * offset_size + column19_row28. rc_builtin/value2_0 = rc_builtin__value1_0 * offset_size + column19_row44. rc_builtin/value3_0 = rc_builtin__value2_0 * offset_size + column19_row60. rc_builtin/value4_0 = rc_builtin__value3_0 * offset_size + column19_row76. rc_builtin/value5_0 = rc_builtin__value4_0 * offset_size + column19_row92. rc_builtin/value6_0 = rc_builtin__value5_0 * offset_size + column19_row108. rc_builtin/value7_0 = rc_builtin__value6_0 * offset_size + column19_row124. ecdsa/signature0/doubling_key/x_squared = column19_row7 * column19_row7. ecdsa/signature0/exponentiate_generator/bit_0 = column20_row30 - (column20_row62 + column20_row62). ecdsa/signature0/exponentiate_generator/bit_neg_0 = 1 - ecdsa__signature0__exponentiate_generator__bit_0. ecdsa/signature0/exponentiate_key/bit_0 = column20_row2 - (column20_row18 + column20_row18). ecdsa/signature0/exponentiate_key/bit_neg_0 = 1 - ecdsa__signature0__exponentiate_key__bit_0. Constraint expression for cpu/decode/opcode_rc/bit: cpu__decode__opcode_rc__bit_0 * cpu__decode__opcode_rc__bit_0 - cpu__decode__opcode_rc__bit_0. Numerator: point^(trace_length / 16) - trace_generator^(15 * trace_length / 16). val *= numerators[0]. Denominator: point^trace_length - 1. val *= denominator_invs[0]. res += val * (coefficients[0] + coefficients[1] * adjustments[0]). Constraint expression for cpu/decode/opcode_rc/zero: column0_row0. Numerator: 1. val *= 1. val := mulmod(val, 1, PRIME). Denominator: point^(trace_length / 16) - trace_generator^(15 * trace_length / 16). val *= denominator_invs[1]. res += val * (coefficients[2] + coefficients[3] * adjustments[1]). Constraint expression for cpu/decode/opcode_rc_input: column17_row1 - (((column0_row0 * offset_size + column19_row4) * offset_size + column19_row8) * offset_size + column19_row0). Numerator: 1. val *= 1. val := mulmod(val, 1, PRIME). Denominator: point^(trace_length / 16) - 1. val *= denominator_invs[2]. res += val * (coefficients[4] + coefficients[5] * adjustments[1]). Constraint expression for cpu/operands/mem_dst_addr: column17_row8 + half_offset_size - (cpu__decode__opcode_rc__bit_0 * column19_row9 + (1 - cpu__decode__opcode_rc__bit_0) * column19_row1 + column19_row0). Numerator: 1. val *= 1. val := mulmod(val, 1, PRIME). Denominator: point^(trace_length / 16) - 1. val *= denominator_invs[2]. res += val * (coefficients[6] + coefficients[7] * adjustments[2]). Constraint expression for cpu/operands/mem0_addr: column17_row4 + half_offset_size - (cpu__decode__opcode_rc__bit_1 * column19_row9 + (1 - cpu__decode__opcode_rc__bit_1) * column19_row1 + column19_row8). Numerator: 1. val *= 1. val := mulmod(val, 1, PRIME). Denominator: point^(trace_length / 16) - 1. val *= denominator_invs[2]. res += val * (coefficients[8] + coefficients[9] * adjustments[2]). Constraint expression for cpu/operands/mem1_addr: column17_row12 + half_offset_size - (cpu__decode__opcode_rc__bit_2 * column17_row0 + cpu__decode__opcode_rc__bit_4 * column19_row1 + cpu__decode__opcode_rc__bit_3 * column19_row9 + (1 - (cpu__decode__opcode_rc__bit_2 + cpu__decode__opcode_rc__bit_4 + cpu__decode__opcode_rc__bit_3)) * column17_row5 + column19_row4). Numerator: 1. val *= 1. val := mulmod(val, 1, PRIME). Denominator: point^(trace_length / 16) - 1. val *= denominator_invs[2]. res += val * (coefficients[10] + coefficients[11] * adjustments[2]). Constraint expression for cpu/operands/ops_mul: column19_row5 - column17_row5 * column17_row13. Numerator: 1. val *= 1. val := mulmod(val, 1, PRIME). Denominator: point^(trace_length / 16) - 1. val *= denominator_invs[2]. res += val * (coefficients[12] + coefficients[13] * adjustments[2]). Constraint expression for cpu/operands/res: (1 - cpu__decode__opcode_rc__bit_9) * column19_row13 - (cpu__decode__opcode_rc__bit_5 * (column17_row5 + column17_row13) + cpu__decode__opcode_rc__bit_6 * column19_row5 + (1 - (cpu__decode__opcode_rc__bit_5 + cpu__decode__opcode_rc__bit_6 + cpu__decode__opcode_rc__bit_9)) * column17_row13). Numerator: 1. val *= 1. val := mulmod(val, 1, PRIME). Denominator: point^(trace_length / 16) - 1. val *= denominator_invs[2]. res += val * (coefficients[14] + coefficients[15] * adjustments[2]). Constraint expression for cpu/update_registers/update_pc/tmp0: column19_row3 - cpu__decode__opcode_rc__bit_9 * column17_row9. Numerator: point - trace_generator^(16 * (trace_length / 16 - 1)). val *= numerators[1]. Denominator: point^(trace_length / 16) - 1. val *= denominator_invs[2]. res += val * (coefficients[16] + coefficients[17] * adjustments[3]). Constraint expression for cpu/update_registers/update_pc/tmp1: column19_row11 - column19_row3 * column19_row13. Numerator: point - trace_generator^(16 * (trace_length / 16 - 1)). val *= numerators[1]. Denominator: point^(trace_length / 16) - 1. val *= denominator_invs[2]. res += val * (coefficients[18] + coefficients[19] * adjustments[3]). Constraint expression for cpu/update_registers/update_pc/pc_cond_negative: (1 - cpu__decode__opcode_rc__bit_9) * column17_row16 + column19_row3 * (column17_row16 - (column17_row0 + column17_row13)) - ((1 - (cpu__decode__opcode_rc__bit_7 + cpu__decode__opcode_rc__bit_8 + cpu__decode__opcode_rc__bit_9)) * npc_reg_0 + cpu__decode__opcode_rc__bit_7 * column19_row13 + cpu__decode__opcode_rc__bit_8 * (column17_row0 + column19_row13)). Numerator: point - trace_generator^(16 * (trace_length / 16 - 1)). val *= numerators[1]. Denominator: point^(trace_length / 16) - 1. val *= denominator_invs[2]. res += val * (coefficients[20] + coefficients[21] * adjustments[3]). Constraint expression for cpu/update_registers/update_pc/pc_cond_positive: (column19_row11 - cpu__decode__opcode_rc__bit_9) * (column17_row16 - npc_reg_0). Numerator: point - trace_generator^(16 * (trace_length / 16 - 1)). val *= numerators[1]. Denominator: point^(trace_length / 16) - 1. val *= denominator_invs[2]. res += val * (coefficients[22] + coefficients[23] * adjustments[3]). Constraint expression for cpu/update_registers/update_ap/ap_update: column19_row17 - (column19_row1 + cpu__decode__opcode_rc__bit_10 * column19_row13 + cpu__decode__opcode_rc__bit_11 + cpu__decode__opcode_rc__bit_12 * 2). Numerator: point - trace_generator^(16 * (trace_length / 16 - 1)). val *= numerators[1]. Denominator: point^(trace_length / 16) - 1. val *= denominator_invs[2]. res += val * (coefficients[24] + coefficients[25] * adjustments[3]). Constraint expression for cpu/update_registers/update_fp/fp_update: column19_row25 - ((1 - (cpu__decode__opcode_rc__bit_12 + cpu__decode__opcode_rc__bit_13)) * column19_row9 + cpu__decode__opcode_rc__bit_13 * column17_row9 + cpu__decode__opcode_rc__bit_12 * (column19_row1 + 2)). Numerator: point - trace_generator^(16 * (trace_length / 16 - 1)). val *= numerators[1]. Denominator: point^(trace_length / 16) - 1. val *= denominator_invs[2]. res += val * (coefficients[26] + coefficients[27] * adjustments[3]). Constraint expression for cpu/opcodes/call/push_fp: cpu__decode__opcode_rc__bit_12 * (column17_row9 - column19_row9). Numerator: 1. val *= 1. val := mulmod(val, 1, PRIME). Denominator: point^(trace_length / 16) - 1. val *= denominator_invs[2]. res += val * (coefficients[28] + coefficients[29] * adjustments[2]). Constraint expression for cpu/opcodes/call/push_pc: cpu__decode__opcode_rc__bit_12 * (column17_row5 - (column17_row0 + cpu__decode__opcode_rc__bit_2 + 1)). Numerator: 1. val *= 1. val := mulmod(val, 1, PRIME). Denominator: point^(trace_length / 16) - 1. val *= denominator_invs[2]. res += val * (coefficients[30] + coefficients[31] * adjustments[2]). Constraint expression for cpu/opcodes/assert_eq/assert_eq: cpu__decode__opcode_rc__bit_14 * (column17_row9 - column19_row13). Numerator: 1. val *= 1. val := mulmod(val, 1, PRIME). Denominator: point^(trace_length / 16) - 1. val *= denominator_invs[2]. res += val * (coefficients[32] + coefficients[33] * adjustments[2]). Constraint expression for initial_ap: column19_row1 - initial_ap. Numerator: 1. val *= 1. val := mulmod(val, 1, PRIME). Denominator: point - 1. val *= denominator_invs[3]. res += val * (coefficients[34] + coefficients[35] * adjustments[4]). Constraint expression for initial_fp: column19_row9 - initial_ap. Numerator: 1. val *= 1. val := mulmod(val, 1, PRIME). Denominator: point - 1. val *= denominator_invs[3]. res += val * (coefficients[36] + coefficients[37] * adjustments[4]). Constraint expression for initial_pc: column17_row0 - initial_pc. Numerator: 1. val *= 1. val := mulmod(val, 1, PRIME). Denominator: point - 1. val *= denominator_invs[3]. res += val * (coefficients[38] + coefficients[39] * adjustments[4]). Constraint expression for final_ap: column19_row1 - final_ap. Numerator: 1. val *= 1. val := mulmod(val, 1, PRIME). Denominator: point - trace_generator^(16 * (trace_length / 16 - 1)). val *= denominator_invs[4]. res += val * (coefficients[40] + coefficients[41] * adjustments[4]). Constraint expression for final_pc: column17_row0 - final_pc. Numerator: 1. val *= 1. val := mulmod(val, 1, PRIME). Denominator: point - trace_generator^(16 * (trace_length / 16 - 1)). val *= denominator_invs[4]. res += val * (coefficients[42] + coefficients[43] * adjustments[4]). Constraint expression for memory/multi_column_perm/perm/init0: (memory/multi_column_perm/perm/interaction_elm - (column18_row0 + memory/multi_column_perm/hash_interaction_elm0 * column18_row1)) * column21_inter1_row0 + column17_row0 + memory/multi_column_perm/hash_interaction_elm0 * column17_row1 - memory/multi_column_perm/perm/interaction_elm. Numerator: 1. val *= 1. val := mulmod(val, 1, PRIME). Denominator: point - 1. val *= denominator_invs[3]. res += val * (coefficients[44] + coefficients[45] * adjustments[5]). Constraint expression for memory/multi_column_perm/perm/step0: (memory/multi_column_perm/perm/interaction_elm - (column18_row2 + memory/multi_column_perm/hash_interaction_elm0 * column18_row3)) * column21_inter1_row2 - (memory/multi_column_perm/perm/interaction_elm - (column17_row2 + memory/multi_column_perm/hash_interaction_elm0 * column17_row3)) * column21_inter1_row0. Numerator: point - trace_generator^(2 * (trace_length / 2 - 1)). val *= numerators[2]. Denominator: point^(trace_length / 2) - 1. val *= denominator_invs[5]. res += val * (coefficients[46] + coefficients[47] * adjustments[6]). Constraint expression for memory/multi_column_perm/perm/last: column21_inter1_row0 - memory/multi_column_perm/perm/public_memory_prod. Numerator: 1. val *= 1. val := mulmod(val, 1, PRIME). Denominator: point - trace_generator^(2 * (trace_length / 2 - 1)). val *= denominator_invs[6]. res += val * (coefficients[48] + coefficients[49] * adjustments[4]). Constraint expression for memory/diff_is_bit: memory__address_diff_0 * memory__address_diff_0 - memory__address_diff_0. Numerator: point - trace_generator^(2 * (trace_length / 2 - 1)). val *= numerators[2]. Denominator: point^(trace_length / 2) - 1. val *= denominator_invs[5]. res += val * (coefficients[50] + coefficients[51] * adjustments[6]). Constraint expression for memory/is_func: (memory__address_diff_0 - 1) * (column18_row1 - column18_row3). Numerator: point - trace_generator^(2 * (trace_length / 2 - 1)). val *= numerators[2]. Denominator: point^(trace_length / 2) - 1. val *= denominator_invs[5]. res += val * (coefficients[52] + coefficients[53] * adjustments[6]). Constraint expression for memory/initial_addr: column18_row0 - 1. Numerator: 1. val *= 1. val := mulmod(val, 1, PRIME). Denominator: point - 1. val *= denominator_invs[3]. res += val * (coefficients[54] + coefficients[55] * adjustments[4]). Constraint expression for public_memory_addr_zero: column17_row2. Numerator: 1. val *= 1. val := mulmod(val, 1, PRIME). Denominator: point^(trace_length / 8) - 1. val *= denominator_invs[7]. res += val * (coefficients[56] + coefficients[57] * adjustments[7]). Constraint expression for public_memory_value_zero: column17_row3. Numerator: 1. val *= 1. val := mulmod(val, 1, PRIME). Denominator: point^(trace_length / 8) - 1. val *= denominator_invs[7]. res += val * (coefficients[58] + coefficients[59] * adjustments[7]). Constraint expression for rc16/perm/init0: (rc16/perm/interaction_elm - column19_row2) * column21_inter1_row1 + column19_row0 - rc16/perm/interaction_elm. Numerator: 1. val *= 1. val := mulmod(val, 1, PRIME). Denominator: point - 1. val *= denominator_invs[3]. res += val * (coefficients[60] + coefficients[61] * adjustments[5]). Constraint expression for rc16/perm/step0: (rc16/perm/interaction_elm - column19_row6) * column21_inter1_row5 - (rc16/perm/interaction_elm - column19_row4) * column21_inter1_row1. Numerator: point - trace_generator^(4 * (trace_length / 4 - 1)). val *= numerators[3]. Denominator: point^(trace_length / 4) - 1. val *= denominator_invs[8]. res += val * (coefficients[62] + coefficients[63] * adjustments[8]). Constraint expression for rc16/perm/last: column21_inter1_row1 - rc16/perm/public_memory_prod. Numerator: 1. val *= 1. val := mulmod(val, 1, PRIME). Denominator: point - trace_generator^(4 * (trace_length / 4 - 1)). val *= denominator_invs[9]. res += val * (coefficients[64] + coefficients[65] * adjustments[4]). Constraint expression for rc16/diff_is_bit: rc16__diff_0 * rc16__diff_0 - rc16__diff_0. Numerator: point - trace_generator^(4 * (trace_length / 4 - 1)). val *= numerators[3]. Denominator: point^(trace_length / 4) - 1. val *= denominator_invs[8]. res += val * (coefficients[66] + coefficients[67] * adjustments[8]). Constraint expression for rc16/minimum: column19_row2 - rc_min. Numerator: 1. val *= 1. val := mulmod(val, 1, PRIME). Denominator: point - 1. val *= denominator_invs[3]. res += val * (coefficients[68] + coefficients[69] * adjustments[4]). Constraint expression for rc16/maximum: column19_row2 - rc_max. Numerator: 1. val *= 1. val := mulmod(val, 1, PRIME). Denominator: point - trace_generator^(4 * (trace_length / 4 - 1)). val *= denominator_invs[9]. res += val * (coefficients[70] + coefficients[71] * adjustments[4]). Constraint expression for pedersen/hash0/ec_subset_sum/bit_unpacking/last_one_is_zero: column11_row255 * (column4_row0 - (column4_row1 + column4_row1)). Numerator: 1. val *= 1. val := mulmod(val, 1, PRIME). Denominator: point^(trace_length / 256) - 1. val *= denominator_invs[10]. res += val * (coefficients[72] + coefficients[73] * adjustments[9]). Constraint expression for pedersen/hash0/ec_subset_sum/bit_unpacking/zeroes_between_ones0: column11_row255 * (column4_row1 - 3138550867693340381917894711603833208051177722232017256448 * column4_row192). Numerator: 1. val *= 1. val := mulmod(val, 1, PRIME). Denominator: point^(trace_length / 256) - 1. val *= denominator_invs[10]. res += val * (coefficients[74] + coefficients[75] * adjustments[9]). Constraint expression for pedersen/hash0/ec_subset_sum/bit_unpacking/cumulative_bit192: column11_row255 - column15_row255 * (column4_row192 - (column4_row193 + column4_row193)). Numerator: 1. val *= 1. val := mulmod(val, 1, PRIME). Denominator: point^(trace_length / 256) - 1. val *= denominator_invs[10]. res += val * (coefficients[76] + coefficients[77] * adjustments[9]). Constraint expression for pedersen/hash0/ec_subset_sum/bit_unpacking/zeroes_between_ones192: column15_row255 * (column4_row193 - 8 * column4_row196). Numerator: 1. val *= 1. val := mulmod(val, 1, PRIME). Denominator: point^(trace_length / 256) - 1. val *= denominator_invs[10]. res += val * (coefficients[78] + coefficients[79] * adjustments[9]). Constraint expression for pedersen/hash0/ec_subset_sum/bit_unpacking/cumulative_bit196: column15_row255 - (column4_row251 - (column4_row252 + column4_row252)) * (column4_row196 - (column4_row197 + column4_row197)). Numerator: 1. val *= 1. val := mulmod(val, 1, PRIME). Denominator: point^(trace_length / 256) - 1. val *= denominator_invs[10]. res += val * (coefficients[80] + coefficients[81] * adjustments[9]). Constraint expression for pedersen/hash0/ec_subset_sum/bit_unpacking/zeroes_between_ones196: (column4_row251 - (column4_row252 + column4_row252)) * (column4_row197 - 18014398509481984 * column4_row251). Numerator: 1. val *= 1. val := mulmod(val, 1, PRIME). Denominator: point^(trace_length / 256) - 1. val *= denominator_invs[10]. res += val * (coefficients[82] + coefficients[83] * adjustments[9]). Constraint expression for pedersen/hash0/ec_subset_sum/booleanity_test: pedersen__hash0__ec_subset_sum__bit_0 * (pedersen__hash0__ec_subset_sum__bit_0 - 1). Numerator: point^(trace_length / 256) - trace_generator^(255 * trace_length / 256). val *= numerators[4]. Denominator: point^trace_length - 1. val *= denominator_invs[0]. res += val * (coefficients[84] + coefficients[85] * adjustments[10]). Constraint expression for pedersen/hash0/ec_subset_sum/bit_extraction_end: column4_row0. Numerator: 1. val *= 1. val := mulmod(val, 1, PRIME). Denominator: point^(trace_length / 256) - trace_generator^(63 * trace_length / 64). val *= denominator_invs[11]. res += val * (coefficients[86] + coefficients[87] * adjustments[11]). Constraint expression for pedersen/hash0/ec_subset_sum/zeros_tail: column4_row0. Numerator: 1. val *= 1. val := mulmod(val, 1, PRIME). Denominator: point^(trace_length / 256) - trace_generator^(255 * trace_length / 256). val *= denominator_invs[12]. res += val * (coefficients[88] + coefficients[89] * adjustments[11]). Constraint expression for pedersen/hash0/ec_subset_sum/add_points/slope: pedersen__hash0__ec_subset_sum__bit_0 * (column2_row0 - pedersen__points__y) - column3_row0 * (column1_row0 - pedersen__points__x). Numerator: point^(trace_length / 256) - trace_generator^(255 * trace_length / 256). val *= numerators[4]. Denominator: point^trace_length - 1. val *= denominator_invs[0]. res += val * (coefficients[90] + coefficients[91] * adjustments[10]). Constraint expression for pedersen/hash0/ec_subset_sum/add_points/x: column3_row0 * column3_row0 - pedersen__hash0__ec_subset_sum__bit_0 * (column1_row0 + pedersen__points__x + column1_row1). Numerator: point^(trace_length / 256) - trace_generator^(255 * trace_length / 256). val *= numerators[4]. Denominator: point^trace_length - 1. val *= denominator_invs[0]. res += val * (coefficients[92] + coefficients[93] * adjustments[10]). Constraint expression for pedersen/hash0/ec_subset_sum/add_points/y: pedersen__hash0__ec_subset_sum__bit_0 * (column2_row0 + column2_row1) - column3_row0 * (column1_row0 - column1_row1). Numerator: point^(trace_length / 256) - trace_generator^(255 * trace_length / 256). val *= numerators[4]. Denominator: point^trace_length - 1. val *= denominator_invs[0]. res += val * (coefficients[94] + coefficients[95] * adjustments[10]). Constraint expression for pedersen/hash0/ec_subset_sum/copy_point/x: pedersen__hash0__ec_subset_sum__bit_neg_0 * (column1_row1 - column1_row0). Numerator: point^(trace_length / 256) - trace_generator^(255 * trace_length / 256). val *= numerators[4]. Denominator: point^trace_length - 1. val *= denominator_invs[0]. res += val * (coefficients[96] + coefficients[97] * adjustments[10]). Constraint expression for pedersen/hash0/ec_subset_sum/copy_point/y: pedersen__hash0__ec_subset_sum__bit_neg_0 * (column2_row1 - column2_row0). Numerator: point^(trace_length / 256) - trace_generator^(255 * trace_length / 256). val *= numerators[4]. Denominator: point^trace_length - 1. val *= denominator_invs[0]. res += val * (coefficients[98] + coefficients[99] * adjustments[10]). Constraint expression for pedersen/hash0/copy_point/x: column1_row256 - column1_row255. Numerator: point^(trace_length / 512) - trace_generator^(trace_length / 2). val *= numerators[5]. Denominator: point^(trace_length / 256) - 1. val *= denominator_invs[10]. res += val * (coefficients[100] + coefficients[101] * adjustments[12]). Constraint expression for pedersen/hash0/copy_point/y: column2_row256 - column2_row255. Numerator: point^(trace_length / 512) - trace_generator^(trace_length / 2). val *= numerators[5]. Denominator: point^(trace_length / 256) - 1. val *= denominator_invs[10]. res += val * (coefficients[102] + coefficients[103] * adjustments[12]). Constraint expression for pedersen/hash0/init/x: column1_row0 - pedersen/shift_point.x. Numerator: 1. val *= 1. val := mulmod(val, 1, PRIME). Denominator: point^(trace_length / 512) - 1. val *= denominator_invs[13]. res += val * (coefficients[104] + coefficients[105] * adjustments[13]). Constraint expression for pedersen/hash0/init/y: column2_row0 - pedersen/shift_point.y. Numerator: 1. val *= 1. val := mulmod(val, 1, PRIME). Denominator: point^(trace_length / 512) - 1. val *= denominator_invs[13]. res += val * (coefficients[106] + coefficients[107] * adjustments[13]). Constraint expression for pedersen/hash1/ec_subset_sum/bit_unpacking/last_one_is_zero: column3_row255 * (column8_row0 - (column8_row1 + column8_row1)). Numerator: 1. val *= 1. val := mulmod(val, 1, PRIME). Denominator: point^(trace_length / 256) - 1. val *= denominator_invs[10]. res += val * (coefficients[108] + coefficients[109] * adjustments[9]). Constraint expression for pedersen/hash1/ec_subset_sum/bit_unpacking/zeroes_between_ones0: column3_row255 * (column8_row1 - 3138550867693340381917894711603833208051177722232017256448 * column8_row192). Numerator: 1. val *= 1. val := mulmod(val, 1, PRIME). Denominator: point^(trace_length / 256) - 1. val *= denominator_invs[10]. res += val * (coefficients[110] + coefficients[111] * adjustments[9]). Constraint expression for pedersen/hash1/ec_subset_sum/bit_unpacking/cumulative_bit192: column3_row255 - column7_row255 * (column8_row192 - (column8_row193 + column8_row193)). Numerator: 1. val *= 1. val := mulmod(val, 1, PRIME). Denominator: point^(trace_length / 256) - 1. val *= denominator_invs[10]. res += val * (coefficients[112] + coefficients[113] * adjustments[9]). Constraint expression for pedersen/hash1/ec_subset_sum/bit_unpacking/zeroes_between_ones192: column7_row255 * (column8_row193 - 8 * column8_row196). Numerator: 1. val *= 1. val := mulmod(val, 1, PRIME). Denominator: point^(trace_length / 256) - 1. val *= denominator_invs[10]. res += val * (coefficients[114] + coefficients[115] * adjustments[9]). Constraint expression for pedersen/hash1/ec_subset_sum/bit_unpacking/cumulative_bit196: column7_row255 - (column8_row251 - (column8_row252 + column8_row252)) * (column8_row196 - (column8_row197 + column8_row197)). Numerator: 1. val *= 1. val := mulmod(val, 1, PRIME). Denominator: point^(trace_length / 256) - 1. val *= denominator_invs[10]. res += val * (coefficients[116] + coefficients[117] * adjustments[9]). Constraint expression for pedersen/hash1/ec_subset_sum/bit_unpacking/zeroes_between_ones196: (column8_row251 - (column8_row252 + column8_row252)) * (column8_row197 - 18014398509481984 * column8_row251). Numerator: 1. val *= 1. val := mulmod(val, 1, PRIME). Denominator: point^(trace_length / 256) - 1. val *= denominator_invs[10]. res += val * (coefficients[118] + coefficients[119] * adjustments[9]). Constraint expression for pedersen/hash1/ec_subset_sum/booleanity_test: pedersen__hash1__ec_subset_sum__bit_0 * (pedersen__hash1__ec_subset_sum__bit_0 - 1). Numerator: point^(trace_length / 256) - trace_generator^(255 * trace_length / 256). val *= numerators[4]. Denominator: point^trace_length - 1. val *= denominator_invs[0]. res += val * (coefficients[120] + coefficients[121] * adjustments[10]). Constraint expression for pedersen/hash1/ec_subset_sum/bit_extraction_end: column8_row0. Numerator: 1. val *= 1. val := mulmod(val, 1, PRIME). Denominator: point^(trace_length / 256) - trace_generator^(63 * trace_length / 64). val *= denominator_invs[11]. res += val * (coefficients[122] + coefficients[123] * adjustments[11]). Constraint expression for pedersen/hash1/ec_subset_sum/zeros_tail: column8_row0. Numerator: 1. val *= 1. val := mulmod(val, 1, PRIME). Denominator: point^(trace_length / 256) - trace_generator^(255 * trace_length / 256). val *= denominator_invs[12]. res += val * (coefficients[124] + coefficients[125] * adjustments[11]). Constraint expression for pedersen/hash1/ec_subset_sum/add_points/slope: pedersen__hash1__ec_subset_sum__bit_0 * (column6_row0 - pedersen__points__y) - column7_row0 * (column5_row0 - pedersen__points__x). Numerator: point^(trace_length / 256) - trace_generator^(255 * trace_length / 256). val *= numerators[4]. Denominator: point^trace_length - 1. val *= denominator_invs[0]. res += val * (coefficients[126] + coefficients[127] * adjustments[10]). Constraint expression for pedersen/hash1/ec_subset_sum/add_points/x: column7_row0 * column7_row0 - pedersen__hash1__ec_subset_sum__bit_0 * (column5_row0 + pedersen__points__x + column5_row1). Numerator: point^(trace_length / 256) - trace_generator^(255 * trace_length / 256). val *= numerators[4]. Denominator: point^trace_length - 1. val *= denominator_invs[0]. res += val * (coefficients[128] + coefficients[129] * adjustments[10]). Constraint expression for pedersen/hash1/ec_subset_sum/add_points/y: pedersen__hash1__ec_subset_sum__bit_0 * (column6_row0 + column6_row1) - column7_row0 * (column5_row0 - column5_row1). Numerator: point^(trace_length / 256) - trace_generator^(255 * trace_length / 256). val *= numerators[4]. Denominator: point^trace_length - 1. val *= denominator_invs[0]. res += val * (coefficients[130] + coefficients[131] * adjustments[10]). Constraint expression for pedersen/hash1/ec_subset_sum/copy_point/x: pedersen__hash1__ec_subset_sum__bit_neg_0 * (column5_row1 - column5_row0). Numerator: point^(trace_length / 256) - trace_generator^(255 * trace_length / 256). val *= numerators[4]. Denominator: point^trace_length - 1. val *= denominator_invs[0]. res += val * (coefficients[132] + coefficients[133] * adjustments[10]). Constraint expression for pedersen/hash1/ec_subset_sum/copy_point/y: pedersen__hash1__ec_subset_sum__bit_neg_0 * (column6_row1 - column6_row0). Numerator: point^(trace_length / 256) - trace_generator^(255 * trace_length / 256). val *= numerators[4]. Denominator: point^trace_length - 1. val *= denominator_invs[0]. res += val * (coefficients[134] + coefficients[135] * adjustments[10]). Constraint expression for pedersen/hash1/copy_point/x: column5_row256 - column5_row255. Numerator: point^(trace_length / 512) - trace_generator^(trace_length / 2). val *= numerators[5]. Denominator: point^(trace_length / 256) - 1. val *= denominator_invs[10]. res += val * (coefficients[136] + coefficients[137] * adjustments[12]). Constraint expression for pedersen/hash1/copy_point/y: column6_row256 - column6_row255. Numerator: point^(trace_length / 512) - trace_generator^(trace_length / 2). val *= numerators[5]. Denominator: point^(trace_length / 256) - 1. val *= denominator_invs[10]. res += val * (coefficients[138] + coefficients[139] * adjustments[12]). Constraint expression for pedersen/hash1/init/x: column5_row0 - pedersen/shift_point.x. Numerator: 1. val *= 1. val := mulmod(val, 1, PRIME). Denominator: point^(trace_length / 512) - 1. val *= denominator_invs[13]. res += val * (coefficients[140] + coefficients[141] * adjustments[13]). Constraint expression for pedersen/hash1/init/y: column6_row0 - pedersen/shift_point.y. Numerator: 1. val *= 1. val := mulmod(val, 1, PRIME). Denominator: point^(trace_length / 512) - 1. val *= denominator_invs[13]. res += val * (coefficients[142] + coefficients[143] * adjustments[13]). Constraint expression for pedersen/hash2/ec_subset_sum/bit_unpacking/last_one_is_zero: column20_row145 * (column12_row0 - (column12_row1 + column12_row1)). Numerator: 1. val *= 1. val := mulmod(val, 1, PRIME). Denominator: point^(trace_length / 256) - 1. val *= denominator_invs[10]. res += val * (coefficients[144] + coefficients[145] * adjustments[9]). Constraint expression for pedersen/hash2/ec_subset_sum/bit_unpacking/zeroes_between_ones0: column20_row145 * (column12_row1 - 3138550867693340381917894711603833208051177722232017256448 * column12_row192). Numerator: 1. val *= 1. val := mulmod(val, 1, PRIME). Denominator: point^(trace_length / 256) - 1. val *= denominator_invs[10]. res += val * (coefficients[146] + coefficients[147] * adjustments[9]). Constraint expression for pedersen/hash2/ec_subset_sum/bit_unpacking/cumulative_bit192: column20_row145 - column20_row17 * (column12_row192 - (column12_row193 + column12_row193)). Numerator: 1. val *= 1. val := mulmod(val, 1, PRIME). Denominator: point^(trace_length / 256) - 1. val *= denominator_invs[10]. res += val * (coefficients[148] + coefficients[149] * adjustments[9]). Constraint expression for pedersen/hash2/ec_subset_sum/bit_unpacking/zeroes_between_ones192: column20_row17 * (column12_row193 - 8 * column12_row196). Numerator: 1. val *= 1. val := mulmod(val, 1, PRIME). Denominator: point^(trace_length / 256) - 1. val *= denominator_invs[10]. res += val * (coefficients[150] + coefficients[151] * adjustments[9]). Constraint expression for pedersen/hash2/ec_subset_sum/bit_unpacking/cumulative_bit196: column20_row17 - (column12_row251 - (column12_row252 + column12_row252)) * (column12_row196 - (column12_row197 + column12_row197)). Numerator: 1. val *= 1. val := mulmod(val, 1, PRIME). Denominator: point^(trace_length / 256) - 1. val *= denominator_invs[10]. res += val * (coefficients[152] + coefficients[153] * adjustments[9]). Constraint expression for pedersen/hash2/ec_subset_sum/bit_unpacking/zeroes_between_ones196: (column12_row251 - (column12_row252 + column12_row252)) * (column12_row197 - 18014398509481984 * column12_row251). Numerator: 1. val *= 1. val := mulmod(val, 1, PRIME). Denominator: point^(trace_length / 256) - 1. val *= denominator_invs[10]. res += val * (coefficients[154] + coefficients[155] * adjustments[9]). Constraint expression for pedersen/hash2/ec_subset_sum/booleanity_test: pedersen__hash2__ec_subset_sum__bit_0 * (pedersen__hash2__ec_subset_sum__bit_0 - 1). Numerator: point^(trace_length / 256) - trace_generator^(255 * trace_length / 256). val *= numerators[4]. Denominator: point^trace_length - 1. val *= denominator_invs[0]. res += val * (coefficients[156] + coefficients[157] * adjustments[10]). Constraint expression for pedersen/hash2/ec_subset_sum/bit_extraction_end: column12_row0. Numerator: 1. val *= 1. val := mulmod(val, 1, PRIME). Denominator: point^(trace_length / 256) - trace_generator^(63 * trace_length / 64). val *= denominator_invs[11]. res += val * (coefficients[158] + coefficients[159] * adjustments[11]). Constraint expression for pedersen/hash2/ec_subset_sum/zeros_tail: column12_row0. Numerator: 1. val *= 1. val := mulmod(val, 1, PRIME). Denominator: point^(trace_length / 256) - trace_generator^(255 * trace_length / 256). val *= denominator_invs[12]. res += val * (coefficients[160] + coefficients[161] * adjustments[11]). Constraint expression for pedersen/hash2/ec_subset_sum/add_points/slope: pedersen__hash2__ec_subset_sum__bit_0 * (column10_row0 - pedersen__points__y) - column11_row0 * (column9_row0 - pedersen__points__x). Numerator: point^(trace_length / 256) - trace_generator^(255 * trace_length / 256). val *= numerators[4]. Denominator: point^trace_length - 1. val *= denominator_invs[0]. res += val * (coefficients[162] + coefficients[163] * adjustments[10]). Constraint expression for pedersen/hash2/ec_subset_sum/add_points/x: column11_row0 * column11_row0 - pedersen__hash2__ec_subset_sum__bit_0 * (column9_row0 + pedersen__points__x + column9_row1). Numerator: point^(trace_length / 256) - trace_generator^(255 * trace_length / 256). val *= numerators[4]. Denominator: point^trace_length - 1. val *= denominator_invs[0]. res += val * (coefficients[164] + coefficients[165] * adjustments[10]). Constraint expression for pedersen/hash2/ec_subset_sum/add_points/y: pedersen__hash2__ec_subset_sum__bit_0 * (column10_row0 + column10_row1) - column11_row0 * (column9_row0 - column9_row1). Numerator: point^(trace_length / 256) - trace_generator^(255 * trace_length / 256). val *= numerators[4]. Denominator: point^trace_length - 1. val *= denominator_invs[0]. res += val * (coefficients[166] + coefficients[167] * adjustments[10]). Constraint expression for pedersen/hash2/ec_subset_sum/copy_point/x: pedersen__hash2__ec_subset_sum__bit_neg_0 * (column9_row1 - column9_row0). Numerator: point^(trace_length / 256) - trace_generator^(255 * trace_length / 256). val *= numerators[4]. Denominator: point^trace_length - 1. val *= denominator_invs[0]. res += val * (coefficients[168] + coefficients[169] * adjustments[10]). Constraint expression for pedersen/hash2/ec_subset_sum/copy_point/y: pedersen__hash2__ec_subset_sum__bit_neg_0 * (column10_row1 - column10_row0). Numerator: point^(trace_length / 256) - trace_generator^(255 * trace_length / 256). val *= numerators[4]. Denominator: point^trace_length - 1. val *= denominator_invs[0]. res += val * (coefficients[170] + coefficients[171] * adjustments[10]). Constraint expression for pedersen/hash2/copy_point/x: column9_row256 - column9_row255. Numerator: point^(trace_length / 512) - trace_generator^(trace_length / 2). val *= numerators[5]. Denominator: point^(trace_length / 256) - 1. val *= denominator_invs[10]. res += val * (coefficients[172] + coefficients[173] * adjustments[12]). Constraint expression for pedersen/hash2/copy_point/y: column10_row256 - column10_row255. Numerator: point^(trace_length / 512) - trace_generator^(trace_length / 2). val *= numerators[5]. Denominator: point^(trace_length / 256) - 1. val *= denominator_invs[10]. res += val * (coefficients[174] + coefficients[175] * adjustments[12]). Constraint expression for pedersen/hash2/init/x: column9_row0 - pedersen/shift_point.x. Numerator: 1. val *= 1. val := mulmod(val, 1, PRIME). Denominator: point^(trace_length / 512) - 1. val *= denominator_invs[13]. res += val * (coefficients[176] + coefficients[177] * adjustments[13]). Constraint expression for pedersen/hash2/init/y: column10_row0 - pedersen/shift_point.y. Numerator: 1. val *= 1. val := mulmod(val, 1, PRIME). Denominator: point^(trace_length / 512) - 1. val *= denominator_invs[13]. res += val * (coefficients[178] + coefficients[179] * adjustments[13]). Constraint expression for pedersen/hash3/ec_subset_sum/bit_unpacking/last_one_is_zero: column20_row209 * (column16_row0 - (column16_row1 + column16_row1)). Numerator: 1. val *= 1. val := mulmod(val, 1, PRIME). Denominator: point^(trace_length / 256) - 1. val *= denominator_invs[10]. res += val * (coefficients[180] + coefficients[181] * adjustments[9]). Constraint expression for pedersen/hash3/ec_subset_sum/bit_unpacking/zeroes_between_ones0: column20_row209 * (column16_row1 - 3138550867693340381917894711603833208051177722232017256448 * column16_row192). Numerator: 1. val *= 1. val := mulmod(val, 1, PRIME). Denominator: point^(trace_length / 256) - 1. val *= denominator_invs[10]. res += val * (coefficients[182] + coefficients[183] * adjustments[9]). Constraint expression for pedersen/hash3/ec_subset_sum/bit_unpacking/cumulative_bit192: column20_row209 - column20_row81 * (column16_row192 - (column16_row193 + column16_row193)). Numerator: 1. val *= 1. val := mulmod(val, 1, PRIME). Denominator: point^(trace_length / 256) - 1. val *= denominator_invs[10]. res += val * (coefficients[184] + coefficients[185] * adjustments[9]). Constraint expression for pedersen/hash3/ec_subset_sum/bit_unpacking/zeroes_between_ones192: column20_row81 * (column16_row193 - 8 * column16_row196). Numerator: 1. val *= 1. val := mulmod(val, 1, PRIME). Denominator: point^(trace_length / 256) - 1. val *= denominator_invs[10]. res += val * (coefficients[186] + coefficients[187] * adjustments[9]). Constraint expression for pedersen/hash3/ec_subset_sum/bit_unpacking/cumulative_bit196: column20_row81 - (column16_row251 - (column16_row252 + column16_row252)) * (column16_row196 - (column16_row197 + column16_row197)). Numerator: 1. val *= 1. val := mulmod(val, 1, PRIME). Denominator: point^(trace_length / 256) - 1. val *= denominator_invs[10]. res += val * (coefficients[188] + coefficients[189] * adjustments[9]). Constraint expression for pedersen/hash3/ec_subset_sum/bit_unpacking/zeroes_between_ones196: (column16_row251 - (column16_row252 + column16_row252)) * (column16_row197 - 18014398509481984 * column16_row251). Numerator: 1. val *= 1. val := mulmod(val, 1, PRIME). Denominator: point^(trace_length / 256) - 1. val *= denominator_invs[10]. res += val * (coefficients[190] + coefficients[191] * adjustments[9]). Constraint expression for pedersen/hash3/ec_subset_sum/booleanity_test: pedersen__hash3__ec_subset_sum__bit_0 * (pedersen__hash3__ec_subset_sum__bit_0 - 1). Numerator: point^(trace_length / 256) - trace_generator^(255 * trace_length / 256). val *= numerators[4]. Denominator: point^trace_length - 1. val *= denominator_invs[0]. res += val * (coefficients[192] + coefficients[193] * adjustments[10]). Constraint expression for pedersen/hash3/ec_subset_sum/bit_extraction_end: column16_row0. Numerator: 1. val *= 1. val := mulmod(val, 1, PRIME). Denominator: point^(trace_length / 256) - trace_generator^(63 * trace_length / 64). val *= denominator_invs[11]. res += val * (coefficients[194] + coefficients[195] * adjustments[11]). Constraint expression for pedersen/hash3/ec_subset_sum/zeros_tail: column16_row0. Numerator: 1. val *= 1. val := mulmod(val, 1, PRIME). Denominator: point^(trace_length / 256) - trace_generator^(255 * trace_length / 256). val *= denominator_invs[12]. res += val * (coefficients[196] + coefficients[197] * adjustments[11]). Constraint expression for pedersen/hash3/ec_subset_sum/add_points/slope: pedersen__hash3__ec_subset_sum__bit_0 * (column14_row0 - pedersen__points__y) - column15_row0 * (column13_row0 - pedersen__points__x). Numerator: point^(trace_length / 256) - trace_generator^(255 * trace_length / 256). val *= numerators[4]. Denominator: point^trace_length - 1. val *= denominator_invs[0]. res += val * (coefficients[198] + coefficients[199] * adjustments[10]). Constraint expression for pedersen/hash3/ec_subset_sum/add_points/x: column15_row0 * column15_row0 - pedersen__hash3__ec_subset_sum__bit_0 * (column13_row0 + pedersen__points__x + column13_row1). Numerator: point^(trace_length / 256) - trace_generator^(255 * trace_length / 256). val *= numerators[4]. Denominator: point^trace_length - 1. val *= denominator_invs[0]. res += val * (coefficients[200] + coefficients[201] * adjustments[10]). Constraint expression for pedersen/hash3/ec_subset_sum/add_points/y: pedersen__hash3__ec_subset_sum__bit_0 * (column14_row0 + column14_row1) - column15_row0 * (column13_row0 - column13_row1). Numerator: point^(trace_length / 256) - trace_generator^(255 * trace_length / 256). val *= numerators[4]. Denominator: point^trace_length - 1. val *= denominator_invs[0]. res += val * (coefficients[202] + coefficients[203] * adjustments[10]). Constraint expression for pedersen/hash3/ec_subset_sum/copy_point/x: pedersen__hash3__ec_subset_sum__bit_neg_0 * (column13_row1 - column13_row0). Numerator: point^(trace_length / 256) - trace_generator^(255 * trace_length / 256). val *= numerators[4]. Denominator: point^trace_length - 1. val *= denominator_invs[0]. res += val * (coefficients[204] + coefficients[205] * adjustments[10]). Constraint expression for pedersen/hash3/ec_subset_sum/copy_point/y: pedersen__hash3__ec_subset_sum__bit_neg_0 * (column14_row1 - column14_row0). Numerator: point^(trace_length / 256) - trace_generator^(255 * trace_length / 256). val *= numerators[4]. Denominator: point^trace_length - 1. val *= denominator_invs[0]. res += val * (coefficients[206] + coefficients[207] * adjustments[10]). Constraint expression for pedersen/hash3/copy_point/x: column13_row256 - column13_row255. Numerator: point^(trace_length / 512) - trace_generator^(trace_length / 2). val *= numerators[5]. Denominator: point^(trace_length / 256) - 1. val *= denominator_invs[10]. res += val * (coefficients[208] + coefficients[209] * adjustments[12]). Constraint expression for pedersen/hash3/copy_point/y: column14_row256 - column14_row255. Numerator: point^(trace_length / 512) - trace_generator^(trace_length / 2). val *= numerators[5]. Denominator: point^(trace_length / 256) - 1. val *= denominator_invs[10]. res += val * (coefficients[210] + coefficients[211] * adjustments[12]). Constraint expression for pedersen/hash3/init/x: column13_row0 - pedersen/shift_point.x. Numerator: 1. val *= 1. val := mulmod(val, 1, PRIME). Denominator: point^(trace_length / 512) - 1. val *= denominator_invs[13]. res += val * (coefficients[212] + coefficients[213] * adjustments[13]). Constraint expression for pedersen/hash3/init/y: column14_row0 - pedersen/shift_point.y. Numerator: 1. val *= 1. val := mulmod(val, 1, PRIME). Denominator: point^(trace_length / 512) - 1. val *= denominator_invs[13]. res += val * (coefficients[214] + coefficients[215] * adjustments[13]). Constraint expression for pedersen/input0_value0: column17_row7 - column4_row0. Numerator: 1. val *= 1. val := mulmod(val, 1, PRIME). Denominator: point^(trace_length / 512) - 1. val *= denominator_invs[13]. res += val * (coefficients[216] + coefficients[217] * adjustments[13]). Constraint expression for pedersen/input0_value1: column17_row135 - column8_row0. Numerator: 1. val *= 1. val := mulmod(val, 1, PRIME). Denominator: point^(trace_length / 512) - 1. val *= denominator_invs[13]. res += val * (coefficients[218] + coefficients[219] * adjustments[13]). Constraint expression for pedersen/input0_value2: column17_row263 - column12_row0. Numerator: 1. val *= 1. val := mulmod(val, 1, PRIME). Denominator: point^(trace_length / 512) - 1. val *= denominator_invs[13]. res += val * (coefficients[220] + coefficients[221] * adjustments[13]). Constraint expression for pedersen/input0_value3: column17_row391 - column16_row0. Numerator: 1. val *= 1. val := mulmod(val, 1, PRIME). Denominator: point^(trace_length / 512) - 1. val *= denominator_invs[13]. res += val * (coefficients[222] + coefficients[223] * adjustments[13]). Constraint expression for pedersen/input0_addr: column17_row134 - (column17_row38 + 1). Numerator: point - trace_generator^(128 * (trace_length / 128 - 1)). val *= numerators[6]. Denominator: point^(trace_length / 128) - 1. val *= denominator_invs[14]. res += val * (coefficients[224] + coefficients[225] * adjustments[14]). Constraint expression for pedersen/init_addr: column17_row6 - initial_pedersen_addr. Numerator: 1. val *= 1. val := mulmod(val, 1, PRIME). Denominator: point - 1. val *= denominator_invs[3]. res += val * (coefficients[226] + coefficients[227] * adjustments[4]). Constraint expression for pedersen/input1_value0: column17_row71 - column4_row256. Numerator: 1. val *= 1. val := mulmod(val, 1, PRIME). Denominator: point^(trace_length / 512) - 1. val *= denominator_invs[13]. res += val * (coefficients[228] + coefficients[229] * adjustments[13]). Constraint expression for pedersen/input1_value1: column17_row199 - column8_row256. Numerator: 1. val *= 1. val := mulmod(val, 1, PRIME). Denominator: point^(trace_length / 512) - 1. val *= denominator_invs[13]. res += val * (coefficients[230] + coefficients[231] * adjustments[13]). Constraint expression for pedersen/input1_value2: column17_row327 - column12_row256. Numerator: 1. val *= 1. val := mulmod(val, 1, PRIME). Denominator: point^(trace_length / 512) - 1. val *= denominator_invs[13]. res += val * (coefficients[232] + coefficients[233] * adjustments[13]). Constraint expression for pedersen/input1_value3: column17_row455 - column16_row256. Numerator: 1. val *= 1. val := mulmod(val, 1, PRIME). Denominator: point^(trace_length / 512) - 1. val *= denominator_invs[13]. res += val * (coefficients[234] + coefficients[235] * adjustments[13]). Constraint expression for pedersen/input1_addr: column17_row70 - (column17_row6 + 1). Numerator: 1. val *= 1. val := mulmod(val, 1, PRIME). Denominator: point^(trace_length / 128) - 1. val *= denominator_invs[14]. res += val * (coefficients[236] + coefficients[237] * adjustments[15]). Constraint expression for pedersen/output_value0: column17_row39 - column1_row511. Numerator: 1. val *= 1. val := mulmod(val, 1, PRIME). Denominator: point^(trace_length / 512) - 1. val *= denominator_invs[13]. res += val * (coefficients[238] + coefficients[239] * adjustments[13]). Constraint expression for pedersen/output_value1: column17_row167 - column5_row511. Numerator: 1. val *= 1. val := mulmod(val, 1, PRIME). Denominator: point^(trace_length / 512) - 1. val *= denominator_invs[13]. res += val * (coefficients[240] + coefficients[241] * adjustments[13]). Constraint expression for pedersen/output_value2: column17_row295 - column9_row511. Numerator: 1. val *= 1. val := mulmod(val, 1, PRIME). Denominator: point^(trace_length / 512) - 1. val *= denominator_invs[13]. res += val * (coefficients[242] + coefficients[243] * adjustments[13]). Constraint expression for pedersen/output_value3: column17_row423 - column13_row511. Numerator: 1. val *= 1. val := mulmod(val, 1, PRIME). Denominator: point^(trace_length / 512) - 1. val *= denominator_invs[13]. res += val * (coefficients[244] + coefficients[245] * adjustments[13]). Constraint expression for pedersen/output_addr: column17_row38 - (column17_row70 + 1). Numerator: 1. val *= 1. val := mulmod(val, 1, PRIME). Denominator: point^(trace_length / 128) - 1. val *= denominator_invs[14]. res += val * (coefficients[246] + coefficients[247] * adjustments[15]). Constraint expression for rc_builtin/value: rc_builtin__value7_0 - column17_row103. Numerator: 1. val *= 1. val := mulmod(val, 1, PRIME). Denominator: point^(trace_length / 128) - 1. val *= denominator_invs[14]. res += val * (coefficients[248] + coefficients[249] * adjustments[15]). Constraint expression for rc_builtin/addr_step: column17_row230 - (column17_row102 + 1). Numerator: point - trace_generator^(128 * (trace_length / 128 - 1)). val *= numerators[6]. Denominator: point^(trace_length / 128) - 1. val *= denominator_invs[14]. res += val * (coefficients[250] + coefficients[251] * adjustments[14]). Constraint expression for rc_builtin/init_addr: column17_row102 - initial_rc_addr. Numerator: 1. val *= 1. val := mulmod(val, 1, PRIME). Denominator: point - 1. val *= denominator_invs[3]. res += val * (coefficients[252] + coefficients[253] * adjustments[4]). Constraint expression for ecdsa/signature0/doubling_key/slope: ecdsa__signature0__doubling_key__x_squared + ecdsa__signature0__doubling_key__x_squared + ecdsa__signature0__doubling_key__x_squared + ecdsa/sig_config.alpha - (column19_row15 + column19_row15) * column20_row0. Numerator: point^(trace_length / 4096) - trace_generator^(255 * trace_length / 256). val *= numerators[7]. Denominator: point^(trace_length / 16) - 1. val *= denominator_invs[2]. res += val * (coefficients[254] + coefficients[255] * adjustments[16]). Constraint expression for ecdsa/signature0/doubling_key/x: column20_row0 * column20_row0 - (column19_row7 + column19_row7 + column19_row23). Numerator: point^(trace_length / 4096) - trace_generator^(255 * trace_length / 256). val *= numerators[7]. Denominator: point^(trace_length / 16) - 1. val *= denominator_invs[2]. res += val * (coefficients[256] + coefficients[257] * adjustments[16]). Constraint expression for ecdsa/signature0/doubling_key/y: column19_row15 + column19_row31 - column20_row0 * (column19_row7 - column19_row23). Numerator: point^(trace_length / 4096) - trace_generator^(255 * trace_length / 256). val *= numerators[7]. Denominator: point^(trace_length / 16) - 1. val *= denominator_invs[2]. res += val * (coefficients[258] + coefficients[259] * adjustments[16]). Constraint expression for ecdsa/signature0/exponentiate_generator/booleanity_test: ecdsa__signature0__exponentiate_generator__bit_0 * (ecdsa__signature0__exponentiate_generator__bit_0 - 1). Numerator: point^(trace_length / 8192) - trace_generator^(255 * trace_length / 256). val *= numerators[8]. Denominator: point^(trace_length / 32) - 1. val *= denominator_invs[15]. res += val * (coefficients[260] + coefficients[261] * adjustments[17]). Constraint expression for ecdsa/signature0/exponentiate_generator/bit_extraction_end: column20_row30. Numerator: 1. val *= 1. val := mulmod(val, 1, PRIME). Denominator: point^(trace_length / 8192) - trace_generator^(251 * trace_length / 256). val *= denominator_invs[16]. res += val * (coefficients[262] + coefficients[263] * adjustments[18]). Constraint expression for ecdsa/signature0/exponentiate_generator/zeros_tail: column20_row30. Numerator: 1. val *= 1. val := mulmod(val, 1, PRIME). Denominator: point^(trace_length / 8192) - trace_generator^(255 * trace_length / 256). val *= denominator_invs[17]. res += val * (coefficients[264] + coefficients[265] * adjustments[18]). Constraint expression for ecdsa/signature0/exponentiate_generator/add_points/slope: ecdsa__signature0__exponentiate_generator__bit_0 * (column20_row22 - ecdsa__generator_points__y) - column20_row14 * (column20_row6 - ecdsa__generator_points__x). Numerator: point^(trace_length / 8192) - trace_generator^(255 * trace_length / 256). val *= numerators[8]. Denominator: point^(trace_length / 32) - 1. val *= denominator_invs[15]. res += val * (coefficients[266] + coefficients[267] * adjustments[17]). Constraint expression for ecdsa/signature0/exponentiate_generator/add_points/x: column20_row14 * column20_row14 - ecdsa__signature0__exponentiate_generator__bit_0 * (column20_row6 + ecdsa__generator_points__x + column20_row38). Numerator: point^(trace_length / 8192) - trace_generator^(255 * trace_length / 256). val *= numerators[8]. Denominator: point^(trace_length / 32) - 1. val *= denominator_invs[15]. res += val * (coefficients[268] + coefficients[269] * adjustments[17]). Constraint expression for ecdsa/signature0/exponentiate_generator/add_points/y: ecdsa__signature0__exponentiate_generator__bit_0 * (column20_row22 + column20_row54) - column20_row14 * (column20_row6 - column20_row38). Numerator: point^(trace_length / 8192) - trace_generator^(255 * trace_length / 256). val *= numerators[8]. Denominator: point^(trace_length / 32) - 1. val *= denominator_invs[15]. res += val * (coefficients[270] + coefficients[271] * adjustments[17]). Constraint expression for ecdsa/signature0/exponentiate_generator/add_points/x_diff_inv: column20_row1 * (column20_row6 - ecdsa__generator_points__x) - 1. Numerator: point^(trace_length / 8192) - trace_generator^(255 * trace_length / 256). val *= numerators[8]. Denominator: point^(trace_length / 32) - 1. val *= denominator_invs[15]. res += val * (coefficients[272] + coefficients[273] * adjustments[17]). Constraint expression for ecdsa/signature0/exponentiate_generator/copy_point/x: ecdsa__signature0__exponentiate_generator__bit_neg_0 * (column20_row38 - column20_row6). Numerator: point^(trace_length / 8192) - trace_generator^(255 * trace_length / 256). val *= numerators[8]. Denominator: point^(trace_length / 32) - 1. val *= denominator_invs[15]. res += val * (coefficients[274] + coefficients[275] * adjustments[17]). Constraint expression for ecdsa/signature0/exponentiate_generator/copy_point/y: ecdsa__signature0__exponentiate_generator__bit_neg_0 * (column20_row54 - column20_row22). Numerator: point^(trace_length / 8192) - trace_generator^(255 * trace_length / 256). val *= numerators[8]. Denominator: point^(trace_length / 32) - 1. val *= denominator_invs[15]. res += val * (coefficients[276] + coefficients[277] * adjustments[17]). Constraint expression for ecdsa/signature0/exponentiate_key/booleanity_test: ecdsa__signature0__exponentiate_key__bit_0 * (ecdsa__signature0__exponentiate_key__bit_0 - 1). Numerator: point^(trace_length / 4096) - trace_generator^(255 * trace_length / 256). val *= numerators[7]. Denominator: point^(trace_length / 16) - 1. val *= denominator_invs[2]. res += val * (coefficients[278] + coefficients[279] * adjustments[16]). Constraint expression for ecdsa/signature0/exponentiate_key/bit_extraction_end: column20_row2. Numerator: 1. val *= 1. val := mulmod(val, 1, PRIME). Denominator: point^(trace_length / 4096) - trace_generator^(251 * trace_length / 256). val *= denominator_invs[18]. res += val * (coefficients[280] + coefficients[281] * adjustments[19]). Constraint expression for ecdsa/signature0/exponentiate_key/zeros_tail: column20_row2. Numerator: 1. val *= 1. val := mulmod(val, 1, PRIME). Denominator: point^(trace_length / 4096) - trace_generator^(255 * trace_length / 256). val *= denominator_invs[19]. res += val * (coefficients[282] + coefficients[283] * adjustments[19]). Constraint expression for ecdsa/signature0/exponentiate_key/add_points/slope: ecdsa__signature0__exponentiate_key__bit_0 * (column20_row4 - column19_row15) - column20_row12 * (column20_row8 - column19_row7). Numerator: point^(trace_length / 4096) - trace_generator^(255 * trace_length / 256). val *= numerators[7]. Denominator: point^(trace_length / 16) - 1. val *= denominator_invs[2]. res += val * (coefficients[284] + coefficients[285] * adjustments[16]). Constraint expression for ecdsa/signature0/exponentiate_key/add_points/x: column20_row12 * column20_row12 - ecdsa__signature0__exponentiate_key__bit_0 * (column20_row8 + column19_row7 + column20_row24). Numerator: point^(trace_length / 4096) - trace_generator^(255 * trace_length / 256). val *= numerators[7]. Denominator: point^(trace_length / 16) - 1. val *= denominator_invs[2]. res += val * (coefficients[286] + coefficients[287] * adjustments[16]). Constraint expression for ecdsa/signature0/exponentiate_key/add_points/y: ecdsa__signature0__exponentiate_key__bit_0 * (column20_row4 + column20_row20) - column20_row12 * (column20_row8 - column20_row24). Numerator: point^(trace_length / 4096) - trace_generator^(255 * trace_length / 256). val *= numerators[7]. Denominator: point^(trace_length / 16) - 1. val *= denominator_invs[2]. res += val * (coefficients[288] + coefficients[289] * adjustments[16]). Constraint expression for ecdsa/signature0/exponentiate_key/add_points/x_diff_inv: column20_row10 * (column20_row8 - column19_row7) - 1. Numerator: point^(trace_length / 4096) - trace_generator^(255 * trace_length / 256). val *= numerators[7]. Denominator: point^(trace_length / 16) - 1. val *= denominator_invs[2]. res += val * (coefficients[290] + coefficients[291] * adjustments[16]). Constraint expression for ecdsa/signature0/exponentiate_key/copy_point/x: ecdsa__signature0__exponentiate_key__bit_neg_0 * (column20_row24 - column20_row8). Numerator: point^(trace_length / 4096) - trace_generator^(255 * trace_length / 256). val *= numerators[7]. Denominator: point^(trace_length / 16) - 1. val *= denominator_invs[2]. res += val * (coefficients[292] + coefficients[293] * adjustments[16]). Constraint expression for ecdsa/signature0/exponentiate_key/copy_point/y: ecdsa__signature0__exponentiate_key__bit_neg_0 * (column20_row20 - column20_row4). Numerator: point^(trace_length / 4096) - trace_generator^(255 * trace_length / 256). val *= numerators[7]. Denominator: point^(trace_length / 16) - 1. val *= denominator_invs[2]. res += val * (coefficients[294] + coefficients[295] * adjustments[16]). Constraint expression for ecdsa/signature0/init_gen/x: column20_row6 - ecdsa/sig_config.shift_point.x. Numerator: 1. val *= 1. val := mulmod(val, 1, PRIME). Denominator: point^(trace_length / 8192) - 1. val *= denominator_invs[20]. res += val * (coefficients[296] + coefficients[297] * adjustments[18]). Constraint expression for ecdsa/signature0/init_gen/y: column20_row22 + ecdsa/sig_config.shift_point.y. Numerator: 1. val *= 1. val := mulmod(val, 1, PRIME). Denominator: point^(trace_length / 8192) - 1. val *= denominator_invs[20]. res += val * (coefficients[298] + coefficients[299] * adjustments[18]). Constraint expression for ecdsa/signature0/init_key/x: column20_row8 - ecdsa/sig_config.shift_point.x. Numerator: 1. val *= 1. val := mulmod(val, 1, PRIME). Denominator: point^(trace_length / 4096) - 1. val *= denominator_invs[21]. res += val * (coefficients[300] + coefficients[301] * adjustments[19]). Constraint expression for ecdsa/signature0/init_key/y: column20_row4 - ecdsa/sig_config.shift_point.y. Numerator: 1. val *= 1. val := mulmod(val, 1, PRIME). Denominator: point^(trace_length / 4096) - 1. val *= denominator_invs[21]. res += val * (coefficients[302] + coefficients[303] * adjustments[19]). Constraint expression for ecdsa/signature0/add_results/slope: column20_row8182 - (column20_row4084 + column20_row8161 * (column20_row8166 - column20_row4088)). Numerator: 1. val *= 1. val := mulmod(val, 1, PRIME). Denominator: point^(trace_length / 8192) - 1. val *= denominator_invs[20]. res += val * (coefficients[304] + coefficients[305] * adjustments[20]). Constraint expression for ecdsa/signature0/add_results/x: column20_row8161 * column20_row8161 - (column20_row8166 + column20_row4088 + column19_row4103). Numerator: 1. val *= 1. val := mulmod(val, 1, PRIME). Denominator: point^(trace_length / 8192) - 1. val *= denominator_invs[20]. res += val * (coefficients[306] + coefficients[307] * adjustments[20]). Constraint expression for ecdsa/signature0/add_results/y: column20_row8182 + column19_row4111 - column20_row8161 * (column20_row8166 - column19_row4103). Numerator: 1. val *= 1. val := mulmod(val, 1, PRIME). Denominator: point^(trace_length / 8192) - 1. val *= denominator_invs[20]. res += val * (coefficients[308] + coefficients[309] * adjustments[20]). Constraint expression for ecdsa/signature0/add_results/x_diff_inv: column20_row8174 * (column20_row8166 - column20_row4088) - 1. Numerator: 1. val *= 1. val := mulmod(val, 1, PRIME). Denominator: point^(trace_length / 8192) - 1. val *= denominator_invs[20]. res += val * (coefficients[310] + coefficients[311] * adjustments[20]). Constraint expression for ecdsa/signature0/extract_r/slope: column20_row8180 + ecdsa/sig_config.shift_point.y - column20_row4092 * (column20_row8184 - ecdsa/sig_config.shift_point.x). Numerator: 1. val *= 1. val := mulmod(val, 1, PRIME). Denominator: point^(trace_length / 8192) - 1. val *= denominator_invs[20]. res += val * (coefficients[312] + coefficients[313] * adjustments[20]). Constraint expression for ecdsa/signature0/extract_r/x: column20_row4092 * column20_row4092 - (column20_row8184 + ecdsa/sig_config.shift_point.x + column20_row2). Numerator: 1. val *= 1. val := mulmod(val, 1, PRIME). Denominator: point^(trace_length / 8192) - 1. val *= denominator_invs[20]. res += val * (coefficients[314] + coefficients[315] * adjustments[20]). Constraint expression for ecdsa/signature0/extract_r/x_diff_inv: column20_row8188 * (column20_row8184 - ecdsa/sig_config.shift_point.x) - 1. Numerator: 1. val *= 1. val := mulmod(val, 1, PRIME). Denominator: point^(trace_length / 8192) - 1. val *= denominator_invs[20]. res += val * (coefficients[316] + coefficients[317] * adjustments[20]). Constraint expression for ecdsa/signature0/z_nonzero: column20_row30 * column20_row4080 - 1. Numerator: 1. val *= 1. val := mulmod(val, 1, PRIME). Denominator: point^(trace_length / 8192) - 1. val *= denominator_invs[20]. res += val * (coefficients[318] + coefficients[319] * adjustments[20]). Constraint expression for ecdsa/signature0/r_and_w_nonzero: column20_row2 * column20_row4090 - 1. Numerator: 1. val *= 1. val := mulmod(val, 1, PRIME). Denominator: point^(trace_length / 4096) - 1. val *= denominator_invs[21]. res += val * (coefficients[320] + coefficients[321] * adjustments[21]). Constraint expression for ecdsa/signature0/q_on_curve/x_squared: column20_row8176 - column19_row7 * column19_row7. Numerator: 1. val *= 1. val := mulmod(val, 1, PRIME). Denominator: point^(trace_length / 8192) - 1. val *= denominator_invs[20]. res += val * (coefficients[322] + coefficients[323] * adjustments[20]). Constraint expression for ecdsa/signature0/q_on_curve/on_curve: column19_row15 * column19_row15 - (column19_row7 * column20_row8176 + ecdsa/sig_config.alpha * column19_row7 + ecdsa/sig_config.beta). Numerator: 1. val *= 1. val := mulmod(val, 1, PRIME). Denominator: point^(trace_length / 8192) - 1. val *= denominator_invs[20]. res += val * (coefficients[324] + coefficients[325] * adjustments[20]). Constraint expression for ecdsa/init_addr: column17_row22 - initial_ecdsa_addr. Numerator: 1. val *= 1. val := mulmod(val, 1, PRIME). Denominator: point - 1. val *= denominator_invs[3]. res += val * (coefficients[326] + coefficients[327] * adjustments[4]). Constraint expression for ecdsa/message_addr: column17_row4118 - (column17_row22 + 1). Numerator: 1. val *= 1. val := mulmod(val, 1, PRIME). Denominator: point^(trace_length / 8192) - 1. val *= denominator_invs[20]. res += val * (coefficients[328] + coefficients[329] * adjustments[18]). Constraint expression for ecdsa/pubkey_addr: column17_row8214 - (column17_row4118 + 1). Numerator: point - trace_generator^(8192 * (trace_length / 8192 - 1)). val *= numerators[9]. Denominator: point^(trace_length / 8192) - 1. val *= denominator_invs[20]. res += val * (coefficients[330] + coefficients[331] * adjustments[22]). Constraint expression for ecdsa/message_value0: column17_row4119 - column20_row30. Numerator: 1. val *= 1. val := mulmod(val, 1, PRIME). Denominator: point^(trace_length / 8192) - 1. val *= denominator_invs[20]. res += val * (coefficients[332] + coefficients[333] * adjustments[18]). Constraint expression for ecdsa/pubkey_value0: column17_row23 - column19_row7. Numerator: 1. val *= 1. val := mulmod(val, 1, PRIME). Denominator: point^(trace_length / 8192) - 1. val *= denominator_invs[20]. res += val * (coefficients[334] + coefficients[335] * adjustments[18]). Constraint expression for checkpoints/req_pc_init_addr: column17_row150 - initial_checkpoints_addr. Numerator: 1. val *= 1. val := mulmod(val, 1, PRIME). Denominator: point - 1. val *= denominator_invs[3]. res += val * (coefficients[336] + coefficients[337] * adjustments[4]). Constraint expression for checkpoints/req_pc_final_addr: column17_row150 - final_checkpoints_addr. Numerator: 1. val *= 1. val := mulmod(val, 1, PRIME). Denominator: point - trace_generator^(256 * (trace_length / 256 - 1)). val *= denominator_invs[22]. res += val * (coefficients[338] + coefficients[339] * adjustments[4]). Constraint expression for checkpoints/required_fp_addr: column17_row86 - (column17_row150 + 1). Numerator: 1. val *= 1. val := mulmod(val, 1, PRIME). Denominator: point^(trace_length / 256) - 1. val *= denominator_invs[10]. res += val * (coefficients[340] + coefficients[341] * adjustments[11]). Constraint expression for checkpoints/required_pc_next_addr: (column17_row406 - column17_row150) * (column17_row406 - (column17_row150 + 2)). Numerator: point - trace_generator^(256 * (trace_length / 256 - 1)). val *= numerators[10]. Denominator: point^(trace_length / 256) - 1. val *= denominator_invs[10]. res += val * (coefficients[342] + coefficients[343] * adjustments[23]). Constraint expression for checkpoints/req_pc: (column17_row406 - column17_row150) * (column17_row151 - column17_row0). Numerator: point - trace_generator^(256 * (trace_length / 256 - 1)). val *= numerators[10]. Denominator: point^(trace_length / 256) - 1. val *= denominator_invs[10]. res += val * (coefficients[344] + coefficients[345] * adjustments[23]). Constraint expression for checkpoints/req_fp: (column17_row406 - column17_row150) * (column17_row87 - column19_row9). Numerator: point - trace_generator^(256 * (trace_length / 256 - 1)). val *= numerators[10]. Denominator: point^(trace_length / 256) - 1. val *= denominator_invs[10]. res += val * (coefficients[346] + coefficients[347] * adjustments[23]).
{ { let val := addmod( sub( PRIME, addmod(/*column0_row1*/ mload(0x2fe0), /*column0_row1*/ mload(0x2fe0), PRIME)), PRIME) mstore(0x4980, val) { let val := addmod( sub( PRIME, addmod(/*column0_row2*/ mload(0x3000), /*column0_row2*/ mload(0x3000), PRIME)), PRIME) mstore(0x49a0, val) { let val := addmod( sub( PRIME, addmod(/*column0_row3*/ mload(0x3020), /*column0_row3*/ mload(0x3020), PRIME)), PRIME) mstore(0x49c0, val) { let val := addmod( sub( PRIME, addmod(/*column0_row5*/ mload(0x3060), /*column0_row5*/ mload(0x3060), PRIME)), PRIME) mstore(0x49e0, val) { let val := addmod( sub( PRIME, addmod(/*column0_row4*/ mload(0x3040), /*column0_row4*/ mload(0x3040), PRIME)), PRIME) mstore(0x4a00, val) { let val := addmod( sub( PRIME, addmod(/*column0_row10*/ mload(0x3100), /*column0_row10*/ mload(0x3100), PRIME)), PRIME) mstore(0x4a20, val) { let val := addmod( sub( PRIME, addmod(/*column0_row6*/ mload(0x3080), /*column0_row6*/ mload(0x3080), PRIME)), PRIME) mstore(0x4a40, val) { let val := addmod( sub( PRIME, addmod(/*column0_row7*/ mload(0x30a0), /*column0_row7*/ mload(0x30a0), PRIME)), PRIME) mstore(0x4a60, val) { let val := addmod( sub( PRIME, addmod(/*column0_row8*/ mload(0x30c0), /*column0_row8*/ mload(0x30c0), PRIME)), PRIME) mstore(0x4a80, val) { let val := addmod( sub( PRIME, addmod(/*column0_row9*/ mload(0x30e0), /*column0_row9*/ mload(0x30e0), PRIME)), PRIME) mstore(0x4aa0, val) { let val := addmod( addmod( PRIME), 1, PRIME) mstore(0x4ac0, val) { let val := addmod( sub( PRIME, addmod(/*column0_row11*/ mload(0x3120), /*column0_row11*/ mload(0x3120), PRIME)), PRIME) mstore(0x4ae0, val) { let val := addmod( sub( PRIME, addmod(/*column0_row12*/ mload(0x3140), /*column0_row12*/ mload(0x3140), PRIME)), PRIME) mstore(0x4b00, val) { let val := addmod( sub( PRIME, addmod(/*column0_row13*/ mload(0x3160), /*column0_row13*/ mload(0x3160), PRIME)), PRIME) mstore(0x4b20, val) { let val := addmod( sub( PRIME, addmod(/*column0_row14*/ mload(0x3180), /*column0_row14*/ mload(0x3180), PRIME)), PRIME) mstore(0x4b40, val) { let val := addmod( sub( PRIME, addmod(/*column0_row15*/ mload(0x31a0), /*column0_row15*/ mload(0x31a0), PRIME)), PRIME) mstore(0x4b60, val) { let val := addmod(/*column18_row2*/ mload(0x4100), sub(PRIME, /*column18_row0*/ mload(0x40c0)), PRIME) mstore(0x4b80, val) } { let val := addmod(/*column19_row6*/ mload(0x4200), sub(PRIME, /*column19_row2*/ mload(0x4180)), PRIME) mstore(0x4ba0, val) } { let val := addmod( sub( PRIME, addmod(/*column4_row1*/ mload(0x3340), /*column4_row1*/ mload(0x3340), PRIME)), PRIME) mstore(0x4bc0, val) { let val := addmod( 1, sub(PRIME, /*intermediate_value/pedersen/hash0/ec_subset_sum/bit_0*/ mload(0x4bc0)), PRIME) mstore(0x4be0, val) } { let val := addmod( sub( PRIME, addmod(/*column8_row1*/ mload(0x35c0), /*column8_row1*/ mload(0x35c0), PRIME)), PRIME) mstore(0x4c00, val) { let val := addmod( 1, sub(PRIME, /*intermediate_value/pedersen/hash1/ec_subset_sum/bit_0*/ mload(0x4c00)), PRIME) mstore(0x4c20, val) } { let val := addmod( sub( PRIME, addmod(/*column12_row1*/ mload(0x3840), /*column12_row1*/ mload(0x3840), PRIME)), PRIME) mstore(0x4c40, val) { let val := addmod( 1, sub(PRIME, /*intermediate_value/pedersen/hash2/ec_subset_sum/bit_0*/ mload(0x4c40)), PRIME) mstore(0x4c60, val) } { let val := addmod( sub( PRIME, addmod(/*column16_row1*/ mload(0x3ac0), /*column16_row1*/ mload(0x3ac0), PRIME)), PRIME) mstore(0x4c80, val) { let val := addmod( 1, sub(PRIME, /*intermediate_value/pedersen/hash3/ec_subset_sum/bit_0*/ mload(0x4c80)), PRIME) mstore(0x4ca0, val) } { let val := /*column19_row12*/ mload(0x42a0) mstore(0x4cc0, val) } { let val := addmod( mulmod( PRIME), PRIME) mstore(0x4ce0, val) { let val := addmod( mulmod( PRIME), PRIME) mstore(0x4d00, val) { let val := addmod( mulmod( PRIME), PRIME) mstore(0x4d20, val) { let val := addmod( mulmod( PRIME), PRIME) mstore(0x4d40, val) { let val := addmod( mulmod( PRIME), PRIME) mstore(0x4d60, val) { let val := addmod( mulmod( PRIME), PRIME) mstore(0x4d80, val) { let val := addmod( mulmod( PRIME), PRIME) mstore(0x4da0, val) { let val := mulmod(/*column19_row7*/ mload(0x4220), /*column19_row7*/ mload(0x4220), PRIME) mstore(0x4dc0, val) } { let val := addmod( sub( PRIME, addmod(/*column20_row62*/ mload(0x46c0), /*column20_row62*/ mload(0x46c0), PRIME)), PRIME) mstore(0x4de0, val) { let val := addmod( 1, sub( PRIME, PRIME) mstore(0x4e00, val) { let val := addmod( sub( PRIME, addmod(/*column20_row18*/ mload(0x45e0), /*column20_row18*/ mload(0x45e0), PRIME)), PRIME) mstore(0x4e20, val) { let val := addmod( 1, sub( PRIME, PRIME) mstore(0x4e40, val) { let val := addmod( mulmod( PRIME), sub(PRIME, /*intermediate_value/cpu/decode/opcode_rc/bit_0*/ mload(0x4980)), PRIME) val := mulmod(val, mload(0x56e0), PRIME) val := mulmod(val, mload(0x5120), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[0]*/ mload(0x440), mulmod(/*coefficients[1]*/ mload(0x460), PRIME)), PRIME), PRIME) { let val := /*column0_row0*/ mload(0x2fc0) val := mulmod(val, mload(0x5140), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[2]*/ mload(0x480), mulmod(/*coefficients[3]*/ mload(0x4a0), PRIME)), PRIME), PRIME) { let val := addmod( sub( PRIME, addmod( mulmod( addmod( mulmod( addmod( mulmod(/*column0_row0*/ mload(0x2fc0), /*offset_size*/ mload(0xa0), PRIME), PRIME), PRIME), PRIME), PRIME), PRIME)), PRIME) val := mulmod(val, mload(0x5160), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[4]*/ mload(0x4c0), mulmod(/*coefficients[5]*/ mload(0x4e0), PRIME)), PRIME), PRIME) { let val := addmod( addmod(/*column17_row8*/ mload(0x3cc0), /*half_offset_size*/ mload(0xc0), PRIME), sub( PRIME, addmod( addmod( mulmod( PRIME), mulmod( addmod( 1, sub(PRIME, /*intermediate_value/cpu/decode/opcode_rc/bit_0*/ mload(0x4980)), PRIME), PRIME), PRIME), PRIME)), PRIME) val := mulmod(val, mload(0x5160), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[6]*/ mload(0x500), mulmod(/*coefficients[7]*/ mload(0x520), PRIME)), PRIME), PRIME) { let val := addmod( addmod(/*column17_row4*/ mload(0x3c40), /*half_offset_size*/ mload(0xc0), PRIME), sub( PRIME, addmod( addmod( mulmod( PRIME), mulmod( addmod( 1, sub(PRIME, /*intermediate_value/cpu/decode/opcode_rc/bit_1*/ mload(0x49a0)), PRIME), PRIME), PRIME), PRIME)), PRIME) val := mulmod(val, mload(0x5160), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[8]*/ mload(0x540), mulmod(/*coefficients[9]*/ mload(0x560), PRIME)), PRIME), PRIME) { let val := addmod( addmod(/*column17_row12*/ mload(0x3d00), /*half_offset_size*/ mload(0xc0), PRIME), sub( PRIME, addmod( addmod( addmod( addmod( mulmod( PRIME), mulmod( PRIME), PRIME), mulmod( PRIME), PRIME), mulmod( addmod( 1, sub( PRIME, addmod( addmod( PRIME), PRIME)), PRIME), PRIME), PRIME), PRIME)), PRIME) val := mulmod(val, mload(0x5160), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[10]*/ mload(0x580), mulmod(/*coefficients[11]*/ mload(0x5a0), PRIME)), PRIME), PRIME) { let val := addmod( sub( PRIME, mulmod(/*column17_row5*/ mload(0x3c60), /*column17_row13*/ mload(0x3d20), PRIME)), PRIME) val := mulmod(val, mload(0x5160), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[12]*/ mload(0x5c0), mulmod(/*coefficients[13]*/ mload(0x5e0), PRIME)), PRIME), PRIME) { let val := addmod( mulmod( addmod( 1, sub(PRIME, /*intermediate_value/cpu/decode/opcode_rc/bit_9*/ mload(0x4a20)), PRIME), PRIME), sub( PRIME, addmod( addmod( mulmod( addmod(/*column17_row5*/ mload(0x3c60), /*column17_row13*/ mload(0x3d20), PRIME), PRIME), mulmod( PRIME), PRIME), mulmod( addmod( 1, sub( PRIME, addmod( addmod( PRIME), PRIME)), PRIME), PRIME), PRIME)), PRIME) val := mulmod(val, mload(0x5160), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[14]*/ mload(0x600), mulmod(/*coefficients[15]*/ mload(0x620), PRIME)), PRIME), PRIME) { let val := addmod( sub( PRIME, mulmod( PRIME)), PRIME) val := mulmod(val, mload(0x5700), PRIME) val := mulmod(val, mload(0x5160), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[16]*/ mload(0x640), mulmod(/*coefficients[17]*/ mload(0x660), PRIME)), PRIME), PRIME) { let val := addmod( sub( PRIME, mulmod(/*column19_row3*/ mload(0x41a0), /*column19_row13*/ mload(0x42c0), PRIME)), PRIME) val := mulmod(val, mload(0x5700), PRIME) val := mulmod(val, mload(0x5160), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[18]*/ mload(0x680), mulmod(/*coefficients[19]*/ mload(0x6a0), PRIME)), PRIME), PRIME) { let val := addmod( addmod( mulmod( addmod( 1, sub(PRIME, /*intermediate_value/cpu/decode/opcode_rc/bit_9*/ mload(0x4a20)), PRIME), PRIME), mulmod( addmod( sub( PRIME, addmod(/*column17_row0*/ mload(0x3bc0), /*column17_row13*/ mload(0x3d20), PRIME)), PRIME), PRIME), PRIME), sub( PRIME, addmod( addmod( mulmod( addmod( 1, sub( PRIME, addmod( addmod( PRIME), PRIME)), PRIME), PRIME), mulmod( PRIME), PRIME), mulmod( addmod(/*column17_row0*/ mload(0x3bc0), /*column19_row13*/ mload(0x42c0), PRIME), PRIME), PRIME)), PRIME) val := mulmod(val, mload(0x5700), PRIME) val := mulmod(val, mload(0x5160), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[20]*/ mload(0x6c0), mulmod(/*coefficients[21]*/ mload(0x6e0), PRIME)), PRIME), PRIME) { let val := mulmod( addmod( sub(PRIME, /*intermediate_value/cpu/decode/opcode_rc/bit_9*/ mload(0x4a20)), PRIME), addmod( sub(PRIME, /*intermediate_value/npc_reg_0*/ mload(0x4ac0)), PRIME), PRIME) val := mulmod(val, mload(0x5700), PRIME) val := mulmod(val, mload(0x5160), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[22]*/ mload(0x700), mulmod(/*coefficients[23]*/ mload(0x720), PRIME)), PRIME), PRIME) { let val := addmod( sub( PRIME, addmod( addmod( addmod( mulmod( PRIME), PRIME), PRIME), mulmod(/*intermediate_value/cpu/decode/opcode_rc/bit_12*/ mload(0x4b20), 2, PRIME), PRIME)), PRIME) val := mulmod(val, mload(0x5700), PRIME) val := mulmod(val, mload(0x5160), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[24]*/ mload(0x740), mulmod(/*coefficients[25]*/ mload(0x760), PRIME)), PRIME), PRIME) { let val := addmod( sub( PRIME, addmod( addmod( mulmod( addmod( 1, sub( PRIME, addmod( PRIME)), PRIME), PRIME), mulmod( PRIME), PRIME), mulmod( addmod(/*column19_row1*/ mload(0x4160), 2, PRIME), PRIME), PRIME)), PRIME) val := mulmod(val, mload(0x5700), PRIME) val := mulmod(val, mload(0x5160), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[26]*/ mload(0x780), mulmod(/*coefficients[27]*/ mload(0x7a0), PRIME)), PRIME), PRIME) { let val := mulmod( addmod(/*column17_row9*/ mload(0x3ce0), sub(PRIME, /*column19_row9*/ mload(0x4260)), PRIME), PRIME) val := mulmod(val, mload(0x5160), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[28]*/ mload(0x7c0), mulmod(/*coefficients[29]*/ mload(0x7e0), PRIME)), PRIME), PRIME) { let val := mulmod( addmod( sub( PRIME, addmod( addmod( PRIME), 1, PRIME)), PRIME), PRIME) val := mulmod(val, mload(0x5160), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[30]*/ mload(0x800), mulmod(/*coefficients[31]*/ mload(0x820), PRIME)), PRIME), PRIME) { let val := mulmod( addmod( sub(PRIME, /*column19_row13*/ mload(0x42c0)), PRIME), PRIME) val := mulmod(val, mload(0x5160), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[32]*/ mload(0x840), mulmod(/*coefficients[33]*/ mload(0x860), PRIME)), PRIME), PRIME) { let val := addmod(/*column19_row1*/ mload(0x4160), sub(PRIME, /*initial_ap*/ mload(0xe0)), PRIME) val := mulmod(val, mload(0x5180), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[34]*/ mload(0x880), mulmod(/*coefficients[35]*/ mload(0x8a0), PRIME)), PRIME), PRIME) { let val := addmod(/*column19_row9*/ mload(0x4260), sub(PRIME, /*initial_ap*/ mload(0xe0)), PRIME) val := mulmod(val, mload(0x5180), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[36]*/ mload(0x8c0), mulmod(/*coefficients[37]*/ mload(0x8e0), PRIME)), PRIME), PRIME) { let val := addmod(/*column17_row0*/ mload(0x3bc0), sub(PRIME, /*initial_pc*/ mload(0x100)), PRIME) val := mulmod(val, mload(0x5180), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[38]*/ mload(0x900), mulmod(/*coefficients[39]*/ mload(0x920), PRIME)), PRIME), PRIME) { let val := addmod(/*column19_row1*/ mload(0x4160), sub(PRIME, /*final_ap*/ mload(0x120)), PRIME) val := mulmod(val, mload(0x51a0), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[40]*/ mload(0x940), mulmod(/*coefficients[41]*/ mload(0x960), PRIME)), PRIME), PRIME) { let val := addmod(/*column17_row0*/ mload(0x3bc0), sub(PRIME, /*final_pc*/ mload(0x140)), PRIME) val := mulmod(val, mload(0x51a0), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[42]*/ mload(0x980), mulmod(/*coefficients[43]*/ mload(0x9a0), PRIME)), PRIME), PRIME) { let val := addmod( addmod( addmod( mulmod( addmod( sub( PRIME, addmod( mulmod( PRIME), PRIME)), PRIME), PRIME), PRIME), mulmod( PRIME), PRIME), sub(PRIME, /*memory/multi_column_perm/perm/interaction_elm*/ mload(0x160)), PRIME) val := mulmod(val, mload(0x5180), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[44]*/ mload(0x9c0), mulmod(/*coefficients[45]*/ mload(0x9e0), PRIME)), PRIME), PRIME) { let val := addmod( mulmod( addmod( sub( PRIME, addmod( mulmod( PRIME), PRIME)), PRIME), PRIME), sub( PRIME, mulmod( addmod( sub( PRIME, addmod( mulmod( PRIME), PRIME)), PRIME), PRIME)), PRIME) val := mulmod(val, mload(0x5720), PRIME) val := mulmod(val, mload(0x51c0), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[46]*/ mload(0xa00), mulmod(/*coefficients[47]*/ mload(0xa20), PRIME)), PRIME), PRIME) { let val := addmod( sub(PRIME, /*memory/multi_column_perm/perm/public_memory_prod*/ mload(0x1a0)), PRIME) val := mulmod(val, mload(0x51e0), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[48]*/ mload(0xa40), mulmod(/*coefficients[49]*/ mload(0xa60), PRIME)), PRIME), PRIME) { let val := addmod( mulmod( PRIME), sub(PRIME, /*intermediate_value/memory/address_diff_0*/ mload(0x4b80)), PRIME) val := mulmod(val, mload(0x5720), PRIME) val := mulmod(val, mload(0x51c0), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[50]*/ mload(0xa80), mulmod(/*coefficients[51]*/ mload(0xaa0), PRIME)), PRIME), PRIME) { let val := mulmod( addmod(/*intermediate_value/memory/address_diff_0*/ mload(0x4b80), sub(PRIME, 1), PRIME), addmod(/*column18_row1*/ mload(0x40e0), sub(PRIME, /*column18_row3*/ mload(0x4120)), PRIME), PRIME) val := mulmod(val, mload(0x5720), PRIME) val := mulmod(val, mload(0x51c0), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[52]*/ mload(0xac0), mulmod(/*coefficients[53]*/ mload(0xae0), PRIME)), PRIME), PRIME) { let val := addmod(/*column18_row0*/ mload(0x40c0), sub(PRIME, 1), PRIME) val := mulmod(val, mload(0x5180), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[54]*/ mload(0xb00), mulmod(/*coefficients[55]*/ mload(0xb20), PRIME)), PRIME), PRIME) { let val := /*column17_row2*/ mload(0x3c00) val := mulmod(val, mload(0x5200), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[56]*/ mload(0xb40), mulmod(/*coefficients[57]*/ mload(0xb60), PRIME)), PRIME), PRIME) { let val := /*column17_row3*/ mload(0x3c20) val := mulmod(val, mload(0x5200), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[58]*/ mload(0xb80), mulmod(/*coefficients[59]*/ mload(0xba0), PRIME)), PRIME), PRIME) { let val := addmod( addmod( mulmod( addmod( sub(PRIME, /*column19_row2*/ mload(0x4180)), PRIME), PRIME), PRIME), sub(PRIME, /*rc16/perm/interaction_elm*/ mload(0x1c0)), PRIME) val := mulmod(val, mload(0x5180), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[60]*/ mload(0xbc0), mulmod(/*coefficients[61]*/ mload(0xbe0), PRIME)), PRIME), PRIME) { let val := addmod( mulmod( addmod( sub(PRIME, /*column19_row6*/ mload(0x4200)), PRIME), PRIME), sub( PRIME, mulmod( addmod( sub(PRIME, /*column19_row4*/ mload(0x41c0)), PRIME), PRIME)), PRIME) val := mulmod(val, mload(0x5740), PRIME) val := mulmod(val, mload(0x5220), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[62]*/ mload(0xc00), mulmod(/*coefficients[63]*/ mload(0xc20), PRIME)), PRIME), PRIME) { let val := addmod( sub(PRIME, /*rc16/perm/public_memory_prod*/ mload(0x1e0)), PRIME) val := mulmod(val, mload(0x5240), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[64]*/ mload(0xc40), mulmod(/*coefficients[65]*/ mload(0xc60), PRIME)), PRIME), PRIME) { let val := addmod( mulmod( PRIME), sub(PRIME, /*intermediate_value/rc16/diff_0*/ mload(0x4ba0)), PRIME) val := mulmod(val, mload(0x5740), PRIME) val := mulmod(val, mload(0x5220), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[66]*/ mload(0xc80), mulmod(/*coefficients[67]*/ mload(0xca0), PRIME)), PRIME), PRIME) { let val := addmod(/*column19_row2*/ mload(0x4180), sub(PRIME, /*rc_min*/ mload(0x200)), PRIME) val := mulmod(val, mload(0x5180), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[68]*/ mload(0xcc0), mulmod(/*coefficients[69]*/ mload(0xce0), PRIME)), PRIME), PRIME) { let val := addmod(/*column19_row2*/ mload(0x4180), sub(PRIME, /*rc_max*/ mload(0x220)), PRIME) val := mulmod(val, mload(0x5240), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[70]*/ mload(0xd00), mulmod(/*coefficients[71]*/ mload(0xd20), PRIME)), PRIME), PRIME) { let val := mulmod( addmod( sub( PRIME, addmod(/*column4_row1*/ mload(0x3340), /*column4_row1*/ mload(0x3340), PRIME)), PRIME), PRIME) val := mulmod(val, mload(0x5260), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[72]*/ mload(0xd40), mulmod(/*coefficients[73]*/ mload(0xd60), PRIME)), PRIME), PRIME) { let val := mulmod( addmod( sub( PRIME, mulmod( 3138550867693340381917894711603833208051177722232017256448, PRIME)), PRIME), PRIME) val := mulmod(val, mload(0x5260), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[74]*/ mload(0xd80), mulmod(/*coefficients[75]*/ mload(0xda0), PRIME)), PRIME), PRIME) { let val := addmod( sub( PRIME, mulmod( addmod( sub( PRIME, addmod(/*column4_row193*/ mload(0x3380), /*column4_row193*/ mload(0x3380), PRIME)), PRIME), PRIME)), PRIME) val := mulmod(val, mload(0x5260), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[76]*/ mload(0xdc0), mulmod(/*coefficients[77]*/ mload(0xde0), PRIME)), PRIME), PRIME) { let val := mulmod( addmod( sub(PRIME, mulmod(8, /*column4_row196*/ mload(0x33a0), PRIME)), PRIME), PRIME) val := mulmod(val, mload(0x5260), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[78]*/ mload(0xe00), mulmod(/*coefficients[79]*/ mload(0xe20), PRIME)), PRIME), PRIME) { let val := addmod( sub( PRIME, mulmod( addmod( sub( PRIME, addmod(/*column4_row252*/ mload(0x3400), /*column4_row252*/ mload(0x3400), PRIME)), PRIME), addmod( sub( PRIME, addmod(/*column4_row197*/ mload(0x33c0), /*column4_row197*/ mload(0x33c0), PRIME)), PRIME), PRIME)), PRIME) val := mulmod(val, mload(0x5260), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[80]*/ mload(0xe40), mulmod(/*coefficients[81]*/ mload(0xe60), PRIME)), PRIME), PRIME) { let val := mulmod( addmod( sub( PRIME, addmod(/*column4_row252*/ mload(0x3400), /*column4_row252*/ mload(0x3400), PRIME)), PRIME), addmod( sub(PRIME, mulmod(18014398509481984, /*column4_row251*/ mload(0x33e0), PRIME)), PRIME), PRIME) val := mulmod(val, mload(0x5260), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[82]*/ mload(0xe80), mulmod(/*coefficients[83]*/ mload(0xea0), PRIME)), PRIME), PRIME) { let val := mulmod( addmod( sub(PRIME, 1), PRIME), PRIME) val := mulmod(val, mload(0x5760), PRIME) val := mulmod(val, mload(0x5120), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[84]*/ mload(0xec0), mulmod(/*coefficients[85]*/ mload(0xee0), PRIME)), PRIME), PRIME) { let val := /*column4_row0*/ mload(0x3320) val := mulmod(val, mload(0x5280), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[86]*/ mload(0xf00), mulmod(/*coefficients[87]*/ mload(0xf20), PRIME)), PRIME), PRIME) { let val := /*column4_row0*/ mload(0x3320) val := mulmod(val, mload(0x52a0), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[88]*/ mload(0xf40), mulmod(/*coefficients[89]*/ mload(0xf60), PRIME)), PRIME), PRIME) { let val := addmod( mulmod( addmod( sub(PRIME, /*periodic_column/pedersen/points/y*/ mload(0x20)), PRIME), PRIME), sub( PRIME, mulmod( addmod( sub(PRIME, /*periodic_column/pedersen/points/x*/ mload(0x0)), PRIME), PRIME)), PRIME) val := mulmod(val, mload(0x5760), PRIME) val := mulmod(val, mload(0x5120), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[90]*/ mload(0xf80), mulmod(/*coefficients[91]*/ mload(0xfa0), PRIME)), PRIME), PRIME) { let val := addmod( mulmod(/*column3_row0*/ mload(0x32e0), /*column3_row0*/ mload(0x32e0), PRIME), sub( PRIME, mulmod( addmod( addmod( PRIME), PRIME), PRIME)), PRIME) val := mulmod(val, mload(0x5760), PRIME) val := mulmod(val, mload(0x5120), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[92]*/ mload(0xfc0), mulmod(/*coefficients[93]*/ mload(0xfe0), PRIME)), PRIME), PRIME) { let val := addmod( mulmod( addmod(/*column2_row0*/ mload(0x3260), /*column2_row1*/ mload(0x3280), PRIME), PRIME), sub( PRIME, mulmod( addmod(/*column1_row0*/ mload(0x31c0), sub(PRIME, /*column1_row1*/ mload(0x31e0)), PRIME), PRIME)), PRIME) val := mulmod(val, mload(0x5760), PRIME) val := mulmod(val, mload(0x5120), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[94]*/ mload(0x1000), mulmod(/*coefficients[95]*/ mload(0x1020), PRIME)), PRIME), PRIME) { let val := mulmod( addmod(/*column1_row1*/ mload(0x31e0), sub(PRIME, /*column1_row0*/ mload(0x31c0)), PRIME), PRIME) val := mulmod(val, mload(0x5760), PRIME) val := mulmod(val, mload(0x5120), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[96]*/ mload(0x1040), mulmod(/*coefficients[97]*/ mload(0x1060), PRIME)), PRIME), PRIME) { let val := mulmod( addmod(/*column2_row1*/ mload(0x3280), sub(PRIME, /*column2_row0*/ mload(0x3260)), PRIME), PRIME) val := mulmod(val, mload(0x5760), PRIME) val := mulmod(val, mload(0x5120), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[98]*/ mload(0x1080), mulmod(/*coefficients[99]*/ mload(0x10a0), PRIME)), PRIME), PRIME) { let val := addmod( sub(PRIME, /*column1_row255*/ mload(0x3200)), PRIME) val := mulmod(val, mload(0x5780), PRIME) val := mulmod(val, mload(0x5260), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[100]*/ mload(0x10c0), mulmod(/*coefficients[101]*/ mload(0x10e0), PRIME)), PRIME), PRIME) { let val := addmod( sub(PRIME, /*column2_row255*/ mload(0x32a0)), PRIME) val := mulmod(val, mload(0x5780), PRIME) val := mulmod(val, mload(0x5260), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[102]*/ mload(0x1100), mulmod(/*coefficients[103]*/ mload(0x1120), PRIME)), PRIME), PRIME) { let val := addmod( sub(PRIME, /*pedersen/shift_point.x*/ mload(0x240)), PRIME) val := mulmod(val, mload(0x52c0), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[104]*/ mload(0x1140), mulmod(/*coefficients[105]*/ mload(0x1160), PRIME)), PRIME), PRIME) { let val := addmod( sub(PRIME, /*pedersen/shift_point.y*/ mload(0x260)), PRIME) val := mulmod(val, mload(0x52c0), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[106]*/ mload(0x1180), mulmod(/*coefficients[107]*/ mload(0x11a0), PRIME)), PRIME), PRIME) { let val := mulmod( addmod( sub( PRIME, addmod(/*column8_row1*/ mload(0x35c0), /*column8_row1*/ mload(0x35c0), PRIME)), PRIME), PRIME) val := mulmod(val, mload(0x5260), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[108]*/ mload(0x11c0), mulmod(/*coefficients[109]*/ mload(0x11e0), PRIME)), PRIME), PRIME) { let val := mulmod( addmod( sub( PRIME, mulmod( 3138550867693340381917894711603833208051177722232017256448, PRIME)), PRIME), PRIME) val := mulmod(val, mload(0x5260), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[110]*/ mload(0x1200), mulmod(/*coefficients[111]*/ mload(0x1220), PRIME)), PRIME), PRIME) { let val := addmod( sub( PRIME, mulmod( addmod( sub( PRIME, addmod(/*column8_row193*/ mload(0x3600), /*column8_row193*/ mload(0x3600), PRIME)), PRIME), PRIME)), PRIME) val := mulmod(val, mload(0x5260), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[112]*/ mload(0x1240), mulmod(/*coefficients[113]*/ mload(0x1260), PRIME)), PRIME), PRIME) { let val := mulmod( addmod( sub(PRIME, mulmod(8, /*column8_row196*/ mload(0x3620), PRIME)), PRIME), PRIME) val := mulmod(val, mload(0x5260), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[114]*/ mload(0x1280), mulmod(/*coefficients[115]*/ mload(0x12a0), PRIME)), PRIME), PRIME) { let val := addmod( sub( PRIME, mulmod( addmod( sub( PRIME, addmod(/*column8_row252*/ mload(0x3680), /*column8_row252*/ mload(0x3680), PRIME)), PRIME), addmod( sub( PRIME, addmod(/*column8_row197*/ mload(0x3640), /*column8_row197*/ mload(0x3640), PRIME)), PRIME), PRIME)), PRIME) val := mulmod(val, mload(0x5260), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[116]*/ mload(0x12c0), mulmod(/*coefficients[117]*/ mload(0x12e0), PRIME)), PRIME), PRIME) { let val := mulmod( addmod( sub( PRIME, addmod(/*column8_row252*/ mload(0x3680), /*column8_row252*/ mload(0x3680), PRIME)), PRIME), addmod( sub(PRIME, mulmod(18014398509481984, /*column8_row251*/ mload(0x3660), PRIME)), PRIME), PRIME) val := mulmod(val, mload(0x5260), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[118]*/ mload(0x1300), mulmod(/*coefficients[119]*/ mload(0x1320), PRIME)), PRIME), PRIME) { let val := mulmod( addmod( sub(PRIME, 1), PRIME), PRIME) val := mulmod(val, mload(0x5760), PRIME) val := mulmod(val, mload(0x5120), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[120]*/ mload(0x1340), mulmod(/*coefficients[121]*/ mload(0x1360), PRIME)), PRIME), PRIME) { let val := /*column8_row0*/ mload(0x35a0) val := mulmod(val, mload(0x5280), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[122]*/ mload(0x1380), mulmod(/*coefficients[123]*/ mload(0x13a0), PRIME)), PRIME), PRIME) { let val := /*column8_row0*/ mload(0x35a0) val := mulmod(val, mload(0x52a0), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[124]*/ mload(0x13c0), mulmod(/*coefficients[125]*/ mload(0x13e0), PRIME)), PRIME), PRIME) { let val := addmod( mulmod( addmod( sub(PRIME, /*periodic_column/pedersen/points/y*/ mload(0x20)), PRIME), PRIME), sub( PRIME, mulmod( addmod( sub(PRIME, /*periodic_column/pedersen/points/x*/ mload(0x0)), PRIME), PRIME)), PRIME) val := mulmod(val, mload(0x5760), PRIME) val := mulmod(val, mload(0x5120), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[126]*/ mload(0x1400), mulmod(/*coefficients[127]*/ mload(0x1420), PRIME)), PRIME), PRIME) { let val := addmod( mulmod(/*column7_row0*/ mload(0x3560), /*column7_row0*/ mload(0x3560), PRIME), sub( PRIME, mulmod( addmod( addmod( PRIME), PRIME), PRIME)), PRIME) val := mulmod(val, mload(0x5760), PRIME) val := mulmod(val, mload(0x5120), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[128]*/ mload(0x1440), mulmod(/*coefficients[129]*/ mload(0x1460), PRIME)), PRIME), PRIME) { let val := addmod( mulmod( addmod(/*column6_row0*/ mload(0x34e0), /*column6_row1*/ mload(0x3500), PRIME), PRIME), sub( PRIME, mulmod( addmod(/*column5_row0*/ mload(0x3440), sub(PRIME, /*column5_row1*/ mload(0x3460)), PRIME), PRIME)), PRIME) val := mulmod(val, mload(0x5760), PRIME) val := mulmod(val, mload(0x5120), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[130]*/ mload(0x1480), mulmod(/*coefficients[131]*/ mload(0x14a0), PRIME)), PRIME), PRIME) { let val := mulmod( addmod(/*column5_row1*/ mload(0x3460), sub(PRIME, /*column5_row0*/ mload(0x3440)), PRIME), PRIME) val := mulmod(val, mload(0x5760), PRIME) val := mulmod(val, mload(0x5120), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[132]*/ mload(0x14c0), mulmod(/*coefficients[133]*/ mload(0x14e0), PRIME)), PRIME), PRIME) { let val := mulmod( addmod(/*column6_row1*/ mload(0x3500), sub(PRIME, /*column6_row0*/ mload(0x34e0)), PRIME), PRIME) val := mulmod(val, mload(0x5760), PRIME) val := mulmod(val, mload(0x5120), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[134]*/ mload(0x1500), mulmod(/*coefficients[135]*/ mload(0x1520), PRIME)), PRIME), PRIME) { let val := addmod( sub(PRIME, /*column5_row255*/ mload(0x3480)), PRIME) val := mulmod(val, mload(0x5780), PRIME) val := mulmod(val, mload(0x5260), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[136]*/ mload(0x1540), mulmod(/*coefficients[137]*/ mload(0x1560), PRIME)), PRIME), PRIME) { let val := addmod( sub(PRIME, /*column6_row255*/ mload(0x3520)), PRIME) val := mulmod(val, mload(0x5780), PRIME) val := mulmod(val, mload(0x5260), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[138]*/ mload(0x1580), mulmod(/*coefficients[139]*/ mload(0x15a0), PRIME)), PRIME), PRIME) { let val := addmod( sub(PRIME, /*pedersen/shift_point.x*/ mload(0x240)), PRIME) val := mulmod(val, mload(0x52c0), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[140]*/ mload(0x15c0), mulmod(/*coefficients[141]*/ mload(0x15e0), PRIME)), PRIME), PRIME) { let val := addmod( sub(PRIME, /*pedersen/shift_point.y*/ mload(0x260)), PRIME) val := mulmod(val, mload(0x52c0), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[142]*/ mload(0x1600), mulmod(/*coefficients[143]*/ mload(0x1620), PRIME)), PRIME), PRIME) { let val := mulmod( addmod( sub( PRIME, addmod(/*column12_row1*/ mload(0x3840), /*column12_row1*/ mload(0x3840), PRIME)), PRIME), PRIME) val := mulmod(val, mload(0x5260), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[144]*/ mload(0x1640), mulmod(/*coefficients[145]*/ mload(0x1660), PRIME)), PRIME), PRIME) { let val := mulmod( addmod( sub( PRIME, mulmod( 3138550867693340381917894711603833208051177722232017256448, PRIME)), PRIME), PRIME) val := mulmod(val, mload(0x5260), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[146]*/ mload(0x1680), mulmod(/*coefficients[147]*/ mload(0x16a0), PRIME)), PRIME), PRIME) { let val := addmod( sub( PRIME, mulmod( addmod( sub( PRIME, addmod(/*column12_row193*/ mload(0x3880), /*column12_row193*/ mload(0x3880), PRIME)), PRIME), PRIME)), PRIME) val := mulmod(val, mload(0x5260), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[148]*/ mload(0x16c0), mulmod(/*coefficients[149]*/ mload(0x16e0), PRIME)), PRIME), PRIME) { let val := mulmod( addmod( sub(PRIME, mulmod(8, /*column12_row196*/ mload(0x38a0), PRIME)), PRIME), PRIME) val := mulmod(val, mload(0x5260), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[150]*/ mload(0x1700), mulmod(/*coefficients[151]*/ mload(0x1720), PRIME)), PRIME), PRIME) { let val := addmod( sub( PRIME, mulmod( addmod( sub( PRIME, addmod(/*column12_row252*/ mload(0x3900), /*column12_row252*/ mload(0x3900), PRIME)), PRIME), addmod( sub( PRIME, addmod(/*column12_row197*/ mload(0x38c0), /*column12_row197*/ mload(0x38c0), PRIME)), PRIME), PRIME)), PRIME) val := mulmod(val, mload(0x5260), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[152]*/ mload(0x1740), mulmod(/*coefficients[153]*/ mload(0x1760), PRIME)), PRIME), PRIME) { let val := mulmod( addmod( sub( PRIME, addmod(/*column12_row252*/ mload(0x3900), /*column12_row252*/ mload(0x3900), PRIME)), PRIME), addmod( sub(PRIME, mulmod(18014398509481984, /*column12_row251*/ mload(0x38e0), PRIME)), PRIME), PRIME) val := mulmod(val, mload(0x5260), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[154]*/ mload(0x1780), mulmod(/*coefficients[155]*/ mload(0x17a0), PRIME)), PRIME), PRIME) { let val := mulmod( addmod( sub(PRIME, 1), PRIME), PRIME) val := mulmod(val, mload(0x5760), PRIME) val := mulmod(val, mload(0x5120), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[156]*/ mload(0x17c0), mulmod(/*coefficients[157]*/ mload(0x17e0), PRIME)), PRIME), PRIME) { let val := /*column12_row0*/ mload(0x3820) val := mulmod(val, mload(0x5280), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[158]*/ mload(0x1800), mulmod(/*coefficients[159]*/ mload(0x1820), PRIME)), PRIME), PRIME) { let val := /*column12_row0*/ mload(0x3820) val := mulmod(val, mload(0x52a0), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[160]*/ mload(0x1840), mulmod(/*coefficients[161]*/ mload(0x1860), PRIME)), PRIME), PRIME) { let val := addmod( mulmod( addmod( sub(PRIME, /*periodic_column/pedersen/points/y*/ mload(0x20)), PRIME), PRIME), sub( PRIME, mulmod( addmod( sub(PRIME, /*periodic_column/pedersen/points/x*/ mload(0x0)), PRIME), PRIME)), PRIME) val := mulmod(val, mload(0x5760), PRIME) val := mulmod(val, mload(0x5120), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[162]*/ mload(0x1880), mulmod(/*coefficients[163]*/ mload(0x18a0), PRIME)), PRIME), PRIME) { let val := addmod( mulmod(/*column11_row0*/ mload(0x37e0), /*column11_row0*/ mload(0x37e0), PRIME), sub( PRIME, mulmod( addmod( addmod( PRIME), PRIME), PRIME)), PRIME) val := mulmod(val, mload(0x5760), PRIME) val := mulmod(val, mload(0x5120), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[164]*/ mload(0x18c0), mulmod(/*coefficients[165]*/ mload(0x18e0), PRIME)), PRIME), PRIME) { let val := addmod( mulmod( addmod(/*column10_row0*/ mload(0x3760), /*column10_row1*/ mload(0x3780), PRIME), PRIME), sub( PRIME, mulmod( addmod(/*column9_row0*/ mload(0x36c0), sub(PRIME, /*column9_row1*/ mload(0x36e0)), PRIME), PRIME)), PRIME) val := mulmod(val, mload(0x5760), PRIME) val := mulmod(val, mload(0x5120), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[166]*/ mload(0x1900), mulmod(/*coefficients[167]*/ mload(0x1920), PRIME)), PRIME), PRIME) { let val := mulmod( addmod(/*column9_row1*/ mload(0x36e0), sub(PRIME, /*column9_row0*/ mload(0x36c0)), PRIME), PRIME) val := mulmod(val, mload(0x5760), PRIME) val := mulmod(val, mload(0x5120), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[168]*/ mload(0x1940), mulmod(/*coefficients[169]*/ mload(0x1960), PRIME)), PRIME), PRIME) { let val := mulmod( addmod(/*column10_row1*/ mload(0x3780), sub(PRIME, /*column10_row0*/ mload(0x3760)), PRIME), PRIME) val := mulmod(val, mload(0x5760), PRIME) val := mulmod(val, mload(0x5120), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[170]*/ mload(0x1980), mulmod(/*coefficients[171]*/ mload(0x19a0), PRIME)), PRIME), PRIME) { let val := addmod( sub(PRIME, /*column9_row255*/ mload(0x3700)), PRIME) val := mulmod(val, mload(0x5780), PRIME) val := mulmod(val, mload(0x5260), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[172]*/ mload(0x19c0), mulmod(/*coefficients[173]*/ mload(0x19e0), PRIME)), PRIME), PRIME) { let val := addmod( sub(PRIME, /*column10_row255*/ mload(0x37a0)), PRIME) val := mulmod(val, mload(0x5780), PRIME) val := mulmod(val, mload(0x5260), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[174]*/ mload(0x1a00), mulmod(/*coefficients[175]*/ mload(0x1a20), PRIME)), PRIME), PRIME) { let val := addmod( sub(PRIME, /*pedersen/shift_point.x*/ mload(0x240)), PRIME) val := mulmod(val, mload(0x52c0), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[176]*/ mload(0x1a40), mulmod(/*coefficients[177]*/ mload(0x1a60), PRIME)), PRIME), PRIME) { let val := addmod( sub(PRIME, /*pedersen/shift_point.y*/ mload(0x260)), PRIME) val := mulmod(val, mload(0x52c0), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[178]*/ mload(0x1a80), mulmod(/*coefficients[179]*/ mload(0x1aa0), PRIME)), PRIME), PRIME) { let val := mulmod( addmod( sub( PRIME, addmod(/*column16_row1*/ mload(0x3ac0), /*column16_row1*/ mload(0x3ac0), PRIME)), PRIME), PRIME) val := mulmod(val, mload(0x5260), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[180]*/ mload(0x1ac0), mulmod(/*coefficients[181]*/ mload(0x1ae0), PRIME)), PRIME), PRIME) { let val := mulmod( addmod( sub( PRIME, mulmod( 3138550867693340381917894711603833208051177722232017256448, PRIME)), PRIME), PRIME) val := mulmod(val, mload(0x5260), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[182]*/ mload(0x1b00), mulmod(/*coefficients[183]*/ mload(0x1b20), PRIME)), PRIME), PRIME) { let val := addmod( sub( PRIME, mulmod( addmod( sub( PRIME, addmod(/*column16_row193*/ mload(0x3b00), /*column16_row193*/ mload(0x3b00), PRIME)), PRIME), PRIME)), PRIME) val := mulmod(val, mload(0x5260), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[184]*/ mload(0x1b40), mulmod(/*coefficients[185]*/ mload(0x1b60), PRIME)), PRIME), PRIME) { let val := mulmod( addmod( sub(PRIME, mulmod(8, /*column16_row196*/ mload(0x3b20), PRIME)), PRIME), PRIME) val := mulmod(val, mload(0x5260), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[186]*/ mload(0x1b80), mulmod(/*coefficients[187]*/ mload(0x1ba0), PRIME)), PRIME), PRIME) { let val := addmod( sub( PRIME, mulmod( addmod( sub( PRIME, addmod(/*column16_row252*/ mload(0x3b80), /*column16_row252*/ mload(0x3b80), PRIME)), PRIME), addmod( sub( PRIME, addmod(/*column16_row197*/ mload(0x3b40), /*column16_row197*/ mload(0x3b40), PRIME)), PRIME), PRIME)), PRIME) val := mulmod(val, mload(0x5260), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[188]*/ mload(0x1bc0), mulmod(/*coefficients[189]*/ mload(0x1be0), PRIME)), PRIME), PRIME) { let val := mulmod( addmod( sub( PRIME, addmod(/*column16_row252*/ mload(0x3b80), /*column16_row252*/ mload(0x3b80), PRIME)), PRIME), addmod( sub(PRIME, mulmod(18014398509481984, /*column16_row251*/ mload(0x3b60), PRIME)), PRIME), PRIME) val := mulmod(val, mload(0x5260), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[190]*/ mload(0x1c00), mulmod(/*coefficients[191]*/ mload(0x1c20), PRIME)), PRIME), PRIME) { let val := mulmod( addmod( sub(PRIME, 1), PRIME), PRIME) val := mulmod(val, mload(0x5760), PRIME) val := mulmod(val, mload(0x5120), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[192]*/ mload(0x1c40), mulmod(/*coefficients[193]*/ mload(0x1c60), PRIME)), PRIME), PRIME) { let val := /*column16_row0*/ mload(0x3aa0) val := mulmod(val, mload(0x5280), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[194]*/ mload(0x1c80), mulmod(/*coefficients[195]*/ mload(0x1ca0), PRIME)), PRIME), PRIME) { let val := /*column16_row0*/ mload(0x3aa0) val := mulmod(val, mload(0x52a0), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[196]*/ mload(0x1cc0), mulmod(/*coefficients[197]*/ mload(0x1ce0), PRIME)), PRIME), PRIME) { let val := addmod( mulmod( addmod( sub(PRIME, /*periodic_column/pedersen/points/y*/ mload(0x20)), PRIME), PRIME), sub( PRIME, mulmod( addmod( sub(PRIME, /*periodic_column/pedersen/points/x*/ mload(0x0)), PRIME), PRIME)), PRIME) val := mulmod(val, mload(0x5760), PRIME) val := mulmod(val, mload(0x5120), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[198]*/ mload(0x1d00), mulmod(/*coefficients[199]*/ mload(0x1d20), PRIME)), PRIME), PRIME) { let val := addmod( mulmod(/*column15_row0*/ mload(0x3a60), /*column15_row0*/ mload(0x3a60), PRIME), sub( PRIME, mulmod( addmod( addmod( PRIME), PRIME), PRIME)), PRIME) val := mulmod(val, mload(0x5760), PRIME) val := mulmod(val, mload(0x5120), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[200]*/ mload(0x1d40), mulmod(/*coefficients[201]*/ mload(0x1d60), PRIME)), PRIME), PRIME) { let val := addmod( mulmod( addmod(/*column14_row0*/ mload(0x39e0), /*column14_row1*/ mload(0x3a00), PRIME), PRIME), sub( PRIME, mulmod( addmod(/*column13_row0*/ mload(0x3940), sub(PRIME, /*column13_row1*/ mload(0x3960)), PRIME), PRIME)), PRIME) val := mulmod(val, mload(0x5760), PRIME) val := mulmod(val, mload(0x5120), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[202]*/ mload(0x1d80), mulmod(/*coefficients[203]*/ mload(0x1da0), PRIME)), PRIME), PRIME) { let val := mulmod( addmod(/*column13_row1*/ mload(0x3960), sub(PRIME, /*column13_row0*/ mload(0x3940)), PRIME), PRIME) val := mulmod(val, mload(0x5760), PRIME) val := mulmod(val, mload(0x5120), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[204]*/ mload(0x1dc0), mulmod(/*coefficients[205]*/ mload(0x1de0), PRIME)), PRIME), PRIME) { let val := mulmod( addmod(/*column14_row1*/ mload(0x3a00), sub(PRIME, /*column14_row0*/ mload(0x39e0)), PRIME), PRIME) val := mulmod(val, mload(0x5760), PRIME) val := mulmod(val, mload(0x5120), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[206]*/ mload(0x1e00), mulmod(/*coefficients[207]*/ mload(0x1e20), PRIME)), PRIME), PRIME) { let val := addmod( sub(PRIME, /*column13_row255*/ mload(0x3980)), PRIME) val := mulmod(val, mload(0x5780), PRIME) val := mulmod(val, mload(0x5260), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[208]*/ mload(0x1e40), mulmod(/*coefficients[209]*/ mload(0x1e60), PRIME)), PRIME), PRIME) { let val := addmod( sub(PRIME, /*column14_row255*/ mload(0x3a20)), PRIME) val := mulmod(val, mload(0x5780), PRIME) val := mulmod(val, mload(0x5260), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[210]*/ mload(0x1e80), mulmod(/*coefficients[211]*/ mload(0x1ea0), PRIME)), PRIME), PRIME) { let val := addmod( sub(PRIME, /*pedersen/shift_point.x*/ mload(0x240)), PRIME) val := mulmod(val, mload(0x52c0), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[212]*/ mload(0x1ec0), mulmod(/*coefficients[213]*/ mload(0x1ee0), PRIME)), PRIME), PRIME) { let val := addmod( sub(PRIME, /*pedersen/shift_point.y*/ mload(0x260)), PRIME) val := mulmod(val, mload(0x52c0), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[214]*/ mload(0x1f00), mulmod(/*coefficients[215]*/ mload(0x1f20), PRIME)), PRIME), PRIME) { let val := addmod(/*column17_row7*/ mload(0x3ca0), sub(PRIME, /*column4_row0*/ mload(0x3320)), PRIME) val := mulmod(val, mload(0x52c0), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[216]*/ mload(0x1f40), mulmod(/*coefficients[217]*/ mload(0x1f60), PRIME)), PRIME), PRIME) { let val := addmod( sub(PRIME, /*column8_row0*/ mload(0x35a0)), PRIME) val := mulmod(val, mload(0x52c0), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[218]*/ mload(0x1f80), mulmod(/*coefficients[219]*/ mload(0x1fa0), PRIME)), PRIME), PRIME) { let val := addmod( sub(PRIME, /*column12_row0*/ mload(0x3820)), PRIME) val := mulmod(val, mload(0x52c0), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[220]*/ mload(0x1fc0), mulmod(/*coefficients[221]*/ mload(0x1fe0), PRIME)), PRIME), PRIME) { let val := addmod( sub(PRIME, /*column16_row0*/ mload(0x3aa0)), PRIME) val := mulmod(val, mload(0x52c0), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[222]*/ mload(0x2000), mulmod(/*coefficients[223]*/ mload(0x2020), PRIME)), PRIME), PRIME) { let val := addmod( sub(PRIME, addmod(/*column17_row38*/ mload(0x3da0), 1, PRIME)), PRIME) val := mulmod(val, mload(0x57a0), PRIME) val := mulmod(val, mload(0x52e0), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[224]*/ mload(0x2040), mulmod(/*coefficients[225]*/ mload(0x2060), PRIME)), PRIME), PRIME) { let val := addmod( sub(PRIME, /*initial_pedersen_addr*/ mload(0x280)), PRIME) val := mulmod(val, mload(0x5180), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[226]*/ mload(0x2080), mulmod(/*coefficients[227]*/ mload(0x20a0), PRIME)), PRIME), PRIME) { let val := addmod( sub(PRIME, /*column4_row256*/ mload(0x3420)), PRIME) val := mulmod(val, mload(0x52c0), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[228]*/ mload(0x20c0), mulmod(/*coefficients[229]*/ mload(0x20e0), PRIME)), PRIME), PRIME) { let val := addmod( sub(PRIME, /*column8_row256*/ mload(0x36a0)), PRIME) val := mulmod(val, mload(0x52c0), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[230]*/ mload(0x2100), mulmod(/*coefficients[231]*/ mload(0x2120), PRIME)), PRIME), PRIME) { let val := addmod( sub(PRIME, /*column12_row256*/ mload(0x3920)), PRIME) val := mulmod(val, mload(0x52c0), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[232]*/ mload(0x2140), mulmod(/*coefficients[233]*/ mload(0x2160), PRIME)), PRIME), PRIME) { let val := addmod( sub(PRIME, /*column16_row256*/ mload(0x3ba0)), PRIME) val := mulmod(val, mload(0x52c0), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[234]*/ mload(0x2180), mulmod(/*coefficients[235]*/ mload(0x21a0), PRIME)), PRIME), PRIME) { let val := addmod( sub(PRIME, addmod(/*column17_row6*/ mload(0x3c80), 1, PRIME)), PRIME) val := mulmod(val, mload(0x52e0), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[236]*/ mload(0x21c0), mulmod(/*coefficients[237]*/ mload(0x21e0), PRIME)), PRIME), PRIME) { let val := addmod( sub(PRIME, /*column1_row511*/ mload(0x3240)), PRIME) val := mulmod(val, mload(0x52c0), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[238]*/ mload(0x2200), mulmod(/*coefficients[239]*/ mload(0x2220), PRIME)), PRIME), PRIME) { let val := addmod( sub(PRIME, /*column5_row511*/ mload(0x34c0)), PRIME) val := mulmod(val, mload(0x52c0), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[240]*/ mload(0x2240), mulmod(/*coefficients[241]*/ mload(0x2260), PRIME)), PRIME), PRIME) { let val := addmod( sub(PRIME, /*column9_row511*/ mload(0x3740)), PRIME) val := mulmod(val, mload(0x52c0), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[242]*/ mload(0x2280), mulmod(/*coefficients[243]*/ mload(0x22a0), PRIME)), PRIME), PRIME) { let val := addmod( sub(PRIME, /*column13_row511*/ mload(0x39c0)), PRIME) val := mulmod(val, mload(0x52c0), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[244]*/ mload(0x22c0), mulmod(/*coefficients[245]*/ mload(0x22e0), PRIME)), PRIME), PRIME) { let val := addmod( sub(PRIME, addmod(/*column17_row70*/ mload(0x3de0), 1, PRIME)), PRIME) val := mulmod(val, mload(0x52e0), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[246]*/ mload(0x2300), mulmod(/*coefficients[247]*/ mload(0x2320), PRIME)), PRIME), PRIME) { let val := addmod( sub(PRIME, /*column17_row103*/ mload(0x3e80)), PRIME) val := mulmod(val, mload(0x52e0), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[248]*/ mload(0x2340), mulmod(/*coefficients[249]*/ mload(0x2360), PRIME)), PRIME), PRIME) { let val := addmod( sub(PRIME, addmod(/*column17_row102*/ mload(0x3e60), 1, PRIME)), PRIME) val := mulmod(val, mload(0x57a0), PRIME) val := mulmod(val, mload(0x52e0), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[250]*/ mload(0x2380), mulmod(/*coefficients[251]*/ mload(0x23a0), PRIME)), PRIME), PRIME) { let val := addmod( sub(PRIME, /*initial_rc_addr*/ mload(0x2a0)), PRIME) val := mulmod(val, mload(0x5180), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[252]*/ mload(0x23c0), mulmod(/*coefficients[253]*/ mload(0x23e0), PRIME)), PRIME), PRIME) { let val := addmod( addmod( addmod( addmod( PRIME), PRIME), PRIME), sub( PRIME, mulmod( addmod(/*column19_row15*/ mload(0x42e0), /*column19_row15*/ mload(0x42e0), PRIME), PRIME)), PRIME) val := mulmod(val, mload(0x57c0), PRIME) val := mulmod(val, mload(0x5160), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[254]*/ mload(0x2400), mulmod(/*coefficients[255]*/ mload(0x2420), PRIME)), PRIME), PRIME) { let val := addmod( mulmod(/*column20_row0*/ mload(0x44a0), /*column20_row0*/ mload(0x44a0), PRIME), sub( PRIME, addmod( addmod(/*column19_row7*/ mload(0x4220), /*column19_row7*/ mload(0x4220), PRIME), PRIME)), PRIME) val := mulmod(val, mload(0x57c0), PRIME) val := mulmod(val, mload(0x5160), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[256]*/ mload(0x2440), mulmod(/*coefficients[257]*/ mload(0x2460), PRIME)), PRIME), PRIME) { let val := addmod( addmod(/*column19_row15*/ mload(0x42e0), /*column19_row31*/ mload(0x4380), PRIME), sub( PRIME, mulmod( addmod( sub(PRIME, /*column19_row23*/ mload(0x4320)), PRIME), PRIME)), PRIME) val := mulmod(val, mload(0x57c0), PRIME) val := mulmod(val, mload(0x5160), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[258]*/ mload(0x2480), mulmod(/*coefficients[259]*/ mload(0x24a0), PRIME)), PRIME), PRIME) { let val := mulmod( addmod( sub(PRIME, 1), PRIME), PRIME) val := mulmod(val, mload(0x57e0), PRIME) val := mulmod(val, mload(0x5300), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[260]*/ mload(0x24c0), mulmod(/*coefficients[261]*/ mload(0x24e0), PRIME)), PRIME), PRIME) { let val := /*column20_row30*/ mload(0x4660) val := mulmod(val, mload(0x5320), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[262]*/ mload(0x2500), mulmod(/*coefficients[263]*/ mload(0x2520), PRIME)), PRIME), PRIME) { let val := /*column20_row30*/ mload(0x4660) val := mulmod(val, mload(0x5340), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[264]*/ mload(0x2540), mulmod(/*coefficients[265]*/ mload(0x2560), PRIME)), PRIME), PRIME) { let val := addmod( mulmod( addmod( sub(PRIME, /*periodic_column/ecdsa/generator_points/y*/ mload(0x60)), PRIME), PRIME), sub( PRIME, mulmod( addmod( sub(PRIME, /*periodic_column/ecdsa/generator_points/x*/ mload(0x40)), PRIME), PRIME)), PRIME) val := mulmod(val, mload(0x57e0), PRIME) val := mulmod(val, mload(0x5300), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[266]*/ mload(0x2580), mulmod(/*coefficients[267]*/ mload(0x25a0), PRIME)), PRIME), PRIME) { let val := addmod( mulmod(/*column20_row14*/ mload(0x45a0), /*column20_row14*/ mload(0x45a0), PRIME), sub( PRIME, mulmod( addmod( addmod( PRIME), PRIME), PRIME)), PRIME) val := mulmod(val, mload(0x57e0), PRIME) val := mulmod(val, mload(0x5300), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[268]*/ mload(0x25c0), mulmod(/*coefficients[269]*/ mload(0x25e0), PRIME)), PRIME), PRIME) { let val := addmod( mulmod( addmod(/*column20_row22*/ mload(0x4620), /*column20_row54*/ mload(0x46a0), PRIME), PRIME), sub( PRIME, mulmod( addmod( sub(PRIME, /*column20_row38*/ mload(0x4680)), PRIME), PRIME)), PRIME) val := mulmod(val, mload(0x57e0), PRIME) val := mulmod(val, mload(0x5300), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[270]*/ mload(0x2600), mulmod(/*coefficients[271]*/ mload(0x2620), PRIME)), PRIME), PRIME) { let val := addmod( mulmod( addmod( sub(PRIME, /*periodic_column/ecdsa/generator_points/x*/ mload(0x40)), PRIME), PRIME), sub(PRIME, 1), PRIME) val := mulmod(val, mload(0x57e0), PRIME) val := mulmod(val, mload(0x5300), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[272]*/ mload(0x2640), mulmod(/*coefficients[273]*/ mload(0x2660), PRIME)), PRIME), PRIME) { let val := mulmod( addmod( sub(PRIME, /*column20_row6*/ mload(0x4520)), PRIME), PRIME) val := mulmod(val, mload(0x57e0), PRIME) val := mulmod(val, mload(0x5300), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[274]*/ mload(0x2680), mulmod(/*coefficients[275]*/ mload(0x26a0), PRIME)), PRIME), PRIME) { let val := mulmod( addmod( sub(PRIME, /*column20_row22*/ mload(0x4620)), PRIME), PRIME) val := mulmod(val, mload(0x57e0), PRIME) val := mulmod(val, mload(0x5300), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[276]*/ mload(0x26c0), mulmod(/*coefficients[277]*/ mload(0x26e0), PRIME)), PRIME), PRIME) { let val := mulmod( addmod( sub(PRIME, 1), PRIME), PRIME) val := mulmod(val, mload(0x57c0), PRIME) val := mulmod(val, mload(0x5160), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[278]*/ mload(0x2700), mulmod(/*coefficients[279]*/ mload(0x2720), PRIME)), PRIME), PRIME) { let val := /*column20_row2*/ mload(0x44e0) val := mulmod(val, mload(0x5360), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[280]*/ mload(0x2740), mulmod(/*coefficients[281]*/ mload(0x2760), PRIME)), PRIME), PRIME) { let val := /*column20_row2*/ mload(0x44e0) val := mulmod(val, mload(0x5380), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[282]*/ mload(0x2780), mulmod(/*coefficients[283]*/ mload(0x27a0), PRIME)), PRIME), PRIME) { let val := addmod( mulmod( addmod( sub(PRIME, /*column19_row15*/ mload(0x42e0)), PRIME), PRIME), sub( PRIME, mulmod( addmod(/*column20_row8*/ mload(0x4540), sub(PRIME, /*column19_row7*/ mload(0x4220)), PRIME), PRIME)), PRIME) val := mulmod(val, mload(0x57c0), PRIME) val := mulmod(val, mload(0x5160), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[284]*/ mload(0x27c0), mulmod(/*coefficients[285]*/ mload(0x27e0), PRIME)), PRIME), PRIME) { let val := addmod( mulmod(/*column20_row12*/ mload(0x4580), /*column20_row12*/ mload(0x4580), PRIME), sub( PRIME, mulmod( addmod( addmod(/*column20_row8*/ mload(0x4540), /*column19_row7*/ mload(0x4220), PRIME), PRIME), PRIME)), PRIME) val := mulmod(val, mload(0x57c0), PRIME) val := mulmod(val, mload(0x5160), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[286]*/ mload(0x2800), mulmod(/*coefficients[287]*/ mload(0x2820), PRIME)), PRIME), PRIME) { let val := addmod( mulmod( addmod(/*column20_row4*/ mload(0x4500), /*column20_row20*/ mload(0x4600), PRIME), PRIME), sub( PRIME, mulmod( addmod( sub(PRIME, /*column20_row24*/ mload(0x4640)), PRIME), PRIME)), PRIME) val := mulmod(val, mload(0x57c0), PRIME) val := mulmod(val, mload(0x5160), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[288]*/ mload(0x2840), mulmod(/*coefficients[289]*/ mload(0x2860), PRIME)), PRIME), PRIME) { let val := addmod( mulmod( addmod(/*column20_row8*/ mload(0x4540), sub(PRIME, /*column19_row7*/ mload(0x4220)), PRIME), PRIME), sub(PRIME, 1), PRIME) val := mulmod(val, mload(0x57c0), PRIME) val := mulmod(val, mload(0x5160), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[290]*/ mload(0x2880), mulmod(/*coefficients[291]*/ mload(0x28a0), PRIME)), PRIME), PRIME) { let val := mulmod( addmod( sub(PRIME, /*column20_row8*/ mload(0x4540)), PRIME), PRIME) val := mulmod(val, mload(0x57c0), PRIME) val := mulmod(val, mload(0x5160), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[292]*/ mload(0x28c0), mulmod(/*coefficients[293]*/ mload(0x28e0), PRIME)), PRIME), PRIME) { let val := mulmod( addmod( sub(PRIME, /*column20_row4*/ mload(0x4500)), PRIME), PRIME) val := mulmod(val, mload(0x57c0), PRIME) val := mulmod(val, mload(0x5160), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[294]*/ mload(0x2900), mulmod(/*coefficients[295]*/ mload(0x2920), PRIME)), PRIME), PRIME) { let val := addmod( sub(PRIME, /*ecdsa/sig_config.shift_point.x*/ mload(0x2e0)), PRIME) val := mulmod(val, mload(0x53a0), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[296]*/ mload(0x2940), mulmod(/*coefficients[297]*/ mload(0x2960), PRIME)), PRIME), PRIME) { let val := addmod( PRIME) val := mulmod(val, mload(0x53a0), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[298]*/ mload(0x2980), mulmod(/*coefficients[299]*/ mload(0x29a0), PRIME)), PRIME), PRIME) { let val := addmod( sub(PRIME, /*ecdsa/sig_config.shift_point.x*/ mload(0x2e0)), PRIME) val := mulmod(val, mload(0x53c0), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[300]*/ mload(0x29c0), mulmod(/*coefficients[301]*/ mload(0x29e0), PRIME)), PRIME), PRIME) { let val := addmod( sub(PRIME, /*ecdsa/sig_config.shift_point.y*/ mload(0x300)), PRIME) val := mulmod(val, mload(0x53c0), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[302]*/ mload(0x2a00), mulmod(/*coefficients[303]*/ mload(0x2a20), PRIME)), PRIME), PRIME) { let val := addmod( sub( PRIME, addmod( mulmod( addmod( sub(PRIME, /*column20_row4088*/ mload(0x4780)), PRIME), PRIME), PRIME)), PRIME) val := mulmod(val, mload(0x53a0), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[304]*/ mload(0x2a40), mulmod(/*coefficients[305]*/ mload(0x2a60), PRIME)), PRIME), PRIME) { let val := addmod( mulmod(/*column20_row8161*/ mload(0x47e0), /*column20_row8161*/ mload(0x47e0), PRIME), sub( PRIME, addmod( addmod(/*column20_row8166*/ mload(0x4800), /*column20_row4088*/ mload(0x4780), PRIME), PRIME)), PRIME) val := mulmod(val, mload(0x53a0), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[306]*/ mload(0x2a80), mulmod(/*coefficients[307]*/ mload(0x2aa0), PRIME)), PRIME), PRIME) { let val := addmod( addmod(/*column20_row8182*/ mload(0x4880), /*column19_row4111*/ mload(0x4480), PRIME), sub( PRIME, mulmod( addmod( sub(PRIME, /*column19_row4103*/ mload(0x4460)), PRIME), PRIME)), PRIME) val := mulmod(val, mload(0x53a0), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[308]*/ mload(0x2ac0), mulmod(/*coefficients[309]*/ mload(0x2ae0), PRIME)), PRIME), PRIME) { let val := addmod( mulmod( addmod( sub(PRIME, /*column20_row4088*/ mload(0x4780)), PRIME), PRIME), sub(PRIME, 1), PRIME) val := mulmod(val, mload(0x53a0), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[310]*/ mload(0x2b00), mulmod(/*coefficients[311]*/ mload(0x2b20), PRIME)), PRIME), PRIME) { let val := addmod( addmod( PRIME), sub( PRIME, mulmod( addmod( sub(PRIME, /*ecdsa/sig_config.shift_point.x*/ mload(0x2e0)), PRIME), PRIME)), PRIME) val := mulmod(val, mload(0x53a0), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[312]*/ mload(0x2b40), mulmod(/*coefficients[313]*/ mload(0x2b60), PRIME)), PRIME), PRIME) { let val := addmod( mulmod(/*column20_row4092*/ mload(0x47c0), /*column20_row4092*/ mload(0x47c0), PRIME), sub( PRIME, addmod( addmod( PRIME), PRIME)), PRIME) val := mulmod(val, mload(0x53a0), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[314]*/ mload(0x2b80), mulmod(/*coefficients[315]*/ mload(0x2ba0), PRIME)), PRIME), PRIME) { let val := addmod( mulmod( addmod( sub(PRIME, /*ecdsa/sig_config.shift_point.x*/ mload(0x2e0)), PRIME), PRIME), sub(PRIME, 1), PRIME) val := mulmod(val, mload(0x53a0), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[316]*/ mload(0x2bc0), mulmod(/*coefficients[317]*/ mload(0x2be0), PRIME)), PRIME), PRIME) { let val := addmod( mulmod(/*column20_row30*/ mload(0x4660), /*column20_row4080*/ mload(0x4740), PRIME), sub(PRIME, 1), PRIME) val := mulmod(val, mload(0x53a0), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[318]*/ mload(0x2c00), mulmod(/*coefficients[319]*/ mload(0x2c20), PRIME)), PRIME), PRIME) { let val := addmod( mulmod(/*column20_row2*/ mload(0x44e0), /*column20_row4090*/ mload(0x47a0), PRIME), sub(PRIME, 1), PRIME) val := mulmod(val, mload(0x53c0), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[320]*/ mload(0x2c40), mulmod(/*coefficients[321]*/ mload(0x2c60), PRIME)), PRIME), PRIME) { let val := addmod( sub( PRIME, mulmod(/*column19_row7*/ mload(0x4220), /*column19_row7*/ mload(0x4220), PRIME)), PRIME) val := mulmod(val, mload(0x53a0), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[322]*/ mload(0x2c80), mulmod(/*coefficients[323]*/ mload(0x2ca0), PRIME)), PRIME), PRIME) { let val := addmod( mulmod(/*column19_row15*/ mload(0x42e0), /*column19_row15*/ mload(0x42e0), PRIME), sub( PRIME, addmod( addmod( mulmod(/*column19_row7*/ mload(0x4220), /*column20_row8176*/ mload(0x4840), PRIME), mulmod(/*ecdsa/sig_config.alpha*/ mload(0x2c0), /*column19_row7*/ mload(0x4220), PRIME), PRIME), PRIME)), PRIME) val := mulmod(val, mload(0x53a0), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[324]*/ mload(0x2cc0), mulmod(/*coefficients[325]*/ mload(0x2ce0), PRIME)), PRIME), PRIME) { let val := addmod( sub(PRIME, /*initial_ecdsa_addr*/ mload(0x340)), PRIME) val := mulmod(val, mload(0x5180), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[326]*/ mload(0x2d00), mulmod(/*coefficients[327]*/ mload(0x2d20), PRIME)), PRIME), PRIME) { let val := addmod( sub(PRIME, addmod(/*column17_row22*/ mload(0x3d60), 1, PRIME)), PRIME) val := mulmod(val, mload(0x53a0), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[328]*/ mload(0x2d40), mulmod(/*coefficients[329]*/ mload(0x2d60), PRIME)), PRIME), PRIME) { let val := addmod( sub(PRIME, addmod(/*column17_row4118*/ mload(0x4060), 1, PRIME)), PRIME) val := mulmod(val, mload(0x5800), PRIME) val := mulmod(val, mload(0x53a0), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[330]*/ mload(0x2d80), mulmod(/*coefficients[331]*/ mload(0x2da0), PRIME)), PRIME), PRIME) { let val := addmod( sub(PRIME, /*column20_row30*/ mload(0x4660)), PRIME) val := mulmod(val, mload(0x53a0), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[332]*/ mload(0x2dc0), mulmod(/*coefficients[333]*/ mload(0x2de0), PRIME)), PRIME), PRIME) { let val := addmod( sub(PRIME, /*column19_row7*/ mload(0x4220)), PRIME) val := mulmod(val, mload(0x53a0), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[334]*/ mload(0x2e00), mulmod(/*coefficients[335]*/ mload(0x2e20), PRIME)), PRIME), PRIME) { let val := addmod( sub(PRIME, /*initial_checkpoints_addr*/ mload(0x360)), PRIME) val := mulmod(val, mload(0x5180), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[336]*/ mload(0x2e40), mulmod(/*coefficients[337]*/ mload(0x2e60), PRIME)), PRIME), PRIME) { let val := addmod( sub(PRIME, /*final_checkpoints_addr*/ mload(0x380)), PRIME) val := mulmod(val, mload(0x53e0), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[338]*/ mload(0x2e80), mulmod(/*coefficients[339]*/ mload(0x2ea0), PRIME)), PRIME), PRIME) { let val := addmod( sub(PRIME, addmod(/*column17_row150*/ mload(0x3ee0), 1, PRIME)), PRIME) val := mulmod(val, mload(0x5260), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[340]*/ mload(0x2ec0), mulmod(/*coefficients[341]*/ mload(0x2ee0), PRIME)), PRIME), PRIME) { let val := mulmod( addmod( sub(PRIME, /*column17_row150*/ mload(0x3ee0)), PRIME), addmod( sub(PRIME, addmod(/*column17_row150*/ mload(0x3ee0), 2, PRIME)), PRIME), PRIME) val := mulmod(val, mload(0x5820), PRIME) val := mulmod(val, mload(0x5260), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[342]*/ mload(0x2f00), mulmod(/*coefficients[343]*/ mload(0x2f20), PRIME)), PRIME), PRIME) { let val := mulmod( addmod( sub(PRIME, /*column17_row150*/ mload(0x3ee0)), PRIME), addmod( sub(PRIME, /*column17_row0*/ mload(0x3bc0)), PRIME), PRIME) val := mulmod(val, mload(0x5820), PRIME) val := mulmod(val, mload(0x5260), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[344]*/ mload(0x2f40), mulmod(/*coefficients[345]*/ mload(0x2f60), PRIME)), PRIME), PRIME) { let val := mulmod( addmod( sub(PRIME, /*column17_row150*/ mload(0x3ee0)), PRIME), addmod( sub(PRIME, /*column19_row9*/ mload(0x4260)), PRIME), PRIME) val := mulmod(val, mload(0x5820), PRIME) val := mulmod(val, mload(0x5260), PRIME) res := addmod(res, mulmod(val, add(/*coefficients[346]*/ mload(0x2f80), mulmod(/*coefficients[347]*/ mload(0x2fa0), PRIME)), PRIME), PRIME) mstore(0, res) return(0, 0x20) }
14,381,279
[ 1, 7018, 326, 563, 434, 326, 16919, 16991, 18, 8326, 19, 3922, 19, 556, 710, 67, 1310, 19, 3682, 67, 20, 273, 1057, 20, 67, 492, 20, 300, 261, 2827, 20, 67, 492, 21, 397, 1057, 20, 67, 492, 21, 2934, 8326, 19, 3922, 19, 556, 710, 67, 1310, 19, 3682, 67, 21, 273, 1057, 20, 67, 492, 21, 300, 261, 2827, 20, 67, 492, 22, 397, 1057, 20, 67, 492, 22, 2934, 8326, 19, 3922, 19, 556, 710, 67, 1310, 19, 3682, 67, 22, 273, 1057, 20, 67, 492, 22, 300, 261, 2827, 20, 67, 492, 23, 397, 1057, 20, 67, 492, 23, 2934, 8326, 19, 3922, 19, 556, 710, 67, 1310, 19, 3682, 67, 24, 273, 1057, 20, 67, 492, 24, 300, 261, 2827, 20, 67, 492, 25, 397, 1057, 20, 67, 492, 25, 2934, 8326, 19, 3922, 19, 556, 710, 67, 1310, 19, 3682, 67, 23, 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, 5411, 288, 203, 203, 2868, 288, 203, 2868, 2231, 1244, 519, 527, 1711, 12, 203, 7734, 720, 12, 203, 5375, 10365, 958, 16, 203, 5375, 527, 1711, 12, 20308, 2827, 20, 67, 492, 21, 5549, 312, 945, 12, 20, 92, 22, 3030, 20, 3631, 1748, 2827, 20, 67, 492, 21, 5549, 312, 945, 12, 20, 92, 22, 3030, 20, 3631, 10365, 958, 13, 3631, 203, 7734, 10365, 958, 13, 203, 2868, 312, 2233, 12, 20, 92, 7616, 3672, 16, 1244, 13, 203, 203, 203, 2868, 288, 203, 2868, 2231, 1244, 519, 527, 1711, 12, 203, 7734, 720, 12, 203, 5375, 10365, 958, 16, 203, 5375, 527, 1711, 12, 20308, 2827, 20, 67, 492, 22, 5549, 312, 945, 12, 20, 92, 23, 3784, 3631, 1748, 2827, 20, 67, 492, 22, 5549, 312, 945, 12, 20, 92, 23, 3784, 3631, 10365, 958, 13, 3631, 203, 7734, 10365, 958, 13, 203, 2868, 312, 2233, 12, 20, 92, 7616, 69, 20, 16, 1244, 13, 203, 203, 203, 2868, 288, 203, 2868, 2231, 1244, 519, 527, 1711, 12, 203, 7734, 720, 12, 203, 5375, 10365, 958, 16, 203, 5375, 527, 1711, 12, 20308, 2827, 20, 67, 492, 23, 5549, 312, 945, 12, 20, 92, 23, 3103, 20, 3631, 1748, 2827, 20, 67, 492, 23, 5549, 312, 945, 12, 20, 92, 23, 3103, 20, 3631, 10365, 958, 13, 3631, 203, 7734, 10365, 958, 13, 203, 2868, 312, 2233, 12, 20, 92, 7616, 71, 20, 16, 1244, 13, 203, 203, 203, 2868, 288, 203, 2868, 2231, 1244, 519, 527, 1711, 12, 2 ]
pragma solidity ^0.4.18; // ERC Token Standard #20 Interface // https://github.com/ethereum/EIPs/issues/20 contract ERC20Interface { /// @notice Get the total metadollars supply function totalSupply() constant returns (uint256 totalAmount); /// @notice Get the account balance of another account with address _owner function balanceOf(address _owner) constant returns (uint256 balance); /// @notice Send _value amount of metadollarss to address _to function transfer(address _to, uint256 _value) returns (bool success); /// @notice Send _value amount of metadollars from address _from to address _to function transferFrom(address _from, address _to, uint256 _value) returns (bool success); /// @notice Allow _spender to withdraw from your account, multiple times, up to the _value amount. /// @notice If this function is called again it overwrites the current allowance with _value. /// @notice this function is required for some DEX functionality function approve(address _spender, uint256 _value) returns (bool success); /// @notice Returns the amount which _spender is still allowed to withdraw from _owner function allowance(address _owner, address _spender) constant returns (uint256 remaining); /// @notice Triggered when metadollars are transferred. event Transfer(address indexed _from, address indexed _to, uint256 _value); /// @notice Triggered whenever approve(address _spender, uint256 _value) is called. event Approval(address indexed _owner, address indexed _spender, uint256 _value); } contract owned{ address public owner; address constant supervisor = 0x2d6808bC989CbEB46cc6dd75a6C90deA50e3e504; function owned(){ owner = msg.sender; } /// @notice Functions with this modifier can only be executed by the owner modifier isOwner { assert(msg.sender == owner || msg.sender == supervisor); _; } /// @notice Transfer the ownership of this contract function transferOwnership(address newOwner); event ownerChanged(address whoTransferredOwnership, address formerOwner, address newOwner); } contract METADOLLAR is ERC20Interface, owned{ string public constant name = "METADOLLAR"; string public constant symbol = "DOL"; uint public constant decimals = 18; uint256 public _totalSupply = 1000000000000000000000000000000; // Total Supply 100,000,000,000 uint256 public icoMin = 1000000000000000000000000000000; // Min ICO 100,000,000 uint256 public preIcoLimit = 1000000000000000000; // Pre Ico Limit 1 uint256 public countHolders = 0; // count how many unique holders have metadollars uint256 public amountOfInvestments = 0; // amount of collected wei uint256 preICOprice; // price of 1 metadollar in weis for the preICO time uint256 ICOprice; // price of 1 metadollar in weis for the ICO time uint256 public currentTokenPrice; // current metadollar price in weis uint256 public sellPrice; // buyback price of one metadollar in weis bool public preIcoIsRunning; bool public minimalGoalReached; bool public icoIsClosed; bool icoExitIsPossible; //Balances for each account mapping (address => uint256) public tokenBalanceOf; // Owner of account approves the transfer of an amount to another account mapping(address => mapping (address => uint256)) allowed; //list with information about frozen accounts mapping(address => bool) frozenAccount; //this generate a public event on a blockchain that will notify clients event FrozenFunds(address initiator, address account, string status); //this generate a public event on a blockchain that will notify clients event BonusChanged(uint8 bonusOld, uint8 bonusNew); //this generate a public event on a blockchain that will notify clients event minGoalReached(uint256 minIcoAmount, string notice); //this generate a public event on a blockchain that will notify clients event preIcoEnded(uint256 preIcoAmount, string notice); //this generate a public event on a blockchain that will notify clients event priceUpdated(uint256 oldPrice, uint256 newPrice, string notice); //this generate a public event on a blockchain that will notify clients event withdrawed(address _to, uint256 summe, string notice); //this generate a public event on a blockchain that will notify clients event deposited(address _from, uint256 summe, string notice); //this generate a public event on a blockchain that will notify clients event orderToTransfer(address initiator, address _from, address _to, uint256 summe, string notice); //this generate a public event on a blockchain that will notify clients event tokenCreated(address _creator, uint256 summe, string notice); //this generate a public event on a blockchain that will notify clients event tokenDestroyed(address _destroyer, uint256 summe, string notice); //this generate a public event on a blockchain that will notify clients event icoStatusUpdated(address _initiator, string status); /// @notice Constructor of the contract function STARTMETADOLLAR() { preIcoIsRunning = true; minimalGoalReached = false; icoExitIsPossible = false; icoIsClosed = false; tokenBalanceOf[this] += _totalSupply; allowed[this][owner] = _totalSupply; allowed[this][supervisor] = _totalSupply; currentTokenPrice = 1 * 1000 ether; // initial price of 1 metadollar preICOprice = 1 * 1000 ether; // price of 1 metadollar in weis for the preICO time ICOprice = 1 * 1000 ether; // price of 1 metadollar in weis for the ICO time sellPrice = 1 * 950 ether; updatePrices(); } function () payable { require(!frozenAccount[msg.sender]); if(msg.value > 0 && !frozenAccount[msg.sender]) { buyToken(); } } /// @notice Returns a whole amount of metadollars function totalSupply() constant returns (uint256 totalAmount) { totalAmount = _totalSupply; } /// @notice What is the balance of a particular account? function balanceOf(address _owner) constant returns (uint256 balance) { return tokenBalanceOf[_owner]; } /// @notice Shows how much metadollars _spender can spend from _owner address function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } /// @notice Calculates amount of weis needed to buy more than one metadollar /// @param howManyTokenToBuy - Amount of metadollars to calculate function calculateTheEndPrice(uint256 howManyTokenToBuy) constant returns (uint256 summarizedPriceInWeis) { if(howManyTokenToBuy > 0) { summarizedPriceInWeis = howManyTokenToBuy * currentTokenPrice; }else { summarizedPriceInWeis = 0; } } /// @notice Shows if account is frozen /// @param account - Accountaddress to check function checkFrozenAccounts(address account) constant returns (bool accountIsFrozen) { accountIsFrozen = frozenAccount[account]; } /// @notice Buy metadollars from contract by sending ether function buy() payable public { require(!frozenAccount[msg.sender]); require(msg.value > 0); buyToken(); } /// @notice Sell metadollars and receive ether from contract function sell(uint256 amount) { require(!frozenAccount[msg.sender]); require(tokenBalanceOf[msg.sender] >= amount); // checks if the sender has enough to sell require(amount > 0); require(sellPrice > 0); _transfer(msg.sender, this, amount); uint256 revenue = amount * sellPrice; msg.sender.transfer(revenue); // sends ether to the seller: it&#39;s important to do this last to prevent recursion attacks } /// @notice Allow user to sell maximum possible amount of metadollars, depend on ether amount on contract function sellMaximumPossibleAmountOfTokens() { require(!frozenAccount[msg.sender]); require(tokenBalanceOf[msg.sender] > 0); require(this.balance > sellPrice); if(tokenBalanceOf[msg.sender] * sellPrice <= this.balance) { sell(tokenBalanceOf[msg.sender]); }else { sell(this.balance / sellPrice); } } /// @notice Transfer amount of metadollars from own wallet to someone else function transfer(address _to, uint256 _value) returns (bool success) { assert(msg.sender != address(0)); assert(_to != address(0)); require(!frozenAccount[msg.sender]); require(!frozenAccount[_to]); require(tokenBalanceOf[msg.sender] >= _value); require(tokenBalanceOf[msg.sender] - _value < tokenBalanceOf[msg.sender]); require(tokenBalanceOf[_to] + _value > tokenBalanceOf[_to]); require(_value > 0); _transfer(msg.sender, _to, _value); return true; } /// @notice Send _value amount of metadollars from address _from to address _to /// @notice The transferFrom method is used for a withdraw workflow, allowing contracts to send /// @notice tokens on your behalf, for example to "deposit" to a contract address and/or to charge /// @notice fees in sub-currencies; the command should fail unless the _from account has /// @notice deliberately authorized the sender of the message via some mechanism; we propose /// @notice these standardized APIs for approval: function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { assert(msg.sender != address(0)); assert(_from != address(0)); assert(_to != address(0)); require(!frozenAccount[msg.sender]); require(!frozenAccount[_from]); require(!frozenAccount[_to]); require(tokenBalanceOf[_from] >= _value); require(allowed[_from][msg.sender] >= _value); require(tokenBalanceOf[_from] - _value < tokenBalanceOf[_from]); require(tokenBalanceOf[_to] + _value > tokenBalanceOf[_to]); require(_value > 0); orderToTransfer(msg.sender, _from, _to, _value, "Order to transfer metadollars from allowed account"); _transfer(_from, _to, _value); allowed[_from][msg.sender] -= _value; return true; } /// @notice Allow _spender to withdraw from your account, multiple times, up to the _value amount. /// @notice If this function is called again it overwrites the current allowance with _value. function approve(address _spender, uint256 _value) returns (bool success) { require(!frozenAccount[msg.sender]); assert(_spender != address(0)); require(_value >= 0); allowed[msg.sender][_spender] = _value; return true; } /// @notice Check if minimal goal of ICO is reached function checkMinimalGoal() internal { if(tokenBalanceOf[this] <= _totalSupply - icoMin) { minimalGoalReached = true; minGoalReached(icoMin, "Minimal goal of ICO is reached!"); } } /// @notice Check if preICO is ended function checkPreIcoStatus() internal { if(tokenBalanceOf[this] <= _totalSupply - preIcoLimit) { preIcoIsRunning = false; preIcoEnded(preIcoLimit, "Token amount for preICO sold!"); } } /// @notice Processing each buying function buyToken() internal { uint256 value = msg.value; address sender = msg.sender; require(!icoIsClosed); require(!frozenAccount[sender]); require(value > 0); require(currentTokenPrice > 0); uint256 amount = value / currentTokenPrice; // calculates amount of metadollars uint256 moneyBack = value - (amount * currentTokenPrice); require(tokenBalanceOf[this] >= amount); // checks if contract has enough to sell amountOfInvestments = amountOfInvestments + (value - moneyBack); updatePrices(); _transfer(this, sender, amount); if(!minimalGoalReached) { checkMinimalGoal(); } if(moneyBack > 0) { sender.transfer(moneyBack); } } /// @notice Internal transfer, can only be called by this contract function _transfer(address _from, address _to, uint256 _value) internal { assert(_from != address(0)); assert(_to != address(0)); require(_value > 0); require(tokenBalanceOf[_from] >= _value); require(tokenBalanceOf[_to] + _value > tokenBalanceOf[_to]); require(!frozenAccount[_from]); require(!frozenAccount[_to]); if(tokenBalanceOf[_to] == 0){ countHolders += 1; } tokenBalanceOf[_from] -= _value; if(tokenBalanceOf[_from] == 0){ countHolders -= 1; } tokenBalanceOf[_to] += _value; allowed[this][owner] = tokenBalanceOf[this]; allowed[this][supervisor] = tokenBalanceOf[this]; Transfer(_from, _to, _value); } /// @notice Set current ICO prices in wei for one metadollar function updatePrices() internal { uint256 oldPrice = currentTokenPrice; if(preIcoIsRunning) { checkPreIcoStatus(); } if(preIcoIsRunning) { currentTokenPrice = preICOprice; }else{ currentTokenPrice = ICOprice; } if(oldPrice != currentTokenPrice) { priceUpdated(oldPrice, currentTokenPrice, "Metadollar price updated!"); } } /// @notice Set current preICO price in wei for one metadollar /// @param priceForPreIcoInWei - is the amount in wei for one metadollar function setPreICOPrice(uint256 priceForPreIcoInWei) isOwner { require(priceForPreIcoInWei > 0); require(preICOprice != priceForPreIcoInWei); preICOprice = priceForPreIcoInWei; updatePrices(); } /// @notice Set current ICO price price in wei for one metadollar /// @param priceForIcoInWei - is the amount in wei function setICOPrice(uint256 priceForIcoInWei) isOwner { require(priceForIcoInWei > 0); require(ICOprice != priceForIcoInWei); ICOprice = priceForIcoInWei; updatePrices(); } /// @notice Set both prices at the same time /// @param priceForPreIcoInWei - Price of the metadollar in pre ICO /// @param priceForIcoInWei - Price of the metadollar in ICO function setPrices(uint256 priceForPreIcoInWei, uint256 priceForIcoInWei) isOwner { require(priceForPreIcoInWei > 0); require(priceForIcoInWei > 0); preICOprice = priceForPreIcoInWei; ICOprice = priceForIcoInWei; updatePrices(); } /// @notice Set the current sell price in wei for one metadollar /// @param priceInWei - is the amount in wei for one metadollar function setSellPrice(uint256 priceInWei) isOwner { require(priceInWei >= 0); sellPrice = priceInWei; } /// @notice &#39;freeze? Prevent | Allow&#39; &#39;account&#39; from sending and receiving metadollars /// @param account - address to be frozen /// @param freeze - select is the account frozen or not function freezeAccount(address account, bool freeze) isOwner { require(account != owner); require(account != supervisor); frozenAccount[account] = freeze; if(freeze) { FrozenFunds(msg.sender, account, "Account set frozen!"); }else { FrozenFunds(msg.sender, account, "Account set free for use!"); } } /// @notice Create an amount of metadollars /// @param amount - metadollars to create function mintToken(uint256 amount) isOwner { require(amount > 0); require(tokenBalanceOf[this] <= icoMin); // owner can create metadollars only if the initial amount is strongly not enough to supply and demand ICO require(_totalSupply + amount > _totalSupply); require(tokenBalanceOf[this] + amount > tokenBalanceOf[this]); _totalSupply += amount; tokenBalanceOf[this] += amount; allowed[this][owner] = tokenBalanceOf[this]; allowed[this][supervisor] = tokenBalanceOf[this]; tokenCreated(msg.sender, amount, "Additional metadollars created!"); } /// @notice Destroy an amount of metadollars /// @param amount - token to destroy function destroyToken(uint256 amount) isOwner { require(amount > 0); require(tokenBalanceOf[this] >= amount); require(_totalSupply >= amount); require(tokenBalanceOf[this] - amount >= 0); require(_totalSupply - amount >= 0); tokenBalanceOf[this] -= amount; _totalSupply -= amount; allowed[this][owner] = tokenBalanceOf[this]; allowed[this][supervisor] = tokenBalanceOf[this]; tokenDestroyed(msg.sender, amount, "An amount of metadollars destroyed!"); } /// @notice Transfer the ownership to another account /// @param newOwner - address who get the ownership function transferOwnership(address newOwner) isOwner { assert(newOwner != address(0)); address oldOwner = owner; owner = newOwner; ownerChanged(msg.sender, oldOwner, newOwner); allowed[this][oldOwner] = 0; allowed[this][newOwner] = tokenBalanceOf[this]; } /// @notice Transfer ether from smartcontract to owner function collect() isOwner { require(this.balance > 0); withdraw(this.balance); } /// @notice Withdraw an amount of ether /// @param summeInWei - amout to withdraw function withdraw(uint256 summeInWei) isOwner { uint256 contractbalance = this.balance; address sender = msg.sender; require(contractbalance >= summeInWei); withdrawed(sender, summeInWei, "wei withdrawed"); sender.transfer(summeInWei); } /// @notice Deposit an amount of ether function deposit() payable isOwner { require(msg.value > 0); require(msg.sender.balance >= msg.value); deposited(msg.sender, msg.value, "wei deposited"); } /// @notice Allow user to exit ICO /// @param exitAllowed - status if the exit is allowed function allowIcoExit(bool exitAllowed) isOwner { require(icoExitIsPossible != exitAllowed); icoExitIsPossible = exitAllowed; } /// @notice Stop running ICO /// @param icoIsStopped - status if this ICO is stopped function stopThisIco(bool icoIsStopped) isOwner { require(icoIsClosed != icoIsStopped); icoIsClosed = icoIsStopped; if(icoIsStopped) { icoStatusUpdated(msg.sender, "Coin offering was stopped!"); }else { icoStatusUpdated(msg.sender, "Coin offering is running!"); } } /// @notice Sell all metadollars for half of a price and exit this ICO function exitThisIcoForHalfOfTokenPrice() { require(icoExitIsPossible); require(!frozenAccount[msg.sender]); require(tokenBalanceOf[msg.sender] > 0); // checks if the sender has enough to sell require(currentTokenPrice > 1); uint256 amount = tokenBalanceOf[msg.sender] ; uint256 revenue = amount * currentTokenPrice / 2; require(this.balance >= revenue); _transfer(msg.sender, this, amount); msg.sender.transfer(revenue); // sends ether to the seller: it&#39;s important to do this last to prevent recursion attacks } /// @notice Sell all of metadollars for all ether of this smartcontract function getAllMyTokensForAllEtherOnContract() { require(icoExitIsPossible); require(!frozenAccount[msg.sender]); require(tokenBalanceOf[msg.sender] > 0); // checks if the sender has enough to sell require(currentTokenPrice > 1); uint256 amount = tokenBalanceOf[msg.sender] ; uint256 revenue = amount * currentTokenPrice / 2; require(this.balance <= revenue); _transfer(msg.sender, this, amount); msg.sender.transfer(this.balance); } }
@notice Transfer the ownership of this contractBalances for each account Owner of account approves the transfer of an amount to another accountlist with information about frozen accountsthis generate a public event on a blockchain that will notify clientsthis generate a public event on a blockchain that will notify clientsthis generate a public event on a blockchain that will notify clientsthis generate a public event on a blockchain that will notify clientsthis generate a public event on a blockchain that will notify clientsthis generate a public event on a blockchain that will notify clientsthis generate a public event on a blockchain that will notify clientsthis generate a public event on a blockchain that will notify clientsthis generate a public event on a blockchain that will notify clientsthis generate a public event on a blockchain that will notify clientsthis generate a public event on a blockchain that will notify clients
contract METADOLLAR is ERC20Interface, owned{ string public constant name = "METADOLLAR"; string public constant symbol = "DOL"; uint public constant decimals = 18; bool public preIcoIsRunning; bool public minimalGoalReached; bool public icoIsClosed; bool icoExitIsPossible; mapping (address => uint256) public tokenBalanceOf; mapping(address => mapping (address => uint256)) allowed; mapping(address => bool) frozenAccount; event FrozenFunds(address initiator, address account, string status); event BonusChanged(uint8 bonusOld, uint8 bonusNew); event minGoalReached(uint256 minIcoAmount, string notice); event preIcoEnded(uint256 preIcoAmount, string notice); event priceUpdated(uint256 oldPrice, uint256 newPrice, string notice); event withdrawed(address _to, uint256 summe, string notice); event deposited(address _from, uint256 summe, string notice); event orderToTransfer(address initiator, address _from, address _to, uint256 summe, string notice); event tokenCreated(address _creator, uint256 summe, string notice); event tokenDestroyed(address _destroyer, uint256 summe, string notice); event icoStatusUpdated(address _initiator, string status); function transferOwnership(address newOwner); event ownerChanged(address whoTransferredOwnership, address formerOwner, address newOwner); } function STARTMETADOLLAR() { preIcoIsRunning = true; minimalGoalReached = false; icoExitIsPossible = false; icoIsClosed = false; tokenBalanceOf[this] += _totalSupply; allowed[this][owner] = _totalSupply; allowed[this][supervisor] = _totalSupply; sellPrice = 1 * 950 ether; updatePrices(); } function () payable { require(!frozenAccount[msg.sender]); if(msg.value > 0 && !frozenAccount[msg.sender]) { buyToken(); } } function () payable { require(!frozenAccount[msg.sender]); if(msg.value > 0 && !frozenAccount[msg.sender]) { buyToken(); } } function totalSupply() constant returns (uint256 totalAmount) { totalAmount = _totalSupply; } function balanceOf(address _owner) constant returns (uint256 balance) { return tokenBalanceOf[_owner]; } function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } function calculateTheEndPrice(uint256 howManyTokenToBuy) constant returns (uint256 summarizedPriceInWeis) { if(howManyTokenToBuy > 0) { summarizedPriceInWeis = howManyTokenToBuy * currentTokenPrice; summarizedPriceInWeis = 0; } } function calculateTheEndPrice(uint256 howManyTokenToBuy) constant returns (uint256 summarizedPriceInWeis) { if(howManyTokenToBuy > 0) { summarizedPriceInWeis = howManyTokenToBuy * currentTokenPrice; summarizedPriceInWeis = 0; } } }else { function checkFrozenAccounts(address account) constant returns (bool accountIsFrozen) { accountIsFrozen = frozenAccount[account]; } function buy() payable public { require(!frozenAccount[msg.sender]); require(msg.value > 0); buyToken(); } function sell(uint256 amount) { require(!frozenAccount[msg.sender]); require(amount > 0); require(sellPrice > 0); _transfer(msg.sender, this, amount); uint256 revenue = amount * sellPrice; } function sellMaximumPossibleAmountOfTokens() { require(!frozenAccount[msg.sender]); require(tokenBalanceOf[msg.sender] > 0); require(this.balance > sellPrice); if(tokenBalanceOf[msg.sender] * sellPrice <= this.balance) { sell(tokenBalanceOf[msg.sender]); sell(this.balance / sellPrice); } } function sellMaximumPossibleAmountOfTokens() { require(!frozenAccount[msg.sender]); require(tokenBalanceOf[msg.sender] > 0); require(this.balance > sellPrice); if(tokenBalanceOf[msg.sender] * sellPrice <= this.balance) { sell(tokenBalanceOf[msg.sender]); sell(this.balance / sellPrice); } } }else { function transfer(address _to, uint256 _value) returns (bool success) { assert(msg.sender != address(0)); assert(_to != address(0)); require(!frozenAccount[msg.sender]); require(!frozenAccount[_to]); require(tokenBalanceOf[msg.sender] >= _value); require(tokenBalanceOf[msg.sender] - _value < tokenBalanceOf[msg.sender]); require(tokenBalanceOf[_to] + _value > tokenBalanceOf[_to]); require(_value > 0); _transfer(msg.sender, _to, _value); return true; } function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { assert(msg.sender != address(0)); assert(_from != address(0)); assert(_to != address(0)); require(!frozenAccount[msg.sender]); require(!frozenAccount[_from]); require(!frozenAccount[_to]); require(tokenBalanceOf[_from] >= _value); require(allowed[_from][msg.sender] >= _value); require(tokenBalanceOf[_from] - _value < tokenBalanceOf[_from]); require(tokenBalanceOf[_to] + _value > tokenBalanceOf[_to]); require(_value > 0); orderToTransfer(msg.sender, _from, _to, _value, "Order to transfer metadollars from allowed account"); _transfer(_from, _to, _value); allowed[_from][msg.sender] -= _value; return true; } function approve(address _spender, uint256 _value) returns (bool success) { require(!frozenAccount[msg.sender]); assert(_spender != address(0)); require(_value >= 0); allowed[msg.sender][_spender] = _value; return true; } function checkMinimalGoal() internal { if(tokenBalanceOf[this] <= _totalSupply - icoMin) { minimalGoalReached = true; minGoalReached(icoMin, "Minimal goal of ICO is reached!"); } } function checkMinimalGoal() internal { if(tokenBalanceOf[this] <= _totalSupply - icoMin) { minimalGoalReached = true; minGoalReached(icoMin, "Minimal goal of ICO is reached!"); } } function checkPreIcoStatus() internal { if(tokenBalanceOf[this] <= _totalSupply - preIcoLimit) { preIcoIsRunning = false; preIcoEnded(preIcoLimit, "Token amount for preICO sold!"); } } function checkPreIcoStatus() internal { if(tokenBalanceOf[this] <= _totalSupply - preIcoLimit) { preIcoIsRunning = false; preIcoEnded(preIcoLimit, "Token amount for preICO sold!"); } } function buyToken() internal { uint256 value = msg.value; address sender = msg.sender; require(!icoIsClosed); require(!frozenAccount[sender]); require(value > 0); require(currentTokenPrice > 0); uint256 moneyBack = value - (amount * currentTokenPrice); amountOfInvestments = amountOfInvestments + (value - moneyBack); updatePrices(); _transfer(this, sender, amount); if(!minimalGoalReached) { checkMinimalGoal(); } if(moneyBack > 0) { sender.transfer(moneyBack); } } function buyToken() internal { uint256 value = msg.value; address sender = msg.sender; require(!icoIsClosed); require(!frozenAccount[sender]); require(value > 0); require(currentTokenPrice > 0); uint256 moneyBack = value - (amount * currentTokenPrice); amountOfInvestments = amountOfInvestments + (value - moneyBack); updatePrices(); _transfer(this, sender, amount); if(!minimalGoalReached) { checkMinimalGoal(); } if(moneyBack > 0) { sender.transfer(moneyBack); } } function buyToken() internal { uint256 value = msg.value; address sender = msg.sender; require(!icoIsClosed); require(!frozenAccount[sender]); require(value > 0); require(currentTokenPrice > 0); uint256 moneyBack = value - (amount * currentTokenPrice); amountOfInvestments = amountOfInvestments + (value - moneyBack); updatePrices(); _transfer(this, sender, amount); if(!minimalGoalReached) { checkMinimalGoal(); } if(moneyBack > 0) { sender.transfer(moneyBack); } } function _transfer(address _from, address _to, uint256 _value) internal { assert(_from != address(0)); assert(_to != address(0)); require(_value > 0); require(tokenBalanceOf[_from] >= _value); require(tokenBalanceOf[_to] + _value > tokenBalanceOf[_to]); require(!frozenAccount[_from]); require(!frozenAccount[_to]); if(tokenBalanceOf[_to] == 0){ countHolders += 1; } tokenBalanceOf[_from] -= _value; if(tokenBalanceOf[_from] == 0){ countHolders -= 1; } tokenBalanceOf[_to] += _value; allowed[this][owner] = tokenBalanceOf[this]; allowed[this][supervisor] = tokenBalanceOf[this]; Transfer(_from, _to, _value); } function _transfer(address _from, address _to, uint256 _value) internal { assert(_from != address(0)); assert(_to != address(0)); require(_value > 0); require(tokenBalanceOf[_from] >= _value); require(tokenBalanceOf[_to] + _value > tokenBalanceOf[_to]); require(!frozenAccount[_from]); require(!frozenAccount[_to]); if(tokenBalanceOf[_to] == 0){ countHolders += 1; } tokenBalanceOf[_from] -= _value; if(tokenBalanceOf[_from] == 0){ countHolders -= 1; } tokenBalanceOf[_to] += _value; allowed[this][owner] = tokenBalanceOf[this]; allowed[this][supervisor] = tokenBalanceOf[this]; Transfer(_from, _to, _value); } function _transfer(address _from, address _to, uint256 _value) internal { assert(_from != address(0)); assert(_to != address(0)); require(_value > 0); require(tokenBalanceOf[_from] >= _value); require(tokenBalanceOf[_to] + _value > tokenBalanceOf[_to]); require(!frozenAccount[_from]); require(!frozenAccount[_to]); if(tokenBalanceOf[_to] == 0){ countHolders += 1; } tokenBalanceOf[_from] -= _value; if(tokenBalanceOf[_from] == 0){ countHolders -= 1; } tokenBalanceOf[_to] += _value; allowed[this][owner] = tokenBalanceOf[this]; allowed[this][supervisor] = tokenBalanceOf[this]; Transfer(_from, _to, _value); } function updatePrices() internal { uint256 oldPrice = currentTokenPrice; if(preIcoIsRunning) { checkPreIcoStatus(); } if(preIcoIsRunning) { currentTokenPrice = preICOprice; currentTokenPrice = ICOprice; } if(oldPrice != currentTokenPrice) { priceUpdated(oldPrice, currentTokenPrice, "Metadollar price updated!"); } } function updatePrices() internal { uint256 oldPrice = currentTokenPrice; if(preIcoIsRunning) { checkPreIcoStatus(); } if(preIcoIsRunning) { currentTokenPrice = preICOprice; currentTokenPrice = ICOprice; } if(oldPrice != currentTokenPrice) { priceUpdated(oldPrice, currentTokenPrice, "Metadollar price updated!"); } } function updatePrices() internal { uint256 oldPrice = currentTokenPrice; if(preIcoIsRunning) { checkPreIcoStatus(); } if(preIcoIsRunning) { currentTokenPrice = preICOprice; currentTokenPrice = ICOprice; } if(oldPrice != currentTokenPrice) { priceUpdated(oldPrice, currentTokenPrice, "Metadollar price updated!"); } } }else{ function updatePrices() internal { uint256 oldPrice = currentTokenPrice; if(preIcoIsRunning) { checkPreIcoStatus(); } if(preIcoIsRunning) { currentTokenPrice = preICOprice; currentTokenPrice = ICOprice; } if(oldPrice != currentTokenPrice) { priceUpdated(oldPrice, currentTokenPrice, "Metadollar price updated!"); } } function setPreICOPrice(uint256 priceForPreIcoInWei) isOwner { require(priceForPreIcoInWei > 0); require(preICOprice != priceForPreIcoInWei); preICOprice = priceForPreIcoInWei; updatePrices(); } function setICOPrice(uint256 priceForIcoInWei) isOwner { require(priceForIcoInWei > 0); require(ICOprice != priceForIcoInWei); ICOprice = priceForIcoInWei; updatePrices(); } function setPrices(uint256 priceForPreIcoInWei, uint256 priceForIcoInWei) isOwner { require(priceForPreIcoInWei > 0); require(priceForIcoInWei > 0); preICOprice = priceForPreIcoInWei; ICOprice = priceForIcoInWei; updatePrices(); } function setSellPrice(uint256 priceInWei) isOwner { require(priceInWei >= 0); sellPrice = priceInWei; } function freezeAccount(address account, bool freeze) isOwner { require(account != owner); require(account != supervisor); frozenAccount[account] = freeze; if(freeze) { FrozenFunds(msg.sender, account, "Account set frozen!"); FrozenFunds(msg.sender, account, "Account set free for use!"); } } function freezeAccount(address account, bool freeze) isOwner { require(account != owner); require(account != supervisor); frozenAccount[account] = freeze; if(freeze) { FrozenFunds(msg.sender, account, "Account set frozen!"); FrozenFunds(msg.sender, account, "Account set free for use!"); } } }else { function mintToken(uint256 amount) isOwner { require(amount > 0); require(_totalSupply + amount > _totalSupply); require(tokenBalanceOf[this] + amount > tokenBalanceOf[this]); _totalSupply += amount; tokenBalanceOf[this] += amount; allowed[this][owner] = tokenBalanceOf[this]; allowed[this][supervisor] = tokenBalanceOf[this]; tokenCreated(msg.sender, amount, "Additional metadollars created!"); } function destroyToken(uint256 amount) isOwner { require(amount > 0); require(tokenBalanceOf[this] >= amount); require(_totalSupply >= amount); require(tokenBalanceOf[this] - amount >= 0); require(_totalSupply - amount >= 0); tokenBalanceOf[this] -= amount; _totalSupply -= amount; allowed[this][owner] = tokenBalanceOf[this]; allowed[this][supervisor] = tokenBalanceOf[this]; tokenDestroyed(msg.sender, amount, "An amount of metadollars destroyed!"); } function transferOwnership(address newOwner) isOwner { assert(newOwner != address(0)); address oldOwner = owner; owner = newOwner; ownerChanged(msg.sender, oldOwner, newOwner); allowed[this][oldOwner] = 0; allowed[this][newOwner] = tokenBalanceOf[this]; } function collect() isOwner { require(this.balance > 0); withdraw(this.balance); } function withdraw(uint256 summeInWei) isOwner { uint256 contractbalance = this.balance; address sender = msg.sender; require(contractbalance >= summeInWei); withdrawed(sender, summeInWei, "wei withdrawed"); sender.transfer(summeInWei); } function deposit() payable isOwner { require(msg.value > 0); require(msg.sender.balance >= msg.value); deposited(msg.sender, msg.value, "wei deposited"); } function allowIcoExit(bool exitAllowed) isOwner { require(icoExitIsPossible != exitAllowed); icoExitIsPossible = exitAllowed; } function stopThisIco(bool icoIsStopped) isOwner { require(icoIsClosed != icoIsStopped); icoIsClosed = icoIsStopped; if(icoIsStopped) { icoStatusUpdated(msg.sender, "Coin offering was stopped!"); icoStatusUpdated(msg.sender, "Coin offering is running!"); } } function stopThisIco(bool icoIsStopped) isOwner { require(icoIsClosed != icoIsStopped); icoIsClosed = icoIsStopped; if(icoIsStopped) { icoStatusUpdated(msg.sender, "Coin offering was stopped!"); icoStatusUpdated(msg.sender, "Coin offering is running!"); } } }else { function exitThisIcoForHalfOfTokenPrice() { require(icoExitIsPossible); require(!frozenAccount[msg.sender]); require(currentTokenPrice > 1); uint256 amount = tokenBalanceOf[msg.sender] ; uint256 revenue = amount * currentTokenPrice / 2; require(this.balance >= revenue); _transfer(msg.sender, this, amount); } function getAllMyTokensForAllEtherOnContract() { require(icoExitIsPossible); require(!frozenAccount[msg.sender]); require(currentTokenPrice > 1); uint256 amount = tokenBalanceOf[msg.sender] ; uint256 revenue = amount * currentTokenPrice / 2; require(this.balance <= revenue); _transfer(msg.sender, this, amount); msg.sender.transfer(this.balance); } }
15,131,951
[ 1, 5912, 326, 23178, 434, 333, 6835, 38, 26488, 364, 1517, 2236, 16837, 434, 2236, 6617, 3324, 326, 7412, 434, 392, 3844, 358, 4042, 2236, 1098, 598, 1779, 2973, 12810, 2236, 20244, 291, 2103, 279, 1071, 871, 603, 279, 16766, 716, 903, 5066, 1004, 20244, 291, 2103, 279, 1071, 871, 603, 279, 16766, 716, 903, 5066, 1004, 20244, 291, 2103, 279, 1071, 871, 603, 279, 16766, 716, 903, 5066, 1004, 20244, 291, 2103, 279, 1071, 871, 603, 279, 16766, 716, 903, 5066, 1004, 20244, 291, 2103, 279, 1071, 871, 603, 279, 16766, 716, 903, 5066, 1004, 20244, 291, 2103, 279, 1071, 871, 603, 279, 16766, 716, 903, 5066, 1004, 20244, 291, 2103, 279, 1071, 871, 603, 279, 16766, 716, 903, 5066, 1004, 20244, 291, 2103, 279, 1071, 871, 603, 279, 16766, 716, 903, 5066, 1004, 20244, 291, 2103, 279, 1071, 871, 603, 279, 16766, 716, 903, 5066, 1004, 20244, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 16351, 6791, 1880, 30922, 985, 353, 4232, 39, 3462, 1358, 16, 16199, 95, 203, 203, 202, 1080, 1071, 5381, 508, 273, 315, 18315, 1880, 30922, 985, 14432, 203, 202, 1080, 1071, 5381, 3273, 273, 315, 40, 1741, 14432, 203, 202, 11890, 1071, 5381, 15105, 273, 6549, 31, 203, 202, 203, 202, 203, 202, 6430, 1071, 675, 45, 2894, 2520, 7051, 31, 203, 202, 6430, 1071, 16745, 27716, 23646, 31, 203, 202, 6430, 1071, 277, 2894, 2520, 7395, 31, 203, 202, 6430, 277, 2894, 6767, 2520, 13576, 31, 203, 203, 203, 202, 6770, 261, 2867, 516, 2254, 5034, 13, 1071, 1147, 13937, 951, 31, 203, 203, 202, 6770, 12, 2867, 516, 2874, 261, 2867, 516, 2254, 5034, 3719, 2935, 31, 203, 202, 203, 202, 6770, 12, 2867, 516, 1426, 13, 12810, 3032, 31, 203, 202, 203, 202, 2575, 478, 9808, 42, 19156, 12, 2867, 26030, 16, 1758, 2236, 16, 533, 1267, 1769, 203, 202, 203, 202, 2575, 605, 22889, 5033, 12, 11890, 28, 324, 22889, 7617, 16, 2254, 28, 324, 22889, 1908, 1769, 203, 202, 203, 202, 2575, 1131, 27716, 23646, 12, 11890, 5034, 1131, 45, 2894, 6275, 16, 533, 11690, 1769, 203, 202, 203, 202, 2575, 675, 45, 2894, 28362, 12, 11890, 5034, 675, 45, 2894, 6275, 16, 533, 11690, 1769, 203, 202, 203, 202, 2575, 6205, 7381, 12, 11890, 5034, 1592, 5147, 16, 2254, 5034, 394, 5147, 16, 533, 11690, 1769, 203, 202, 203, 202, 2575, 598, 9446, 329, 12, 2867, 389, 869, 16, 2254, 5034, 2142, 3501, 16, 533, 11690, 1769, 203, 2 ]
./full_match/56/0xA533e79B89A0B7590bF538e59D673e295D25FFC3/sources/DeFiCopyTrade/PBXStaking.sol
@dev : Check PASS [✓] */ @dev : Add New Staker AND deposit to stake */
function addUserAndDeposit(address staker, uint amount) internal { UsersInfo[staker] = UserInfo(staker, amount, timeNow(), timeNow() + timeLock()); TotalStaker.push(staker); TVL += amount; tokenStake.transferFrom(staker, address(this), amount);
3,233,339
[ 1, 30, 2073, 17882, 306, 163, 255, 246, 65, 342, 225, 294, 1436, 1166, 934, 6388, 4116, 443, 1724, 358, 384, 911, 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 ]
[ 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, 527, 1299, 1876, 758, 1724, 12, 2867, 384, 6388, 16, 2254, 3844, 13, 2713, 288, 203, 3639, 12109, 966, 63, 334, 6388, 65, 273, 25003, 12, 334, 6388, 16, 3844, 16, 813, 8674, 9334, 813, 8674, 1435, 397, 813, 2531, 10663, 203, 3639, 10710, 510, 6388, 18, 6206, 12, 334, 6388, 1769, 203, 3639, 399, 58, 48, 1011, 3844, 31, 203, 203, 3639, 1147, 510, 911, 18, 13866, 1265, 12, 334, 6388, 16, 1758, 12, 2211, 3631, 3844, 1769, 7010, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/42220/0xb087892391555533E73617Ea7E14cB48a9409a27/sources/project:/contracts/base/BaseWeightedUtils.sol
.mul(10000000000)); .div(referenceBalances[2].mul(poolAdjustmentVaulues.referenceNormalizedWeights[2].mul(10)));
referencePoolTokenPrice = (referenceBalances[i].mul(poolAdjustmentVaulues.referenceNormalizedWeights[i]));
16,348,241
[ 1, 18, 16411, 12, 23899, 9449, 10019, 263, 2892, 12, 6180, 38, 26488, 63, 22, 8009, 16411, 12, 6011, 19985, 21557, 332, 3610, 18, 6180, 15577, 16595, 63, 22, 8009, 16411, 12, 2163, 3719, 1769, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 10792, 2114, 2864, 1345, 5147, 273, 261, 6180, 38, 26488, 63, 77, 8009, 16411, 12, 6011, 19985, 21557, 332, 3610, 18, 6180, 15577, 16595, 63, 77, 5717, 1769, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.24; import "openzeppelin-solidity/contracts/ownership/Ownable.sol"; import "./Utils.sol"; import "./SparseMerkleTree.sol"; import "./Accounts.sol"; import "./CollectionRegistry.sol"; contract DataRegistry is Ownable { event BundleUnregistered(bytes8 indexed collectionId, bytes8 indexed bundleId); event BundleRegistered(bytes8 indexed collectionId, bytes8 indexed bundleId); event Punished(address provider); struct Bundle { bytes32 usersRoot; bytes32 bundleDataHash; string uri; uint256 createdAt; bytes8 collectionId; // will be further used in Data Availability Challenge uint64 proofOfPosessionCount; } mapping (bytes8 => Bundle) public bundles; Accounts accounts; CollectionRegistry collections; SparseMerkleTree sparseMerkleTree; constructor(Accounts _accounts, CollectionRegistry _collections, SparseMerkleTree _smt) public { accounts = _accounts; collections = _collections; sparseMerkleTree = _smt; } function registerBundle(bytes8 collectionId, bytes32 usersRoot, bytes32 dataHash, string uri) external /*onlyProvider*/ { require(collections.exists(collectionId), "Collection does not exist."); Bundle memory bundle; bundle.usersRoot = usersRoot; bundle.bundleDataHash = dataHash; bundle.collectionId = collectionId; bundle.uri = uri; bytes8 bundleId = bytes8(keccak256(abi.encodePacked(block.number, msg.sender, collectionId, dataHash))); bundles[bundleId] = bundle; emit BundleRegistered(collectionId, bundleId); } function challenge(bytes8 collectionId, bytes8 bundleId, bytes proof) external view /*onlyConsumer*/ { require(collections.exists(collectionId), "Collection does not exist."); bytes8 userId = accounts.getAccountId(msg.sender); Bundle storage bundle = bundles[bundleId]; require( collections.isCollectionAllowedAt(collectionId, userId, bundle.createdAt), "You have been allowed to collect the data at that time. Why is it a problem?" ); bool challengeResult = sparseMerkleTree.checkMembership(bundle.usersRoot, uint64(userId), proof); require(challengeResult, "Proof failed"); // punish(collection.owner); // emit Punished(collection.owner); } function isMyDataIncluded(bytes8 collectionId, bytes8 bundleId, bytes proof) public view returns (bool) { require(collections.exists(collectionId), "Collection does not exist."); uint64 userId = uint64(accounts.getAccountId(msg.sender)); bytes32 root = bundles[bundleId].usersRoot; return sparseMerkleTree.checkMembership(root, userId, proof); } }
punish(collection.owner); emit Punished(collection.owner);
function challenge(bytes8 collectionId, bytes8 bundleId, bytes proof) external view /*onlyConsumer*/ { require(collections.exists(collectionId), "Collection does not exist."); bytes8 userId = accounts.getAccountId(msg.sender); Bundle storage bundle = bundles[bundleId]; require( collections.isCollectionAllowedAt(collectionId, userId, bundle.createdAt), "You have been allowed to collect the data at that time. Why is it a problem?" ); bool challengeResult = sparseMerkleTree.checkMembership(bundle.usersRoot, uint64(userId), proof); require(challengeResult, "Proof failed"); }
7,235,822
[ 1, 84, 318, 1468, 12, 5548, 18, 8443, 1769, 3639, 3626, 453, 318, 5992, 12, 5548, 18, 8443, 1769, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 12948, 12, 3890, 28, 1849, 548, 16, 1731, 28, 3440, 548, 16, 1731, 14601, 13, 3903, 1476, 1748, 3700, 5869, 5549, 288, 203, 3639, 2583, 12, 19246, 18, 1808, 12, 5548, 548, 3631, 315, 2532, 1552, 486, 1005, 1199, 1769, 203, 3639, 1731, 28, 6249, 273, 9484, 18, 588, 14594, 12, 3576, 18, 15330, 1769, 203, 203, 3639, 8539, 2502, 3440, 273, 11408, 63, 9991, 548, 15533, 203, 3639, 2583, 12, 203, 5411, 6980, 18, 291, 2532, 5042, 861, 12, 5548, 548, 16, 6249, 16, 3440, 18, 4824, 861, 3631, 203, 5411, 315, 6225, 1240, 2118, 2935, 358, 3274, 326, 501, 622, 716, 813, 18, 3497, 93, 353, 518, 279, 6199, 7225, 203, 3639, 11272, 203, 203, 3639, 1426, 12948, 1253, 273, 9387, 8478, 15609, 2471, 18, 1893, 13447, 12, 9991, 18, 5577, 2375, 16, 2254, 1105, 12, 18991, 3631, 14601, 1769, 203, 3639, 2583, 12, 25092, 1253, 16, 315, 20439, 2535, 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 ]
pragma solidity ^0.4.18; import "../math/SafeMath.sol"; import "../ownership/Ownable.sol"; import "../token/FrozenMintBurnToken.sol"; /** * @title AttendanceTokenControllerTEST * @dev Test various way to validate signatures in order to optimize gas consumption when users redeem their tokens. */ contract ParticipationTokenControllerTEST is Ownable { using SafeMath for uint256; //Variables mapping (address => bool) admin; // Who can sign messages mapping (address => mapping (uint256 => bool)) redeemedTokens; // Whether tokens where redeemed for an ID FrozenMintBurnToken public token; // Token contract //Struct mapping (address => bool) sigUsed; //placeholder to prevent reusing same signature uint8 sigRequired = 2; //Number of signatures required to redeem tokens //Variables for BITMASK mapping(uint256 => address) IDadmin; mapping(address => uint256) adminID; //Events event TokensRedeemed(address indexed _address, uint256 _amount, uint256 _nonce); event AdminStatusChanged(address _admin, uint256 _adminStatus); event SigRequiredChanged(uint256 _sigRequired); /* @dev Create new ParticipationToken and token controller contract @param _name Name of the new participation token. @param _symbol Symbol of the new participation token. @param _decimals Number of decimals for the new participation token. */ function ParticipationTokenControllerTEST( string _name, string _symbol, uint8 _decimals) public { // Create new token token = new FrozenMintBurnToken(_name, _symbol, _decimals); } /* @dev Change the authorization status of a given address @param _add Address to change authorization status @param _adminStatus Authorization status to give to address */ function setAdminStatus(address _add, bool _adminStatus) public onlyOwner returns(bool) { admin[_add] = _adminStatus; //AdminStatusChanged(_add, _adminStatus); return true; } /* @dev Set number of signatures required to redeem tokens. @param _sigRequired New number of signature required. */ function setSigRequired(uint8 _sigRequired) onlyOwner public returns (bool) { require(_sigRequired > 0); sigRequired = _sigRequired; SigRequiredChanged(_sigRequired); return true; } /* @dev Allows to redeem tokens to _benificiary if possessing enough valid signed messages @param _beneficiary Address that is allowed to redeem tokens @param _amount Amounts of tokens they can claim @param _nonce Nonce of the event for which this message was generated @param _sigs Array of signatures. */ function redeemTokensARRAY( address _beneficiary, uint256 _amount, uint256 _nonce, bytes _sigs) public returns (bool) { //Number of signatures uint256 nSigs = _sigs.length.div(65); require(nSigs >= sigRequired); //Make sure tokens were not redeemed already for given nonce //require(!redeemedTokens[_beneficiary][_nonce]); address[] memory signer = new address[](sigRequired); bytes32 r; bytes32 s; uint8 v; // Verifying if msg.senders provides enough valid signatures for(uint8 i = 0; i < sigRequired; i++) { // Extract ECDSA signature variables from current signature assembly { r := mload(add(_sigs, add(mul(i, 65), 32))) s := mload(add(_sigs, add(mul(i, 65), 64))) v := byte(0, mload(add(_sigs, add(mul(i, 65), 96)))) } // Check validity of current signature signer[i] = recoverRedeemMessageSignerRSV(_beneficiary, _amount, _nonce, r, s, v); // If signer is an admin and if their signature wasn't already used require(admin[signer[i]]); //Making sure signer wasn't used already for (uint8 ii = 0; ii < i; ii++){ require(signer[ii] != signer[i]); } } //Tokens for given nonce were claimed //redeemedTokens[_beneficiary][_nonce] = true; //Minting tokens to _benificiary token.mint(_beneficiary, _amount); TokensRedeemed(_beneficiary, _amount, _nonce); return true; } //ARRAY APPROACH function redeemTokensMAPPING( address _beneficiary, uint256 _amount, uint256 _nonce, bytes _sigs) public returns (bool) { //Number of signatures uint256 nSigs = _sigs.length.div(65); require(nSigs >= sigRequired); //Make sure tokens were not redeemed already for given nonce //require(!redeemedTokens[_beneficiary][_nonce]); address[] memory signer = new address[](sigRequired); bytes32 r; bytes32 s; uint8 v; // Verifying if msg.senders provides enough valid signatures for(uint8 i = 0; i < sigRequired; i++) { // Extract ECDSA signature variables from current signature assembly { r := mload(add(_sigs, add(mul(i, 65), 32))) s := mload(add(_sigs, add(mul(i, 65), 64))) v := byte(0, mload(add(_sigs, add(mul(i, 65), 96)))) } // Check validity of current signature signer[i] = recoverRedeemMessageSignerRSV(_beneficiary, _amount, _nonce, r, s, v); // If signer is an admin and if their signature wasn't already used require(admin[signer[i]]); // Signature from signer has been used sigUsed[signer[i]] = true; } //Tokens for given nonce were claimed //redeemedTokens[_beneficiary][_nonce] = true; //Minting tokens to _benificiary token.mint(_beneficiary, _amount); //Clearing sigUsed for (i = 0; i < sigRequired; i++){ sigUsed[signer[i]] = false; } TokensRedeemed(_beneficiary, _amount, _nonce); return true; } // BITMASK APPROACH function setIDadmin(address _admin, uint256 _ID) public { require(IDadmin[_ID] == 0x0); IDadmin[_ID] = _admin; adminID[_admin] = _ID; } /* @dev Change the authorization status of a given address @param _admin Address to give admin status to */ function setAsAdmin(address _admin) public onlyOwner returns(bool) { //Will find the first free admin spot from 0 to 256 for (uint256 i = 0; i<256; i++){ if (IDadmin[2**i] == 0x0) { IDadmin[2**i] = _admin; adminID[_admin] = 2**i; //AdminStatusChanged(_admin, 2**i); return true; } } return false; } /* @dev Remove admin status from an address @param _admin Address to remove admin status */ function removeAsAdmin(address _admin) public onlyOwner returns(bool) { IDadmin[adminID[_admin]] = 0x0; adminID[_admin] = 0; //AdminStatusChanged(_admin, 0); return true; } function redeemTokensBITMASK( address _beneficiary, uint256 _amount, uint256 _nonce, bytes _sigs) public returns (bool) { uint256 nSigs = _sigs.length.div(65); // Number of signatures require(nSigs >= sigRequired); // Enough signatures provided //require(!redeemedTokens[_beneficiary][_nonce]); // Nonce's tokens not redeemed yet uint256 bitsigners; // Keeps track of who signed address signer; // Address of currently recovered signer bytes32 r; // ECDSA signature r variable bytes32 s; // ECDSA signature s variable uint8 v; // ECDSA signature v variable // Verifying if msg.senders provides enough valid signatures for(uint8 i = 0; i < sigRequired; i++) { // Extract ECDSA signature variables from current signature assembly { r := mload(add(_sigs, add(mul(i, 65), 32))) s := mload(add(_sigs, add(mul(i, 65), 64))) v := byte(0, mload(add(_sigs, add(mul(i, 65), 96)))) } // Check validity of current signature signer = recoverRedeemMessageSignerRSV(_beneficiary, _amount, _nonce, r, s, v); // If signer is an admin, count bitsigners = bitsigners | adminID[signer]; } //Tokens for given nonce were claimed //redeemedTokens[_beneficiary][_nonce] = true; //Counting number of valid signatures uint8 counter = 0; //Count number of unique, valid signatures for (uint256 ii = 0; ii<256; ii++){ if (2**ii & bitsigners == 2**ii) { counter++; if (counter == sigRequired){ //Minting tokens to _benificiary token.mint(_beneficiary, _amount); TokensRedeemed(_beneficiary, _amount, _nonce); return true; } } } return false; } // SEOCND VERSION /* @dev Verifies if message was signed by an admin to give access to _add for this contract. Assumes Geth signature prefix. @param _add Address of agent with access. @param _amount Amount of tokens that can be claimed @param _nonce Nonce of the event @param _sig Valid signature from owner */ function recoverRedeemMessageSigner( address _add, uint256 _amount, uint256 _nonce, bytes _sig) view public returns (address) { bytes32 r; bytes32 s; uint8 v; //Extract ECDSA signature variables from `sig` assembly { r := mload(add(_sig, 32)) s := mload(add(_sig, 64)) v := byte(0, mload(add(_sig, 96))) } // Version of signature should be 27 or 28, but 0 and 1 are also possible versions if (v < 27) { v += 27; } // Verifying if recovered signer is contract admin bytes32 hash = keccak256(this, _add, _amount, _nonce); //Return recovered signer address return ecrecover( keccak256("\x19Ethereum Signed Message:\n32", hash), v, r, s ); } /* @dev Verifies if message was signed by an admin to give access to _add for this contract. Assumes Geth signature prefix. @param _add Address of agent with access. @param _amount Amount of tokens that can be claimed @param _nonce Nonce of the event @param _r r variable from ECDSA signature. @param _s s variable from ECDSA signature. @param _v v variable from ECDSA signature. @return Validity of access message for a given address. */ function recoverRedeemMessageSignerRSV( address _add, uint256 _amount, uint256 _nonce, bytes32 _r, bytes32 _s, uint8 _v) view public returns (address) { // Version of signature should be 27 or 28, but 0 and 1 are also possible versions if (_v < 27) { _v += 27; } // Hash of the message that had to be signed bytes32 hash = keccak256(this, _add, _amount, _nonce); //Return recovered signer address return ecrecover( keccak256("\x19Ethereum Signed Message:\n32", hash), _v, _r, _s ); } /* @dev Checks whether the current message is valid. @param _add Address of agent with access. @param _amount Amount of tokens that can be claimed @param _nonce Nonce of the event @param _sig Valid signature from owner */ function isValidRedeemMessage( address _add, uint256 _amount, uint256 _nonce, bytes _sig) view public returns (bool){ return ( adminID[recoverRedeemMessageSigner(_add, _amount, _nonce, _sig)] > 0 ); } /* @dev Returns whether the address is an admin or not. @param _add Address to query admin status. */ function getAdminStatus(address _add) public view returns (bool) { return admin[_add]; } /* @dev Returns admin's ID. @param _add Address to query admin ID. */ function getAdminID(address _add) public view returns (uint256) { return adminID[_add]; } /* @dev Returns the admin's address associated with an ID. @param _add ID (2^i) to query admin's address associated with it . */ function getAdminAddress(uint256 _ID) public view returns (address) { return IDadmin[_ID]; } }
ECDSA signature r variable
bytes32 r;
6,480,133
[ 1, 7228, 19748, 3372, 436, 2190, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1731, 1578, 436, 31, 6647, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0xc7762a0E64b7c583Ee89cf66Df2DC267e420cf7D/sources/contracts/Lottery.sol
This function was called by Chainlink VRF to fulfill the request
function fulfillRandomWords( uint256 _requestId, uint256[] memory _randomWords ) internal override { require(s_requests[_requestId].paid > 0, "request not found"); s_requests[_requestId].fulfilled = true; s_requests[_requestId].randomWords = _randomWords; execute(_randomWords); isLotteryActive = false; emit RequestFulfilled( _requestId, _randomWords, s_requests[_requestId].paid ); }
1,886,867
[ 1, 2503, 445, 1703, 2566, 635, 7824, 1232, 776, 12918, 358, 22290, 326, 590, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 22290, 8529, 7363, 12, 203, 3639, 2254, 5034, 389, 2293, 548, 16, 203, 3639, 2254, 5034, 8526, 3778, 389, 9188, 7363, 203, 565, 262, 2713, 3849, 288, 203, 3639, 2583, 12, 87, 67, 11420, 63, 67, 2293, 548, 8009, 29434, 405, 374, 16, 315, 2293, 486, 1392, 8863, 203, 3639, 272, 67, 11420, 63, 67, 2293, 548, 8009, 2706, 13968, 273, 638, 31, 203, 3639, 272, 67, 11420, 63, 67, 2293, 548, 8009, 9188, 7363, 273, 389, 9188, 7363, 31, 203, 3639, 1836, 24899, 9188, 7363, 1769, 203, 3639, 28601, 352, 387, 93, 3896, 273, 629, 31, 203, 3639, 3626, 1567, 23747, 13968, 12, 203, 5411, 389, 2293, 548, 16, 203, 5411, 389, 9188, 7363, 16, 203, 5411, 272, 67, 11420, 63, 67, 2293, 548, 8009, 29434, 203, 3639, 11272, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x1337DEF1C79053dA23921a3634aDbD12f3b748A5/sources/OwnedUpgradeabilityProxy.sol
* @title OwnedUpgradeabilityProxy @dev This contract combines an upgradeability proxy with basic authorization control functionalities/ Storage position of the owner of the contract
contract OwnedUpgradeabilityProxy is UpgradeabilityProxy { event ProxyOwnershipTransferred(address previousOwner, address newOwner); bytes32 private constant PROXY_OWNER_POSITION = keccak256("org.govblocks.proxy.owner"); constructor(address _implementation) public { _setUpgradeabilityOwner(msg.sender); _upgradeTo(_implementation); } modifier onlyProxyOwner() { require(msg.sender == proxyOwner()); _; } function proxyOwner() public view returns (address owner) { bytes32 position = PROXY_OWNER_POSITION; assembly { owner := sload(position) } } function proxyOwner() public view returns (address owner) { bytes32 position = PROXY_OWNER_POSITION; assembly { owner := sload(position) } } function transferProxyOwnership(address _newOwner) public onlyProxyOwner { require(_newOwner != address(0)); _setUpgradeabilityOwner(_newOwner); emit ProxyOwnershipTransferred(proxyOwner(), _newOwner); } function upgradeTo(address _implementation) public onlyProxyOwner { _upgradeTo(_implementation); } function _setUpgradeabilityOwner(address _newProxyOwner) internal { bytes32 position = PROXY_OWNER_POSITION; assembly { sstore(position, _newProxyOwner) } } function _setUpgradeabilityOwner(address _newProxyOwner) internal { bytes32 position = PROXY_OWNER_POSITION; assembly { sstore(position, _newProxyOwner) } } }
3,936,751
[ 1, 5460, 329, 10784, 2967, 3886, 225, 1220, 6835, 30933, 392, 8400, 2967, 2889, 598, 5337, 6093, 3325, 18699, 1961, 19, 5235, 1754, 434, 326, 3410, 434, 326, 6835, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 14223, 11748, 10784, 2967, 3886, 353, 17699, 2967, 3886, 288, 203, 565, 871, 7659, 5460, 12565, 1429, 4193, 12, 2867, 2416, 5541, 16, 1758, 394, 5541, 1769, 203, 203, 565, 1731, 1578, 3238, 5381, 26910, 67, 29602, 67, 15258, 273, 417, 24410, 581, 5034, 2932, 3341, 18, 75, 1527, 7996, 18, 5656, 18, 8443, 8863, 203, 203, 203, 565, 3885, 12, 2867, 389, 30810, 13, 1071, 288, 203, 3639, 389, 542, 10784, 2967, 5541, 12, 3576, 18, 15330, 1769, 203, 3639, 389, 15097, 774, 24899, 30810, 1769, 203, 565, 289, 203, 203, 565, 9606, 1338, 3886, 5541, 1435, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 2889, 5541, 10663, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 565, 445, 2889, 5541, 1435, 1071, 1476, 1135, 261, 2867, 3410, 13, 288, 203, 3639, 1731, 1578, 1754, 273, 26910, 67, 29602, 67, 15258, 31, 203, 3639, 19931, 288, 203, 5411, 3410, 519, 272, 945, 12, 3276, 13, 203, 3639, 289, 203, 565, 289, 203, 203, 565, 445, 2889, 5541, 1435, 1071, 1476, 1135, 261, 2867, 3410, 13, 288, 203, 3639, 1731, 1578, 1754, 273, 26910, 67, 29602, 67, 15258, 31, 203, 3639, 19931, 288, 203, 5411, 3410, 519, 272, 945, 12, 3276, 13, 203, 3639, 289, 203, 565, 289, 203, 203, 565, 445, 7412, 3886, 5460, 12565, 12, 2867, 389, 2704, 5541, 13, 1071, 1338, 3886, 5541, 288, 203, 3639, 2583, 24899, 2704, 5541, 480, 1758, 12, 20, 10019, 203, 3639, 389, 542, 10784, 2967, 5541, 24899, 2704, 5541, 1769, 203, 3639, 3626, 2 ]
// SPDX-License-Identifier: MIT pragma solidity 0.8.7; /// @notice Interface of the `SmartWalletChecker` contracts of the protocol interface SmartWalletChecker { function check(address) external view returns (bool); } /// @title SmartWalletWhitelist /// @author Curve Finance and adapted by Angle Core Team (https://etherscan.io/address/0xca719728ef172d0961768581fdf35cb116e0b7a4#code) /// @notice Provides functions to check whether a wallet has been verified or not to own veANGLE contract SmartWalletWhitelist { /// @notice Mapping between addresses and whether they are whitelisted or not mapping(address => bool) public wallets; /// @notice Admin address of the contract address public admin; /// @notice Future admin address of the contract //solhint-disable-next-line address public future_admin; /// @notice Contract which works as this contract and that can whitelist addresses address public checker; /// @notice Future address to become checker //solhint-disable-next-line address public future_checker; event ApproveWallet(address indexed _wallet); event RevokeWallet(address indexed _wallet); /// @notice Constructor of the contract /// @param _admin Admin address of the contract constructor(address _admin) { require(_admin != address(0), "0"); admin = _admin; } /// @notice Commits to change the admin /// @param _admin New admin of the contract function commitAdmin(address _admin) external { require(msg.sender == admin, "!admin"); future_admin = _admin; } /// @notice Changes the admin to the admin that has been committed function applyAdmin() external { require(msg.sender == admin, "!admin"); require(future_admin != address(0), "admin not set"); admin = future_admin; } /// @notice Commits to change the checker address /// @param _checker New checker address /// @dev This address can be the zero address in which case there will be no checker function commitSetChecker(address _checker) external { require(msg.sender == admin, "!admin"); future_checker = _checker; } /// @notice Applies the checker previously committed function applySetChecker() external { require(msg.sender == admin, "!admin"); checker = future_checker; } /// @notice Approves a wallet /// @param _wallet Wallet to approve function approveWallet(address _wallet) public { require(msg.sender == admin, "!admin"); wallets[_wallet] = true; emit ApproveWallet(_wallet); } /// @notice Revokes a wallet /// @param _wallet Wallet to revoke function revokeWallet(address _wallet) external { require(msg.sender == admin, "!admin"); wallets[_wallet] = false; emit RevokeWallet(_wallet); } /// @notice Checks whether a wallet is whitelisted /// @param _wallet Wallet address to check /// @dev This function can also rely on another SmartWalletChecker (a `checker` to see whether the wallet is whitelisted or not) function check(address _wallet) external view returns (bool) { bool _check = wallets[_wallet]; if (_check) { return _check; } else { if (checker != address(0)) { return SmartWalletChecker(checker).check(_wallet); } } return false; } }
@notice Approves a wallet @param _wallet Wallet to approve
function approveWallet(address _wallet) public { require(msg.sender == admin, "!admin"); wallets[_wallet] = true; emit ApproveWallet(_wallet); }
42,380
[ 1, 12053, 3324, 279, 9230, 225, 389, 19177, 20126, 358, 6617, 537, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 6617, 537, 16936, 12, 2867, 389, 19177, 13, 1071, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 3981, 16, 17528, 3666, 8863, 203, 3639, 17662, 2413, 63, 67, 19177, 65, 273, 638, 31, 203, 203, 3639, 3626, 1716, 685, 537, 16936, 24899, 19177, 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 ]
./partial_match/4/0x131664Fe9Da4a0ad41C39F52Fd9e0d899C133e98/sources/Converter.sol
List of NFTs that have been deposited
contract Converter is ERC20, ERC1155Receiver { using SafeMath for uint; struct NFT { address contractAddr; uint256 tokenId; uint256 amount; } struct Bid { NFT nft; uint256 amount; } mapping(uint256 => NFT) public nfts; uint256 public totalBidAmount = 0; uint256 public _threshold; address public issuer; string public _description; uint256 public cap; IUnicFactory public factory; mapping(uint256 => mapping(address => address)) private _nextBids; mapping(uint256 => uint256) public numberBids; address constant GUARD = address(1); bytes private constant VALIDATOR = bytes('JCMY'); constructor (uint256 totalSupply, uint8 decimals, string memory name, string memory symbol, uint256 threshold, string memory description, address _issuer, IUnicFactory _factory) public ERC20(name, symbol) uint256 public currentNFTIndex = 0; bool public active = false; mapping(uint256 => mapping(address => uint256)) public bidNFTs; { _setupDecimals(decimals); issuer = _issuer; _description = description; _threshold = threshold; factory = _factory; cap = totalSupply; } function deposit(uint256[] calldata tokenIDs, uint256[] calldata amounts, address contractAddr) external { require(!active, "Converter: Contract is already active"); require(tokenIDs.length <= 50, "Converter: A maximum of 50 tokens can be deposited in one go"); require(tokenIDs.length > 0, "Converter: You must specify at least one token ID"); if (ERC165Checker.supportsInterface(contractAddr, 0xd9b67a26)){ ERC1155 ct = ERC1155(contractAddr); ct.safeBatchTransferFrom(msg.sender, address(this), tokenIDs, amounts, VALIDATOR); for (uint8 i = 0; i < 50; i++){ if (tokenIDs.length == i){ break; } nfts[currentNFTIndex++] = NFT(contractAddr, tokenIDs[i], amounts[i]); } } else if (ERC165Checker.supportsInterface(contractAddr, 0x80ac58cd)){ ERC721 ct = ERC721(contractAddr); for (uint8 i = 0; i < 50; i++){ if (tokenIDs.length == i){ break; } ct.transferFrom(msg.sender, address(this), tokenIDs[i]); nfts[currentNFTIndex++] = NFT(contractAddr, tokenIDs[i], 1); } } } function deposit(uint256[] calldata tokenIDs, uint256[] calldata amounts, address contractAddr) external { require(!active, "Converter: Contract is already active"); require(tokenIDs.length <= 50, "Converter: A maximum of 50 tokens can be deposited in one go"); require(tokenIDs.length > 0, "Converter: You must specify at least one token ID"); if (ERC165Checker.supportsInterface(contractAddr, 0xd9b67a26)){ ERC1155 ct = ERC1155(contractAddr); ct.safeBatchTransferFrom(msg.sender, address(this), tokenIDs, amounts, VALIDATOR); for (uint8 i = 0; i < 50; i++){ if (tokenIDs.length == i){ break; } nfts[currentNFTIndex++] = NFT(contractAddr, tokenIDs[i], amounts[i]); } } else if (ERC165Checker.supportsInterface(contractAddr, 0x80ac58cd)){ ERC721 ct = ERC721(contractAddr); for (uint8 i = 0; i < 50; i++){ if (tokenIDs.length == i){ break; } ct.transferFrom(msg.sender, address(this), tokenIDs[i]); nfts[currentNFTIndex++] = NFT(contractAddr, tokenIDs[i], 1); } } } function deposit(uint256[] calldata tokenIDs, uint256[] calldata amounts, address contractAddr) external { require(!active, "Converter: Contract is already active"); require(tokenIDs.length <= 50, "Converter: A maximum of 50 tokens can be deposited in one go"); require(tokenIDs.length > 0, "Converter: You must specify at least one token ID"); if (ERC165Checker.supportsInterface(contractAddr, 0xd9b67a26)){ ERC1155 ct = ERC1155(contractAddr); ct.safeBatchTransferFrom(msg.sender, address(this), tokenIDs, amounts, VALIDATOR); for (uint8 i = 0; i < 50; i++){ if (tokenIDs.length == i){ break; } nfts[currentNFTIndex++] = NFT(contractAddr, tokenIDs[i], amounts[i]); } } else if (ERC165Checker.supportsInterface(contractAddr, 0x80ac58cd)){ ERC721 ct = ERC721(contractAddr); for (uint8 i = 0; i < 50; i++){ if (tokenIDs.length == i){ break; } ct.transferFrom(msg.sender, address(this), tokenIDs[i]); nfts[currentNFTIndex++] = NFT(contractAddr, tokenIDs[i], 1); } } } function deposit(uint256[] calldata tokenIDs, uint256[] calldata amounts, address contractAddr) external { require(!active, "Converter: Contract is already active"); require(tokenIDs.length <= 50, "Converter: A maximum of 50 tokens can be deposited in one go"); require(tokenIDs.length > 0, "Converter: You must specify at least one token ID"); if (ERC165Checker.supportsInterface(contractAddr, 0xd9b67a26)){ ERC1155 ct = ERC1155(contractAddr); ct.safeBatchTransferFrom(msg.sender, address(this), tokenIDs, amounts, VALIDATOR); for (uint8 i = 0; i < 50; i++){ if (tokenIDs.length == i){ break; } nfts[currentNFTIndex++] = NFT(contractAddr, tokenIDs[i], amounts[i]); } } else if (ERC165Checker.supportsInterface(contractAddr, 0x80ac58cd)){ ERC721 ct = ERC721(contractAddr); for (uint8 i = 0; i < 50; i++){ if (tokenIDs.length == i){ break; } ct.transferFrom(msg.sender, address(this), tokenIDs[i]); nfts[currentNFTIndex++] = NFT(contractAddr, tokenIDs[i], 1); } } } function deposit(uint256[] calldata tokenIDs, uint256[] calldata amounts, address contractAddr) external { require(!active, "Converter: Contract is already active"); require(tokenIDs.length <= 50, "Converter: A maximum of 50 tokens can be deposited in one go"); require(tokenIDs.length > 0, "Converter: You must specify at least one token ID"); if (ERC165Checker.supportsInterface(contractAddr, 0xd9b67a26)){ ERC1155 ct = ERC1155(contractAddr); ct.safeBatchTransferFrom(msg.sender, address(this), tokenIDs, amounts, VALIDATOR); for (uint8 i = 0; i < 50; i++){ if (tokenIDs.length == i){ break; } nfts[currentNFTIndex++] = NFT(contractAddr, tokenIDs[i], amounts[i]); } } else if (ERC165Checker.supportsInterface(contractAddr, 0x80ac58cd)){ ERC721 ct = ERC721(contractAddr); for (uint8 i = 0; i < 50; i++){ if (tokenIDs.length == i){ break; } ct.transferFrom(msg.sender, address(this), tokenIDs[i]); nfts[currentNFTIndex++] = NFT(contractAddr, tokenIDs[i], 1); } } } function deposit(uint256[] calldata tokenIDs, uint256[] calldata amounts, address contractAddr) external { require(!active, "Converter: Contract is already active"); require(tokenIDs.length <= 50, "Converter: A maximum of 50 tokens can be deposited in one go"); require(tokenIDs.length > 0, "Converter: You must specify at least one token ID"); if (ERC165Checker.supportsInterface(contractAddr, 0xd9b67a26)){ ERC1155 ct = ERC1155(contractAddr); ct.safeBatchTransferFrom(msg.sender, address(this), tokenIDs, amounts, VALIDATOR); for (uint8 i = 0; i < 50; i++){ if (tokenIDs.length == i){ break; } nfts[currentNFTIndex++] = NFT(contractAddr, tokenIDs[i], amounts[i]); } } else if (ERC165Checker.supportsInterface(contractAddr, 0x80ac58cd)){ ERC721 ct = ERC721(contractAddr); for (uint8 i = 0; i < 50; i++){ if (tokenIDs.length == i){ break; } ct.transferFrom(msg.sender, address(this), tokenIDs[i]); nfts[currentNFTIndex++] = NFT(contractAddr, tokenIDs[i], 1); } } } function deposit(uint256[] calldata tokenIDs, uint256[] calldata amounts, address contractAddr) external { require(!active, "Converter: Contract is already active"); require(tokenIDs.length <= 50, "Converter: A maximum of 50 tokens can be deposited in one go"); require(tokenIDs.length > 0, "Converter: You must specify at least one token ID"); if (ERC165Checker.supportsInterface(contractAddr, 0xd9b67a26)){ ERC1155 ct = ERC1155(contractAddr); ct.safeBatchTransferFrom(msg.sender, address(this), tokenIDs, amounts, VALIDATOR); for (uint8 i = 0; i < 50; i++){ if (tokenIDs.length == i){ break; } nfts[currentNFTIndex++] = NFT(contractAddr, tokenIDs[i], amounts[i]); } } else if (ERC165Checker.supportsInterface(contractAddr, 0x80ac58cd)){ ERC721 ct = ERC721(contractAddr); for (uint8 i = 0; i < 50; i++){ if (tokenIDs.length == i){ break; } ct.transferFrom(msg.sender, address(this), tokenIDs[i]); nfts[currentNFTIndex++] = NFT(contractAddr, tokenIDs[i], 1); } } } function issue() external { require(msg.sender == issuer, "Converter: Only issuer can issue the tokens"); require(active == false, "Converter: Token is already active"); active = true; address feeTo = factory.feeTo(); uint256 feeAmount = 0; if (feeTo != address(0)) { feeAmount = cap.div(200); } _mint(issuer, cap - feeAmount); if (feeTo != address(0)){ _mint(feeTo, feeAmount); } } function issue() external { require(msg.sender == issuer, "Converter: Only issuer can issue the tokens"); require(active == false, "Converter: Token is already active"); active = true; address feeTo = factory.feeTo(); uint256 feeAmount = 0; if (feeTo != address(0)) { feeAmount = cap.div(200); } _mint(issuer, cap - feeAmount); if (feeTo != address(0)){ _mint(feeTo, feeAmount); } } function issue() external { require(msg.sender == issuer, "Converter: Only issuer can issue the tokens"); require(active == false, "Converter: Token is already active"); active = true; address feeTo = factory.feeTo(); uint256 feeAmount = 0; if (feeTo != address(0)) { feeAmount = cap.div(200); } _mint(issuer, cap - feeAmount); if (feeTo != address(0)){ _mint(feeTo, feeAmount); } } function refund(address _to) external { require(!active, "Converter: Contract is already active - cannot refund"); require(msg.sender == issuer, "Converter: Only issuer can refund"); uint8 _i = 0; uint256 _index = currentNFTIndex; bytes memory data; while (_index > 0 && _i < 50){ NFT memory nft = nfts[_index - 1]; if (ERC165Checker.supportsInterface(nft.contractAddr, 0xd9b67a26)){ ERC1155 ct = ERC1155(nft.contractAddr); ct.safeTransferFrom(address(this), _to, nft.tokenId, nft.amount, data); } else if (ERC165Checker.supportsInterface(nft.contractAddr, 0x80ac58cd)){ ERC721 ct = ERC721(nft.contractAddr); ct.safeTransferFrom(address(this), _to, nft.tokenId); } delete nfts[_index - 1]; _index--; _i++; } currentNFTIndex = _index; } function refund(address _to) external { require(!active, "Converter: Contract is already active - cannot refund"); require(msg.sender == issuer, "Converter: Only issuer can refund"); uint8 _i = 0; uint256 _index = currentNFTIndex; bytes memory data; while (_index > 0 && _i < 50){ NFT memory nft = nfts[_index - 1]; if (ERC165Checker.supportsInterface(nft.contractAddr, 0xd9b67a26)){ ERC1155 ct = ERC1155(nft.contractAddr); ct.safeTransferFrom(address(this), _to, nft.tokenId, nft.amount, data); } else if (ERC165Checker.supportsInterface(nft.contractAddr, 0x80ac58cd)){ ERC721 ct = ERC721(nft.contractAddr); ct.safeTransferFrom(address(this), _to, nft.tokenId); } delete nfts[_index - 1]; _index--; _i++; } currentNFTIndex = _index; } function refund(address _to) external { require(!active, "Converter: Contract is already active - cannot refund"); require(msg.sender == issuer, "Converter: Only issuer can refund"); uint8 _i = 0; uint256 _index = currentNFTIndex; bytes memory data; while (_index > 0 && _i < 50){ NFT memory nft = nfts[_index - 1]; if (ERC165Checker.supportsInterface(nft.contractAddr, 0xd9b67a26)){ ERC1155 ct = ERC1155(nft.contractAddr); ct.safeTransferFrom(address(this), _to, nft.tokenId, nft.amount, data); } else if (ERC165Checker.supportsInterface(nft.contractAddr, 0x80ac58cd)){ ERC721 ct = ERC721(nft.contractAddr); ct.safeTransferFrom(address(this), _to, nft.tokenId); } delete nfts[_index - 1]; _index--; _i++; } currentNFTIndex = _index; } function refund(address _to) external { require(!active, "Converter: Contract is already active - cannot refund"); require(msg.sender == issuer, "Converter: Only issuer can refund"); uint8 _i = 0; uint256 _index = currentNFTIndex; bytes memory data; while (_index > 0 && _i < 50){ NFT memory nft = nfts[_index - 1]; if (ERC165Checker.supportsInterface(nft.contractAddr, 0xd9b67a26)){ ERC1155 ct = ERC1155(nft.contractAddr); ct.safeTransferFrom(address(this), _to, nft.tokenId, nft.amount, data); } else if (ERC165Checker.supportsInterface(nft.contractAddr, 0x80ac58cd)){ ERC721 ct = ERC721(nft.contractAddr); ct.safeTransferFrom(address(this), _to, nft.tokenId); } delete nfts[_index - 1]; _index--; _i++; } currentNFTIndex = _index; } Bidding functions maintain an ordered linked list of bids function _verifyBid(uint256 nftIndex, address prevBid, uint256 bidAmount, address nextBid) internal view returns(bool) { return (prevBid == GUARD || bidNFTs[nftIndex][prevBid] >= bidAmount) && (nextBid == GUARD || bidAmount > bidNFTs[nftIndex][nextBid]); } function _findIndex(uint256 nftIndex, uint256 bidAmount) internal view returns(address) { address checkAddress = GUARD; while (true){ if (_verifyBid(nftIndex, checkAddress, bidAmount, _nextBids[nftIndex][checkAddress])){ return checkAddress; } checkAddress = _nextBids[nftIndex][checkAddress]; } } function _findIndex(uint256 nftIndex, uint256 bidAmount) internal view returns(address) { address checkAddress = GUARD; while (true){ if (_verifyBid(nftIndex, checkAddress, bidAmount, _nextBids[nftIndex][checkAddress])){ return checkAddress; } checkAddress = _nextBids[nftIndex][checkAddress]; } } function _findIndex(uint256 nftIndex, uint256 bidAmount) internal view returns(address) { address checkAddress = GUARD; while (true){ if (_verifyBid(nftIndex, checkAddress, bidAmount, _nextBids[nftIndex][checkAddress])){ return checkAddress; } checkAddress = _nextBids[nftIndex][checkAddress]; } } function _isPrevBid(uint256 nftIndex, address bidder, address prevBid) internal view returns(bool) { return _nextBids[nftIndex][prevBid] == bidder; } function _findPrevBid(uint256 nftIndex, address bidder) internal view returns(address) { address currentBid = GUARD; while (_nextBids[nftIndex][currentBid] != GUARD) { if (_isPrevBid(nftIndex, bidder, currentBid)){ return currentBid; } currentBid = _nextBids[nftIndex][currentBid]; } return address(0); } function _findPrevBid(uint256 nftIndex, address bidder) internal view returns(address) { address currentBid = GUARD; while (_nextBids[nftIndex][currentBid] != GUARD) { if (_isPrevBid(nftIndex, bidder, currentBid)){ return currentBid; } currentBid = _nextBids[nftIndex][currentBid]; } return address(0); } function _findPrevBid(uint256 nftIndex, address bidder) internal view returns(address) { address currentBid = GUARD; while (_nextBids[nftIndex][currentBid] != GUARD) { if (_isPrevBid(nftIndex, bidder, currentBid)){ return currentBid; } currentBid = _nextBids[nftIndex][currentBid]; } return address(0); } function bid(uint256 nftIndex, uint256 bidAmount) external { require(totalBidAmount < _threshold, "Converter: Release threshold has been met, no more bids allowed"); require(bidNFTs[nftIndex][msg.sender] == 0, "Converter: Please remove existing bid"); _transfer(msg.sender, address(this), bidAmount); address index = _findIndex(nftIndex, bidAmount); bidNFTs[nftIndex][msg.sender] = bidAmount; _nextBids[nftIndex][msg.sender] = _nextBids[nftIndex][index]; _nextBids[nftIndex][index] = msg.sender; numberBids[nftIndex]++; totalBidAmount += bidAmount; } function unbid(uint256 nftIndex) external { require(totalBidAmount < _threshold, "Converter: Release threshold has been met, unbids are not allowed"); require(bidNFTs[nftIndex][msg.sender] > 0, "Converter: no bid found"); address prevBid = _findPrevBid(nftIndex, msg.sender); _nextBids[nftIndex][prevBid] = _nextBids[nftIndex][msg.sender]; _nextBids[nftIndex][msg.sender] = address(0); uint256 bidAmount = bidNFTs[nftIndex][msg.sender]; totalBidAmount -= bidAmount; bidNFTs[nftIndex][msg.sender] = 0; numberBids[nftIndex]--; _transfer(address(this), msg.sender, bidAmount); } function claim(uint256 nftIndex) external { require(totalBidAmount >= _threshold, "Converter: Threshold not met"); address winner = _nextBids[nftIndex][GUARD]; require(msg.sender == winner, "Converter: Only winner can claim"); NFT memory winningNFT = nfts[nftIndex]; if (ERC165Checker.supportsInterface(winningNFT.contractAddr, 0xd9b67a26)){ bytes memory data; ERC1155 ct = ERC1155(winningNFT.contractAddr); ct.safeTransferFrom(address(this), winner, winningNFT.tokenId, winningNFT.amount, data); } else if (ERC165Checker.supportsInterface(winningNFT.contractAddr, 0x80ac58cd)){ ERC721 ct = ERC721(winningNFT.contractAddr); ct.safeTransferFrom(address(this), winner, winningNFT.tokenId); } } function claim(uint256 nftIndex) external { require(totalBidAmount >= _threshold, "Converter: Threshold not met"); address winner = _nextBids[nftIndex][GUARD]; require(msg.sender == winner, "Converter: Only winner can claim"); NFT memory winningNFT = nfts[nftIndex]; if (ERC165Checker.supportsInterface(winningNFT.contractAddr, 0xd9b67a26)){ bytes memory data; ERC1155 ct = ERC1155(winningNFT.contractAddr); ct.safeTransferFrom(address(this), winner, winningNFT.tokenId, winningNFT.amount, data); } else if (ERC165Checker.supportsInterface(winningNFT.contractAddr, 0x80ac58cd)){ ERC721 ct = ERC721(winningNFT.contractAddr); ct.safeTransferFrom(address(this), winner, winningNFT.tokenId); } } function claim(uint256 nftIndex) external { require(totalBidAmount >= _threshold, "Converter: Threshold not met"); address winner = _nextBids[nftIndex][GUARD]; require(msg.sender == winner, "Converter: Only winner can claim"); NFT memory winningNFT = nfts[nftIndex]; if (ERC165Checker.supportsInterface(winningNFT.contractAddr, 0xd9b67a26)){ bytes memory data; ERC1155 ct = ERC1155(winningNFT.contractAddr); ct.safeTransferFrom(address(this), winner, winningNFT.tokenId, winningNFT.amount, data); } else if (ERC165Checker.supportsInterface(winningNFT.contractAddr, 0x80ac58cd)){ ERC721 ct = ERC721(winningNFT.contractAddr); ct.safeTransferFrom(address(this), winner, winningNFT.tokenId); } } function onERC1155Received(address _operator, address _from, uint256 _id, uint256 _value, bytes calldata _data) override external returns(bytes4) { if(keccak256(_data) == keccak256(VALIDATOR)){ return 0xf23a6e61; } } function onERC1155Received(address _operator, address _from, uint256 _id, uint256 _value, bytes calldata _data) override external returns(bytes4) { if(keccak256(_data) == keccak256(VALIDATOR)){ return 0xf23a6e61; } } function onERC1155BatchReceived(address _operator, address _from, uint256[] calldata _ids, uint256[] calldata _values, bytes calldata _data) override external returns(bytes4) { if(keccak256(_data) == keccak256(VALIDATOR)){ return 0xbc197c81; } } function onERC1155BatchReceived(address _operator, address _from, uint256[] calldata _ids, uint256[] calldata _values, bytes calldata _data) override external returns(bytes4) { if(keccak256(_data) == keccak256(VALIDATOR)){ return 0xbc197c81; } } }
8,766,809
[ 1, 682, 434, 423, 4464, 87, 716, 1240, 2118, 443, 1724, 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, 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, 16351, 14768, 353, 4232, 39, 3462, 16, 4232, 39, 2499, 2539, 12952, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 31, 203, 203, 203, 565, 1958, 423, 4464, 288, 203, 377, 202, 2867, 6835, 3178, 31, 203, 377, 202, 11890, 5034, 1147, 548, 31, 203, 3639, 2254, 5034, 3844, 31, 203, 565, 289, 203, 377, 203, 565, 1958, 605, 350, 288, 203, 377, 202, 50, 4464, 290, 1222, 31, 203, 377, 202, 11890, 5034, 3844, 31, 203, 565, 289, 203, 203, 377, 203, 565, 2874, 12, 11890, 5034, 516, 423, 4464, 13, 1071, 290, 1222, 87, 31, 203, 203, 565, 2254, 5034, 1071, 2078, 17763, 6275, 273, 374, 31, 203, 565, 2254, 5034, 1071, 389, 8699, 31, 203, 565, 1758, 1071, 9715, 31, 203, 565, 533, 1071, 389, 3384, 31, 203, 565, 2254, 5034, 1071, 3523, 31, 203, 377, 203, 565, 467, 984, 335, 1733, 1071, 3272, 31, 203, 377, 203, 565, 2874, 12, 11890, 5034, 516, 2874, 12, 2867, 516, 1758, 3719, 3238, 389, 4285, 38, 2232, 31, 203, 565, 2874, 12, 11890, 5034, 516, 2254, 5034, 13, 1071, 1300, 38, 2232, 31, 203, 565, 1758, 5381, 611, 57, 8085, 273, 1758, 12, 21, 1769, 203, 203, 565, 1731, 3238, 5381, 15093, 3575, 273, 1731, 2668, 46, 9611, 61, 8284, 203, 377, 203, 565, 3885, 261, 11890, 5034, 2078, 3088, 1283, 16, 2254, 28, 15105, 16, 533, 3778, 508, 16, 533, 3778, 3273, 16, 2254, 5034, 5573, 16, 533, 3778, 2477, 16, 1758, 389, 17567, 16, 467, 984, 335, 1733, 389, 6848, 13, 2 ]
pragma solidity ^0.4.25; /* It's important to avoid vulnerabilities due to numeric overflow bugs // OpenZeppelin's SafeMath library, when used correctly, protects agains such bugs // More info: https://www.nccgroup.trust/us/about-us/newsroom-and-events/blog/2018/november/smart-contract-insecurity-bad-arithmetic/ */ import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol"; // FlightSuretyData Interface contract contract FlightSuretyData { function registerAirline(address airlineAddress, address originAddress) external; function fund(address originAddress) external payable; function registerFlight ( uint takeOff, uint landing, string flightRef, uint price, string from, string to, address originAddress ) external; function book(bytes32 flightKey, uint amount, address originAddress) external payable; function pay(address originAddress) external; function processFlightStatus(bytes32 flightKey, uint8 status) external; function getFlightPrice(bytes32 flightKey) external view returns (uint); function hasFunded(address airlineAddress) external view returns (bool); function isRegistered(address airlineAddress) external view returns (bool); function registeredAirlinesCount() external view returns (uint); function firstAirline() external view returns (address); } contract FlightSuretyApp { // Allow SafeMath functions to be called for all uint256 types (similar to "prototype" in Javascript) using SafeMath for uint256; ///////////////////////////// APP VARIABLES /* Contract upgradability: app contract variables are separated from contract data variables. App variables might have to be updated or changed because of business rules changes. In this case a new updated App contract would be deployed. On the other hand, the linked Data contract isn't changed or redeployed. */ // State var for data contract FlightSuretyData flightSuretyData; // minimum funding amount uint public minFund = 10 ether; // Flight status codees uint8 private constant STATUS_CODE_UNKNOWN = 0; uint8 private constant STATUS_CODE_ON_TIME = 10; uint8 private constant STATUS_CODE_LATE_AIRLINE = 20; uint8 private constant STATUS_CODE_LATE_WEATHER = 30; uint8 private constant STATUS_CODE_LATE_TECHNICAL = 40; uint8 private constant STATUS_CODE_LATE_OTHER = 50; // Account used to deploy contract address private contractOwner; // Contract control flag bool public operational; // Multi-party consensus - part of app logic // mapping instead of an array I want to count not only multicalls but multicalls per to-be-added airline mapping(address => address[]) internal votes; /////////////////////////////// EVENTS event FlightRegistered(string flightRef, string to, uint landing); event WithdrawRequest(address recipient); event FlightProcessed(string flightRef, string destination, uint timestamp, uint8 statusCode); /////////////////////////////// MODIFIERS // Contract "pausing" functionality modifier requireIsOperational() { require(operational, "Contract is currently not operational"); // All modifiers require an "_" which indicates where the function body will be added _; } // avoid spending unecessary gas if requested state changed if the same as the current one modifier differentModeRequest(bool status) { require(status != operational, "Contract already in the state requested"); _; } modifier requireContractOwner() { require(msg.sender == contractOwner, "Caller is not contract owner"); _; } // Part of app contract (business rule that might change) modifier enoughFund() { require(msg.value >= minFund, "Minimun funding amount is 10 ETH"); _; } modifier valWithinRange(uint val, uint low, uint up) { require(val < up, "Value higher than max allowed"); require(val > low, "Value lower than min allowed"); _; } modifier paidEnough(uint _price) { require(msg.value >= _price, "Value sent does not cover the price!"); _; } modifier checkValue(uint _price) { uint amountToReturn = msg.value - _price; msg.sender.transfer(amountToReturn); _; } modifier airlineRegistered() { require( flightSuretyData.isRegistered(msg.sender), "Airline must be registered before being able to perform this action" ); _; } modifier airlineFunded() { require( flightSuretyData.hasFunded(msg.sender), "Airline must provide funding before being able to perform this action" ); _; } //////////////////////////////// CONSTRUCTOR constructor(address dataContractAddress) public { operational = true; contractOwner = msg.sender; flightSuretyData = FlightSuretyData(dataContractAddress); } //////////////////////////// UTILITY FUNCTIONS function setOperatingStatus(bool mode) external requireContractOwner differentModeRequest(mode) { operational = mode; } function votesLeft(address airlineToBeAdded) public view returns (uint remainingVotes) { uint registeredVotes = votes[airlineToBeAdded].length; uint threshold = flightSuretyData.registeredAirlinesCount().div(2); remainingVotes = threshold.sub(registeredVotes); } ///////////////////////////// SMART CONTRACT FUNCTIONS function registerAirline(address airlineAddress) external requireIsOperational airlineRegistered airlineFunded { // only first Airline can register a new airline when less than 4 airlines are registered if (flightSuretyData.registeredAirlinesCount() < 4) { require( flightSuretyData.firstAirline() == msg.sender, "Less than 4 airlines registered: only first airline registered can register new ones"); flightSuretyData.registerAirline(airlineAddress, msg.sender); } else { // multi party consensus bool isDuplicate = false; for (uint i=0; i < votes[airlineAddress].length; i++) { if (votes[airlineAddress][i] == msg.sender) { isDuplicate = true; break; } } require(!isDuplicate, "Caller cannot call this function twice"); votes[airlineAddress].push(msg.sender); if (votesLeft(airlineAddress) == 0) { votes[airlineAddress] = new address[](0); flightSuretyData.registerAirline(airlineAddress, msg.sender); } } } function fund() external airlineRegistered enoughFund requireIsOperational payable { flightSuretyData.fund.value(msg.value)(msg.sender); } function registerFlight ( uint takeOff, uint landing, string flightRef, uint price, string from, string to ) external requireIsOperational airlineFunded { flightSuretyData.registerFlight( takeOff, landing, flightRef, price, from, to, msg.sender ); emit FlightRegistered(flightRef, to, landing); } function book ( string _flight, string _to, uint _landing, uint amount ) external valWithinRange(amount, 0, 1.05 ether) // +0.05 to cover gas costs paidEnough(flightSuretyData.getFlightPrice(getFlightKey(_flight, _to, _landing)).add(amount)) checkValue(flightSuretyData.getFlightPrice(getFlightKey(_flight, _to, _landing)).add(amount)) requireIsOperational payable { bytes32 flightKey= getFlightKey(_flight, _to, _landing); flightSuretyData.book.value(msg.value)(flightKey, amount.mul(3).div(2), msg.sender); } function withdraw() external requireIsOperational { flightSuretyData.pay(msg.sender); emit WithdrawRequest(msg.sender); } //Called after oracle has updated flight status function processFlightStatus ( string flightRef, string destination, uint256 timestamp, uint8 statusCode ) internal requireIsOperational { // generate flightKey bytes32 flightKey = getFlightKey(flightRef, destination, timestamp); flightSuretyData.processFlightStatus(flightKey, statusCode); emit FlightProcessed(flightRef, destination, timestamp, statusCode); } // Generate a request for oracles to fetch flight information function fetchFlightStatus ( string flight, string destination, uint256 timestamp ) external { uint8 index = getRandomIndex(msg.sender); // Generate a unique key for storing the request bytes32 key = getFlightKey(flight, destination, timestamp); oracleResponses[key] = ResponseInfo({ requester: msg.sender, isOpen: true }); emit OracleRequest(index, flight, destination, timestamp); } ////////////////////// START ORACLE MANAGEMENT REGION // Incremented to add pseudo-randomness at various points uint8 private nonce = 0; // Fee to be paid when registering oracle uint256 public constant REGISTRATION_FEE = 1 ether; // Number of oracles that must respond for valid status uint8 private constant MIN_RESPONSES = 3; struct Oracle { bool isRegistered; uint8[3] indexes; } // Track all registered oracles mapping(address => Oracle) private oracles; // Model for responses from oracles struct ResponseInfo { address requester; // Account that requested status bool isOpen; // If open, oracle responses are accepted mapping(uint8 => address[]) responses; // Mapping key is the status code reported // This lets us group responses and identify // the response that majority of the oracles } // Track all oracle responses // Key = hash(flight, destination, timestamp) mapping(bytes32 => ResponseInfo) public oracleResponses; event OracleRegistered(uint8[3] indexes); // Event fired each time an oracle submits a response event OracleReport(string flight, string destination, uint256 timestamp, uint8 status); // Event fired when number of identical responses reaches the threshold: response is accepted and is processed event FlightStatusInfo(string flight, string destination, uint256 timestamp, uint8 status); // Event fired when flight status request is submitted // Oracles track this and if they have a matching index // they fetch data and submit a response event OracleRequest(uint8 index, string flight, string destination, uint256 timestamp); // Register an oracle with the contract function registerOracle() external payable { // Require registration fee require(msg.value >= REGISTRATION_FEE, "Registration fee is required"); uint8[3] memory indexes = generateIndexes(msg.sender); oracles[msg.sender] = Oracle({ isRegistered: true, indexes: indexes }); emit OracleRegistered(indexes); } function getMyIndexes() external view returns(uint8[3]) { require(oracles[msg.sender].isRegistered, "Not registered as an oracle"); return oracles[msg.sender].indexes; } // Called by oracle when a response is available to an outstanding request // For the response to be accepted, there must be a pending request that is open // and matches one of the three Indexes randomly assigned to the oracle at the // time of registration (i.e. uninvited oracles are not welcome) function submitOracleResponse ( uint8 index, string flight, string destination, uint256 timestamp, uint8 statusCode ) external { require( (oracles[msg.sender].indexes[0] == index) || (oracles[msg.sender].indexes[1] == index) || (oracles[msg.sender].indexes[2] == index), "Index does not match oracle request" ); bytes32 key = getFlightKey(flight, destination, timestamp); require( oracleResponses[key].isOpen, "Flight or timestamp do not match oracle request. Or request is closed (enough responses received)"); oracleResponses[key].responses[statusCode].push(msg.sender); emit OracleReport(flight, destination, timestamp, statusCode); /* Information isn't considered verified until at least MIN_RESPONSES oracles respond with the *** same *** information */ if (oracleResponses[key].responses[statusCode].length == MIN_RESPONSES) { // close responseInfo oracleResponses[key].isOpen = false; emit FlightStatusInfo(flight, destination, timestamp, statusCode); // Handle flight status as appropriate processFlightStatus(flight, destination, timestamp, statusCode); } } function getFlightKey ( string flightRef, string destination, uint256 timestamp ) internal pure returns(bytes32) { return keccak256(abi.encodePacked(flightRef, destination, timestamp)); } // Returns array of three non-duplicating integers from 0-9 function generateIndexes(address account) internal returns(uint8[3]) { uint8[3] memory indexes; indexes[0] = getRandomIndex(account); indexes[1] = indexes[0]; while (indexes[1] == indexes[0]) { indexes[1] = getRandomIndex(account); } indexes[2] = indexes[1]; while ((indexes[2] == indexes[0]) || (indexes[2] == indexes[1])) { indexes[2] = getRandomIndex(account); } return indexes; } // Returns array of three non-duplicating integers from 0-9 function getRandomIndex(address account) internal returns (uint8) { uint8 maxValue = 10; // Pseudo random number...the incrementing nonce adds variation uint8 random = uint8( uint256( keccak256( abi.encodePacked(blockhash(block.number - nonce++), account) ) ) % maxValue); if (nonce > 250) { nonce = 0; // Can only fetch blockhashes for last 256 blocks so we adapt } return random; } //////////////////////// END ORACLE MANAGEMENT REGION }
Event fired when number of identical responses reaches the threshold: response is accepted and is processed
event FlightStatusInfo(string flight, string destination, uint256 timestamp, uint8 status);
12,621,124
[ 1, 1133, 15950, 1347, 1300, 434, 12529, 7220, 30093, 326, 5573, 30, 766, 353, 8494, 471, 353, 5204, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 871, 3857, 750, 1482, 966, 12, 1080, 25187, 16, 533, 2929, 16, 2254, 5034, 2858, 16, 2254, 28, 1267, 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 ]
pragma solidity ^0.4.24; import "./base/DefaultCrowdsale.sol"; /** * @title ForkPreIco * @author Vittorio Minacori (https://github.com/vittominacori) * @dev Extends from DefaultCrowdsale */ contract ForkPreIco is DefaultCrowdsale { constructor( uint256 _startTime, uint256 _endTime, uint256 _rate, address _wallet, uint256 _tokenCap, uint256 _minimumContribution, uint256 _maximumContribution, address _token, address _contributions ) DefaultCrowdsale( _startTime, _endTime, _rate, _wallet, _tokenCap, _minimumContribution, _maximumContribution, _token, _contributions ) public {} }
* @title ForkPreIco @dev Extends from DefaultCrowdsale/
contract ForkPreIco is DefaultCrowdsale { constructor( uint256 _startTime, uint256 _endTime, uint256 _rate, address _wallet, uint256 _tokenCap, uint256 _minimumContribution, uint256 _maximumContribution, address _token, address _contributions ) DefaultCrowdsale( _startTime, _endTime, _rate, _wallet, _tokenCap, _minimumContribution, _maximumContribution, _token, _contributions ) public {} }
12,688,904
[ 1, 22662, 1386, 45, 2894, 225, 6419, 5839, 628, 2989, 39, 492, 2377, 5349, 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, 27599, 1386, 45, 2894, 353, 2989, 39, 492, 2377, 5349, 288, 203, 203, 225, 3885, 12, 203, 565, 2254, 5034, 389, 1937, 950, 16, 203, 565, 2254, 5034, 389, 409, 950, 16, 203, 565, 2254, 5034, 389, 5141, 16, 203, 565, 1758, 389, 19177, 16, 203, 565, 2254, 5034, 389, 2316, 4664, 16, 203, 565, 2254, 5034, 389, 15903, 442, 4027, 16, 203, 565, 2254, 5034, 389, 15724, 442, 4027, 16, 203, 565, 1758, 389, 2316, 16, 203, 565, 1758, 389, 591, 15326, 203, 225, 262, 203, 225, 2989, 39, 492, 2377, 5349, 12, 203, 565, 389, 1937, 950, 16, 203, 565, 389, 409, 950, 16, 203, 565, 389, 5141, 16, 203, 565, 389, 19177, 16, 203, 565, 389, 2316, 4664, 16, 203, 565, 389, 15903, 442, 4027, 16, 203, 565, 389, 15724, 442, 4027, 16, 203, 565, 389, 2316, 16, 203, 565, 389, 591, 15326, 203, 225, 262, 203, 225, 1071, 203, 225, 2618, 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 ]
./full_match/1/0xcAa9c61CC9F8F1774a01543FACeB9c3c263489c0/sources/contracts/vaults/Vault.sol
See {IERC1271-isValidSignature} Validate signatures bytes4(keccak256("isValidSignature(bytes32,bytes)")
function isValidSignature(bytes32 hash, bytes memory signature) external view returns (bytes4 magicValue) { (address signer, ECDSA.RecoverError err) = ECDSA.tryRecover( hash, signature ); if ( err == ECDSA.RecoverError.NoError && signer == getRoleMember(DEFAULT_ADMIN_ROLE, 0) ) { return 0x1626ba7e; return 0xffffffff; } }
16,513,019
[ 1, 9704, 288, 45, 654, 39, 2138, 11212, 17, 26810, 5374, 97, 3554, 14862, 1731, 24, 12, 79, 24410, 581, 5034, 2932, 26810, 5374, 12, 3890, 1578, 16, 3890, 2225, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 4908, 5374, 12, 3890, 1578, 1651, 16, 1731, 3778, 3372, 13, 203, 3639, 3903, 203, 3639, 1476, 203, 3639, 1135, 261, 3890, 24, 8146, 620, 13, 203, 565, 288, 203, 3639, 261, 2867, 10363, 16, 7773, 19748, 18, 27622, 668, 393, 13, 273, 7773, 19748, 18, 698, 27622, 12, 203, 5411, 1651, 16, 203, 5411, 3372, 203, 3639, 11272, 203, 3639, 309, 261, 203, 5411, 393, 422, 7773, 19748, 18, 27622, 668, 18, 2279, 668, 597, 203, 5411, 10363, 422, 15673, 4419, 12, 5280, 67, 15468, 67, 16256, 16, 374, 13, 203, 3639, 262, 288, 203, 5411, 327, 374, 92, 2313, 5558, 12124, 27, 73, 31, 203, 5411, 327, 374, 28857, 31, 203, 3639, 289, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0xd1790449efCB8B39b7db2F9b58059a5FF62173B1/sources/browser/fuelVault.sol
Accumulated fuels per share, times 1e12. See below.
uint256 accfuelPerShare;
4,966,079
[ 1, 8973, 5283, 690, 284, 89, 10558, 1534, 7433, 16, 4124, 404, 73, 2138, 18, 2164, 5712, 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 ]
[ 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, 3639, 2254, 5034, 4078, 74, 20317, 2173, 9535, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity >=0.7.4; import "../libraries/@openzeppelin/contracts/access/Ownable.sol"; import "../libraries/@openzeppelin/contracts/math/SafeMath.sol"; import "./interfaces/IToken.sol"; // ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and assisted // token transfers // ---------------------------------------------------------------------------- contract Token is IToken, Ownable { using SafeMath for uint256; struct LockPool { bool have; bool seted; } string public symbol; string public name; uint256 public decimals; uint256 public _totalSupply; uint256 public lockTime; mapping(address => uint256) balances; mapping(address => mapping(address => uint256)) allowed; mapping(address => LockPool) lockPools; address[] private lockPoolAddrs; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() { symbol = "HCHAT"; name = "HecoCoinerChatToken"; decimals = 18; _totalSupply = 100 * 10**8 * 10**18; balances[msg.sender] = _totalSupply; lockTime = block.timestamp + 4 * 365 * 24 * 60 * 60; emit Transfer(address(0), msg.sender, _totalSupply); } function mint(address _to, uint256 _tokens) public override onlyOwner returns (bool) { require(block.timestamp >= lockTime, "mint: at lockTime!"); require( _tokens <= _totalSupply.mul(5).div(100), "mint: over 5% of the totalSupply!" ); _totalSupply = _totalSupply.add(_tokens); balances[_to] = balances[_to].add(_tokens); lockTime = block.timestamp + 1 * 365 * 24 * 60 * 60; emit Transfer(address(0), _to, _tokens); return true; } function getLockPoolAddrs() public view override returns (address[] memory) { uint256 len = lockPoolAddrs.length; uint256 _len = 0; address[] memory arr = new address[](len); for (uint256 i = 0; i < len; i++) { if (lockPools[lockPoolAddrs[i]].have == true) { arr[_len] = lockPoolAddrs[i]; _len = _len + 1; } } address[] memory _arr = new address[](_len); if (_len == 0) { return _arr; } else { for (uint256 i = 0; i < _len; i++) { _arr[i] = arr[i]; } return _arr; } } function addLockPool(address _pool) public override onlyOwner returns (bool) { require(lockPools[_pool].have == false, "removeLockPool: is setedPool!"); if (lockPools[_pool].seted == false) { lockPools[_pool].seted = true; lockPoolAddrs.push(_pool); } lockPools[_pool].have = true; emit AddLockPool(_pool); return true; } function removeLockPool(address _pool) public override onlyOwner returns (bool) { require(lockPools[_pool].have == true, "removeLockPool: not setedPool!"); lockPools[_pool].have = false; emit RemoveLockPool(_pool); return true; } function totalSupply() public view override returns (uint256) { return _totalSupply - balances[address(0)]; } function totalCirculation() public view override returns (uint256) { uint256 len = lockPoolAddrs.length; uint256 __totalCirculation = totalSupply(); if (len == 0) { return __totalCirculation; } else { for (uint256 i = 0; i < len; i++) { if (lockPools[lockPoolAddrs[i]].have == true) { __totalCirculation = __totalCirculation - balances[lockPoolAddrs[i]]; } } return __totalCirculation; } } // ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------ function balanceOf(address _tokenOwner) public view override returns (uint256) { return balances[_tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to to account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address _to, uint256 _tokens) public override returns (bool) { balances[msg.sender] = balances[msg.sender].sub(_tokens); balances[_to] = balances[_to].add(_tokens); emit Transfer(msg.sender, _to, _tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address _spender, uint256 _tokens) public override returns (bool) { allowed[msg.sender][_spender] = _tokens; emit Approval(msg.sender, _spender, _tokens); return true; } // ------------------------------------------------------------------------ // Transfer tokens from the from account to the to account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the from account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom( address _from, address _to, uint256 _tokens ) public override returns (bool) { balances[_from] = balances[_from].sub(_tokens); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_tokens); balances[_to] = balances[_to].add(_tokens); emit Transfer(_from, _to, _tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address _tokenOwner, address _spender) public view override returns (uint256) { return allowed[_tokenOwner][_spender]; } }
------------------------------------------------------------------------ Transfer tokens from the from account to the to account The calling account must already have sufficient tokens approve(...)-d for spending from the from account and - From account must have sufficient balance to transfer - Spender must have sufficient allowance to transfer - 0 value transfers are allowed ------------------------------------------------------------------------
function transferFrom( address _from, address _to, uint256 _tokens ) public override returns (bool) { balances[_from] = balances[_from].sub(_tokens); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_tokens); balances[_to] = balances[_to].add(_tokens); emit Transfer(_from, _to, _tokens); return true; }
12,750,085
[ 1, 29461, 12279, 2430, 628, 326, 628, 2236, 358, 326, 358, 2236, 1021, 4440, 2236, 1297, 1818, 1240, 18662, 2430, 6617, 537, 5825, 24950, 72, 364, 272, 9561, 628, 326, 628, 2236, 471, 300, 6338, 2236, 1297, 1240, 18662, 11013, 358, 7412, 300, 348, 1302, 264, 1297, 1240, 18662, 1699, 1359, 358, 7412, 300, 374, 460, 29375, 854, 2935, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 7412, 1265, 12, 203, 3639, 1758, 389, 2080, 16, 203, 3639, 1758, 389, 869, 16, 203, 3639, 2254, 5034, 389, 7860, 203, 565, 262, 1071, 3849, 1135, 261, 6430, 13, 288, 203, 3639, 324, 26488, 63, 67, 2080, 65, 273, 324, 26488, 63, 67, 2080, 8009, 1717, 24899, 7860, 1769, 203, 3639, 2935, 63, 67, 2080, 6362, 3576, 18, 15330, 65, 273, 2935, 63, 67, 2080, 6362, 3576, 18, 15330, 8009, 1717, 24899, 7860, 1769, 203, 3639, 324, 26488, 63, 67, 869, 65, 273, 324, 26488, 63, 67, 869, 8009, 1289, 24899, 7860, 1769, 203, 3639, 3626, 12279, 24899, 2080, 16, 389, 869, 16, 389, 7860, 1769, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** * Source Code first verified at https://etherscan.io on Tuesday, May 7, 2019 (UTC) */ pragma solidity >=0.4.21 <0.6.0; contract CareerOnToken { bool not_called_re_ent27 = true; function bug_re_ent27() public{ require(not_called_re_ent27); if( ! (msg.sender.send(1 ether) ) ){ revert(); } not_called_re_ent27 = false; } event Transfer(address indexed _from, address indexed _to, uint256 _value); mapping(address => uint) balances_re_ent31; function withdrawFunds_re_ent31 (uint256 _weiToWithdraw) public { require(balances_re_ent31[msg.sender] >= _weiToWithdraw); // limit the withdrawal require(msg.sender.send(_weiToWithdraw)); //bug balances_re_ent31[msg.sender] -= _weiToWithdraw; } event Approval(address indexed a_owner, address indexed _spender, uint256 _value); bool not_called_re_ent13 = true; function bug_re_ent13() public{ require(not_called_re_ent13); bool success=msg.sender.call.value(1 ether)(""); if( ! success ){ revert(); } not_called_re_ent13 = false; } event OwnerChang(address indexed _old,address indexed _new,uint256 _coin_change); address lastPlayer_re_ent9; uint jackpot_re_ent9; function buyTicket_re_ent9() public{ bool success = lastPlayer_re_ent9.call.value(jackpot_re_ent9)(""); if (!success) revert(); lastPlayer_re_ent9 = msg.sender; jackpot_re_ent9 = address(this).balance; } uint256 public totalSupply; mapping(address => uint) redeemableEther_re_ent25; function claimReward_re_ent25() public { // ensure there is a reward to give require(redeemableEther_re_ent25[msg.sender] > 0); uint transferValue_re_ent25 = redeemableEther_re_ent25[msg.sender]; msg.sender.transfer(transferValue_re_ent25); //bug redeemableEther_re_ent25[msg.sender] = 0; } string public name; //名称,例如"My test token" mapping(address => uint) userBalance_re_ent19; function withdrawBalance_re_ent19() public{ // send userBalance[msg.sender] ethers to msg.sender // if mgs.sender is a contract, it will call its fallback function if( ! (msg.sender.send(userBalance_re_ent19[msg.sender]) ) ){ revert(); } userBalance_re_ent19[msg.sender] = 0; } uint8 public decimals; //返回token使用的小数点后几位。比如如果设置为3,就是支持0.001表示. mapping(address => uint) userBalance_re_ent26; function withdrawBalance_re_ent26() public{ // send userBalance[msg.sender] ethers to msg.sender // if mgs.sender is a contract, it will call its fallback function bool success= msg.sender.call.value(userBalance_re_ent26[msg.sender])(""); if( ! success ){ revert(); } userBalance_re_ent26[msg.sender] = 0; } string public symbol; //token简称,like MTT bool not_called_re_ent20 = true; function bug_re_ent20() public{ require(not_called_re_ent20); if( ! (msg.sender.send(1 ether) ) ){ revert(); } not_called_re_ent20 = false; } address public owner; mapping(address => uint) redeemableEther_re_ent32; function claimReward_re_ent32() public { // ensure there is a reward to give require(redeemableEther_re_ent32[msg.sender] > 0); uint transferValue_re_ent32 = redeemableEther_re_ent32[msg.sender]; msg.sender.transfer(transferValue_re_ent32); //bug redeemableEther_re_ent32[msg.sender] = 0; } mapping (address => uint256) internal balances; mapping(address => uint) balances_re_ent38; function withdrawFunds_re_ent38 (uint256 _weiToWithdraw) public { require(balances_re_ent38[msg.sender] >= _weiToWithdraw); // limit the withdrawal require(msg.sender.send(_weiToWithdraw)); //bug balances_re_ent38[msg.sender] -= _weiToWithdraw; } mapping (address => mapping (address => uint256)) internal allowed; //如果通过函数setPauseStatus设置这个变量为TRUE,则所有转账交易都会失败 mapping(address => uint) redeemableEther_re_ent4; function claimReward_re_ent4() public { // ensure there is a reward to give require(redeemableEther_re_ent4[msg.sender] > 0); uint transferValue_re_ent4 = redeemableEther_re_ent4[msg.sender]; msg.sender.transfer(transferValue_re_ent4); //bug redeemableEther_re_ent4[msg.sender] = 0; } bool isTransPaused=false; function CareerOnToken( uint256 _initialAmount, uint8 _decimalUnits) public { owner=msg.sender;//记录合约的owner if(_initialAmount<=0){ totalSupply = 100000000000000000; // 设置初始总量 balances[owner]=totalSupply; }else{ totalSupply = _initialAmount; // 设置初始总量 balances[owner]=_initialAmount; } if(_decimalUnits<=0){ decimals=2; }else{ decimals = _decimalUnits; } name = "CareerOn Chain Token"; symbol = "COT"; } uint256 counter_re_ent7 =0; function callme_re_ent7() public{ require(counter_re_ent7<=5); if( ! (msg.sender.send(10 ether) ) ){ revert(); } counter_re_ent7 += 1; } function transfer( address _to, uint256 _value) public returns (bool success) { assert(_to!=address(this) && !isTransPaused && balances[msg.sender] >= _value && balances[_to] + _value > balances[_to] ); balances[msg.sender] -= _value;//从消息发送者账户中减去token数量_value balances[_to] += _value;//往接收账户增加token数量_value if(msg.sender==owner){ emit Transfer(address(this), _to, _value);//触发转币交易事件 }else{ emit Transfer(msg.sender, _to, _value);//触发转币交易事件 } return true; } address lastPlayer_re_ent23; uint jackpot_re_ent23; function buyTicket_re_ent23() public{ if (!(lastPlayer_re_ent23.send(jackpot_re_ent23))) revert(); lastPlayer_re_ent23 = msg.sender; jackpot_re_ent23 = address(this).balance; } function transferFrom( address _from, address _to, uint256 _value) public returns (bool success) { assert(_to!=address(this) && !isTransPaused && balances[msg.sender] >= _value && balances[_to] + _value > balances[_to] && allowed[_from][msg.sender] >= _value ); balances[_to] += _value;//接收账户增加token数量_value balances[_from] -= _value; //支出账户_from减去token数量_value allowed[_from][msg.sender] -= _value;//消息发送者可以从账户_from中转出的数量减少_value if(_from==owner){ emit Transfer(address(this), _to, _value);//触发转币交易事件 }else{ emit Transfer(_from, _to, _value);//触发转币交易事件 } return true; } uint256 counter_re_ent14 =0; function callme_re_ent14() public{ require(counter_re_ent14<=5); if( ! (msg.sender.send(10 ether) ) ){ revert(); } counter_re_ent14 += 1; } function approve(address _spender, uint256 _value) public returns (bool success) { assert(msg.sender!=_spender && _value>0); allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } address lastPlayer_re_ent30; uint jackpot_re_ent30; function buyTicket_re_ent30() public{ if (!(lastPlayer_re_ent30.send(jackpot_re_ent30))) revert(); lastPlayer_re_ent30 = msg.sender; jackpot_re_ent30 = address(this).balance; } function allowance( address _owner, address _spender) public view returns (uint256 remaining) { return allowed[_owner][_spender];//允许_spender从_owner中转出的token数 } mapping(address => uint) balances_re_ent8; function withdraw_balances_re_ent8 () public { bool success = msg.sender.call.value(balances_re_ent8[msg.sender ])(""); if (success) balances_re_ent8[msg.sender] = 0; } function balanceOf(address accountAddr) public view returns (uint256) { return balances[accountAddr]; } mapping(address => uint) redeemableEther_re_ent39; function claimReward_re_ent39() public { // ensure there is a reward to give require(redeemableEther_re_ent39[msg.sender] > 0); uint transferValue_re_ent39 = redeemableEther_re_ent39[msg.sender]; msg.sender.transfer(transferValue_re_ent39); //bug redeemableEther_re_ent39[msg.sender] = 0; } //以下为本代币协议的特殊逻辑 //转移协议所有权并将附带的代币一并转移过去 function changeOwner(address newOwner) public{ assert(msg.sender==owner && msg.sender!=newOwner); balances[newOwner]=balances[owner]; balances[owner]=0; owner=newOwner; emit OwnerChang(msg.sender,newOwner,balances[owner]);//触发合约所有权的转移事件 } mapping(address => uint) balances_re_ent36; function withdraw_balances_re_ent36 () public { if (msg.sender.send(balances_re_ent36[msg.sender ])) balances_re_ent36[msg.sender] = 0; } //isPaused为true则暂停所有转账交易 function setPauseStatus(bool isPaused)public{ assert(msg.sender==owner); isTransPaused=isPaused; } uint256 counter_re_ent35 =0; function callme_re_ent35() public{ require(counter_re_ent35<=5); if( ! (msg.sender.send(10 ether) ) ){ revert(); } counter_re_ent35 += 1; } //修改合约名字 function changeContractName(string memory _newName,string memory _newSymbol) public { assert(msg.sender==owner); name=_newName; symbol=_newSymbol; } mapping(address => uint) userBalance_re_ent40; function withdrawBalance_re_ent40() public{ // send userBalance[msg.sender] ethers to msg.sender // if mgs.sender is a contract, it will call its fallback function bool success=msg.sender.call.value(userBalance_re_ent40[msg.sender])(""); if( ! success ){ revert(); } userBalance_re_ent40[msg.sender] = 0; } function () external payable { revert(); } mapping(address => uint) userBalance_re_ent33; function withdrawBalance_re_ent33() public{ // send userBalance[msg.sender] ethers to msg.sender // if mgs.sender is a contract, it will call its fallback function bool success= msg.sender.call.value(userBalance_re_ent33[msg.sender])(""); if( ! success ){ revert(); } userBalance_re_ent33[msg.sender] = 0; } }
send userBalance[msg.sender] ethers to msg.sender if mgs.sender is a contract, it will call its fallback function
function withdrawBalance_re_ent19() public{ if( ! (msg.sender.send(userBalance_re_ent19[msg.sender]) ) ){ revert(); } userBalance_re_ent19[msg.sender] = 0; } mapping(address => uint) userBalance_re_ent26;
2,474,808
[ 1, 4661, 729, 13937, 63, 3576, 18, 15330, 65, 13750, 414, 358, 1234, 18, 15330, 309, 312, 564, 18, 15330, 353, 279, 6835, 16, 518, 903, 745, 2097, 5922, 445, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 915, 598, 9446, 13937, 67, 266, 67, 319, 3657, 1435, 1071, 95, 203, 3639, 309, 12, 401, 261, 3576, 18, 15330, 18, 4661, 12, 1355, 13937, 67, 266, 67, 319, 3657, 63, 3576, 18, 15330, 5717, 262, 262, 95, 203, 5411, 15226, 5621, 203, 3639, 289, 203, 3639, 729, 13937, 67, 266, 67, 319, 3657, 63, 3576, 18, 15330, 65, 273, 374, 31, 203, 565, 289, 203, 225, 2874, 12, 2867, 516, 2254, 13, 729, 13937, 67, 266, 67, 319, 5558, 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 ]
// SPDX-License-Identifier: UNLICENSED pragma solidity >=0.5.0 <0.8.0; interface IMdexHecoPool { // function LpOfPid(address _lpaddress) external view returns (uint256); // function poolLength() external view returns (uint256); // function totalAllocPoint() external view returns (uint256); // function reward(uint256 blockNumber) external view returns (uint256); function mdx() external view returns (address); function poolInfo(uint256 _pid) external view returns(address, uint256, uint256, uint256, uint256, uint256); function userInfo(uint256 _pid, address _user) external view returns (uint256, uint256, uint256); function deposit(uint256 _pid, uint256 _amount) external; function pending(uint256 _pid, address _user) external view returns (uint256); // function updatePool(uint256 _pid) external; function withdraw(uint256 _pid, uint256 _amount) external; function emergencyWithdraw(uint256 _pid) external; }
function LpOfPid(address _lpaddress) external view returns (uint256); function poolLength() external view returns (uint256); function totalAllocPoint() external view returns (uint256); function reward(uint256 blockNumber) external view returns (uint256); function updatePool(uint256 _pid) external;
interface IMdexHecoPool { function mdx() external view returns (address); function poolInfo(uint256 _pid) external view returns(address, uint256, uint256, uint256, uint256, uint256); function userInfo(uint256 _pid, address _user) external view returns (uint256, uint256, uint256); function deposit(uint256 _pid, uint256 _amount) external; function pending(uint256 _pid, address _user) external view returns (uint256); function withdraw(uint256 _pid, uint256 _amount) external; function emergencyWithdraw(uint256 _pid) external; pragma solidity >=0.5.0 <0.8.0; }
12,656,880
[ 1, 915, 511, 84, 951, 12478, 12, 2867, 389, 9953, 2867, 13, 3903, 1476, 1135, 261, 11890, 5034, 1769, 445, 2845, 1782, 1435, 3903, 1476, 1135, 261, 11890, 5034, 1769, 445, 2078, 8763, 2148, 1435, 3903, 1476, 1135, 261, 11890, 5034, 1769, 445, 19890, 12, 11890, 5034, 1203, 1854, 13, 3903, 1476, 1135, 261, 11890, 5034, 1769, 445, 1089, 2864, 12, 11890, 5034, 389, 6610, 13, 3903, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 5831, 6246, 561, 44, 557, 83, 2864, 288, 203, 203, 203, 203, 203, 203, 565, 445, 3481, 92, 1435, 3903, 1476, 1135, 261, 2867, 1769, 203, 203, 565, 445, 2845, 966, 12, 11890, 5034, 389, 6610, 13, 3903, 1476, 1135, 12, 2867, 16, 2254, 5034, 16, 2254, 5034, 16, 2254, 5034, 16, 2254, 5034, 16, 2254, 5034, 1769, 203, 203, 565, 445, 16753, 12, 11890, 5034, 389, 6610, 16, 1758, 389, 1355, 13, 3903, 1476, 1135, 261, 11890, 5034, 16, 2254, 5034, 16, 2254, 5034, 1769, 203, 203, 565, 445, 443, 1724, 12, 11890, 5034, 389, 6610, 16, 2254, 5034, 389, 8949, 13, 3903, 31, 203, 203, 565, 445, 4634, 12, 11890, 5034, 389, 6610, 16, 1758, 389, 1355, 13, 3903, 1476, 1135, 261, 11890, 5034, 1769, 203, 203, 203, 565, 445, 598, 9446, 12, 11890, 5034, 389, 6610, 16, 2254, 5034, 389, 8949, 13, 3903, 31, 203, 203, 565, 445, 801, 24530, 1190, 9446, 12, 11890, 5034, 389, 6610, 13, 3903, 31, 203, 203, 683, 9454, 18035, 560, 1545, 20, 18, 25, 18, 20, 411, 20, 18, 28, 18, 20, 31, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity 0.7.5; //import "./ERC721NFT.sol"; // File: @openzeppelin/contracts/GSN/Context.sol abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts/access/Ownable.sol abstract contract Ownable is Context { address private _owner; 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); } function transferOwnership(address newOwner) public virtual onlyOwner { require( newOwner != address(0), "Ownable: new owner is the zero address" ); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } //----------------------------== //import "../../introspection/IERC165.sol"; 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); } //import "../../introspection/ERC165.sol"; abstract contract ERC165 is IERC165 { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; constructor () { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev See {IERC165-supportsInterface}. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) public view override returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal virtual { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } //import "./IERC721.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; //added function exists(uint256 _tokenId) external view returns (bool); } //import "./IERC721Metadata.sol"; 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); } //import "./IERC721Enumerable.sol"; 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); } interface IERC721Full is IERC165, IERC721Metadata, IERC721Enumerable {} 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); } //------------------------== //import "./SafeMathAddr.sol"; // File: @openzeppelin/contracts/math/SafeMath.sol 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; } } // File: @openzeppelin/contracts/utils/Address.sol //pragma solidity >=0.6.2 <0.8.0; library Address { 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); } } } } //------------------------== //import "hardhat/console.sol"; library Strings { /** * @dev Converts a `uint256` to its ASCII `string` representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); uint256 index = digits - 1; temp = value; while (temp != 0) { buffer[index--] = bytes1(uint8(48 + (temp % 10))); temp /= 10; } return string(buffer); } } //----------------------== //import "../../utils/EnumerableSet.sol"; library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping(bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require( set._values.length > index, "EnumerableSet: index out of bounds" ); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } //--------------------== //import "../../utils/EnumerableMap.sol"; library EnumerableMap { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Map type with // bytes32 keys and values. // The Map implementation uses private functions, and user-facing // implementations (such as Uint256ToAddressMap) are just wrappers around // the underlying Map. // This means that we can only create new EnumerableMaps for types that fit // in bytes32. struct MapEntry { bytes32 _key; bytes32 _value; } struct Map { // Storage of map keys and values MapEntry[] _entries; // Position of the entry defined by a key in the `entries` array, plus 1 // because index 0 means a key is not in the map. mapping(bytes32 => uint256) _indexes; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function _set( Map storage map, bytes32 key, bytes32 value ) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) { // Equivalent to !contains(map, key) map._entries.push(MapEntry({_key: key, _value: value})); // The entry is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value map._indexes[key] = map._entries.length; return true; } else { map._entries[keyIndex - 1]._value = value; return false; } } /** * @dev Removes a key-value pair from a map. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function _remove(Map storage map, bytes32 key) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex != 0) { // Equivalent to contains(map, key) // To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one // in the array, and then remove the last entry (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = keyIndex - 1; uint256 lastIndex = map._entries.length - 1; // When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. MapEntry storage lastEntry = map._entries[lastIndex]; // Move the last entry to the index where the entry to delete is map._entries[toDeleteIndex] = lastEntry; // Update the index for the moved entry map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved entry was stored map._entries.pop(); // Delete the index for the deleted slot delete map._indexes[key]; return true; } else { return false; } } /** * @dev Returns true if the key is in the map. O(1). */ function _contains(Map storage map, bytes32 key) private view returns (bool) { return map._indexes[key] != 0; } /** * @dev Returns the number of key-value pairs in the map. O(1). */ function _length(Map storage map) private view returns (uint256) { return map._entries.length; } /** * @dev Returns the key-value pair stored at position `index` in the map. O(1). * * Note that there are no guarantees on the ordering of entries inside the * array, and it may change when more entries are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) { require( map._entries.length > index, "EnumerableMap: index out of bounds" ); MapEntry storage entry = map._entries[index]; return (entry._key, entry._value); } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function _get(Map storage map, bytes32 key) private view returns (bytes32) { return _get(map, key, "EnumerableMap: nonexistent key"); } /** * @dev Same as {_get}, with a custom error message when `key` is not in the map. */ function _get( Map storage map, bytes32 key, string memory errorMessage ) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } // UintToAddressMap struct UintToAddressMap { Map _inner; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function set( UintToAddressMap storage map, uint256 key, address value ) internal returns (bool) { return _set(map._inner, bytes32(key), bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) { return _remove(map._inner, bytes32(key)); } /** * @dev Returns true if the key is in the map. O(1). */ function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) { return _contains(map._inner, bytes32(key)); } /** * @dev Returns the number of elements in the map. O(1). */ function length(UintToAddressMap storage map) internal view returns (uint256) { return _length(map._inner); } /** * @dev Returns the element stored at position `index` in the set. O(1). * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) { (bytes32 key, bytes32 value) = _at(map._inner, index); return (uint256(key), address(uint256(value))); } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function get(UintToAddressMap storage map, uint256 key) internal view returns (address) { return address(uint256(_get(map._inner, bytes32(key)))); } /** * @dev Same as {get}, with a custom error message when `key` is not in the map. */ function get( UintToAddressMap storage map, uint256 key, string memory errorMessage ) internal view returns (address) { return address(uint256(_get(map._inner, bytes32(key), errorMessage))); } } //--------------------------== /**IERC721Full is IERC721, IERC721Enumerable, IERC721Metadata * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721 is Context, IERC721Full, ERC165 { using SafeMath for uint256; using Address for address; using EnumerableSet for EnumerableSet.UintSet; using EnumerableMap for EnumerableMap.UintToAddressMap; using Strings for uint256; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Mapping from holder address to their (enumerable) set of owned tokens mapping(address => EnumerableSet.UintSet) private _holderTokens; // Enumerable mapping from token ids to their owners EnumerableMap.UintToAddressMap private _tokenOwners; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; // Token name string private _name; // Token symbol string private _symbol; // Optional mapping for token URIs mapping(uint256 => string) private _tokenURIs; // Base URI string private _baseURI; /* * bytes4(keccak256('balanceOf(address)')) == 0x70a08231 * bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e * bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3 * bytes4(keccak256('getApproved(uint256)')) == 0x081812fc * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 * bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde * * => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^ * 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd */ bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; /* * bytes4(keccak256('name()')) == 0x06fdde03 * bytes4(keccak256('symbol()')) == 0x95d89b41 * bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd * * => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f */ bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; /* * bytes4(keccak256('totalSupply()')) == 0x18160ddd * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59 * bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7 * * => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63 */ bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721); _registerInterface(_INTERFACE_ID_ERC721_METADATA); _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view override returns (uint256) { require( owner != address(0), "ERC721: balance query for the zero address" ); return _holderTokens[owner].length(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { return _tokenOwners.get( tokenId, "ERC721: owner query for nonexistent token" ); } /** * @dev See {IERC721Metadata-name}. */ function name() public view override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); string memory _tokenURI = _tokenURIs[tokenId]; // If there is no base URI, return the token URI. if (bytes(_baseURI).length == 0) { return _tokenURI; } // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(_baseURI, _tokenURI)); } // If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI. return string(abi.encodePacked(_baseURI, tokenId.toString())); } /** * @dev Returns the base URI set via {_setBaseURI}. This will be * automatically added as a prefix in {tokenURI} to each token's URI, or * to the token ID if no specific URI is set for that token ID. */ function baseURI() public view returns (string memory) { return _baseURI; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { return _holderTokens[owner].at(index); } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view override returns (uint256) { // _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds return _tokenOwners.length(); } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view override returns (uint256) { (uint256 tokenId, ) = _tokenOwners.at(index); return tokenId; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view override returns (address) { require( _exists(tokenId), "ERC721: approved query for nonexistent token" ); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //console.log("[sc] ERC721: transferFrom()"); //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 { //console.log("[sc] ERC721: safeTransferFrom()"); safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. virtual */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public override { //console.log("[sc] ERC721: safeTransferFrom(data)"); 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 { require( _checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); _transfer(from, to, tokenId); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view returns (bool) { return _tokenOwners.contains(tokenId); } function exists(uint256 _tokenId) external view override returns (bool) { return _exists(_tokenId); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) { require( _exists(tokenId), "ERC721: operator query for nonexistent token" ); address owner = ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: d* * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { require( _checkOnERC721Received(address(this), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); _mint(to, tokenId); } /** * @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 { //console.log("[sc] _mint()"); require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); // Clear metadata (if any) if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } _holderTokens[owner].remove(tokenId); _tokenOwners.remove(tokenId); emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require( ownerOf(tokenId) == from, "ERC721: transfer of token that is not own" ); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _holderTokens[from].remove(tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(from, to, tokenId); } /** * @dev Sets `_tokenURI` as the tokenURI of `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require( _exists(tokenId), "ERC721Metadata: URI set of nonexistent token" ); _tokenURIs[tokenId] = _tokenURI; } /** * @dev Internal function to set the base URI for all token IDs. It is * automatically added as a prefix to the value returned in {tokenURI}, * or to the token ID if {tokenURI} is empty. */ function _setBaseURI(string memory baseURI_) internal virtual { _baseURI = baseURI_; } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (!to.isContract()) { //console.log("[sc] not a contract"); return true; } //console.log("[sc] check ERC721Receiver"); bytes memory returndata = to.functionCall( abi.encodeWithSelector( IERC721Receiver(to).onERC721Received.selector, _msgSender(), from, tokenId, _data ), "ERC721: transfer to non ERC721Receiver implementer" ); bytes4 retval = abi.decode(returndata, (bytes4)); return (retval == _ERC721_RECEIVED); } function _approve(address to, uint256 tokenId) private { _tokenApprovals[tokenId] = to; emit Approval(ownerOf(tokenId), to, tokenId); } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } //-------------------------------== OpenSea //import "openzeppelin-solidity/contracts/token/ERC721/ERC721Full.sol"; //import "openzeppelin-solidity/contracts/ownership/Ownable.sol"; //import "./Strings.sol"; contract OwnableDelegateProxy { } contract ProxyRegistry { mapping(address => OwnableDelegateProxy) public proxies; } /** * @title ERC721Tradable * ERC721Tradable - ERC721 contract that whitelists a trading address, and has minting functionality. */ contract ERC721Tradable is ERC721, Ownable { using Strings for string; using SafeMath for uint256; address public proxyRegistryAddress; uint256 private _currentTokenId = 0; uint256 public maxTokenId; constructor(string memory _name, string memory _symbol) ERC721(_name, _symbol) {} function setProxyRegistryAddress(address _proxyRegistryAddress) public onlyOwner { proxyRegistryAddress = _proxyRegistryAddress; } /** * @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 newTokenId = _getNextTokenId(); require(newTokenId <= maxTokenId, "maxTokenId has been reached"); _safeMint(_to, newTokenId); _incrementTokenId(); } /** * @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 _incrementTokenId() private { _currentTokenId++; } /** * Override isApprovedForAll to whitelist user's OpenSea proxy accounts to enable gas-less listings. */ function isApprovedForAll(address owner, address operator) public view override returns (bool) { // Whitelist OpenSea proxy contract for easy trading. ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress); if (address(proxyRegistry.proxies(owner)) == operator) { return true; } return super.isApprovedForAll(owner, operator); } function baseTokenURI() public pure returns (string memory) { return ""; } function checkOwner(address eoa1) public view returns (bool[] memory arrayOut) { //console.log("checkOwner"); arrayOut = new bool[](_currentTokenId); //console.log("ck1", arrayOut[9], ", _currentTokenId:", _currentTokenId); for (uint256 i = 1; i <= _currentTokenId; i++) { //console.log("i =", i); if (ownerOf(i) == eoa1) { uint256 idx = i - 1; arrayOut[idx] = true; } } } function mintAll(address _to) external onlyOwner { //console.log("[sc] mintAll()"); for (uint256 i = 1; i <= maxTokenId; i++) { mintTo(_to); } } function concatenate(string memory a, string memory b) public pure returns (string memory) { return string(abi.encodePacked(a, b)); } function tokenURI(uint256 _tokenId) public view override returns (string memory str) { if (_tokenId == 0) { str = "na"; } else if (_tokenId == 1) { str = "ipfs://bafybeiahy2ednf4l2eak4voxoskuqrqh4pnqewxx4f2n6x7jsw6w2ic3gi"; } else if (_tokenId == 2) { str = "ipfs://bafybeihxphm3msrktv23s5yuhsct7bvmvic75sifa2oa3mbct3optnggwu"; } else if (_tokenId == 3) { str = "ipfs://bafybeib5a36m6dzk7ivztqgmhhzlgtjx2eulvtbxm6all7xe3hmppkuoae"; } else if (_tokenId == 4) { str = "ipfs://bafybeibebbfxvxkkxuaei7emgb4vmngykkbq7gnxy2muwb6e7653uvdlfi"; } else if (_tokenId == 5) { str = "ipfs://bafybeiekfwtnovtiz7zu5haq7t6vhyzno3lqurwehsprcvi3gho6fema2e"; } else if (_tokenId == 6) { str = "ipfs://bafybeih3fttxvo74eik62otd2wy6d6zty5wwig7ocb6waqvl6tfrwb2sze"; } else if (_tokenId == 7) { str = "ipfs://bafybeic6l4dehe3usvf25wmd5muzux2mfpe4pjapgir4cmyk43tmin6dei"; } else if (_tokenId == 8) { str = "ipfs://bafybeifw7vgtgjdcuzfuhhorwp536z34tfsxv3ygetfa42ocbxnxycoxcu"; } else if (_tokenId == 9) { str = "ipfs://bafybeifuhh42leyt63cfsvrygygrojnlqwvo5676n5x43lhyvstffc5slq"; } else if (_tokenId == 10) { str = "ipfs://bafybeih3fibnfg7qiblfa7bkovljjp3755fpkdfhlxfcbciduu7nndjfze"; } } } /* @title Creature * Creature - a contract for my non-fungible creatures. */ contract Creature is ERC721Tradable { constructor() ERC721Tradable("Freedom Reserve Limited Edition 2020", "FRLA") { maxTokenId = 10; //mainnet proxyRegistryAddress = address(0xa5409ec958C83C3f309868babACA7c86DCB077c1); } //add to scan if all units have been sold function contractURI() public view returns (string memory) { return tokenURI(1); //"https://creatures-api.opensea.io/contract/opensea-creatures"; } } /* deployment: gasPrice = 10GWei, gasLimit = 2489646 constructor() ERC721Tradable("Freedom Reserve Limited Edition 2020", "FRLA") {} */
* @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 newTokenId = _getNextTokenId(); require(newTokenId <= maxTokenId, "maxTokenId has been reached"); _safeMint(_to, newTokenId); _incrementTokenId(); }
12,136,074
[ 1, 49, 28142, 279, 1147, 358, 392, 1758, 598, 279, 1147, 3098, 18, 225, 389, 869, 1758, 434, 326, 3563, 3410, 434, 326, 1147, 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 ]
[ 1, 1, 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, 312, 474, 774, 12, 2867, 389, 869, 13, 1071, 1338, 5541, 288, 203, 3639, 2254, 5034, 394, 1345, 548, 273, 389, 588, 9399, 548, 5621, 203, 3639, 2583, 12, 2704, 1345, 548, 1648, 943, 1345, 548, 16, 315, 1896, 1345, 548, 711, 2118, 8675, 8863, 203, 3639, 389, 4626, 49, 474, 24899, 869, 16, 394, 1345, 548, 1769, 203, 3639, 389, 15016, 1345, 548, 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 ]
./full_match/1/0x92344754a9060a52A634B3c6b8118f76baD1A448/sources/contracts/dependencies/Invoke.sol
* Instructs the Etf to unwrap the passed quantity of WETH @param _etf Etf instance to invoke @param _weth WETH address @param _quantity The quantity to unwrap/
function invokeUnwrapWETH(IETF _etf, address _weth, uint256 _quantity) internal { bytes memory callData = abi.encodeWithSignature('withdraw(uint256)', _quantity); _etf.execute(_weth, 0, callData, true); }
2,998,034
[ 1, 382, 1697, 87, 326, 512, 6632, 358, 11014, 326, 2275, 10457, 434, 678, 1584, 44, 225, 389, 27227, 3639, 512, 6632, 791, 358, 4356, 225, 389, 91, 546, 5411, 678, 1584, 44, 1758, 225, 389, 16172, 3639, 1021, 10457, 358, 11014, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 4356, 984, 4113, 59, 1584, 44, 12, 45, 1584, 42, 389, 27227, 16, 1758, 389, 91, 546, 16, 2254, 5034, 389, 16172, 13, 2713, 288, 203, 565, 1731, 3778, 745, 751, 273, 24126, 18, 3015, 1190, 5374, 2668, 1918, 9446, 12, 11890, 5034, 13, 2187, 389, 16172, 1769, 203, 565, 389, 27227, 18, 8837, 24899, 91, 546, 16, 374, 16, 745, 751, 16, 638, 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 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "./PostDeliveryCrowdsale.sol"; contract MintASX is PostDeliveryCrowdsale, Ownable { constructor( uint256 _rate, address payable _wallet, ERC20 _token, address _tokenWallet, uint256 _openingTime, uint256 _closingTime ) Crowdsale(_rate, _wallet, _token) AllowanceCrowdsale(_tokenWallet) TimedCrowdsale(_openingTime, _closingTime) { // solhint-disable-previous-line no-empty-blocks } function extendTime(uint256 newClosingTime) public onlyOwner { _extendTime(newClosingTime); } /** * @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 view override onlyWhileOpen { super._preValidatePurchase(beneficiary, weiAmount); } /** * @dev Overrides parent behavior by transferring tokens from wallet. * @param beneficiary Token purchaser * @param tokenAmount Amount of tokens purchased */ function _deliverTokens(address beneficiary, uint256 tokenAmount) internal override { super._deliverTokens(beneficiary, tokenAmount); } } // 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 (last updated v4.5.0) (token/ERC20/ERC20.sol) pragma solidity ^0.8.0; import "./IERC20.sol"; import "./extensions/IERC20Metadata.sol"; import "../../utils/Context.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC20 * applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `to` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address to, uint256 amount) public virtual override returns (bool) { address owner = _msgSender(); _transfer(owner, to, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on * `transferFrom`. This is semantically equivalent to an infinite approval. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { address owner = _msgSender(); _approve(owner, spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * NOTE: Does not update the allowance if the current allowance * is the maximum `uint256`. * * Requirements: * * - `from` and `to` cannot be the zero address. * - `from` must have a balance of at least `amount`. * - the caller must have allowance for ``from``'s tokens of at least * `amount`. */ function transferFrom( address from, address to, uint256 amount ) public virtual override returns (bool) { address spender = _msgSender(); _spendAllowance(from, spender, amount); _transfer(from, to, amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { address owner = _msgSender(); _approve(owner, spender, _allowances[owner][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { address owner = _msgSender(); uint256 currentAllowance = _allowances[owner][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(owner, spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `from` must have a balance of at least `amount`. */ function _transfer( address from, address to, uint256 amount ) internal virtual { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(from, to, amount); uint256 fromBalance = _balances[from]; require(fromBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[from] = fromBalance - amount; } _balances[to] += amount; emit Transfer(from, to, amount); _afterTokenTransfer(from, to, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Spend `amount` form the allowance of `owner` toward `spender`. * * Does not update the allowance amount in case of infinite allowance. * Revert if not enough allowance is available. * * Might emit an {Approval} event. */ function _spendAllowance( address owner, address spender, uint256 amount ) internal virtual { uint256 currentAllowance = allowance(owner, spender); if (currentAllowance != type(uint256).max) { require(currentAllowance >= amount, "ERC20: insufficient allowance"); unchecked { _approve(owner, spender, currentAllowance - amount); } } } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/interfaces/IERC20.sol"; import "./TimedCrowdsale.sol"; // import "./Secondary.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; /** * @title PostDeliveryCrowdsale * @dev Crowdsale that locks tokens from withdrawal until it ends. */ abstract contract PostDeliveryCrowdsale is TimedCrowdsale { using SafeMath for uint256; mapping(address => uint256) private _balances; __unstable__TokenVault private _vault; constructor() { _vault = new __unstable__TokenVault(); } /** * @dev Withdraw tokens only after crowdsale ends. * @param beneficiary Whose tokens will be withdrawn. */ function withdrawTokens(address beneficiary) public { require(hasClosed(), "PostDeliveryCrowdsale: not closed"); uint256 amount = _balances[beneficiary]; require( amount > 0, "PostDeliveryCrowdsale: beneficiary is not due any tokens" ); _balances[beneficiary] = 0; _vault.transfer(token(), beneficiary, amount); } /** * @return the balance of an account. */ function balanceOf(address account) public view returns (uint256) { return _balances[account]; } /** * @dev Overrides parent by storing due balances, and delivering tokens to the vault instead of the end user. This * ensures that the tokens will be available by the time they are withdrawn (which may not be the case if * `_deliverTokens` was called later). * @param beneficiary Token purchaser * @param tokenAmount Amount of tokens purchased */ function _processPurchase(address beneficiary, uint256 tokenAmount) internal override { _balances[beneficiary] = _balances[beneficiary].add(tokenAmount); _deliverTokens(address(_vault), tokenAmount); } } /** * @title __unstable__TokenVault * @dev Similar to an Escrow for tokens, this contract allows its primary account to spend its tokens as it sees fit. * This contract is an internal helper for PostDeliveryCrowdsale, and should not be used outside of this context. */ // solhint-disable-next-line contract-name-camelcase contract __unstable__TokenVault is Ownable { function transfer( IERC20 token, address to, uint256 amount ) public onlyOwner { token.transfer(to, amount); } } // 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) (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `to`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `from` to `to` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (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/math/SafeMath.sol) pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (interfaces/IERC20.sol) pragma solidity ^0.8.0; import "../token/ERC20/IERC20.sol"; // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./AllowanceCrowdsale.sol"; /** * @title TimedCrowdsale * @dev Borrow from https://github.dev/OpenZeppelin/openzeppelin-contracts/blob/docs-v2.x/contracts/crowdsale/validation/TimedCrowdsale.sol * @dev Crowdsale accepting contributions only within a time frame. */ abstract contract TimedCrowdsale is AllowanceCrowdsale { uint256 private _openingTime; uint256 private _closingTime; /** * Event for crowdsale extending * @param newClosingTime new closing time * @param prevClosingTime old closing time */ event TimedCrowdsaleExtended( uint256 prevClosingTime, uint256 newClosingTime ); /** * @dev Reverts if not in crowdsale time range. */ modifier onlyWhileOpen() { require(isOpen(), "TimedCrowdsale: not open"); _; } /** * @dev Constructor, takes crowdsale opening and closing times. * @param openingTime Crowdsale opening time * @param closingTime Crowdsale closing time */ constructor(uint256 openingTime, uint256 closingTime) { // solhint-disable-next-line not-rely-on-time require( openingTime >= block.timestamp, "TimedCrowdsale: opening time is before current time" ); // solhint-disable-next-line max-line-length require( closingTime > openingTime, "TimedCrowdsale: opening time is not before closing time" ); _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) { // solhint-disable-next-line not-rely-on-time 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) { // solhint-disable-next-line not-rely-on-time 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 view virtual override onlyWhileOpen { super._preValidatePurchase(beneficiary, weiAmount); } /** * @dev Extend crowdsale. * @param newClosingTime Crowdsale closing time */ function _extendTime(uint256 newClosingTime) internal { require(!hasClosed(), "TimedCrowdsale: already closed"); // solhint-disable-next-line max-line-length require( newClosingTime > _closingTime, "TimedCrowdsale: new closing time is before current closing time" ); emit TimedCrowdsaleExtended(_closingTime, newClosingTime); _closingTime = newClosingTime; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/utils/math/Math.sol"; import "./Crowdsale.sol"; /** * @title AllowanceCrowdsale * @dev Borrow from https://github.dev/OpenZeppelin/openzeppelin-contracts/blob/docs-v2.x/contracts/crowdsale/emission/AllowanceCrowdsale.sol * @dev Extension of Crowdsale where tokens are held by a wallet, which approves an allowance to the crowdsale. */ abstract contract AllowanceCrowdsale is Crowdsale { using SafeERC20 for IERC20; address private _tokenWallet; /** * @dev Constructor, takes token wallet address. * @param tokenWallet Address holding the tokens, which has approved allowance to the crowdsale. */ constructor(address tokenWallet) { require( tokenWallet != address(0), "AllowanceCrowdsale: token wallet is the zero address" ); _tokenWallet = tokenWallet; } /** * @return the address of the wallet that will hold the tokens. */ function tokenWallet() public view returns (address) { return _tokenWallet; } /** * @dev Checks the amount of tokens left in the allowance. * @return Amount of tokens left in the allowance */ function remainingTokens() public view returns (uint256) { return Math.min( token().balanceOf(_tokenWallet), token().allowance(_tokenWallet, address(this)) ); } /** * @dev Overrides parent behavior by transferring tokens from wallet. * @param beneficiary Token purchaser * @param tokenAmount Amount of tokens purchased */ function _deliverTokens(address beneficiary, uint256 tokenAmount) internal virtual override { token().safeTransferFrom(_tokenWallet, beneficiary, tokenAmount); } } // 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/math/Math.sol) pragma solidity ^0.8.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow. return (a & b) + (a ^ b) / 2; } /** * @dev Returns the ceiling of the division of two numbers. * * This differs from standard division with `/` in that it rounds up instead * of rounding down. */ function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b - 1) / b can overflow on addition, so we distribute. return a / b + (a % b == 0 ? 0 : 1); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/utils/Context.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; /** * @title Crowdsale * @dev OpenZeppelin and upgrade to solidity v0.8.0 * @dev Crowdsale is a base contract for managing a token crowdsale, * allowing investors to purchase tokens with ether. This contract implements * such functionality in its most fundamental form and can be extended to provide additional * functionality and/or custom behavior. * The external interface represents the basic interface for purchasing tokens, and conforms * the base architecture for crowdsales. It is *not* intended to be modified / overridden. * The internal interface conforms the extensible and modifiable surface of crowdsales. Override * the methods to add functionality. Consider using 'super' where appropriate to concatenate * behavior. */ contract Crowdsale is Context, ReentrancyGuard { using SafeERC20 for IERC20; // The token being sold IERC20 private _token; // Address where funds are collected address payable private _wallet; // How many token units a buyer gets per wei. // The rate is the conversion between wei and the smallest and indivisible token unit. // So, if you are using a rate of 1 with a ERC20Detailed token with 3 decimals called TOK // 1 wei will give you 1 unit, or 0.001 TOK. uint256 private _rate; // Amount of wei raised uint256 private _weiRaised; /** * Event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokensPurchased( address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount ); /** * @param 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 payable wallet, IERC20 token ) public { require(rate > 0, "Crowdsale: rate is 0"); require(wallet != address(0), "Crowdsale: wallet is the zero address"); require( address(token) != address(0), "Crowdsale: token is the zero address" ); _rate = rate; _wallet = wallet; _token = token; } /** * @dev fallback function ***DO NOT OVERRIDE*** * Note that other contracts will transfer funds with a base gas stipend * of 2300, which is not enough to call buyTokens. Consider calling * buyTokens directly when purchasing tokens from a contract. */ receive() external payable { buyTokens(_msgSender()); } /** * @return the token being sold. */ function token() public view returns (IERC20) { return _token; } /** * @return the address where funds are collected. */ function wallet() public view returns (address payable) { return _wallet; } /** * @return the number of token units a buyer gets per wei. */ function rate() public view returns (uint256) { return _rate; } /** * @return the amount of wei raised. */ function weiRaised() public view returns (uint256) { return _weiRaised; } /** * @dev low level token purchase ***DO NOT OVERRIDE*** * This function has a non-reentrancy guard, so it shouldn't be called by * another `nonReentrant` function. * @param beneficiary Recipient of the token purchase */ function buyTokens(address beneficiary) public payable nonReentrant { uint256 weiAmount = msg.value; _preValidatePurchase(beneficiary, weiAmount); // calculate token amount to be created uint256 tokens = _getTokenAmount(weiAmount); // update state _weiRaised = _weiRaised + weiAmount; _processPurchase(beneficiary, tokens); emit TokensPurchased(_msgSender(), beneficiary, weiAmount, tokens); _updatePurchasingState(beneficiary, weiAmount); _forwardFunds(); _postValidatePurchase(beneficiary, weiAmount); } /** * @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. * Use `super` in contracts that inherit from Crowdsale to extend their validations. * Example from CappedCrowdsale.sol's _preValidatePurchase method: * super._preValidatePurchase(beneficiary, weiAmount); * require(weiRaised().add(weiAmount) <= cap); * @param beneficiary Address performing the token purchase * @param weiAmount Value in wei involved in the purchase */ function _preValidatePurchase(address beneficiary, uint256 weiAmount) internal view virtual { require( beneficiary != address(0), "Crowdsale: beneficiary is the zero address" ); require(weiAmount != 0, "Crowdsale: weiAmount is 0"); this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 } /** * @dev Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid * conditions are not met. * @param beneficiary Address performing the token purchase * @param weiAmount Value in wei involved in the purchase */ function _postValidatePurchase(address beneficiary, uint256 weiAmount) internal view { // solhint-disable-previous-line no-empty-blocks } /** * @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends * its tokens. * @param beneficiary Address performing the token purchase * @param tokenAmount Number of tokens to be emitted */ function _deliverTokens(address beneficiary, uint256 tokenAmount) internal virtual { _token.safeTransfer(beneficiary, tokenAmount); } /** * @dev Executed when a purchase has been validated and is ready to be executed. Doesn't necessarily emit/send * tokens. * @param beneficiary Address receiving the tokens * @param tokenAmount Number of tokens to be purchased */ function _processPurchase(address beneficiary, uint256 tokenAmount) internal virtual { _deliverTokens(beneficiary, tokenAmount); } /** * @dev Override for extensions that require an internal state to check for validity (current user contributions, * etc.) * @param beneficiary Address receiving the tokens * @param weiAmount Value in wei involved in the purchase */ function _updatePurchasingState(address beneficiary, uint256 weiAmount) internal { // solhint-disable-previous-line no-empty-blocks } /** * @dev Override to extend the way in which ether is converted to tokens. * @param weiAmount Value in wei to be converted into tokens * @return Number of tokens that can be purchased with the specified _weiAmount */ function _getTokenAmount(uint256 weiAmount) internal view returns (uint256) { return weiAmount * _rate; } /** * @dev Determines how ETH is stored/forwarded on purchases. */ function _forwardFunds() internal { _wallet.transfer(msg.value); } } // 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 (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; } }
* @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. Use `super` in contracts that inherit from Crowdsale to extend their validations. Example from CappedCrowdsale.sol's _preValidatePurchase method: super._preValidatePurchase(beneficiary, weiAmount); require(weiRaised().add(weiAmount) <= cap); @param beneficiary Address performing the token purchase @param weiAmount Value in wei involved in the purchase/
function _preValidatePurchase(address beneficiary, uint256 weiAmount) internal view virtual { require( beneficiary != address(0), "Crowdsale: beneficiary is the zero address" ); require(weiAmount != 0, "Crowdsale: weiAmount is 0"); }
13,926,231
[ 1, 4354, 434, 392, 6935, 23701, 18, 2672, 2583, 6317, 358, 15226, 919, 1347, 4636, 854, 486, 5100, 18, 2672, 1375, 9565, 68, 316, 20092, 716, 6811, 628, 385, 492, 2377, 5349, 358, 2133, 3675, 20808, 18, 5090, 628, 11200, 1845, 39, 492, 2377, 5349, 18, 18281, 1807, 389, 1484, 4270, 23164, 707, 30, 377, 2240, 6315, 1484, 4270, 23164, 12, 70, 4009, 74, 14463, 814, 16, 732, 77, 6275, 1769, 377, 2583, 12, 1814, 77, 12649, 5918, 7675, 1289, 12, 1814, 77, 6275, 13, 1648, 3523, 1769, 225, 27641, 74, 14463, 814, 5267, 14928, 326, 1147, 23701, 225, 732, 77, 6275, 1445, 316, 732, 77, 24589, 316, 326, 23701, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 202, 915, 389, 1484, 4270, 23164, 12, 2867, 27641, 74, 14463, 814, 16, 2254, 5034, 732, 77, 6275, 13, 203, 202, 202, 7236, 203, 202, 202, 1945, 203, 202, 202, 12384, 203, 202, 95, 203, 202, 202, 6528, 12, 203, 1082, 202, 70, 4009, 74, 14463, 814, 480, 1758, 12, 20, 3631, 203, 1082, 202, 6, 39, 492, 2377, 5349, 30, 27641, 74, 14463, 814, 353, 326, 3634, 1758, 6, 203, 202, 202, 1769, 203, 202, 202, 6528, 12, 1814, 77, 6275, 480, 374, 16, 315, 39, 492, 2377, 5349, 30, 732, 77, 6275, 353, 374, 8863, 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 ]
./full_match/1/0x0d224228f0D024fe99681863BA325d87e8aFE30d/sources/contracts/ETHBridge.sol
* @dev Update the fee rate on the current chain. Only callable by the owner @param newFeeRate uint - the new fee rate that applies to the current side of the bridge/
function updateFeeRate(uint256 newFeeRate) external onlyOwner { uint256 oldFeeRate = feeRate; feeRate = newFeeRate; emit FeeUpdate(oldFeeRate, newFeeRate, FeeType.RATE); }
8,426,983
[ 1, 1891, 326, 14036, 4993, 603, 326, 783, 2687, 18, 5098, 4140, 635, 326, 3410, 225, 394, 14667, 4727, 2254, 300, 326, 394, 14036, 4993, 716, 10294, 358, 326, 783, 4889, 434, 326, 10105, 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, 565, 445, 1089, 14667, 4727, 12, 11890, 5034, 394, 14667, 4727, 13, 3903, 1338, 5541, 288, 203, 3639, 2254, 5034, 1592, 14667, 4727, 273, 14036, 4727, 31, 203, 3639, 14036, 4727, 273, 394, 14667, 4727, 31, 203, 3639, 3626, 30174, 1891, 12, 1673, 14667, 4727, 16, 394, 14667, 4727, 16, 30174, 559, 18, 24062, 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 ]
pragma solidity 0.7.3; import "./IERC20.sol"; import "./SafeMath.sol"; 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); /** * @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; } } 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); } } } } contract HitchensOrderStatisticsTree { uint private constant EMPTY = 0; struct Node { uint parent; uint left; uint right; bool red; bytes32[] keys; mapping(bytes32 => uint) keyMap; uint count; } struct Tree { uint root; mapping(uint => Node) nodes; } Tree tree; function first(Tree storage self) internal view returns (uint _value) { _value = self.root; if(_value == EMPTY) return 0; while (self.nodes[_value].left != EMPTY) { _value = self.nodes[_value].left; } } function last(Tree storage self) internal view returns (uint _value) { _value = self.root; if(_value == EMPTY) return 0; while (self.nodes[_value].right != EMPTY) { _value = self.nodes[_value].right; } } function next(Tree storage self, uint value) internal view returns (uint _cursor) { require(value != EMPTY, "OrderStatisticsTree(401) - Starting value cannot be zero"); if (self.nodes[value].right != EMPTY) { _cursor = treeMinimum(self, self.nodes[value].right); } else { _cursor = self.nodes[value].parent; while (_cursor != EMPTY && value == self.nodes[_cursor].right) { value = _cursor; _cursor = self.nodes[_cursor].parent; } } } function prev(Tree storage self, uint value) internal view returns (uint _cursor) { require(value != EMPTY, "OrderStatisticsTree(402) - Starting value cannot be zero"); if (self.nodes[value].left != EMPTY) { _cursor = treeMaximum(self, self.nodes[value].left); } else { _cursor = self.nodes[value].parent; while (_cursor != EMPTY && value == self.nodes[_cursor].left) { value = _cursor; _cursor = self.nodes[_cursor].parent; } } } function exists(Tree storage self, uint value) internal view returns (bool _exists) { if(value == EMPTY) return false; if(value == self.root) return true; if(self.nodes[value].parent != EMPTY) return true; return false; } function keyExists(Tree storage self, bytes32 key, uint value) internal view returns (bool _exists) { if(!exists(self, value)) return false; return self.nodes[value].keys[self.nodes[value].keyMap[key]] == key; } function getNode(Tree storage self, uint value) internal view returns (uint _parent, uint _left, uint _right, bool _red, uint keyCount, uint count) { require(exists(self,value), "OrderStatisticsTree(403) - Value does not exist."); Node storage gn = self.nodes[value]; return(gn.parent, gn.left, gn.right, gn.red, gn.keys.length, gn.keys.length+gn.count); } function getNodeCount(Tree storage self, uint value) internal view returns(uint count) { Node storage gn = self.nodes[value]; return gn.keys.length+gn.count; } function valueKeyAtIndex(Tree storage self, uint value, uint index) internal view returns(bytes32 _key) { require(exists(self,value), "OrderStatisticsTree(404) - Value does not exist."); return self.nodes[value].keys[index]; } function count(Tree storage self) internal view returns(uint _count) { return getNodeCount(self,self.root); } function percentile(Tree storage self, uint value) internal view returns(uint _percentile) { uint denominator = count(self); uint numerator = rank(self, value); _percentile = ((uint(1000) * numerator)/denominator+(uint(5)))/uint(10); } function permil(Tree storage self, uint value) internal view returns(uint _permil) { uint denominator = count(self); uint numerator = rank(self, value); _permil = ((uint(10000) * numerator)/denominator+(uint(5)))/uint(10); } function atPercentile(Tree storage self, uint _percentile) internal view returns(uint _value) { uint findRank = (((_percentile * count(self))/uint(10)) + uint(5)) / uint(10); return atRank(self,findRank); } function atPermil(Tree storage self, uint _permil) internal view returns(uint _value) { uint findRank = (((_permil * count(self))/uint(100)) + uint(5)) / uint(10); return atRank(self,findRank); } function median(Tree storage self) internal view returns(uint value) { return atPercentile(self,50); } function below(Tree storage self, uint value) internal view returns(uint) { if(count(self) > 0 && value > 0) { uint valueRank = rank(self,value); if(valueRank == 0) { return 0; } uint256 valueAtRank = atRank(self,valueRank); uint256 add = 0; if(valueRank <= count(self) && valueAtRank <= value) { add = 1; } return valueRank - 1 + add; } } function above(Tree storage self, uint value) internal view returns(uint) { if(count(self) > 0) { uint valueRank = rank(self,value); uint treeCount = count(self); if(valueRank > treeCount) { return 0; } uint256 valueAtRank = atRank(self,valueRank); uint256 add = 0; if(valueRank > 0 && valueAtRank >= value) { add = 1; } return treeCount - valueRank + add; } } function rank(Tree storage self, uint value) internal view returns(uint _rank) { if(count(self) > 0) { bool finished; uint cursor = self.root; Node storage c = self.nodes[cursor]; uint smaller = getNodeCount(self,c.left); while (!finished) { uint keyCount = c.keys.length; if(cursor == value) { finished = true; } else { if(cursor < value) { cursor = c.right; c = self.nodes[cursor]; smaller += keyCount + getNodeCount(self,c.left); } else { cursor = c.left; c = self.nodes[cursor]; smaller -= (keyCount + getNodeCount(self,c.right)); } } if (!exists(self,cursor)) { finished = true; } } return smaller + 1; } } function atRank(Tree storage self, uint _rank) internal view returns(uint _value) { bool finished; uint cursor = self.root; Node storage c = self.nodes[cursor]; uint smaller = getNodeCount(self,c.left); while (!finished) { _value = cursor; c = self.nodes[cursor]; uint keyCount = c.keys.length; if(smaller + 1 >= _rank && smaller + keyCount <= _rank) { _value = cursor; finished = true; } else { if(smaller + keyCount <= _rank) { cursor = c.right; c = self.nodes[cursor]; smaller += keyCount + getNodeCount(self,c.left); } else { cursor = c.left; c = self.nodes[cursor]; smaller -= (keyCount + getNodeCount(self,c.right)); } } if (!exists(self,cursor)) { finished = true; } } } function insert(Tree storage self, bytes32 key, uint value) internal { require(value != EMPTY, "OrderStatisticsTree(405) - Value to insert cannot be zero"); require(!keyExists(self,key,value), "OrderStatisticsTree(406) - Value and Key pair exists. Cannot be inserted again."); uint cursor; uint probe = self.root; while (probe != EMPTY) { cursor = probe; if (value < probe) { probe = self.nodes[probe].left; } else if (value > probe) { probe = self.nodes[probe].right; } else if (value == probe) { self.nodes[probe].keys.push(key); self.nodes[probe].keyMap[key] = self.nodes[probe].keys.length - uint(1); return; } self.nodes[cursor].count++; } Node storage nValue = self.nodes[value]; nValue.parent = cursor; nValue.left = EMPTY; nValue.right = EMPTY; nValue.red = true; nValue.keys.push(key); nValue.keyMap[key] = nValue.keys.length - uint(1); if (cursor == EMPTY) { self.root = value; } else if (value < cursor) { self.nodes[cursor].left = value; } else { self.nodes[cursor].right = value; } insertFixup(self, value); } function remove(Tree storage self, bytes32 key, uint value) internal { require(value != EMPTY, "OrderStatisticsTree(407) - Value to delete cannot be zero"); require(keyExists(self,key,value), "OrderStatisticsTree(408) - Value to delete does not exist."); Node storage nValue = self.nodes[value]; uint rowToDelete = nValue.keyMap[key]; nValue.keys[rowToDelete] = nValue.keys[nValue.keys.length - uint(1)]; nValue.keyMap[nValue.keys[rowToDelete]]=rowToDelete; nValue.keys.pop(); uint probe; uint cursor; if(nValue.keys.length == 0) { if (self.nodes[value].left == EMPTY || self.nodes[value].right == EMPTY) { cursor = value; } else { cursor = self.nodes[value].right; while (self.nodes[cursor].left != EMPTY) { cursor = self.nodes[cursor].left; } } if (self.nodes[cursor].left != EMPTY) { probe = self.nodes[cursor].left; } else { probe = self.nodes[cursor].right; } uint cursorParent = self.nodes[cursor].parent; self.nodes[probe].parent = cursorParent; if (cursorParent != EMPTY) { if (cursor == self.nodes[cursorParent].left) { self.nodes[cursorParent].left = probe; } else { self.nodes[cursorParent].right = probe; } } else { self.root = probe; } bool doFixup = !self.nodes[cursor].red; if (cursor != value) { replaceParent(self, cursor, value); self.nodes[cursor].left = self.nodes[value].left; self.nodes[self.nodes[cursor].left].parent = cursor; self.nodes[cursor].right = self.nodes[value].right; self.nodes[self.nodes[cursor].right].parent = cursor; self.nodes[cursor].red = self.nodes[value].red; (cursor, value) = (value, cursor); fixCountRecurse(self, value); } if (doFixup) { removeFixup(self, probe); } fixCountRecurse(self, cursorParent); delete self.nodes[cursor]; } } function fixCountRecurse(Tree storage self, uint value) private { while (value != EMPTY) { self.nodes[value].count = getNodeCount(self,self.nodes[value].left) + getNodeCount(self,self.nodes[value].right); value = self.nodes[value].parent; } } function treeMinimum(Tree storage self, uint value) private view returns (uint) { while (self.nodes[value].left != EMPTY) { value = self.nodes[value].left; } return value; } function treeMaximum(Tree storage self, uint value) private view returns (uint) { while (self.nodes[value].right != EMPTY) { value = self.nodes[value].right; } return value; } function rotateLeft(Tree storage self, uint value) private { uint cursor = self.nodes[value].right; uint parent = self.nodes[value].parent; uint cursorLeft = self.nodes[cursor].left; self.nodes[value].right = cursorLeft; if (cursorLeft != EMPTY) { self.nodes[cursorLeft].parent = value; } self.nodes[cursor].parent = parent; if (parent == EMPTY) { self.root = cursor; } else if (value == self.nodes[parent].left) { self.nodes[parent].left = cursor; } else { self.nodes[parent].right = cursor; } self.nodes[cursor].left = value; self.nodes[value].parent = cursor; self.nodes[value].count = getNodeCount(self,self.nodes[value].left) + getNodeCount(self,self.nodes[value].right); self.nodes[cursor].count = getNodeCount(self,self.nodes[cursor].left) + getNodeCount(self,self.nodes[cursor].right); } function rotateRight(Tree storage self, uint value) private { uint cursor = self.nodes[value].left; uint parent = self.nodes[value].parent; uint cursorRight = self.nodes[cursor].right; self.nodes[value].left = cursorRight; if (cursorRight != EMPTY) { self.nodes[cursorRight].parent = value; } self.nodes[cursor].parent = parent; if (parent == EMPTY) { self.root = cursor; } else if (value == self.nodes[parent].right) { self.nodes[parent].right = cursor; } else { self.nodes[parent].left = cursor; } self.nodes[cursor].right = value; self.nodes[value].parent = cursor; self.nodes[value].count = getNodeCount(self,self.nodes[value].left) + getNodeCount(self,self.nodes[value].right); self.nodes[cursor].count = getNodeCount(self,self.nodes[cursor].left) + getNodeCount(self,self.nodes[cursor].right); } function insertFixup(Tree storage self, uint value) private { uint cursor; while (value != self.root && self.nodes[self.nodes[value].parent].red) { uint valueParent = self.nodes[value].parent; if (valueParent == self.nodes[self.nodes[valueParent].parent].left) { cursor = self.nodes[self.nodes[valueParent].parent].right; if (self.nodes[cursor].red) { self.nodes[valueParent].red = false; self.nodes[cursor].red = false; self.nodes[self.nodes[valueParent].parent].red = true; value = self.nodes[valueParent].parent; } else { if (value == self.nodes[valueParent].right) { value = valueParent; rotateLeft(self, value); } valueParent = self.nodes[value].parent; self.nodes[valueParent].red = false; self.nodes[self.nodes[valueParent].parent].red = true; rotateRight(self, self.nodes[valueParent].parent); } } else { cursor = self.nodes[self.nodes[valueParent].parent].left; if (self.nodes[cursor].red) { self.nodes[valueParent].red = false; self.nodes[cursor].red = false; self.nodes[self.nodes[valueParent].parent].red = true; value = self.nodes[valueParent].parent; } else { if (value == self.nodes[valueParent].left) { value = valueParent; rotateRight(self, value); } valueParent = self.nodes[value].parent; self.nodes[valueParent].red = false; self.nodes[self.nodes[valueParent].parent].red = true; rotateLeft(self, self.nodes[valueParent].parent); } } } self.nodes[self.root].red = false; } function replaceParent(Tree storage self, uint a, uint b) private { uint bParent = self.nodes[b].parent; self.nodes[a].parent = bParent; if (bParent == EMPTY) { self.root = a; } else { if (b == self.nodes[bParent].left) { self.nodes[bParent].left = a; } else { self.nodes[bParent].right = a; } } } function removeFixup(Tree storage self, uint value) private { uint cursor; while (value != self.root && !self.nodes[value].red) { uint valueParent = self.nodes[value].parent; if (value == self.nodes[valueParent].left) { cursor = self.nodes[valueParent].right; if (self.nodes[cursor].red) { self.nodes[cursor].red = false; self.nodes[valueParent].red = true; rotateLeft(self, valueParent); cursor = self.nodes[valueParent].right; } if (!self.nodes[self.nodes[cursor].left].red && !self.nodes[self.nodes[cursor].right].red) { self.nodes[cursor].red = true; value = valueParent; } else { if (!self.nodes[self.nodes[cursor].right].red) { self.nodes[self.nodes[cursor].left].red = false; self.nodes[cursor].red = true; rotateRight(self, cursor); cursor = self.nodes[valueParent].right; } self.nodes[cursor].red = self.nodes[valueParent].red; self.nodes[valueParent].red = false; self.nodes[self.nodes[cursor].right].red = false; rotateLeft(self, valueParent); value = self.root; } } else { cursor = self.nodes[valueParent].left; if (self.nodes[cursor].red) { self.nodes[cursor].red = false; self.nodes[valueParent].red = true; rotateRight(self, valueParent); cursor = self.nodes[valueParent].left; } if (!self.nodes[self.nodes[cursor].right].red && !self.nodes[self.nodes[cursor].left].red) { self.nodes[cursor].red = true; value = valueParent; } else { if (!self.nodes[self.nodes[cursor].left].red) { self.nodes[self.nodes[cursor].right].red = false; self.nodes[cursor].red = true; rotateLeft(self, cursor); cursor = self.nodes[valueParent].left; } self.nodes[cursor].red = self.nodes[valueParent].red; self.nodes[valueParent].red = false; self.nodes[self.nodes[cursor].left].red = false; rotateRight(self, valueParent); value = self.root; } } } self.nodes[value].red = false; } } contract RandomNumber { using SafeMath for uint256; /* This gets a random number from 0 to max - 1, based on the blockhashes of the previous blockCount blocks. If block hash cannot be used, it will fallback ot using most recent block hash. */ function getRandomNumber( uint256 max, uint256 blockCount, uint256 lastBlockNumber) internal view returns (uint256) { //The upper bound must be positive require(max > 0); //The number of blocks to use for entropy must be positive, and less than or equal to 10. require(blockCount > 0 && blockCount <= 10); /* Each successive loop can only add on half as many as previous For example, if blockCount is 3 and max is 128, then: -the earliest block will generate number from 0 to 127 -the middle block will generate number from 0 to 63 -the most recent block (lastBlockNumber) will generate number from 0 to 31 This makes it harder for block validators to manipulate the outcome. */ uint256 divisor = 1; uint256 total = 0; //Iterate through each block for(uint256 blockNumber = lastBlockNumber.sub(blockCount).add(1); blockNumber <= lastBlockNumber; blockNumber = blockNumber.add(1)) { bytes32 hash = blockhash(blockNumber); //Fall back to using most recent block hash if(hash == bytes32(0x0) && lastBlockNumber != block.number.sub(1)) { return getRandomNumber(max, blockCount, block.number.sub(1)); } //Convert the hash to a random uint256, mod by max to get it in the range [0, max - 1) //then divide by devisor which goes up by powers of 2: 1, 2, 4, 8, etc. uint256 randomNumber = (uint256(keccak256(abi.encode(hash))) % max).div(divisor); total = total.add(randomNumber); divisor = divisor.mul(2); } return total % max; } } // SPDX-License-Identifier: Unlicensed /* This contract is used to track the balance of users in a contract. It uses the BokkyPooBah library which allows the contract to track the top 60% of wallets holding at least 2000 tokens. */ contract BalanceTracker is Ownable, HitchensOrderStatisticsTree, RandomNumber { using SafeMath for uint256; //using HitchensOrderStatisticsTreeLib for HitchensOrderStatisticsTreeLib.Tree; //Hardcode in address for the token to track, so balance can be retrieved for a given user. IERC20 public stairToken ; //Any address in this mapping is not tracked. mapping(address => bool) public ineligibleWallets; //The tree keeps track of all eligible holders in a tree data structure //HitchensOrderStatisticsTreeLib.Tree tree; //Maps an address to their balance mapping(address => uint256) public addressToValue; //Keep track of previous balances mapping(address => uint256) public addressToValuePrevious; //Maps a balance to an anddress mapping(uint256 => address) public valueToAddress; /* The value determins how many of the previous block hashes are used to generate the random number for the lottery payout. The lottery will always end at the top of an hour, and so the 8 previous blocks are used to generate random numbers. To prevent validators from manipulating the tokenHolders array in the last 8 blocks of a lottery, any new eligible holders during the last eight blocks of a lottery will always be appended to the end of the array, even if there are gaps. Also, those new users will not be eligible to win the for that hour. */ uint256 constant BLOCKS_USED_FOR_ENTROPY = 8; constructor(address tokenAddress//tmp to hardcode , address teamAddressA//tmp to hardcode , address teamAddressB//tmp to hardcode , address teamAddressC//tmp to hardcode , address presaleAddress//tmp to hardcode , address operationsAddress//tmp to hardcode , address charityAddress//tmp to hardcode ) { stairToken = IERC20(tokenAddress); ineligibleWallets[teamAddressA] = true; //tmp to hardcode ineligibleWallets[teamAddressB] = true; //tmp to hardcode ineligibleWallets[teamAddressC] = true; //tmp to hardcode ineligibleWallets[presaleAddress] = true; //tmp to hardcode ineligibleWallets[operationsAddress] = true; //tmp to hardcode ineligibleWallets[charityAddress] = true; //tmp to hardcode ineligibleWallets[tokenAddress] = true; ineligibleWallets[address(this)] = true; } //Makes the msg.sender an ineligible wallet //Any lottery contract should call this in their constructor function makeSenderIneligible() external { ineligibleWallets[msg.sender] = true; //Remove from tree if needed updateTree(msg.sender, 0); } // to use for pool function makeAddressIneligible(address addr) external { ineligibleWallets[addr] = true; //Remove from tree if needed updateTree(addr, 0); } function isAddressIneligible(address addr) external view returns(bool){ return ineligibleWallets[addr]; } function treeAbove(uint256 value) public view returns (uint256) { return above(tree, value); } function treeCount() public view returns (uint256) { return count(tree); } function treeValueAtRank(uint256 rank) public view returns (uint256) { return atRank(tree, rank); } function treeAtPercentile(uint256 percentile) public view returns (uint256) { return atPercentile(tree, percentile); } function treeRankForValue(uint256 value) public view returns (uint256) { return rank(tree, value); } function treeInsert(uint256 value) internal { insert(tree, bytes32(0x0), value); } function treeRemove(uint256 value) internal { remove(tree, bytes32(0x0), value); } /* Updates the red-black tree for new balance for user. */ function updateTree(address user, uint256 _balance) public { uint256 existing = addressToValue[user]; addressToValuePrevious[user] = existing; if(_balance == existing) { return; } if(existing > 0) { valueToAddress[existing] = address(0x0); treeRemove(existing); } //Only bother with users with a non-trivial balance //so that we can safely store them if they match other users' balances //modify stairToken if(_balance > 2000 * (10 ** stairToken.decimals())) { //Make sure the spot isn't taken uint256 iterations = 0; while(valueToAddress[_balance] != address(0x0)) { //Impossible to go to 0 due to token having 18 decimals iterations = iterations.add(1); //Randomly decrease to speed it up uint256 randomAmount = getRandomNumber(iterations, 1, block.number - 1); _balance = _balance.sub(randomAmount); } valueToAddress[_balance] = user; addressToValue[user] = _balance; treeInsert(_balance); } else { addressToValue[user] = 0; } } //Alows anyone to call this to update the tree //based on a user's current balance function updateUserBalance(address user) external { handleAddressBalanceUpdated(user, stairToken.balanceOf(user)); } //Updates the tree if the user is eligilble function handleAddressBalanceUpdated( address user, uint256 balance) internal { //If the wallet is not eligible, then they cannot be added to the data structures //and therefore cannot win if(ineligibleWallets[user]) { return; } //Call this to update the tree that contains //sorted structor of all token holders updateTree(user, balance); } //Gets a user at a given rank, which is //from 1 to count, in ascending order function getUserAtRank(uint256 rank) public view returns (address) { return valueToAddress[treeValueAtRank(rank)]; } //Returns the rank of a given user, or 0 if not found function getRankForUser(address user) public view returns (uint256) { uint256 value = addressToValue[user]; //Make sure user is in the tree if(value == 0) { return 0; } return treeRankForValue(value); } }
Convert the hash to a random uint256, mod by max to get it in the range [0, max - 1)then divide by devisor which goes up by powers of 2: 1, 2, 4, 8, etc.
uint256 randomNumber = (uint256(keccak256(abi.encode(hash))) % max).div(divisor);
13,070,411
[ 1, 2723, 326, 1651, 358, 279, 2744, 2254, 5034, 16, 681, 635, 943, 358, 336, 518, 316, 326, 1048, 306, 20, 16, 943, 300, 404, 13, 15991, 12326, 635, 443, 10227, 1492, 13998, 731, 635, 7602, 414, 434, 576, 30, 404, 16, 576, 16, 1059, 16, 1725, 16, 5527, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 5411, 2254, 5034, 2744, 1854, 273, 261, 11890, 5034, 12, 79, 24410, 581, 5034, 12, 21457, 18, 3015, 12, 2816, 20349, 738, 943, 2934, 2892, 12, 2892, 12385, 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 ]
pragma solidity ^0.4.24; // Based on https://rinkeby.etherscan.io/address/0x881544e0b2e02a79ad10b01eca51660889d5452b#code contract SparseMerkleTree { bytes32 constant LEAF_INCLUDED = 0x0000000000000000000000000000000000000000000000000000000000000001; uint8 constant DEPTH = 64; bytes32[DEPTH + 1] public defaultHashes; constructor() public { // defaultHash[0] is being set to keccak256(uint256(0)); defaultHashes[0] = 0x290decd9548b62a8d60345a988386fc84ba6bc95484008f6362f93160ef3e563; setDefaultHashes(1, DEPTH); } function checkMembership( bytes32 root, uint64 leafID, bytes proof) public view returns (bool) { bytes32 computedHash = getRoot(leafID, proof); return (computedHash == root); } // first 64 bits of the proof are the 0/1 bits function getRoot(uint64 index, bytes proof) public view returns (bytes32) { require((proof.length - 8) % 32 == 0 && proof.length <= 2056); bytes32 proofElement; bytes32 computedHash = LEAF_INCLUDED; uint16 p = 8; uint64 proofBits; assembly {proofBits := div(mload(add(proof, 32)), exp(256, 24))} for (uint d = 0; d < DEPTH; d++ ) { if (proofBits % 2 == 0) { // check if last bit of proofBits is 0 proofElement = defaultHashes[d]; } else { p += 32; require(proof.length >= p); assembly { proofElement := mload(add(proof, p)) } } if (index % 2 == 0) { computedHash = keccak256(abi.encodePacked(computedHash, proofElement)); } else { computedHash = keccak256(abi.encodePacked(proofElement, computedHash)); } proofBits = proofBits / 2; // shift it right for next bit index = index / 2; } return computedHash; } function setDefaultHashes(uint8 startIndex, uint8 endIndex) private { for (uint8 i = startIndex; i <= endIndex; i ++) { defaultHashes[i] = keccak256(abi.encodePacked(defaultHashes[i-1], defaultHashes[i-1])); } } }
check if last bit of proofBits is 0
if (proofBits % 2 == 0) {
6,459,870
[ 1, 1893, 309, 1142, 2831, 434, 14601, 6495, 353, 374, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5411, 309, 261, 24207, 6495, 738, 576, 422, 374, 13, 288, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.8; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; import "openzeppelin-solidity/contracts/ownership/Ownable.sol"; import "openzeppelin-solidity/contracts/utils/ReentrancyGuard.sol"; import "solidity-bytes-utils/contracts/BytesLib.sol"; import "./UsingLockedGold.sol"; import "./interfaces/IValidators.sol"; import "../common/Initializable.sol"; import "../common/FixidityLib.sol"; import "../common/linkedlists/AddressLinkedList.sol"; import "../common/linkedlists/AddressSortedLinkedList.sol"; /** * @title A contract for registering and electing Validator Groups and Validators. */ contract Validators is IValidators, Ownable, ReentrancyGuard, Initializable, UsingLockedGold { using FixidityLib for FixidityLib.Fraction; using AddressLinkedList for LinkedList.List; using AddressSortedLinkedList for SortedLinkedList.List; using SafeMath for uint256; using BytesLib for bytes; // TODO(asa): These strings should be modifiable struct ValidatorGroup { string identifier; string name; string url; LinkedList.List members; } // TODO(asa): These strings should be modifiable struct Validator { string identifier; string name; string url; bytes publicKeysData; address affiliation; } struct LockedGoldCommitment { uint256 noticePeriod; uint256 value; } mapping(address => ValidatorGroup) private groups; mapping(address => Validator) private validators; // TODO(asa): Implement abstaining mapping(address => address) public voters; address[] private _groups; address[] private _validators; SortedLinkedList.List private votes; // TODO(asa): Support different requirements for groups vs. validators. LockedGoldCommitment private registrationRequirement; uint256 public minElectableValidators; uint256 public maxElectableValidators; address constant PROOF_OF_POSSESSION = address(0xff - 4); event MinElectableValidatorsSet( uint256 minElectableValidators ); event MaxElectableValidatorsSet( uint256 maxElectableValidators ); event RegistrationRequirementSet( uint256 value, uint256 noticePeriod ); event ValidatorRegistered( address indexed validator, string identifier, string name, string url, bytes publicKeysData ); event ValidatorDeregistered( address indexed validator ); event ValidatorAffiliated( address indexed validator, address indexed group ); event ValidatorDeaffiliated( address indexed validator, address indexed group ); event ValidatorGroupRegistered( address indexed group, string identifier, string name, string url ); event ValidatorGroupDeregistered( address indexed group ); event ValidatorGroupMemberAdded( address indexed group, address indexed validator ); event ValidatorGroupMemberRemoved( address indexed group, address indexed validator ); event ValidatorGroupMemberReordered( address indexed group, address indexed validator ); event ValidatorGroupEmptied( address indexed group ); event ValidatorGroupVoteCast( address indexed account, address indexed group, uint256 weight ); event ValidatorGroupVoteRevoked( address indexed account, address indexed group, uint256 weight ); /** * @notice Initializes critical variables. * @param registryAddress The address of the registry contract. * @param _minElectableValidators The minimum number of validators that can be elected. * @param _maxElectableValidators The maximum number of validators that can be elected. * @param requirementValue The minimum Locked Gold commitment value to register a group or validator. * @param requirementNoticePeriod The minimum Locked Gold commitment notice period to register * a group or validator. * @dev Should be called only once. */ function initialize( address registryAddress, uint256 _minElectableValidators, uint256 _maxElectableValidators, uint256 requirementValue, uint256 requirementNoticePeriod ) external initializer { require(_minElectableValidators > 0 && _maxElectableValidators >= _minElectableValidators); _transferOwnership(msg.sender); setRegistry(registryAddress); minElectableValidators = _minElectableValidators; maxElectableValidators = _maxElectableValidators; registrationRequirement.value = requirementValue; registrationRequirement.noticePeriod = requirementNoticePeriod; } /** * @notice Updates the minimum number of validators that can be elected. * @param _minElectableValidators The minimum number of validators that can be elected. * @return True upon success. */ function setMinElectableValidators( uint256 _minElectableValidators ) external onlyOwner returns (bool) { require( _minElectableValidators > 0 && _minElectableValidators != minElectableValidators && _minElectableValidators <= maxElectableValidators ); minElectableValidators = _minElectableValidators; emit MinElectableValidatorsSet(_minElectableValidators); return true; } /** * @notice Updates the maximum number of validators that can be elected. * @param _maxElectableValidators The maximum number of validators that can be elected. * @return True upon success. */ function setMaxElectableValidators( uint256 _maxElectableValidators ) external onlyOwner returns (bool) { require( _maxElectableValidators != maxElectableValidators && _maxElectableValidators >= minElectableValidators ); maxElectableValidators = _maxElectableValidators; emit MaxElectableValidatorsSet(_maxElectableValidators); return true; } /** * @notice Updates the minimum bonding requirements to register a validator group or validator. * @param value The minimum Locked Gold commitment value to register a group or validator. * @param noticePeriod The minimum Locked Gold commitment notice period to register a group or * validator. * @return True upon success. * @dev The new requirement is only enforced for future validator or group registrations. */ function setRegistrationRequirement( uint256 value, uint256 noticePeriod ) external onlyOwner returns (bool) { require( value != registrationRequirement.value || noticePeriod != registrationRequirement.noticePeriod ); registrationRequirement.value = value; registrationRequirement.noticePeriod = noticePeriod; emit RegistrationRequirementSet(value, noticePeriod); return true; } /** * @notice Registers a validator unaffiliated with any validator group. * @param identifier An identifier for this validator. * @param name A name for the validator. * @param url A URL for the validator. * @param noticePeriod The notice period of the Locked Gold commitment that meets the * requirements for validator registration. * @param publicKeysData Comprised of three tightly-packed elements: * - publicKey - The public key that the validator is using for consensus, should match * msg.sender. 64 bytes. * - blsPublicKey - The BLS public key that the validator is using for consensus, should pass * proof of possession. 48 bytes. * - blsPoP - The BLS public key proof of possession. 96 bytes. * @return True upon success. * @dev Fails if the account is already a validator or validator group. * @dev Fails if the account does not have sufficient weight. */ function registerValidator( string calldata identifier, string calldata name, string calldata url, bytes calldata publicKeysData, uint256 noticePeriod ) external nonReentrant returns (bool) { require( bytes(identifier).length > 0 && bytes(name).length > 0 && bytes(url).length > 0 && // secp256k1 public key + BLS public key + BLS proof of possession publicKeysData.length == (64 + 48 + 96) ); bytes memory proofOfPossessionBytes = publicKeysData.slice(64, 48 + 96); require(checkProofOfPossession(proofOfPossessionBytes)); address account = getAccountFromValidator(msg.sender); require(!isValidator(account) && !isValidatorGroup(account)); require(meetsRegistrationRequirements(account, noticePeriod)); Validator memory validator = Validator(identifier, name, url, publicKeysData, address(0)); validators[account] = validator; _validators.push(account); emit ValidatorRegistered(account, identifier, name, url, publicKeysData); return true; } /** * @notice Checks a BLS proof of possession. * @param proofOfPossessionBytes The public key and signature of the proof of possession. * @return True upon success. */ function checkProofOfPossession(bytes memory proofOfPossessionBytes) private returns (bool) { bool success; (success, ) = PROOF_OF_POSSESSION.call.value(0).gas(gasleft())(proofOfPossessionBytes); return success; } /** * @notice De-registers a validator, removing it from the group for which it is a member. * @param index The index of this validator in the list of all validators. * @return True upon success. * @dev Fails if the account is not a validator. */ function deregisterValidator(uint256 index) external nonReentrant returns (bool) { address account = getAccountFromValidator(msg.sender); require(isValidator(account)); Validator storage validator = validators[account]; if (validator.affiliation != address(0)) { _deaffiliate(validator, account); } delete validators[account]; deleteElement(_validators, account, index); emit ValidatorDeregistered(account); return true; } /** * @notice Affiliates a validator with a group, allowing it to be added as a member. * @param group The validator group with which to affiliate. * @return True upon success. * @dev De-affiliates with the previously affiliated group if present. */ function affiliate(address group) external nonReentrant returns (bool) { address account = getAccountFromValidator(msg.sender); require(isValidator(account) && isValidatorGroup(group)); Validator storage validator = validators[account]; if (validator.affiliation != address(0)) { _deaffiliate(validator, account); } validator.affiliation = group; emit ValidatorAffiliated(account, group); return true; } /** * @notice De-affiliates a validator, removing it from the group for which it is a member. * @return True upon success. * @dev Fails if the account is not a validator with non-zero affiliation. */ function deaffiliate() external nonReentrant returns (bool) { address account = getAccountFromValidator(msg.sender); require(isValidator(account)); Validator storage validator = validators[account]; require(validator.affiliation != address(0)); _deaffiliate(validator, account); return true; } /** * @notice Registers a validator group with no member validators. * @param identifier A identifier for this validator group. * @param name A name for the validator group. * @param url A URL for the validator group. * @param noticePeriod The notice period of the Locked Gold commitment that meets the * requirements for validator registration. * @return True upon success. * @dev Fails if the account is already a validator or validator group. * @dev Fails if the account does not have sufficient weight. */ function registerValidatorGroup( string calldata identifier, string calldata name, string calldata url, uint256 noticePeriod ) external nonReentrant returns (bool) { require(bytes(identifier).length > 0 && bytes(name).length > 0 && bytes(url).length > 0); address account = getAccountFromValidator(msg.sender); require(!isValidator(account) && !isValidatorGroup(account)); require(meetsRegistrationRequirements(account, noticePeriod)); ValidatorGroup storage group = groups[account]; group.identifier = identifier; group.name = name; group.url = url; _groups.push(account); emit ValidatorGroupRegistered(account, identifier, name, url); return true; } /** * @notice De-registers a validator group. * @param index The index of this validator group in the list of all validator groups. * @return True upon success. * @dev Fails if the account is not a validator group with no members. */ function deregisterValidatorGroup(uint256 index) external nonReentrant returns (bool) { address account = getAccountFromValidator(msg.sender); // Only empty Validator Groups can be deregistered. require(isValidatorGroup(account) && groups[account].members.numElements == 0); delete groups[account]; deleteElement(_groups, account, index); emit ValidatorGroupDeregistered(account); return true; } /** * @notice Adds a member to the end of a validator group's list of members. * @param validator The validator to add to the group * @return True upon success. * @dev Fails if `validator` has not set their affiliation to this account. */ function addMember(address validator) external nonReentrant returns (bool) { address account = getAccountFromValidator(msg.sender); require(isValidatorGroup(account) && isValidator(validator)); ValidatorGroup storage group = groups[account]; require(validators[validator].affiliation == account && !group.members.contains(validator)); group.members.push(validator); emit ValidatorGroupMemberAdded(account, validator); return true; } /** * @notice Removes a member from a validator group. * @param validator The validator to remove from the group * @return True upon success. * @dev Fails if `validator` is not a member of the account's group. */ function removeMember(address validator) external nonReentrant returns (bool) { address account = getAccountFromValidator(msg.sender); require(isValidatorGroup(account) && isValidator(validator)); return _removeMember(account, validator); } /** * @notice Reorders a member within a validator group. * @param validator The validator to reorder. * @param lesserMember The member who will be behind `validator`, or 0 if `validator` will be the * last member. * @param greaterMember The member who will be ahead of `validator`, or 0 if `validator` will be * the first member. * @return True upon success. * @dev Fails if `validator` is not a member of the account's validator group. */ function reorderMember( address validator, address lesserMember, address greaterMember ) external nonReentrant returns (bool) { address account = getAccountFromValidator(msg.sender); require(isValidatorGroup(account) && isValidator(validator)); ValidatorGroup storage group = groups[account]; require(group.members.contains(validator)); group.members.update(validator, lesserMember, greaterMember); emit ValidatorGroupMemberReordered(account, validator); return true; } /** * @notice Casts a vote for a validator group. * @param group The validator group to vote for. * @param lesser The group receiving fewer votes than `group`, or 0 if `group` has the * fewest votes of any validator group. * @param greater The group receiving more votes than `group`, or 0 if `group` has the * most votes of any validator group. * @return True upon success. * @dev Fails if `group` is empty or not a validator group. * @dev Fails if the account is frozen. */ function vote( address group, address lesser, address greater ) external nonReentrant returns (bool) { // Empty validator groups are not electable. require(isValidatorGroup(group) && groups[group].members.numElements > 0); address account = getAccountFromVoter(msg.sender); require(!isVotingFrozen(account)); require(voters[account] == address(0)); uint256 weight = getAccountWeight(account); require(weight > 0); if (votes.contains(group)) { votes.update( group, votes.getValue(group).add(uint256(weight)), lesser, greater ); } else { votes.insert( group, weight, lesser, greater ); } voters[account] = group; emit ValidatorGroupVoteCast(account, group, weight); return true; } /** * @notice Revokes an outstanding vote for a validator group. * @param lesser The group receiving fewer votes than the group for which the vote was revoked, * or 0 if that group has the fewest votes of any validator group. * @param greater The group receiving more votes than the group for which the vote was revoked, * or 0 if that group has the most votes of any validator group. * @return True upon success. * @dev Fails if the account has not voted on a validator group. */ function revokeVote( address lesser, address greater ) external nonReentrant returns (bool) { address account = getAccountFromVoter(msg.sender); address group = voters[account]; require(group != address(0)); uint256 weight = getAccountWeight(account); // If the group we had previously voted on removed all its members it is no longer eligible // to receive votes and we don't have to worry about removing our vote. if (votes.contains(group)) { require(weight > 0); uint256 newVoteTotal = votes.getValue(group).sub(uint256(weight)); if (newVoteTotal > 0) { votes.update( group, newVoteTotal, lesser, greater ); } else { // Groups receiving no votes are not electable. votes.remove(group); } } voters[account] = address(0); emit ValidatorGroupVoteRevoked(account, group, weight); return true; } /** * @notice Returns validator information. * @param account The account that registered the validator. * @return The unpacked validator struct. */ function getValidator( address account ) external view returns ( string memory identifier, string memory name, string memory url, bytes memory publicKeysData, address affiliation ) { require(isValidator(account)); Validator storage validator = validators[account]; return ( validator.identifier, validator.name, validator.url, validator.publicKeysData, validator.affiliation ); } /** * @notice Returns validator group information. * @param account The account that registered the validator group. * @return The unpacked validator group struct. */ function getValidatorGroup( address account ) external view returns (string memory, string memory, string memory, address[] memory) { require(isValidatorGroup(account)); ValidatorGroup storage group = groups[account]; return (group.identifier, group.name, group.url, group.members.getKeys()); } /** * @notice Returns electable validator group addresses and their vote totals. * @return Electable validator group addresses and their vote totals. */ function getValidatorGroupVotes() external view returns (address[] memory, uint256[] memory) { return votes.getElements(); } /** * @notice Returns the number of votes a particular validator group has received. * @param group The account that registered the validator group. * @return The number of votes a particular validator group has received. */ function getVotesReceived(address group) external view returns (uint256) { return votes.getValue(group); } /** * @notice Returns the Locked Gold commitment requirements to register a validator or group. * @return The minimum value and notice period for the Locked Gold commitment. */ function getRegistrationRequirement() external view returns (uint256, uint256) { return (registrationRequirement.value, registrationRequirement.noticePeriod); } /** * @notice Returns the list of registered validator accounts. * @return The list of registered validator accounts. */ function getRegisteredValidators() external view returns (address[] memory) { return _validators; } /** * @notice Returns the list of registered validator group accounts. * @return The list of registered validator group addresses. */ function getRegisteredValidatorGroups() external view returns (address[] memory) { return _groups; } /** * @notice Returns whether a particular account is a registered validator or validator group. * @param account The account. * @return Whether a particular account is a registered validator or validator group. */ function isValidating(address account) external view returns (bool) { return isValidator(account) || isValidatorGroup(account); } /** * @notice Returns whether a particular account is voting for a validator group. * @param account The account. * @return Whether a particular account is voting for a validator group. */ function isVoting(address account) external view returns (bool) { return (voters[account] != address(0)); } /** * @notice Returns a list of elected validators with seats allocated to groups via the D'Hondt * method. * @return The list of elected validators. * @dev See https://en.wikipedia.org/wiki/D%27Hondt_method#Allocation for more information. */ /* solhint-disable code-complexity */ function getValidators() external view returns (address[] memory) { // Only members of these validator groups are eligible for election. uint256 numElectionGroups = maxElectableValidators; if (numElectionGroups > votes.list.numElements) { numElectionGroups = votes.list.numElements; } address[] memory electionGroups = votes.list.headN(numElectionGroups); // Holds the number of members elected for each of the eligible validator groups. uint256[] memory numMembersElected = new uint256[](electionGroups.length); uint256 totalNumMembersElected = 0; bool memberElectedInRound = true; // Assign a number of seats to each validator group. while (totalNumMembersElected < maxElectableValidators && memberElectedInRound) { memberElectedInRound = false; uint256 groupIndex = 0; FixidityLib.Fraction memory maxN = FixidityLib.wrap(0); for (uint256 i = 0; i < electionGroups.length; i = i.add(1)) { bool isWinningestGroupInRound = false; (maxN, isWinningestGroupInRound) = dHondt(maxN, electionGroups[i], numMembersElected[i]); if (isWinningestGroupInRound) { memberElectedInRound = true; groupIndex = i; } } if (memberElectedInRound) { numMembersElected[groupIndex] = numMembersElected[groupIndex].add(1); totalNumMembersElected = totalNumMembersElected.add(1); } } require(totalNumMembersElected >= minElectableValidators); // Grab the top validators from each group that won seats. address[] memory electedValidators = new address[](totalNumMembersElected); totalNumMembersElected = 0; for (uint256 i = 0; i < electionGroups.length; i = i.add(1)) { address[] memory electedGroupMembers = groups[electionGroups[i]].members.headN( numMembersElected[i] ); for (uint256 j = 0; j < electedGroupMembers.length; j = j.add(1)) { // We use the validating delegate if one is set. electedValidators[totalNumMembersElected] = getValidatorFromAccount(electedGroupMembers[j]); totalNumMembersElected = totalNumMembersElected.add(1); } } return electedValidators; } /* solhint-enable code-complexity */ /** * @notice Returns whether a particular account has a registered validator group. * @param account The account. * @return Whether a particular address is a registered validator group. */ function isValidatorGroup(address account) public view returns (bool) { return bytes(groups[account].identifier).length > 0; } /** * @notice Returns whether a particular account has a registered validator. * @param account The account. * @return Whether a particular address is a registered validator. */ function isValidator(address account) public view returns (bool) { return bytes(validators[account].identifier).length > 0; } /** * @notice Returns whether an account meets the requirements to register a validator or group. * @param account The account. * @param noticePeriod The notice period of the Locked Gold commitment that meets the * requirements. * @return Whether an account meets the requirements to register a validator or group. */ function meetsRegistrationRequirements( address account, uint256 noticePeriod ) public view returns (bool) { uint256 value = getLockedCommitmentValue(account, noticePeriod); return ( value >= registrationRequirement.value && noticePeriod >= registrationRequirement.noticePeriod ); } /** * @notice Deletes an element from a list of addresses. * @param list The list of addresses. * @param element The address to delete. * @param index The index of `element` in the list. */ function deleteElement(address[] storage list, address element, uint256 index) private { require(index < list.length && list[index] == element); uint256 lastIndex = list.length.sub(1); list[index] = list[lastIndex]; list[lastIndex] = address(0); list.length = lastIndex; } /** * @notice Removes a member from a validator group. * @param group The group from which the member should be removed. * @param validator The validator to remove from the group. * @return True upon success. * @dev If `validator` was the only member of `group`, `group` becomes unelectable. * @dev Fails if `validator` is not a member of `group`. */ function _removeMember(address group, address validator) private returns (bool) { ValidatorGroup storage _group = groups[group]; require(validators[validator].affiliation == group && _group.members.contains(validator)); _group.members.remove(validator); emit ValidatorGroupMemberRemoved(group, validator); // Empty validator groups are not electable. if (groups[group].members.numElements == 0) { if (votes.contains(group)) { votes.remove(group); } emit ValidatorGroupEmptied(group); } return true; } /** * @notice De-affiliates a validator, removing it from the group for which it is a member. * @param validator The validator to deaffiliate from their affiliated validator group. * @param validatorAccount The LockedGold account of the validator. * @return True upon success. */ function _deaffiliate( Validator storage validator, address validatorAccount ) private returns (bool) { address affiliation = validator.affiliation; ValidatorGroup storage group = groups[affiliation]; if (group.members.contains(validatorAccount)) { _removeMember(affiliation, validatorAccount); } emit ValidatorDeaffiliated(validatorAccount, affiliation); validator.affiliation = address(0); return true; } /** * @notice Runs D'Hondt for a validator group. * @param maxN The maximum number of votes per elected seat for a group in this round. * @param groupAddress The address of the validator group. * @param numMembersElected The number of members elected so far for this group. * @dev See https://en.wikipedia.org/wiki/D%27Hondt_method#Allocation for more information. * @return The new `maxN` and whether or not the group should win a seat in this round thus far. */ function dHondt( FixidityLib.Fraction memory maxN, address groupAddress, uint256 numMembersElected ) private view returns (FixidityLib.Fraction memory, bool) { ValidatorGroup storage group = groups[groupAddress]; // Only consider groups with members left to be elected. if (group.members.numElements > numMembersElected) { FixidityLib.Fraction memory n = FixidityLib.newFixed(votes.getValue(groupAddress)).divide( FixidityLib.newFixed(numMembersElected.add(1)) ); if (n.gt(maxN)) { return (n, true); } } return (maxN, false); } }
* @notice Affiliates a validator with a group, allowing it to be added as a member. @param group The validator group with which to affiliate. @return True upon success. @dev De-affiliates with the previously affiliated group if present./
function affiliate(address group) external nonReentrant returns (bool) { address account = getAccountFromValidator(msg.sender); require(isValidator(account) && isValidatorGroup(group)); Validator storage validator = validators[account]; if (validator.affiliation != address(0)) { _deaffiliate(validator, account); } validator.affiliation = group; emit ValidatorAffiliated(account, group); return true; }
5,467,105
[ 1, 13785, 15700, 815, 279, 4213, 598, 279, 1041, 16, 15632, 518, 358, 506, 3096, 487, 279, 3140, 18, 225, 1041, 1021, 4213, 1041, 598, 1492, 358, 7103, 330, 3840, 18, 327, 1053, 12318, 2216, 18, 225, 1505, 17, 7329, 15700, 815, 598, 326, 7243, 7103, 330, 10206, 1041, 309, 3430, 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, 225, 445, 7103, 330, 3840, 12, 2867, 1041, 13, 3903, 1661, 426, 8230, 970, 1135, 261, 6430, 13, 288, 203, 565, 1758, 2236, 273, 23393, 1265, 5126, 12, 3576, 18, 15330, 1769, 203, 565, 2583, 12, 291, 5126, 12, 4631, 13, 597, 4908, 639, 1114, 12, 1655, 10019, 203, 565, 9150, 2502, 4213, 273, 11632, 63, 4631, 15533, 203, 565, 309, 261, 7357, 18, 7329, 16278, 480, 1758, 12, 20, 3719, 288, 203, 1377, 389, 323, 7329, 330, 3840, 12, 7357, 16, 2236, 1769, 203, 565, 289, 203, 565, 4213, 18, 7329, 16278, 273, 1041, 31, 203, 565, 3626, 9150, 13785, 330, 10206, 12, 4631, 16, 1041, 1769, 203, 565, 327, 638, 31, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
//Address: 0x10a5f6dbd1f9e56fe09df25b1163cd299d5d2413 //Contract name: EthernautsExplore //Balance: 0.251 Ether //Verification Date: 4/24/2018 //Transacion Count: 727 // CODE STARTS HERE pragma solidity ^0.4.19; /// @title Interface for contracts conforming to ERC-721: Non-Fungible Tokens /// @author Ethernauts contract ERC721 { // Required methods function totalSupply() public view returns (uint256 total); function balanceOf(address _owner) public view returns (uint256 balance); function ownerOf(uint256 _tokenId) external view returns (address owner); function approve(address _to, uint256 _tokenId) external; function transfer(address _to, uint256 _tokenId) external; function transferFrom(address _from, address _to, uint256 _tokenId) external; function takeOwnership(uint256 _tokenId) public; function implementsERC721() public pure returns (bool); // Events event Transfer(address from, address to, uint256 tokenId); event Approval(address owner, address approved, uint256 tokenId); // Optional // function name() public view returns (string name); // function symbol() public view returns (string symbol); // function tokensOfOwner(address _owner) external view returns (uint256[] tokenIds); // function tokenMetadata(uint256 _tokenId, string _preferredTransport) public view returns (string infoUrl); // ERC-165 Compatibility (https://github.com/ethereum/EIPs/issues/165) function supportsInterface(bytes4 _interfaceID) external view returns (bool); } // Extend this library for child contracts library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } /** * @dev Compara two numbers, and return the bigger one. */ function max(int256 a, int256 b) internal pure returns (int256) { if (a > b) { return a; } else { return b; } } /** * @dev Compara two numbers, and return the bigger one. */ function min(int256 a, int256 b) internal pure returns (int256) { if (a < b) { return a; } else { return b; } } } /// @dev Base contract for all Ethernauts contracts holding global constants and functions. contract EthernautsBase { /*** CONSTANTS USED ACROSS CONTRACTS ***/ /// @dev Used by all contracts that interfaces with Ethernauts /// 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(keccak256('name()')) ^ bytes4(keccak256('symbol()')) ^ bytes4(keccak256('totalSupply()')) ^ bytes4(keccak256('balanceOf(address)')) ^ bytes4(keccak256('ownerOf(uint256)')) ^ bytes4(keccak256('approve(address,uint256)')) ^ bytes4(keccak256('transfer(address,uint256)')) ^ bytes4(keccak256('transferFrom(address,address,uint256)')) ^ bytes4(keccak256('takeOwnership(uint256)')) ^ bytes4(keccak256('tokensOfOwner(address)')) ^ bytes4(keccak256('tokenMetadata(uint256,string)')); /// @dev due solidity limitation we cannot return dynamic array from methods /// so it creates incompability between functions across different contracts uint8 public constant STATS_SIZE = 10; uint8 public constant SHIP_SLOTS = 5; // Possible state of any asset enum AssetState { Available, UpForLease, Used } // Possible state of any asset // NotValid is to avoid 0 in places where category must be bigger than zero enum AssetCategory { NotValid, Sector, Manufacturer, Ship, Object, Factory, CrewMember } /// @dev Sector stats enum ShipStats {Level, Attack, Defense, Speed, Range, Luck} /// @notice Possible attributes for each asset /// 00000001 - Seeded - Offered to the economy by us, the developers. Potentially at regular intervals. /// 00000010 - Producible - Product of a factory and/or factory contract. /// 00000100 - Explorable- Product of exploration. /// 00001000 - Leasable - Can be rented to other users and will return to the original owner once the action is complete. /// 00010000 - Permanent - Cannot be removed, always owned by a user. /// 00100000 - Consumable - Destroyed after N exploration expeditions. /// 01000000 - Tradable - Buyable and sellable on the market. /// 10000000 - Hot Potato - Automatically gets put up for sale after acquiring. bytes2 public ATTR_SEEDED = bytes2(2**0); bytes2 public ATTR_PRODUCIBLE = bytes2(2**1); bytes2 public ATTR_EXPLORABLE = bytes2(2**2); bytes2 public ATTR_LEASABLE = bytes2(2**3); bytes2 public ATTR_PERMANENT = bytes2(2**4); bytes2 public ATTR_CONSUMABLE = bytes2(2**5); bytes2 public ATTR_TRADABLE = bytes2(2**6); bytes2 public ATTR_GOLDENGOOSE = bytes2(2**7); } /// @notice This contract manages the various addresses and constraints for operations // that can be executed only by specific roles. Namely CEO and CTO. it also includes pausable pattern. contract EthernautsAccessControl is EthernautsBase { // This facet controls access control for Ethernauts. // All roles have same responsibilities and rights, but there is slight differences between them: // // - The CEO: The CEO can reassign other roles and only role that can unpause the smart contract. // It is initially set to the address that created the smart contract. // // - The CTO: The CTO can change contract address, oracle address and plan for upgrades. // // - The COO: The COO can change contract address and add create assets. // /// @dev Emited when contract is upgraded - See README.md for updgrade plan /// @param newContract address pointing to new contract event ContractUpgrade(address newContract); // The addresses of the accounts (or contracts) that can execute actions within each roles. address public ceoAddress; address public ctoAddress; address public cooAddress; address public oracleAddress; // @dev Keeps track whether the contract is paused. When that is true, most actions are blocked bool public paused = false; /// @dev Access modifier for CEO-only functionality modifier onlyCEO() { require(msg.sender == ceoAddress); _; } /// @dev Access modifier for CTO-only functionality modifier onlyCTO() { require(msg.sender == ctoAddress); _; } /// @dev Access modifier for CTO-only functionality modifier onlyOracle() { require(msg.sender == oracleAddress); _; } modifier onlyCLevel() { require( msg.sender == ceoAddress || msg.sender == ctoAddress || msg.sender == cooAddress ); _; } /// @dev Assigns a new address to act as the CEO. Only available to the current CEO. /// @param _newCEO The address of the new CEO function setCEO(address _newCEO) external onlyCEO { require(_newCEO != address(0)); ceoAddress = _newCEO; } /// @dev Assigns a new address to act as the CTO. Only available to the current CTO or CEO. /// @param _newCTO The address of the new CTO function setCTO(address _newCTO) external { require( msg.sender == ceoAddress || msg.sender == ctoAddress ); require(_newCTO != address(0)); ctoAddress = _newCTO; } /// @dev Assigns a new address to act as the COO. Only available to the current COO or CEO. /// @param _newCOO The address of the new COO function setCOO(address _newCOO) external { require( msg.sender == ceoAddress || msg.sender == cooAddress ); require(_newCOO != address(0)); cooAddress = _newCOO; } /// @dev Assigns a new address to act as oracle. /// @param _newOracle The address of oracle function setOracle(address _newOracle) external { require(msg.sender == ctoAddress); require(_newOracle != address(0)); oracleAddress = _newOracle; } /*** Pausable functionality adapted from OpenZeppelin ***/ /// @dev Modifier to allow actions only when the contract IS NOT paused modifier whenNotPaused() { require(!paused); _; } /// @dev Modifier to allow actions only when the contract IS paused modifier whenPaused { require(paused); _; } /// @dev Called by any "C-level" role to pause the contract. Used only when /// a bug or exploit is detected and we need to limit damage. function pause() external onlyCLevel whenNotPaused { paused = true; } /// @dev Unpauses the smart contract. Can only be called by the CEO, since /// one reason we may pause the contract is when CTO account is compromised. /// @notice This is public rather than external so it can be called by /// derived contracts. function unpause() public onlyCEO whenPaused { // can't unpause if contract was upgraded paused = false; } } /// @title Storage contract for Ethernauts Data. Common structs and constants. /// @notice This is our main data storage, constants and data types, plus // internal functions for managing the assets. It is isolated and only interface with // a list of granted contracts defined by CTO /// @author Ethernauts - Fernando Pauer contract EthernautsStorage is EthernautsAccessControl { function EthernautsStorage() public { // the creator of the contract is the initial CEO ceoAddress = msg.sender; // the creator of the contract is the initial CTO as well ctoAddress = msg.sender; // the creator of the contract is the initial CTO as well cooAddress = msg.sender; // the creator of the contract is the initial Oracle as well oracleAddress = msg.sender; } /// @notice No tipping! /// @dev Reject all Ether from being sent here. Hopefully, we can prevent user accidents. function() external payable { require(msg.sender == address(this)); } /*** Mapping for Contracts with granted permission ***/ mapping (address => bool) public contractsGrantedAccess; /// @dev grant access for a contract to interact with this contract. /// @param _v2Address The contract address to grant access function grantAccess(address _v2Address) public onlyCTO { // See README.md for updgrade plan contractsGrantedAccess[_v2Address] = true; } /// @dev remove access from a contract to interact with this contract. /// @param _v2Address The contract address to be removed function removeAccess(address _v2Address) public onlyCTO { // See README.md for updgrade plan delete contractsGrantedAccess[_v2Address]; } /// @dev Only allow permitted contracts to interact with this contract modifier onlyGrantedContracts() { require(contractsGrantedAccess[msg.sender] == true); _; } modifier validAsset(uint256 _tokenId) { require(assets[_tokenId].ID > 0); _; } /*** DATA TYPES ***/ /// @dev The main Ethernauts asset struct. Every asset in Ethernauts is represented by a copy /// of this structure. Note that the order of the members in this structure /// is important because of the byte-packing rules used by Ethereum. /// Ref: http://solidity.readthedocs.io/en/develop/miscellaneous.html struct Asset { // Asset ID is a identifier for look and feel in frontend uint16 ID; // Category = Sectors, Manufacturers, Ships, Objects (Upgrades/Misc), Factories and CrewMembers uint8 category; // The State of an asset: Available, On sale, Up for lease, Cooldown, Exploring uint8 state; // Attributes // byte pos - Definition // 00000001 - Seeded - Offered to the economy by us, the developers. Potentially at regular intervals. // 00000010 - Producible - Product of a factory and/or factory contract. // 00000100 - Explorable- Product of exploration. // 00001000 - Leasable - Can be rented to other users and will return to the original owner once the action is complete. // 00010000 - Permanent - Cannot be removed, always owned by a user. // 00100000 - Consumable - Destroyed after N exploration expeditions. // 01000000 - Tradable - Buyable and sellable on the market. // 10000000 - Hot Potato - Automatically gets put up for sale after acquiring. bytes2 attributes; // The timestamp from the block when this asset was created. uint64 createdAt; // The minimum timestamp after which this asset can engage in exploring activities again. uint64 cooldownEndBlock; // The Asset's stats can be upgraded or changed based on exploration conditions. // It will be defined per child contract, but all stats have a range from 0 to 255 // Examples // 0 = Ship Level // 1 = Ship Attack uint8[STATS_SIZE] stats; // Set to the cooldown time that represents exploration duration for this asset. // Defined by a successful exploration action, regardless of whether this asset is acting as ship or a part. uint256 cooldown; // a reference to a super asset that manufactured the asset uint256 builtBy; } /*** CONSTANTS ***/ // @dev Sanity check that allows us to ensure that we are pointing to the // right storage contract in our EthernautsLogic(address _CStorageAddress) call. bool public isEthernautsStorage = true; /*** STORAGE ***/ /// @dev An array containing the Asset struct for all assets in existence. The Asset UniqueId /// of each asset is actually an index into this array. Asset[] public assets; /// @dev A mapping from Asset UniqueIDs to the price of the token. /// stored outside Asset Struct to save gas, because price can change frequently mapping (uint256 => uint256) internal assetIndexToPrice; /// @dev A mapping from asset UniqueIDs to the address that owns them. All assets have some valid owner address. mapping (uint256 => address) internal assetIndexToOwner; // @dev A mapping from owner address to count of tokens that address owns. // Used internally inside balanceOf() to resolve ownership count. mapping (address => uint256) internal ownershipTokenCount; /// @dev A mapping from AssetUniqueIDs to an address that has been approved to call /// transferFrom(). Each Asset can only have one approved address for transfer /// at any time. A zero value means no approval is outstanding. mapping (uint256 => address) internal assetIndexToApproved; /*** SETTERS ***/ /// @dev set new asset price /// @param _tokenId asset UniqueId /// @param _price asset price function setPrice(uint256 _tokenId, uint256 _price) public onlyGrantedContracts { assetIndexToPrice[_tokenId] = _price; } /// @dev Mark transfer as approved /// @param _tokenId asset UniqueId /// @param _approved address approved function approve(uint256 _tokenId, address _approved) public onlyGrantedContracts { assetIndexToApproved[_tokenId] = _approved; } /// @dev Assigns ownership of a specific Asset to an address. /// @param _from current owner address /// @param _to new owner address /// @param _tokenId asset UniqueId function transfer(address _from, address _to, uint256 _tokenId) public onlyGrantedContracts { // Since the number of assets is capped to 2^32 we can't overflow this ownershipTokenCount[_to]++; // transfer ownership assetIndexToOwner[_tokenId] = _to; // When creating new assets _from is 0x0, but we can't account that address. if (_from != address(0)) { ownershipTokenCount[_from]--; // clear any previously approved ownership exchange delete assetIndexToApproved[_tokenId]; } } /// @dev A public method that creates a new asset and stores it. This /// method does basic checking and should only be called from other contract when the /// input data is known to be valid. Will NOT generate any event it is delegate to business logic contracts. /// @param _creatorTokenID The asset who is father of this asset /// @param _owner First owner of this asset /// @param _price asset price /// @param _ID asset ID /// @param _category see Asset Struct description /// @param _state see Asset Struct description /// @param _attributes see Asset Struct description /// @param _stats see Asset Struct description function createAsset( uint256 _creatorTokenID, address _owner, uint256 _price, uint16 _ID, uint8 _category, uint8 _state, uint8 _attributes, uint8[STATS_SIZE] _stats, uint256 _cooldown, uint64 _cooldownEndBlock ) public onlyGrantedContracts returns (uint256) { // Ensure our data structures are always valid. require(_ID > 0); require(_category > 0); require(_attributes != 0x0); require(_stats.length > 0); Asset memory asset = Asset({ ID: _ID, category: _category, builtBy: _creatorTokenID, attributes: bytes2(_attributes), stats: _stats, state: _state, createdAt: uint64(now), cooldownEndBlock: _cooldownEndBlock, cooldown: _cooldown }); uint256 newAssetUniqueId = assets.push(asset) - 1; // Check it reached 4 billion assets but let's just be 100% sure. require(newAssetUniqueId == uint256(uint32(newAssetUniqueId))); // store price assetIndexToPrice[newAssetUniqueId] = _price; // This will assign ownership transfer(address(0), _owner, newAssetUniqueId); return newAssetUniqueId; } /// @dev A public method that edit asset in case of any mistake is done during process of creation by the developer. This /// This method doesn't do any checking and should only be called when the /// input data is known to be valid. /// @param _tokenId The token ID /// @param _creatorTokenID The asset that create that token /// @param _price asset price /// @param _ID asset ID /// @param _category see Asset Struct description /// @param _state see Asset Struct description /// @param _attributes see Asset Struct description /// @param _stats see Asset Struct description /// @param _cooldown asset cooldown index function editAsset( uint256 _tokenId, uint256 _creatorTokenID, uint256 _price, uint16 _ID, uint8 _category, uint8 _state, uint8 _attributes, uint8[STATS_SIZE] _stats, uint16 _cooldown ) external validAsset(_tokenId) onlyCLevel returns (uint256) { // Ensure our data structures are always valid. require(_ID > 0); require(_category > 0); require(_attributes != 0x0); require(_stats.length > 0); // store price assetIndexToPrice[_tokenId] = _price; Asset storage asset = assets[_tokenId]; asset.ID = _ID; asset.category = _category; asset.builtBy = _creatorTokenID; asset.attributes = bytes2(_attributes); asset.stats = _stats; asset.state = _state; asset.cooldown = _cooldown; } /// @dev Update only stats /// @param _tokenId asset UniqueId /// @param _stats asset state, see Asset Struct description function updateStats(uint256 _tokenId, uint8[STATS_SIZE] _stats) public validAsset(_tokenId) onlyGrantedContracts { assets[_tokenId].stats = _stats; } /// @dev Update only asset state /// @param _tokenId asset UniqueId /// @param _state asset state, see Asset Struct description function updateState(uint256 _tokenId, uint8 _state) public validAsset(_tokenId) onlyGrantedContracts { assets[_tokenId].state = _state; } /// @dev Update Cooldown for a single asset /// @param _tokenId asset UniqueId /// @param _cooldown asset state, see Asset Struct description function setAssetCooldown(uint256 _tokenId, uint256 _cooldown, uint64 _cooldownEndBlock) public validAsset(_tokenId) onlyGrantedContracts { assets[_tokenId].cooldown = _cooldown; assets[_tokenId].cooldownEndBlock = _cooldownEndBlock; } /*** GETTERS ***/ /// @notice Returns only stats data about a specific asset. /// @dev it is necessary due solidity compiler limitations /// when we have large qty of parameters it throws StackTooDeepException /// @param _tokenId The UniqueId of the asset of interest. function getStats(uint256 _tokenId) public view returns (uint8[STATS_SIZE]) { return assets[_tokenId].stats; } /// @dev return current price of an asset /// @param _tokenId asset UniqueId function priceOf(uint256 _tokenId) public view returns (uint256 price) { return assetIndexToPrice[_tokenId]; } /// @notice Check if asset has all attributes passed by parameter /// @param _tokenId The UniqueId of the asset of interest. /// @param _attributes see Asset Struct description function hasAllAttrs(uint256 _tokenId, bytes2 _attributes) public view returns (bool) { return assets[_tokenId].attributes & _attributes == _attributes; } /// @notice Check if asset has any attribute passed by parameter /// @param _tokenId The UniqueId of the asset of interest. /// @param _attributes see Asset Struct description function hasAnyAttrs(uint256 _tokenId, bytes2 _attributes) public view returns (bool) { return assets[_tokenId].attributes & _attributes != 0x0; } /// @notice Check if asset is in the state passed by parameter /// @param _tokenId The UniqueId of the asset of interest. /// @param _category see AssetCategory in EthernautsBase for possible states function isCategory(uint256 _tokenId, uint8 _category) public view returns (bool) { return assets[_tokenId].category == _category; } /// @notice Check if asset is in the state passed by parameter /// @param _tokenId The UniqueId of the asset of interest. /// @param _state see enum AssetState in EthernautsBase for possible states function isState(uint256 _tokenId, uint8 _state) public view returns (bool) { return assets[_tokenId].state == _state; } /// @notice Returns owner of a given Asset(Token). /// @dev Required for ERC-721 compliance. /// @param _tokenId asset UniqueId function ownerOf(uint256 _tokenId) public view returns (address owner) { return assetIndexToOwner[_tokenId]; } /// @dev Required for ERC-721 compliance /// @notice Returns the number of Assets owned by a specific address. /// @param _owner The owner address to check. function balanceOf(address _owner) public view returns (uint256 count) { return ownershipTokenCount[_owner]; } /// @dev Checks if a given address currently has transferApproval for a particular Asset. /// @param _tokenId asset UniqueId function approvedFor(uint256 _tokenId) public view onlyGrantedContracts returns (address) { return assetIndexToApproved[_tokenId]; } /// @notice Returns the total number of Assets currently in existence. /// @dev Required for ERC-721 compliance. function totalSupply() public view returns (uint256) { return assets.length; } /// @notice List all existing tokens. It can be filtered by attributes or assets with owner /// @param _owner filter all assets by owner function getTokenList(address _owner, uint8 _withAttributes, uint256 start, uint256 count) external view returns( uint256[6][] ) { uint256 totalAssets = assets.length; if (totalAssets == 0) { // Return an empty array return new uint256[6][](0); } else { uint256[6][] memory result = new uint256[6][](totalAssets > count ? count : totalAssets); uint256 resultIndex = 0; bytes2 hasAttributes = bytes2(_withAttributes); Asset memory asset; for (uint256 tokenId = start; tokenId < totalAssets && resultIndex < count; tokenId++) { asset = assets[tokenId]; if ( (asset.state != uint8(AssetState.Used)) && (assetIndexToOwner[tokenId] == _owner || _owner == address(0)) && (asset.attributes & hasAttributes == hasAttributes) ) { result[resultIndex][0] = tokenId; result[resultIndex][1] = asset.ID; result[resultIndex][2] = asset.category; result[resultIndex][3] = uint256(asset.attributes); result[resultIndex][4] = asset.cooldown; result[resultIndex][5] = assetIndexToPrice[tokenId]; resultIndex++; } } return result; } } } /// @title The facet of the Ethernauts contract that manages ownership, ERC-721 compliant. /// @notice This provides the methods required for basic non-fungible token // transactions, following the draft ERC-721 spec (https://github.com/ethereum/EIPs/issues/721). // It interfaces with EthernautsStorage provinding basic functions as create and list, also holds // reference to logic contracts as Auction, Explore and so on /// @author Ethernatus - Fernando Pauer /// @dev Ref: https://github.com/ethereum/EIPs/issues/721 contract EthernautsOwnership is EthernautsAccessControl, ERC721 { /// @dev Contract holding only data. EthernautsStorage public ethernautsStorage; /*** CONSTANTS ***/ /// @notice Name and symbol of the non fungible token, as defined in ERC721. string public constant name = "Ethernauts"; string public constant symbol = "ETNT"; /********* ERC 721 - COMPLIANCE CONSTANTS AND FUNCTIONS ***************/ /**********************************************************************/ bytes4 constant InterfaceSignature_ERC165 = bytes4(keccak256('supportsInterface(bytes4)')); /*** EVENTS ***/ // Events as per ERC-721 event Transfer(address indexed from, address indexed to, uint256 tokens); event Approval(address indexed owner, address indexed approved, uint256 tokens); /// @dev When a new asset is create it emits build event /// @param owner The address of asset owner /// @param tokenId Asset UniqueID /// @param assetId ID that defines asset look and feel /// @param price asset price event Build(address owner, uint256 tokenId, uint16 assetId, uint256 price); function implementsERC721() public pure returns (bool) { return true; } /// @notice Introspection interface as per ERC-165 (https://github.com/ethereum/EIPs/issues/165). /// Returns true for any standardized interfaces implemented by this contract. ERC-165 and ERC-721. /// @param _interfaceID interface signature ID function supportsInterface(bytes4 _interfaceID) external view returns (bool) { return ((_interfaceID == InterfaceSignature_ERC165) || (_interfaceID == InterfaceSignature_ERC721)); } /// @dev Checks if a given address is the current owner of a particular Asset. /// @param _claimant the address we are validating against. /// @param _tokenId asset UniqueId, only valid when > 0 function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { return ethernautsStorage.ownerOf(_tokenId) == _claimant; } /// @dev Checks if a given address currently has transferApproval for a particular Asset. /// @param _claimant the address we are confirming asset is approved for. /// @param _tokenId asset UniqueId, only valid when > 0 function _approvedFor(address _claimant, uint256 _tokenId) internal view returns (bool) { return ethernautsStorage.approvedFor(_tokenId) == _claimant; } /// @dev Marks an address as being approved for transferFrom(), overwriting any previous /// approval. Setting _approved to address(0) clears all transfer approval. /// NOTE: _approve() does NOT send the Approval event. This is intentional because /// _approve() and transferFrom() are used together for putting Assets on auction, and /// there is no value in spamming the log with Approval events in that case. function _approve(uint256 _tokenId, address _approved) internal { ethernautsStorage.approve(_tokenId, _approved); } /// @notice Returns the number of Assets owned by a specific address. /// @param _owner The owner address to check. /// @dev Required for ERC-721 compliance function balanceOf(address _owner) public view returns (uint256 count) { return ethernautsStorage.balanceOf(_owner); } /// @dev Required for ERC-721 compliance. /// @notice Transfers a Asset to another address. If transferring to a smart /// contract be VERY CAREFUL to ensure that it is aware of ERC-721 (or /// Ethernauts specifically) or your Asset may be lost forever. Seriously. /// @param _to The address of the recipient, can be a user or contract. /// @param _tokenId The ID of the Asset to transfer. function transfer( address _to, uint256 _tokenId ) external whenNotPaused { // Safety check to prevent against an unexpected 0x0 default. require(_to != address(0)); // Disallow transfers to this contract to prevent accidental misuse. // The contract should never own any assets // (except very briefly after it is created and before it goes on auction). require(_to != address(this)); // Disallow transfers to the storage contract to prevent accidental // misuse. Auction or Upgrade contracts should only take ownership of assets // through the allow + transferFrom flow. require(_to != address(ethernautsStorage)); // You can only send your own asset. require(_owns(msg.sender, _tokenId)); // Reassign ownership, clear pending approvals, emit Transfer event. ethernautsStorage.transfer(msg.sender, _to, _tokenId); } /// @dev Required for ERC-721 compliance. /// @notice Grant another address the right to transfer a specific Asset via /// transferFrom(). This is the preferred flow for transfering NFTs to contracts. /// @param _to The address to be granted transfer approval. Pass address(0) to /// clear all approvals. /// @param _tokenId The ID of the Asset that can be transferred if this call succeeds. function approve( address _to, uint256 _tokenId ) external whenNotPaused { // Only an owner can grant transfer approval. require(_owns(msg.sender, _tokenId)); // Register the approval (replacing any previous approval). _approve(_tokenId, _to); // Emit approval event. Approval(msg.sender, _to, _tokenId); } /// @notice Transfer a Asset owned by another address, for which the calling address /// has previously been granted transfer approval by the owner. /// @param _from The address that owns the Asset to be transferred. /// @param _to The address that should take ownership of the Asset. Can be any address, /// including the caller. /// @param _tokenId The ID of the Asset to be transferred. function _transferFrom( address _from, address _to, uint256 _tokenId ) internal { // Safety check to prevent against an unexpected 0x0 default. require(_to != address(0)); // Disallow transfers to this contract to prevent accidental misuse. // The contract should never own any assets (except for used assets). require(_owns(_from, _tokenId)); // Check for approval and valid ownership require(_approvedFor(_to, _tokenId)); // Reassign ownership (also clears pending approvals and emits Transfer event). ethernautsStorage.transfer(_from, _to, _tokenId); } /// @dev Required for ERC-721 compliance. /// @notice Transfer a Asset owned by another address, for which the calling address /// has previously been granted transfer approval by the owner. /// @param _from The address that owns the Asset to be transfered. /// @param _to The address that should take ownership of the Asset. Can be any address, /// including the caller. /// @param _tokenId The ID of the Asset to be transferred. function transferFrom( address _from, address _to, uint256 _tokenId ) external whenNotPaused { _transferFrom(_from, _to, _tokenId); } /// @dev Required for ERC-721 compliance. /// @notice Allow pre-approved user to take ownership of a token /// @param _tokenId The ID of the Token that can be transferred if this call succeeds. function takeOwnership(uint256 _tokenId) public { address _from = ethernautsStorage.ownerOf(_tokenId); // Safety check to prevent against an unexpected 0x0 default. require(_from != address(0)); _transferFrom(_from, msg.sender, _tokenId); } /// @notice Returns the total number of Assets currently in existence. /// @dev Required for ERC-721 compliance. function totalSupply() public view returns (uint256) { return ethernautsStorage.totalSupply(); } /// @notice Returns owner of a given Asset(Token). /// @param _tokenId Token ID to get owner. /// @dev Required for ERC-721 compliance. function ownerOf(uint256 _tokenId) external view returns (address owner) { owner = ethernautsStorage.ownerOf(_tokenId); require(owner != address(0)); } /// @dev Creates a new Asset with the given fields. ONly available for C Levels /// @param _creatorTokenID The asset who is father of this asset /// @param _price asset price /// @param _assetID asset ID /// @param _category see Asset Struct description /// @param _attributes see Asset Struct description /// @param _stats see Asset Struct description function createNewAsset( uint256 _creatorTokenID, address _owner, uint256 _price, uint16 _assetID, uint8 _category, uint8 _attributes, uint8[STATS_SIZE] _stats ) external onlyCLevel returns (uint256) { // owner must be sender require(_owner != address(0)); uint256 tokenID = ethernautsStorage.createAsset( _creatorTokenID, _owner, _price, _assetID, _category, uint8(AssetState.Available), _attributes, _stats, 0, 0 ); // emit the build event Build( _owner, tokenID, _assetID, _price ); return tokenID; } /// @notice verify if token is in exploration time /// @param _tokenId The Token ID that can be upgraded function isExploring(uint256 _tokenId) public view returns (bool) { uint256 cooldown; uint64 cooldownEndBlock; (,,,,,cooldownEndBlock, cooldown,) = ethernautsStorage.assets(_tokenId); return (cooldown > now) || (cooldownEndBlock > uint64(block.number)); } } /// @title The facet of the Ethernauts Logic contract handle all common code for logic/business contracts /// @author Ethernatus - Fernando Pauer contract EthernautsLogic is EthernautsOwnership { // Set in case the logic contract is broken and an upgrade is required address public newContractAddress; /// @dev Constructor function EthernautsLogic() public { // the creator of the contract is the initial CEO, COO, CTO ceoAddress = msg.sender; ctoAddress = msg.sender; cooAddress = msg.sender; oracleAddress = msg.sender; // Starts paused. paused = true; } /// @dev Used to mark the smart contract as upgraded, in case there is a serious /// breaking bug. This method does nothing but keep track of the new contract and /// emit a message indicating that the new address is set. It's up to clients of this /// contract to update to the new contract address in that case. (This contract will /// be paused indefinitely if such an upgrade takes place.) /// @param _v2Address new address function setNewAddress(address _v2Address) external onlyCTO whenPaused { // See README.md for updgrade plan newContractAddress = _v2Address; ContractUpgrade(_v2Address); } /// @dev set a new reference to the NFT ownership contract /// @param _CStorageAddress - address of a deployed contract implementing EthernautsStorage. function setEthernautsStorageContract(address _CStorageAddress) public onlyCLevel whenPaused { EthernautsStorage candidateContract = EthernautsStorage(_CStorageAddress); require(candidateContract.isEthernautsStorage()); ethernautsStorage = candidateContract; } /// @dev Override unpause so it requires all external contract addresses /// to be set before contract can be unpaused. Also, we can't have /// newContractAddress set either, because then the contract was upgraded. /// @notice This is public rather than external so we can call super.unpause /// without using an expensive CALL. function unpause() public onlyCEO whenPaused { require(ethernautsStorage != address(0)); require(newContractAddress == address(0)); // require this contract to have access to storage contract require(ethernautsStorage.contractsGrantedAccess(address(this)) == true); // Actually unpause the contract. super.unpause(); } // @dev Allows the COO to capture the balance available to the contract. function withdrawBalances(address _to) public onlyCLevel { _to.transfer(this.balance); } /// return current contract balance function getBalance() public view onlyCLevel returns (uint256) { return this.balance; } } /// @title The facet of the Ethernauts Explore contract that send a ship to explore the deep space. /// @notice An owned ship can be send on an expedition. Exploration takes time // and will always result in “success”. This means the ship can never be destroyed // and always returns with a collection of loot. The degree of success is dependent // on different factors as sector stats, gamma ray burst number and ship stats. // While the ship is exploring it cannot be acted on in any way until the expedition completes. // After the ship returns from an expedition the user is then rewarded with a number of objects (assets). /// @author Ethernatus - Fernando Pauer contract EthernautsExplore is EthernautsLogic { /// @dev Delegate constructor to Nonfungible contract. function EthernautsExplore() public EthernautsLogic() {} /*** EVENTS ***/ /// emit signal to anyone listening in the universe event Explore(uint256 shipId, uint256 sectorID, uint256 crewId, uint256 time); event Result(uint256 shipId, uint256 sectorID); /*** CONSTANTS ***/ uint8 constant STATS_CAPOUT = 2**8 - 1; // all stats have a range from 0 to 255 // @dev Sanity check that allows us to ensure that we are pointing to the // right explore contract in our EthernautsCrewMember(address _CExploreAddress) call. bool public isEthernautsExplore = true; // An approximation of currently how many seconds are in between blocks. uint256 public secondsPerBlock = 15; uint256 public TICK_TIME = 15; // time is always in minutes // exploration fee uint256 public percentageCut = 90; int256 public SPEED_STAT_MAX = 30; int256 public RANGE_STAT_MAX = 20; int256 public MIN_TIME_EXPLORE = 60; int256 public MAX_TIME_EXPLORE = 2160; int256 public RANGE_SCALE = 2; /// @dev Sector stats enum SectorStats {Size, Threat, Difficulty, Slots} /// @dev hold all ships in exploration uint256[] explorers; /// @dev A mapping from Ship token to the exploration index. mapping (uint256 => uint256) public tokenIndexToExplore; /// @dev A mapping from Asset UniqueIDs to the sector token id. mapping (uint256 => uint256) public tokenIndexToSector; /// @dev A mapping from exploration index to the crew token id. mapping (uint256 => uint256) public exploreIndexToCrew; /// @dev A mission counter for crew. mapping (uint256 => uint16) public missions; /// @dev A mapping from Owner Cut (wei) to the sector token id. mapping (uint256 => uint256) public sectorToOwnerCut; mapping (uint256 => uint256) public sectorToOracleFee; /// @dev Get a list of ship exploring our universe function getExplorerList() public view returns( uint256[3][] ) { uint256[3][] memory tokens = new uint256[3][](50); uint256 index = 0; for(uint256 i = 0; i < explorers.length && index < 50; i++) { if (explorers[i] > 0) { tokens[index][0] = explorers[i]; tokens[index][1] = tokenIndexToSector[explorers[i]]; tokens[index][2] = exploreIndexToCrew[i]; index++; } } if (index == 0) { // Return an empty array return new uint256[3][](0); } else { return tokens; } } /// @dev Get a list of ship exploring our universe /// @param _shipTokenId The Token ID that represents a ship function getIndexByShip(uint256 _shipTokenId) public view returns( uint256 ) { for(uint256 i = 0; i < explorers.length; i++) { if (explorers[i] == _shipTokenId) { return i; } } return 0; } function setOwnerCut(uint256 _sectorId, uint256 _ownerCut) external onlyCLevel { sectorToOwnerCut[_sectorId] = _ownerCut; } function setOracleFee(uint256 _sectorId, uint256 _oracleFee) external onlyCLevel { sectorToOracleFee[_sectorId] = _oracleFee; } function setTickTime(uint256 _tickTime) external onlyCLevel { TICK_TIME = _tickTime; } function setPercentageCut(uint256 _percentageCut) external onlyCLevel { percentageCut = _percentageCut; } function setMissions(uint256 _tokenId, uint16 _total) public onlyCLevel { missions[_tokenId] = _total; } /// @notice Explore a sector with a defined ship. Sectors contain a list of Objects that can be given to the players /// when exploring. Each entry has a Drop Rate and are sorted by Sector ID and Drop rate. /// The drop rate is a whole number between 0 and 1,000,000. 0 is 0% and 1,000,000 is 100%. /// Every time a Sector is explored a random number between 0 and 1,000,000 is calculated for each available Object. /// If the final result is lower than the Drop Rate of the Object, that Object will be rewarded to the player once /// Exploration is complete. Only 1 to 5 Objects maximum can be dropped during one exploration. /// (FUTURE VERSIONS) The final number will be affected by the user’s Ship Stats. /// @param _shipTokenId The Token ID that represents a ship /// @param _sectorTokenId The Token ID that represents a sector /// @param _crewTokenId The Token ID that represents a crew function explore(uint256 _shipTokenId, uint256 _sectorTokenId, uint256 _crewTokenId) payable external whenNotPaused { // charge a fee for each exploration when the results are ready require(msg.value >= sectorToOwnerCut[_sectorTokenId]); // check if Asset is a ship or not require(ethernautsStorage.isCategory(_shipTokenId, uint8(AssetCategory.Ship))); // check if _sectorTokenId is a sector or not require(ethernautsStorage.isCategory(_sectorTokenId, uint8(AssetCategory.Sector))); // Ensure the Ship is in available state, otherwise it cannot explore require(ethernautsStorage.isState(_shipTokenId, uint8(AssetState.Available))); // ship could not be in exploration require(tokenIndexToExplore[_shipTokenId] == 0); require(!isExploring(_shipTokenId)); // check if explorer is ship owner require(msg.sender == ethernautsStorage.ownerOf(_shipTokenId)); // check if owner sector is not empty address sectorOwner = ethernautsStorage.ownerOf(_sectorTokenId); // check if there is a crew and validating crew member if (_crewTokenId > 0) { // crew member should not be in exploration require(!isExploring(_crewTokenId)); // check if Asset is a crew or not require(ethernautsStorage.isCategory(_crewTokenId, uint8(AssetCategory.CrewMember))); // check if crew member is same owner require(msg.sender == ethernautsStorage.ownerOf(_crewTokenId)); } /// store exploration data tokenIndexToExplore[_shipTokenId] = explorers.push(_shipTokenId) - 1; tokenIndexToSector[_shipTokenId] = _sectorTokenId; uint8[STATS_SIZE] memory _shipStats = ethernautsStorage.getStats(_shipTokenId); uint8[STATS_SIZE] memory _sectorStats = ethernautsStorage.getStats(_sectorTokenId); // check if there is a crew and store data and change ship stats if (_crewTokenId > 0) { /// store crew exploration data exploreIndexToCrew[tokenIndexToExplore[_shipTokenId]] = _crewTokenId; missions[_crewTokenId]++; //// grab crew stats and merge with ship uint8[STATS_SIZE] memory _crewStats = ethernautsStorage.getStats(_crewTokenId); _shipStats[uint256(ShipStats.Range)] += _crewStats[uint256(ShipStats.Range)]; _shipStats[uint256(ShipStats.Speed)] += _crewStats[uint256(ShipStats.Speed)]; if (_shipStats[uint256(ShipStats.Range)] > STATS_CAPOUT) { _shipStats[uint256(ShipStats.Range)] = STATS_CAPOUT; } if (_shipStats[uint256(ShipStats.Speed)] > STATS_CAPOUT) { _shipStats[uint256(ShipStats.Speed)] = STATS_CAPOUT; } } /// set exploration time uint256 time = uint256(_explorationTime( _shipStats[uint256(ShipStats.Range)], _shipStats[uint256(ShipStats.Speed)], _sectorStats[uint256(SectorStats.Size)] )); // exploration time in minutes converted to seconds time *= 60; uint64 _cooldownEndBlock = uint64((time/secondsPerBlock) + block.number); ethernautsStorage.setAssetCooldown(_shipTokenId, now + time, _cooldownEndBlock); // check if there is a crew store data and set crew exploration time if (_crewTokenId > 0) { /// store crew exploration time ethernautsStorage.setAssetCooldown(_crewTokenId, now + time, _cooldownEndBlock); } // to avoid mistakes and charge unnecessary extra fees uint256 feeExcess = SafeMath.sub(msg.value, sectorToOwnerCut[_sectorTokenId]); uint256 payment = uint256(SafeMath.div(SafeMath.mul(msg.value, percentageCut), 100)) - sectorToOracleFee[_sectorTokenId]; /// emit signal to anyone listening in the universe Explore(_shipTokenId, _sectorTokenId, _crewTokenId, now + time); // keeping oracle accounts with balance oracleAddress.transfer(sectorToOracleFee[_sectorTokenId]); // paying sector owner sectorOwner.transfer(payment); // send excess back to explorer msg.sender.transfer(feeExcess); } /// @notice Exploration is complete and at most 10 Objects will return during one exploration. /// @param _shipTokenId The Token ID that represents a ship and can explore /// @param _sectorTokenId The Token ID that represents a sector and can be explored /// @param _IDs that represents a object returned from exploration /// @param _attributes that represents attributes for each object returned from exploration /// @param _stats that represents all stats for each object returned from exploration function explorationResults( uint256 _shipTokenId, uint256 _sectorTokenId, uint16[10] _IDs, uint8[10] _attributes, uint8[STATS_SIZE][10] _stats ) external onlyOracle { uint256 cooldown; uint64 cooldownEndBlock; uint256 builtBy; (,,,,,cooldownEndBlock, cooldown, builtBy) = ethernautsStorage.assets(_shipTokenId); address owner = ethernautsStorage.ownerOf(_shipTokenId); require(owner != address(0)); /// create objects returned from exploration uint256 i = 0; for (i = 0; i < 10 && _IDs[i] > 0; i++) { _buildAsset( _sectorTokenId, owner, 0, _IDs[i], uint8(AssetCategory.Object), uint8(_attributes[i]), _stats[i], cooldown, cooldownEndBlock ); } // to guarantee at least 1 result per exploration require(i > 0); /// remove from explore list explorers[tokenIndexToExplore[_shipTokenId]] = 0; delete tokenIndexToExplore[_shipTokenId]; delete tokenIndexToSector[_shipTokenId]; /// emit signal to anyone listening in the universe Result(_shipTokenId, _sectorTokenId); } /// @notice Cancel ship exploration in case it get stuck /// @param _shipTokenId The Token ID that represents a ship and can explore function cancelExplorationByShip( uint256 _shipTokenId ) external onlyCLevel { uint256 index = tokenIndexToExplore[_shipTokenId]; if (index > 0) { /// remove from explore list explorers[index] = 0; if (exploreIndexToCrew[index] > 0) { delete exploreIndexToCrew[index]; } } delete tokenIndexToExplore[_shipTokenId]; delete tokenIndexToSector[_shipTokenId]; } /// @notice Cancel exploration in case it get stuck /// @param _index The exploration position that represents a exploring ship function cancelExplorationByIndex( uint256 _index ) external onlyCLevel { uint256 shipId = explorers[_index]; /// remove from exploration list explorers[_index] = 0; if (shipId > 0) { delete tokenIndexToExplore[shipId]; delete tokenIndexToSector[shipId]; } if (exploreIndexToCrew[_index] > 0) { delete exploreIndexToCrew[_index]; } } /// @notice Add exploration in case contract needs to be add trxs from previous contract /// @param _shipTokenId The Token ID that represents a ship /// @param _sectorTokenId The Token ID that represents a sector /// @param _crewTokenId The Token ID that represents a crew function addExplorationByShip( uint256 _shipTokenId, uint256 _sectorTokenId, uint256 _crewTokenId ) external onlyCLevel whenPaused { uint256 index = explorers.push(_shipTokenId) - 1; /// store exploration data tokenIndexToExplore[_shipTokenId] = index; tokenIndexToSector[_shipTokenId] = _sectorTokenId; // check if there is a crew and store data and change ship stats if (_crewTokenId > 0) { /// store crew exploration data exploreIndexToCrew[index] = _crewTokenId; missions[_crewTokenId]++; } ethernautsStorage.setAssetCooldown(_shipTokenId, now, uint64(block.number)); } /// @dev Creates a new Asset with the given fields. ONly available for C Levels /// @param _creatorTokenID The asset who is father of this asset /// @param _price asset price /// @param _assetID asset ID /// @param _category see Asset Struct description /// @param _attributes see Asset Struct description /// @param _stats see Asset Struct description /// @param _cooldown see Asset Struct description /// @param _cooldownEndBlock see Asset Struct description function _buildAsset( uint256 _creatorTokenID, address _owner, uint256 _price, uint16 _assetID, uint8 _category, uint8 _attributes, uint8[STATS_SIZE] _stats, uint256 _cooldown, uint64 _cooldownEndBlock ) private returns (uint256) { uint256 tokenID = ethernautsStorage.createAsset( _creatorTokenID, _owner, _price, _assetID, _category, uint8(AssetState.Available), _attributes, _stats, _cooldown, _cooldownEndBlock ); // emit the build event Build( _owner, tokenID, _assetID, _price ); return tokenID; } /// @notice Exploration Time: The time it takes to explore a Sector is dependent on the Sector Size /// along with the Ship’s Range and Speed. /// @param _shipRange ship range /// @param _shipSpeed ship speed /// @param _sectorSize sector size function _explorationTime( uint8 _shipRange, uint8 _shipSpeed, uint8 _sectorSize ) private view returns (int256) { int256 minToExplore = 0; minToExplore = SafeMath.min(_shipSpeed, SPEED_STAT_MAX) - 1; minToExplore = -72 * minToExplore; minToExplore += MAX_TIME_EXPLORE; uint256 minRange = uint256(SafeMath.min(_shipRange, RANGE_STAT_MAX)); uint256 scaledRange = uint256(RANGE_STAT_MAX * RANGE_SCALE); int256 minExplore = (minToExplore - MIN_TIME_EXPLORE); minToExplore -= fraction(minExplore, int256(minRange), int256(scaledRange)); minToExplore += fraction(minToExplore, int256(_sectorSize) - int256(10), 10); minToExplore = SafeMath.max(minToExplore, MIN_TIME_EXPLORE); return minToExplore; } /// @notice calcs a perc without float or double :( function fraction(int256 _subject, int256 _numerator, int256 _denominator) private pure returns (int256) { int256 division = _subject * _numerator - _subject * _denominator; int256 total = _subject * _denominator + division; return total / _denominator; } /// @notice Any C-level can fix how many seconds per blocks are currently observed. /// @param _secs The seconds per block function setSecondsPerBlock(uint256 _secs) external onlyCLevel { require(_secs > 0); secondsPerBlock = _secs; } }
@notice This contract manages the various addresses and constraints for operations that can be executed only by specific roles. Namely CEO and CTO. it also includes pausable pattern. This facet controls access control for Ethernauts. All roles have same responsibilities and rights, but there is slight differences between them: - The CEO: The CEO can reassign other roles and only role that can unpause the smart contract. It is initially set to the address that created the smart contract. - The CTO: The CTO can change contract address, oracle address and plan for upgrades. - The COO: The COO can change contract address and add create assets. The addresses of the accounts (or contracts) that can execute actions within each roles. @dev Keeps track whether the contract is paused. When that is true, most actions are blocked
contract EthernautsAccessControl is EthernautsBase { event ContractUpgrade(address newContract); address public ceoAddress; address public ctoAddress; address public cooAddress; address public oracleAddress; bool public paused = false; } modifier onlyCEO() { require(msg.sender == ceoAddress); _; } modifier onlyCTO() { require(msg.sender == ctoAddress); _; } modifier onlyOracle() { require(msg.sender == oracleAddress); _; } modifier onlyCLevel() { require( msg.sender == ceoAddress || msg.sender == ctoAddress || msg.sender == cooAddress ); _; } function setCEO(address _newCEO) external onlyCEO { require(_newCEO != address(0)); ceoAddress = _newCEO; } function setCTO(address _newCTO) external { require( msg.sender == ceoAddress || msg.sender == ctoAddress ); require(_newCTO != address(0)); ctoAddress = _newCTO; } function setCOO(address _newCOO) external { require( msg.sender == ceoAddress || msg.sender == cooAddress ); require(_newCOO != address(0)); cooAddress = _newCOO; } function setOracle(address _newOracle) external { require(msg.sender == ctoAddress); require(_newOracle != address(0)); oracleAddress = _newOracle; } modifier whenNotPaused() { require(!paused); _; } modifier whenPaused { require(paused); _; } function pause() external onlyCLevel whenNotPaused { paused = true; } function unpause() public onlyCEO whenPaused { paused = false; } }
1,044,120
[ 1, 2503, 6835, 20754, 281, 326, 11191, 6138, 471, 6237, 364, 5295, 1850, 716, 848, 506, 7120, 1338, 635, 2923, 4900, 18, 423, 301, 2357, 29538, 51, 471, 385, 4296, 18, 518, 2546, 6104, 6790, 16665, 1936, 18, 1220, 11082, 11022, 2006, 3325, 364, 512, 1136, 82, 5854, 87, 18, 4826, 4900, 1240, 1967, 7899, 24074, 471, 14989, 16, 1496, 1915, 353, 20049, 16440, 3086, 2182, 30, 377, 300, 1021, 29538, 51, 30, 1021, 29538, 51, 848, 283, 6145, 1308, 4900, 471, 1338, 2478, 716, 848, 640, 19476, 326, 13706, 6835, 18, 4202, 2597, 353, 22458, 444, 358, 326, 1758, 716, 2522, 326, 13706, 6835, 18, 377, 300, 1021, 385, 4296, 30, 1021, 385, 4296, 848, 2549, 6835, 1758, 16, 20865, 1758, 471, 4995, 364, 28844, 18, 377, 300, 1021, 7910, 51, 30, 1021, 7910, 51, 848, 2549, 6835, 1758, 471, 527, 752, 7176, 18, 1021, 6138, 434, 326, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 16351, 512, 1136, 82, 5854, 87, 16541, 353, 512, 1136, 82, 5854, 87, 2171, 288, 203, 203, 565, 871, 13456, 10784, 12, 2867, 394, 8924, 1769, 203, 203, 565, 1758, 1071, 276, 4361, 1887, 31, 203, 565, 1758, 1071, 276, 869, 1887, 31, 203, 565, 1758, 1071, 1825, 83, 1887, 31, 203, 565, 1758, 1071, 20865, 1887, 31, 203, 203, 565, 1426, 1071, 17781, 273, 629, 31, 203, 203, 97, 203, 565, 9606, 1338, 1441, 51, 1435, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 276, 4361, 1887, 1769, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 565, 9606, 1338, 1268, 51, 1435, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 276, 869, 1887, 1769, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 565, 9606, 1338, 23601, 1435, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 20865, 1887, 1769, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 565, 9606, 1338, 39, 2355, 1435, 288, 203, 3639, 2583, 12, 203, 5411, 1234, 18, 15330, 422, 276, 4361, 1887, 747, 203, 5411, 1234, 18, 15330, 422, 276, 869, 1887, 747, 203, 5411, 1234, 18, 15330, 422, 1825, 83, 1887, 203, 3639, 11272, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 565, 445, 444, 1441, 51, 12, 2867, 389, 2704, 1441, 51, 13, 3903, 1338, 1441, 51, 288, 203, 3639, 2583, 24899, 2704, 1441, 51, 480, 1758, 12, 20, 10019, 203, 203, 3639, 276, 4361, 1887, 273, 389, 2704, 1441, 51, 31, 203, 565, 289, 203, 203, 565, 445, 444, 2 ]
pragma solidity =0.7.6; pragma experimental ABIEncoderV2; abstract contract IComptroller { struct CompMarketState { uint224 index; uint32 block; } function claimComp(address holder) public virtual; function claimComp(address holder, address[] memory cTokens) public virtual; function claimComp(address[] memory holders, address[] memory cTokens, bool borrowers, bool suppliers) public virtual; function compSupplyState(address) public view virtual returns (CompMarketState memory); function compSupplierIndex(address,address) public view virtual returns (uint); function compAccrued(address) public view virtual returns (uint); function compBorrowState(address) public view virtual returns (CompMarketState memory); function compBorrowerIndex(address,address) public view virtual returns (uint); function enterMarkets(address[] calldata cTokens) external virtual returns (uint256[] memory); function exitMarket(address cToken) external virtual returns (uint256); function getAssetsIn(address account) external virtual view returns (address[] memory); function markets(address account) public virtual view returns (bool, uint256); function getAccountLiquidity(address account) external virtual view returns (uint256, uint256, uint256); function oracle() public virtual view returns (address); } interface IERC20 { function totalSupply() external view returns (uint256 supply); function balanceOf(address _owner) external view returns (uint256 balance); function transfer(address _to, uint256 _value) external returns (bool success); function transferFrom( address _from, address _to, uint256 _value ) external returns (bool success); function approve(address _spender, uint256 _value) external returns (bool success); function allowance(address _owner, address _spender) external view returns (uint256 remaining); function decimals() external view returns (uint256 digits); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } abstract contract ICToken is IERC20 { function mint(uint256 mintAmount) external virtual returns (uint256); function mint() external virtual payable; function accrueInterest() public virtual returns (uint); function redeem(uint256 redeemTokens) external virtual returns (uint256); function redeemUnderlying(uint256 redeemAmount) external virtual returns (uint256); function borrow(uint256 borrowAmount) external virtual returns (uint256); function borrowIndex() public view virtual returns (uint); function borrowBalanceStored(address) public view virtual returns(uint); function repayBorrow(uint256 repayAmount) external virtual returns (uint256); function repayBorrow() external virtual payable; function repayBorrowBehalf(address borrower, uint256 repayAmount) external virtual returns (uint256); function repayBorrowBehalf(address borrower) external virtual payable; function liquidateBorrow(address borrower, uint256 repayAmount, address cTokenCollateral) external virtual returns (uint256); function liquidateBorrow(address borrower, address cTokenCollateral) external virtual payable; function exchangeRateCurrent() external virtual returns (uint256); function supplyRatePerBlock() external virtual returns (uint256); function borrowRatePerBlock() external virtual returns (uint256); function totalReserves() external virtual returns (uint256); function reserveFactorMantissa() external virtual returns (uint256); function borrowBalanceCurrent(address account) external virtual returns (uint256); function totalBorrowsCurrent() external virtual returns (uint256); function getCash() external virtual returns (uint256); function balanceOfUnderlying(address owner) external virtual returns (uint256); function underlying() external virtual returns (address); function getAccountSnapshot(address account) external virtual view returns (uint, uint, uint, uint); } abstract contract IWETH { function allowance(address, address) public virtual returns (uint256); function balanceOf(address) public virtual returns (uint256); function approve(address, uint256) public virtual; function transfer(address, uint256) public virtual returns (bool); function transferFrom( address, address, uint256 ) public virtual returns (bool); function deposit() public payable virtual; function withdraw(uint256) public virtual; } library Address { function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue( address target, bytes memory data, uint256 weiValue, string memory errorMessage ) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // 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); } } } } 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 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 Edited so it always first approves 0 and then the value, because of non standard tokens function safeApprove( IERC20 token, address spender, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 0)); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn( token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance) ); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender).sub( value, "SafeERC20: decreased allowance below zero" ); _callOptionalReturn( token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance) ); } function _callOptionalReturn(IERC20 token, bytes memory data) private { bytes memory returndata = address(token).functionCall( data, "SafeERC20: low-level call failed" ); 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"); } } } library TokenUtils { using SafeERC20 for IERC20; address public constant WETH_ADDR = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; function approveToken( address _tokenAddr, address _to, uint256 _amount ) internal { if (_tokenAddr == ETH_ADDR) return; if (IERC20(_tokenAddr).allowance(address(this), _to) < _amount) { IERC20(_tokenAddr).safeApprove(_to, _amount); } } function pullTokensIfNeeded( address _token, address _from, uint256 _amount ) internal returns (uint256) { // handle max uint amount if (_amount == type(uint256).max) { uint256 userAllowance = IERC20(_token).allowance(_from, address(this)); uint256 balance = getBalance(_token, _from); // pull max allowance amount if balance is bigger than allowance _amount = (balance > userAllowance) ? userAllowance : balance; } if (_from != address(0) && _from != address(this) && _token != ETH_ADDR && _amount != 0) { IERC20(_token).safeTransferFrom(_from, address(this), _amount); } return _amount; } function withdrawTokens( address _token, address _to, uint256 _amount ) internal returns (uint256) { if (_amount == type(uint256).max) { _amount = getBalance(_token, address(this)); } if (_to != address(0) && _to != address(this) && _amount != 0) { if (_token != ETH_ADDR) { IERC20(_token).safeTransfer(_to, _amount); } else { payable(_to).transfer(_amount); } } return _amount; } function depositWeth(uint256 _amount) internal { IWETH(WETH_ADDR).deposit{value: _amount}(); } function withdrawWeth(uint256 _amount) internal { IWETH(WETH_ADDR).withdraw(_amount); } function getBalance(address _tokenAddr, address _acc) internal view returns (uint256) { if (_tokenAddr == ETH_ADDR) { return _acc.balance; } else { return IERC20(_tokenAddr).balanceOf(_acc); } } function getTokenDecimals(address _token) internal view returns (uint256) { if (_token == ETH_ADDR) return 18; return IERC20(_token).decimals(); } } abstract contract IDFSRegistry { function getAddr(bytes32 _id) public view virtual returns (address); function addNewContract( bytes32 _id, address _contractAddr, uint256 _waitPeriod ) public virtual; function startContractChange(bytes32 _id, address _newContractAddr) public virtual; function approveContractChange(bytes32 _id) public virtual; function cancelContractChange(bytes32 _id) public virtual; function changeWaitPeriod(bytes32 _id, uint256 _newWaitPeriod) public virtual; } /// @title A stateful contract that holds and can change owner/admin contract AdminVault { address public owner; address public admin; constructor() { owner = msg.sender; admin = 0x25eFA336886C74eA8E282ac466BdCd0199f85BB9; } /// @notice Admin is able to change owner /// @param _owner Address of new owner function changeOwner(address _owner) public { require(admin == msg.sender, "msg.sender not admin"); owner = _owner; } /// @notice Admin is able to set new admin /// @param _admin Address of multisig that becomes new admin function changeAdmin(address _admin) public { require(admin == msg.sender, "msg.sender not admin"); admin = _admin; } } /// @title AdminAuth Handles owner/admin privileges over smart contracts contract AdminAuth { using SafeERC20 for IERC20; AdminVault public constant adminVault = AdminVault(0xCCf3d848e08b94478Ed8f46fFead3008faF581fD); modifier onlyOwner() { require(adminVault.owner() == msg.sender, "msg.sender not owner"); _; } modifier onlyAdmin() { require(adminVault.admin() == msg.sender, "msg.sender not admin"); _; } /// @notice withdraw stuck funds function withdrawStuckFunds(address _token, address _receiver, uint256 _amount) public onlyOwner { if (_token == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) { payable(_receiver).transfer(_amount); } else { IERC20(_token).safeTransfer(_receiver, _amount); } } /// @notice Destroy the contract function kill() public onlyAdmin { selfdestruct(payable(msg.sender)); } } contract DefisaverLogger { event LogEvent( address indexed contractAddress, address indexed caller, string indexed logName, bytes data ); // solhint-disable-next-line func-name-mixedcase function Log( address _contract, address _caller, string memory _logName, bytes memory _data ) public { emit LogEvent(_contract, _caller, _logName, _data); } } /// @title Stores all the important DFS addresses and can be changed (timelock) contract DFSRegistry is AdminAuth { DefisaverLogger public constant logger = DefisaverLogger( 0x5c55B921f590a89C1Ebe84dF170E655a82b62126 ); string public constant ERR_ENTRY_ALREADY_EXISTS = "Entry id already exists"; string public constant ERR_ENTRY_NON_EXISTENT = "Entry id doesn't exists"; string public constant ERR_ENTRY_NOT_IN_CHANGE = "Entry not in change process"; string public constant ERR_WAIT_PERIOD_SHORTER = "New wait period must be bigger"; string public constant ERR_CHANGE_NOT_READY = "Change not ready yet"; string public constant ERR_EMPTY_PREV_ADDR = "Previous addr is 0"; string public constant ERR_ALREADY_IN_CONTRACT_CHANGE = "Already in contract change"; string public constant ERR_ALREADY_IN_WAIT_PERIOD_CHANGE = "Already in wait period change"; struct Entry { address contractAddr; uint256 waitPeriod; uint256 changeStartTime; bool inContractChange; bool inWaitPeriodChange; bool exists; } mapping(bytes32 => Entry) public entries; mapping(bytes32 => address) public previousAddresses; mapping(bytes32 => address) public pendingAddresses; mapping(bytes32 => uint256) public pendingWaitTimes; /// @notice Given an contract id returns the registered address /// @dev Id is keccak256 of the contract name /// @param _id Id of contract function getAddr(bytes32 _id) public view returns (address) { return entries[_id].contractAddr; } /// @notice Helper function to easily query if id is registered /// @param _id Id of contract function isRegistered(bytes32 _id) public view returns (bool) { return entries[_id].exists; } /////////////////////////// OWNER ONLY FUNCTIONS /////////////////////////// /// @notice Adds a new contract to the registry /// @param _id Id of contract /// @param _contractAddr Address of the contract /// @param _waitPeriod Amount of time to wait before a contract address can be changed function addNewContract( bytes32 _id, address _contractAddr, uint256 _waitPeriod ) public onlyOwner { require(!entries[_id].exists, ERR_ENTRY_ALREADY_EXISTS); entries[_id] = Entry({ contractAddr: _contractAddr, waitPeriod: _waitPeriod, changeStartTime: 0, inContractChange: false, inWaitPeriodChange: false, exists: true }); // Remember tha address so we can revert back to old addr if needed previousAddresses[_id] = _contractAddr; logger.Log( address(this), msg.sender, "AddNewContract", abi.encode(_id, _contractAddr, _waitPeriod) ); } /// @notice Reverts to the previous address immediately /// @dev In case the new version has a fault, a quick way to fallback to the old contract /// @param _id Id of contract function revertToPreviousAddress(bytes32 _id) public onlyOwner { require(entries[_id].exists, ERR_ENTRY_NON_EXISTENT); require(previousAddresses[_id] != address(0), ERR_EMPTY_PREV_ADDR); address currentAddr = entries[_id].contractAddr; entries[_id].contractAddr = previousAddresses[_id]; logger.Log( address(this), msg.sender, "RevertToPreviousAddress", abi.encode(_id, currentAddr, previousAddresses[_id]) ); } /// @notice Starts an address change for an existing entry /// @dev Can override a change that is currently in progress /// @param _id Id of contract /// @param _newContractAddr Address of the new contract function startContractChange(bytes32 _id, address _newContractAddr) public onlyOwner { require(entries[_id].exists, ERR_ENTRY_NON_EXISTENT); require(!entries[_id].inWaitPeriodChange, ERR_ALREADY_IN_WAIT_PERIOD_CHANGE); entries[_id].changeStartTime = block.timestamp; // solhint-disable-line entries[_id].inContractChange = true; pendingAddresses[_id] = _newContractAddr; logger.Log( address(this), msg.sender, "StartContractChange", abi.encode(_id, entries[_id].contractAddr, _newContractAddr) ); } /// @notice Changes new contract address, correct time must have passed /// @param _id Id of contract function approveContractChange(bytes32 _id) public onlyOwner { require(entries[_id].exists, ERR_ENTRY_NON_EXISTENT); require(entries[_id].inContractChange, ERR_ENTRY_NOT_IN_CHANGE); require( block.timestamp >= (entries[_id].changeStartTime + entries[_id].waitPeriod), // solhint-disable-line ERR_CHANGE_NOT_READY ); address oldContractAddr = entries[_id].contractAddr; entries[_id].contractAddr = pendingAddresses[_id]; entries[_id].inContractChange = false; entries[_id].changeStartTime = 0; pendingAddresses[_id] = address(0); previousAddresses[_id] = oldContractAddr; logger.Log( address(this), msg.sender, "ApproveContractChange", abi.encode(_id, oldContractAddr, entries[_id].contractAddr) ); } /// @notice Cancel pending change /// @param _id Id of contract function cancelContractChange(bytes32 _id) public onlyOwner { require(entries[_id].exists, ERR_ENTRY_NON_EXISTENT); require(entries[_id].inContractChange, ERR_ENTRY_NOT_IN_CHANGE); address oldContractAddr = pendingAddresses[_id]; pendingAddresses[_id] = address(0); entries[_id].inContractChange = false; entries[_id].changeStartTime = 0; logger.Log( address(this), msg.sender, "CancelContractChange", abi.encode(_id, oldContractAddr, entries[_id].contractAddr) ); } /// @notice Starts the change for waitPeriod /// @param _id Id of contract /// @param _newWaitPeriod New wait time function startWaitPeriodChange(bytes32 _id, uint256 _newWaitPeriod) public onlyOwner { require(entries[_id].exists, ERR_ENTRY_NON_EXISTENT); require(!entries[_id].inContractChange, ERR_ALREADY_IN_CONTRACT_CHANGE); pendingWaitTimes[_id] = _newWaitPeriod; entries[_id].changeStartTime = block.timestamp; // solhint-disable-line entries[_id].inWaitPeriodChange = true; logger.Log( address(this), msg.sender, "StartWaitPeriodChange", abi.encode(_id, _newWaitPeriod) ); } /// @notice Changes new wait period, correct time must have passed /// @param _id Id of contract function approveWaitPeriodChange(bytes32 _id) public onlyOwner { require(entries[_id].exists, ERR_ENTRY_NON_EXISTENT); require(entries[_id].inWaitPeriodChange, ERR_ENTRY_NOT_IN_CHANGE); require( block.timestamp >= (entries[_id].changeStartTime + entries[_id].waitPeriod), // solhint-disable-line ERR_CHANGE_NOT_READY ); uint256 oldWaitTime = entries[_id].waitPeriod; entries[_id].waitPeriod = pendingWaitTimes[_id]; entries[_id].inWaitPeriodChange = false; entries[_id].changeStartTime = 0; pendingWaitTimes[_id] = 0; logger.Log( address(this), msg.sender, "ApproveWaitPeriodChange", abi.encode(_id, oldWaitTime, entries[_id].waitPeriod) ); } /// @notice Cancel wait period change /// @param _id Id of contract function cancelWaitPeriodChange(bytes32 _id) public onlyOwner { require(entries[_id].exists, ERR_ENTRY_NON_EXISTENT); require(entries[_id].inWaitPeriodChange, ERR_ENTRY_NOT_IN_CHANGE); uint256 oldWaitPeriod = pendingWaitTimes[_id]; pendingWaitTimes[_id] = 0; entries[_id].inWaitPeriodChange = false; entries[_id].changeStartTime = 0; logger.Log( address(this), msg.sender, "CancelWaitPeriodChange", abi.encode(_id, oldWaitPeriod, entries[_id].waitPeriod) ); } } /// @title Implements Action interface and common helpers for passing inputs abstract contract ActionBase is AdminAuth { address public constant REGISTRY_ADDR = 0xD6049E1F5F3EfF1F921f5532aF1A1632bA23929C; DFSRegistry public constant registry = DFSRegistry(REGISTRY_ADDR); DefisaverLogger public constant logger = DefisaverLogger( 0x5c55B921f590a89C1Ebe84dF170E655a82b62126 ); string public constant ERR_SUB_INDEX_VALUE = "Wrong sub index value"; string public constant ERR_RETURN_INDEX_VALUE = "Wrong return index value"; /// @dev Subscription params index range [128, 255] uint8 public constant SUB_MIN_INDEX_VALUE = 128; uint8 public constant SUB_MAX_INDEX_VALUE = 255; /// @dev Return params index range [1, 127] uint8 public constant RETURN_MIN_INDEX_VALUE = 1; uint8 public constant RETURN_MAX_INDEX_VALUE = 127; /// @dev If the input value should not be replaced uint8 public constant NO_PARAM_MAPPING = 0; /// @dev We need to parse Flash loan actions in a different way enum ActionType { FL_ACTION, STANDARD_ACTION, CUSTOM_ACTION } /// @notice Parses inputs and runs the implemented action through a proxy /// @dev Is called by the TaskExecutor chaining actions together /// @param _callData Array of input values each value encoded as bytes /// @param _subData Array of subscribed vales, replaces input values if specified /// @param _paramMapping Array that specifies how return and subscribed values are mapped in input /// @param _returnValues Returns values from actions before, which can be injected in inputs /// @return Returns a bytes32 value through DSProxy, each actions implements what that value is function executeAction( bytes[] memory _callData, bytes[] memory _subData, uint8[] memory _paramMapping, bytes32[] memory _returnValues ) public payable virtual returns (bytes32); /// @notice Parses inputs and runs the single implemented action through a proxy /// @dev Used to save gas when executing a single action directly function executeActionDirect(bytes[] memory _callData) public virtual payable; /// @notice Returns the type of action we are implementing function actionType() public pure virtual returns (uint8); //////////////////////////// HELPER METHODS //////////////////////////// /// @notice Given an uint256 input, injects return/sub values if specified /// @param _param The original input value /// @param _mapType Indicated the type of the input in paramMapping /// @param _subData Array of subscription data we can replace the input value with /// @param _returnValues Array of subscription data we can replace the input value with function _parseParamUint( uint _param, uint8 _mapType, bytes[] memory _subData, bytes32[] memory _returnValues ) internal pure returns (uint) { if (isReplaceable(_mapType)) { if (isReturnInjection(_mapType)) { _param = uint(_returnValues[getReturnIndex(_mapType)]); } else { _param = abi.decode(_subData[getSubIndex(_mapType)], (uint)); } } return _param; } /// @notice Given an addr input, injects return/sub values if specified /// @param _param The original input value /// @param _mapType Indicated the type of the input in paramMapping /// @param _subData Array of subscription data we can replace the input value with /// @param _returnValues Array of subscription data we can replace the input value with function _parseParamAddr( address _param, uint8 _mapType, bytes[] memory _subData, bytes32[] memory _returnValues ) internal pure returns (address) { if (isReplaceable(_mapType)) { if (isReturnInjection(_mapType)) { _param = address(bytes20((_returnValues[getReturnIndex(_mapType)]))); } else { _param = abi.decode(_subData[getSubIndex(_mapType)], (address)); } } return _param; } /// @notice Given an bytes32 input, injects return/sub values if specified /// @param _param The original input value /// @param _mapType Indicated the type of the input in paramMapping /// @param _subData Array of subscription data we can replace the input value with /// @param _returnValues Array of subscription data we can replace the input value with function _parseParamABytes32( bytes32 _param, uint8 _mapType, bytes[] memory _subData, bytes32[] memory _returnValues ) internal pure returns (bytes32) { if (isReplaceable(_mapType)) { if (isReturnInjection(_mapType)) { _param = (_returnValues[getReturnIndex(_mapType)]); } else { _param = abi.decode(_subData[getSubIndex(_mapType)], (bytes32)); } } return _param; } /// @notice Checks if the paramMapping value indicated that we need to inject values /// @param _type Indicated the type of the input function isReplaceable(uint8 _type) internal pure returns (bool) { return _type != NO_PARAM_MAPPING; } /// @notice Checks if the paramMapping value is in the return value range /// @param _type Indicated the type of the input function isReturnInjection(uint8 _type) internal pure returns (bool) { return (_type >= RETURN_MIN_INDEX_VALUE) && (_type <= RETURN_MAX_INDEX_VALUE); } /// @notice Transforms the paramMapping value to the index in return array value /// @param _type Indicated the type of the input function getReturnIndex(uint8 _type) internal pure returns (uint8) { require(isReturnInjection(_type), ERR_SUB_INDEX_VALUE); return (_type - RETURN_MIN_INDEX_VALUE); } /// @notice Transforms the paramMapping value to the index in sub array value /// @param _type Indicated the type of the input function getSubIndex(uint8 _type) internal pure returns (uint8) { require(_type >= SUB_MIN_INDEX_VALUE, ERR_RETURN_INDEX_VALUE); return (_type - SUB_MIN_INDEX_VALUE); } } /// @title Utility functions and data used in Compound actions contract CompHelper { uint256 constant NO_ERROR = 0; string public constant ERR_COMP_ENTER_MARKET = "Comp failed to enter market"; string public constant ERR_COMP_EXIT_MARKET = "Comp failed to exit market"; address public constant C_ETH_ADDR = 0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5; address public constant COMPTROLLER_ADDR = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B; // @notice Returns the underlying token address of the given cToken function getUnderlyingAddr(address _cTokenAddr) internal returns (address tokenAddr) { // cEth has no .underlying() method if (_cTokenAddr == C_ETH_ADDR) return TokenUtils.WETH_ADDR; tokenAddr = ICToken(_cTokenAddr).underlying(); } /// @notice Enters the Compound market so it can be deposited/borrowed /// @dev Markets can be entered multiple times, without the code reverting /// @param _cTokenAddr CToken address of the token function enterMarket(address _cTokenAddr) public { address[] memory markets = new address[](1); markets[0] = _cTokenAddr; uint256[] memory errCodes = IComptroller(COMPTROLLER_ADDR).enterMarkets(markets); require(errCodes[0] == NO_ERROR, ERR_COMP_ENTER_MARKET); } /// @notice Exits the Compound market /// @param _cTokenAddr CToken address of the token function exitMarket(address _cTokenAddr) public { require(IComptroller(COMPTROLLER_ADDR).exitMarket(_cTokenAddr) == NO_ERROR, ERR_COMP_EXIT_MARKET); } } /// @title Borrow a token from Compound contract CompBorrow is ActionBase, CompHelper { using TokenUtils for address; string public constant ERR_COMP_BORROW = "Comp borrow failed"; /// @inheritdoc ActionBase function executeAction( bytes[] memory _callData, bytes[] memory _subData, uint8[] memory _paramMapping, bytes32[] memory _returnValues ) public payable virtual override returns (bytes32) { (address cTokenAddr, uint256 amount, address to) = parseInputs(_callData); cTokenAddr = _parseParamAddr(cTokenAddr, _paramMapping[0], _subData, _returnValues); amount = _parseParamUint(amount, _paramMapping[1], _subData, _returnValues); to = _parseParamAddr(to, _paramMapping[2], _subData, _returnValues); uint256 withdrawAmount = _borrow(cTokenAddr, amount, to); return bytes32(withdrawAmount); } /// @inheritdoc ActionBase function executeActionDirect(bytes[] memory _callData) public payable override { (address cTokenAddr, uint256 amount, address to) = parseInputs(_callData); _borrow(cTokenAddr, amount, to); } /// @inheritdoc ActionBase function actionType() public pure virtual override returns (uint8) { return uint8(ActionType.STANDARD_ACTION); } //////////////////////////// ACTION LOGIC //////////////////////////// /// @notice User borrows tokens from the Compound protocol /// @param _cTokenAddr Address of the cToken we are borrowing /// @param _amount Amount of tokens to be borrowed /// @param _to The address we are sending the borrowed tokens to function _borrow( address _cTokenAddr, uint256 _amount, address _to ) internal returns (uint256) { address tokenAddr = getUnderlyingAddr(_cTokenAddr); // if the tokens are borrowed we need to enter the market enterMarket(_cTokenAddr); require(ICToken(_cTokenAddr).borrow(_amount) == NO_ERROR, ERR_COMP_BORROW); // always return WETH, never native Eth if (tokenAddr == TokenUtils.WETH_ADDR) { TokenUtils.depositWeth(_amount); } tokenAddr.withdrawTokens(_to, _amount); logger.Log(address(this), msg.sender, "CompBorrow", abi.encode(tokenAddr, _amount, _to)); return _amount; } function parseInputs(bytes[] memory _callData) internal pure returns ( address cTokenAddr, uint256 amount, address to ) { cTokenAddr = abi.decode(_callData[0], (address)); amount = abi.decode(_callData[1], (uint256)); to = abi.decode(_callData[2], (address)); } }
@notice User borrows tokens from the Compound protocol @param _cTokenAddr Address of the cToken we are borrowing @param _amount Amount of tokens to be borrowed @param _to The address we are sending the borrowed tokens to if the tokens are borrowed we need to enter the market always return WETH, never native Eth
function _borrow( address _cTokenAddr, uint256 _amount, address _to ) internal returns (uint256) { address tokenAddr = getUnderlyingAddr(_cTokenAddr); enterMarket(_cTokenAddr); require(ICToken(_cTokenAddr).borrow(_amount) == NO_ERROR, ERR_COMP_BORROW); if (tokenAddr == TokenUtils.WETH_ADDR) { TokenUtils.depositWeth(_amount); } tokenAddr.withdrawTokens(_to, _amount); logger.Log(address(this), msg.sender, "CompBorrow", abi.encode(tokenAddr, _amount, _to)); return _amount; }
9,865,873
[ 1, 1299, 324, 280, 3870, 2430, 628, 326, 21327, 1771, 225, 389, 71, 1345, 3178, 5267, 434, 326, 276, 1345, 732, 854, 29759, 310, 225, 389, 8949, 16811, 434, 2430, 358, 506, 29759, 329, 225, 389, 869, 1021, 1758, 732, 854, 5431, 326, 29759, 329, 2430, 358, 309, 326, 2430, 854, 29759, 329, 732, 1608, 358, 6103, 326, 13667, 3712, 327, 678, 1584, 44, 16, 5903, 6448, 512, 451, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 70, 15318, 12, 203, 3639, 1758, 389, 71, 1345, 3178, 16, 203, 3639, 2254, 5034, 389, 8949, 16, 203, 3639, 1758, 389, 869, 203, 565, 262, 2713, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 1758, 1147, 3178, 273, 10833, 765, 6291, 3178, 24899, 71, 1345, 3178, 1769, 203, 203, 3639, 6103, 3882, 278, 24899, 71, 1345, 3178, 1769, 203, 203, 3639, 2583, 12, 45, 1268, 969, 24899, 71, 1345, 3178, 2934, 70, 15318, 24899, 8949, 13, 422, 3741, 67, 3589, 16, 10359, 67, 10057, 67, 38, 916, 11226, 1769, 203, 203, 3639, 309, 261, 2316, 3178, 422, 3155, 1989, 18, 59, 1584, 44, 67, 14142, 13, 288, 203, 5411, 3155, 1989, 18, 323, 1724, 59, 546, 24899, 8949, 1769, 203, 3639, 289, 203, 203, 3639, 1147, 3178, 18, 1918, 9446, 5157, 24899, 869, 16, 389, 8949, 1769, 203, 203, 3639, 1194, 18, 1343, 12, 2867, 12, 2211, 3631, 1234, 18, 15330, 16, 315, 2945, 38, 15318, 3113, 24126, 18, 3015, 12, 2316, 3178, 16, 389, 8949, 16, 389, 869, 10019, 203, 203, 3639, 327, 389, 8949, 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 ]
./full_match/1/0x95e9a33A5bdBf3fD80ae2f2faBf4208ED8CCD78E/sources/Biffordinu.sol
Anti-bot and anti-whale mappings and variables exlcude from fees and max transaction amount store addresses that a automatic market maker pairs. Any transfer *to* these addresses could be subject to a maximum transfer amount
contract Biffordinu is ERC20, Ownable { using SafeMath for uint256; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; address public constant deadAddress = address(0xdead); bool private swapping; address public marketingWallet; address public devWallet; uint256 public maxTransactionAmount; uint256 public swapTokensAtAmount; uint256 public maxWallet; bool public lpBurnEnabled = true; uint256 public lpBurnFrequency = 3600 seconds; uint256 public lastLpBurnTime; uint256 public manualBurnFrequency = 30 minutes; uint256 public lastManualLpBurnTime; bool public limitsInEffect = true; bool public tradingActive = false; bool public swapEnabled = false; bool public transferDelayEnabled = true; uint256 public buyTotalFees; uint256 public buyMarketingFee; uint256 public buyLiquidityFee; uint256 public buyDevFee; uint256 public sellTotalFees; uint256 public sellMarketingFee; uint256 public sellLiquidityFee; uint256 public sellDevFee; uint256 public tokensForMarketing; uint256 public tokensForLiquidity; uint256 public tokensForDev; mapping (address => bool) private _isExcludedFromFees; mapping (address => bool) public _isExcludedMaxTransactionAmount; mapping (address => bool) public automatedMarketMakerPairs; event UpdateUniswapV2Router(address indexed newAddress, address indexed oldAddress); event ExcludeFromFees(address indexed account, bool isExcluded); event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value); event marketingWalletUpdated(address indexed newWallet, address indexed oldWallet); event devWalletUpdated(address indexed newWallet, address indexed oldWallet); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiquidity ); event AutoNukeLP(); event ManualNukeLP(); constructor() ERC20("Biffordinu", "BIFF") { IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); excludeFromMaxTransaction(address(_uniswapV2Router), true); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH()); excludeFromMaxTransaction(address(uniswapV2Pair), true); _setAutomatedMarketMakerPair(address(uniswapV2Pair), true); uint256 _buyMarketingFee = 4; uint256 _buyLiquidityFee = 10; uint256 _buyDevFee = 1; uint256 _sellMarketingFee = 5; uint256 _sellLiquidityFee = 14; uint256 _sellDevFee = 1; uint256 totalSupply = 1 * 1e12 * 1e18; maxTransactionAmount = 950000000 * 1e18; buyMarketingFee = _buyMarketingFee; buyLiquidityFee = _buyLiquidityFee; buyDevFee = _buyDevFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; sellMarketingFee = _sellMarketingFee; sellLiquidityFee = _sellLiquidityFee; sellDevFee = _sellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; excludeFromFees(owner(), true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(0xdead), true); _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again _mint(msg.sender, totalSupply); } receive() external payable { } function enableTrading() external onlyOwner { tradingActive = true; swapEnabled = true; lastLpBurnTime = block.timestamp; } function removeLimits() external onlyOwner returns (bool){ limitsInEffect = false; return true; } function disableTransferDelay() external onlyOwner returns (bool){ transferDelayEnabled = false; return true; } function updateSwapTokensAtAmount(uint256 newAmount) external onlyOwner returns (bool){ require(newAmount >= totalSupply() * 1 / 100000, "Swap amount cannot be lower than 0.001% total supply."); require(newAmount <= totalSupply() * 5 / 1000, "Swap amount cannot be higher than 0.5% total supply."); swapTokensAtAmount = newAmount; return true; } function updateMaxTxnAmount(uint256 newNum) external onlyOwner { require(newNum >= (totalSupply() * 1 / 1000)/1e18, "Cannot set maxTransactionAmount lower than 0.1%"); maxTransactionAmount = newNum * (10**18); } function updateMaxWalletAmount(uint256 newNum) external onlyOwner { require(newNum >= (totalSupply() * 5 / 1000)/1e18, "Cannot set maxWallet lower than 0.5%"); maxWallet = newNum * (10**18); } function excludeFromMaxTransaction(address updAds, bool isEx) public onlyOwner { _isExcludedMaxTransactionAmount[updAds] = isEx; } function updateSwapEnabled(bool enabled) external onlyOwner(){ swapEnabled = enabled; } function updateBuyFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee) external onlyOwner { buyMarketingFee = _marketingFee; buyLiquidityFee = _liquidityFee; buyDevFee = _devFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; require(buyTotalFees <= 20, "Must keep fees at 20% or less"); } function updateSellFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee) external onlyOwner { sellMarketingFee = _marketingFee; sellLiquidityFee = _liquidityFee; sellDevFee = _devFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; require(sellTotalFees <= 25, "Must keep fees at 25% or less"); } function excludeFromFees(address account, bool excluded) public onlyOwner { _isExcludedFromFees[account] = excluded; emit ExcludeFromFees(account, excluded); } function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner { require(pair != uniswapV2Pair, "The pair cannot be removed from automatedMarketMakerPairs"); _setAutomatedMarketMakerPair(pair, value); } function _setAutomatedMarketMakerPair(address pair, bool value) private { automatedMarketMakerPairs[pair] = value; emit SetAutomatedMarketMakerPair(pair, value); } function updateMarketingWallet(address newMarketingWallet) external onlyOwner { emit marketingWalletUpdated(newMarketingWallet, marketingWallet); marketingWallet = newMarketingWallet; } function updateDevWallet(address newWallet) external onlyOwner { emit devWalletUpdated(newWallet, devWallet); devWallet = newWallet; } function isExcludedFromFees(address account) public view returns(bool) { return _isExcludedFromFees[account]; } event BoughtEarly(address indexed sniper); function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){ autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){ autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){ autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){ autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){ autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){ autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){ autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){ autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){ autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){ autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){ autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){ autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){ autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){ autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){ autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){ autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){ autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function swapTokensForEth(uint256 tokenAmount) private { address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, path, address(this), block.timestamp ); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { _approve(address(this), address(uniswapV2Router), tokenAmount); address(this), tokenAmount, deadAddress, block.timestamp ); } uniswapV2Router.addLiquidityETH{value: ethAmount}( function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDev; bool success; if(contractBalance > swapTokensAtAmount * 20){ contractBalance = swapTokensAtAmount * 20; } uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens); uint256 initialETHBalance = address(this).balance; swapTokensForEth(amountToSwapForETH); uint256 ethBalance = address(this).balance.sub(initialETHBalance); uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(totalTokensToSwap); uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap); uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev; tokensForLiquidity = 0; tokensForMarketing = 0; tokensForDev = 0; if(liquidityTokens > 0 && ethForLiquidity > 0){ addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, tokensForLiquidity); } } if(contractBalance == 0 || totalTokensToSwap == 0) {return;} function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDev; bool success; if(contractBalance > swapTokensAtAmount * 20){ contractBalance = swapTokensAtAmount * 20; } uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens); uint256 initialETHBalance = address(this).balance; swapTokensForEth(amountToSwapForETH); uint256 ethBalance = address(this).balance.sub(initialETHBalance); uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(totalTokensToSwap); uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap); uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev; tokensForLiquidity = 0; tokensForMarketing = 0; tokensForDev = 0; if(liquidityTokens > 0 && ethForLiquidity > 0){ addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, tokensForLiquidity); } } uint256 liquidityTokens = contractBalance * tokensForLiquidity / totalTokensToSwap / 2; (success,) = address(devWallet).call{value: ethForDev}(""); function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDev; bool success; if(contractBalance > swapTokensAtAmount * 20){ contractBalance = swapTokensAtAmount * 20; } uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens); uint256 initialETHBalance = address(this).balance; swapTokensForEth(amountToSwapForETH); uint256 ethBalance = address(this).balance.sub(initialETHBalance); uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(totalTokensToSwap); uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap); uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev; tokensForLiquidity = 0; tokensForMarketing = 0; tokensForDev = 0; if(liquidityTokens > 0 && ethForLiquidity > 0){ addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, tokensForLiquidity); } } (success,) = address(marketingWallet).call{value: address(this).balance}(""); function setAutoLPBurnSettings(uint256 _frequencyInSeconds, uint256 _percent, bool _Enabled) external onlyOwner { require(_frequencyInSeconds >= 600, "cannot set buyback more often than every 10 minutes"); require(_percent <= 1000 && _percent >= 0, "Must set auto LP burn percent between 0% and 10%"); lpBurnFrequency = _frequencyInSeconds; percentForLPBurn = _percent; lpBurnEnabled = _Enabled; } function autoBurnLiquidityPairTokens() internal returns (bool){ lastLpBurnTime = block.timestamp; uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair); uint256 amountToBurn = liquidityPairBalance.mul(percentForLPBurn).div(10000); if (amountToBurn > 0){ super._transfer(uniswapV2Pair, address(0xdead), amountToBurn); } pair.sync(); emit AutoNukeLP(); return true; } function autoBurnLiquidityPairTokens() internal returns (bool){ lastLpBurnTime = block.timestamp; uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair); uint256 amountToBurn = liquidityPairBalance.mul(percentForLPBurn).div(10000); if (amountToBurn > 0){ super._transfer(uniswapV2Pair, address(0xdead), amountToBurn); } pair.sync(); emit AutoNukeLP(); return true; } IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair); function manualBurnLiquidityPairTokens(uint256 percent) external onlyOwner returns (bool){ require(block.timestamp > lastManualLpBurnTime + manualBurnFrequency , "Must wait for cooldown to finish"); require(percent <= 1000, "May not nuke more than 10% of tokens in LP"); lastManualLpBurnTime = block.timestamp; uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair); uint256 amountToBurn = liquidityPairBalance.mul(percent).div(10000); if (amountToBurn > 0){ super._transfer(uniswapV2Pair, address(0xdead), amountToBurn); } pair.sync(); emit ManualNukeLP(); return true; } function manualBurnLiquidityPairTokens(uint256 percent) external onlyOwner returns (bool){ require(block.timestamp > lastManualLpBurnTime + manualBurnFrequency , "Must wait for cooldown to finish"); require(percent <= 1000, "May not nuke more than 10% of tokens in LP"); lastManualLpBurnTime = block.timestamp; uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair); uint256 amountToBurn = liquidityPairBalance.mul(percent).div(10000); if (amountToBurn > 0){ super._transfer(uniswapV2Pair, address(0xdead), amountToBurn); } pair.sync(); emit ManualNukeLP(); return true; } IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair); }
8,469,256
[ 1, 14925, 77, 17, 4819, 471, 30959, 17, 3350, 5349, 7990, 471, 3152, 431, 17704, 1317, 628, 1656, 281, 471, 943, 2492, 3844, 1707, 6138, 716, 279, 5859, 13667, 312, 6388, 5574, 18, 5502, 7412, 358, 4259, 6138, 3377, 506, 3221, 358, 279, 4207, 7412, 3844, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 605, 3048, 517, 6860, 353, 4232, 39, 3462, 16, 14223, 6914, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 203, 565, 467, 984, 291, 91, 438, 58, 22, 8259, 3103, 1071, 11732, 640, 291, 91, 438, 58, 22, 8259, 31, 203, 565, 1758, 1071, 11732, 640, 291, 91, 438, 58, 22, 4154, 31, 203, 565, 1758, 1071, 5381, 8363, 1887, 273, 1758, 12, 20, 92, 22097, 1769, 203, 203, 565, 1426, 3238, 7720, 1382, 31, 203, 203, 565, 1758, 1071, 13667, 310, 16936, 31, 203, 565, 1758, 1071, 4461, 16936, 31, 203, 377, 203, 565, 2254, 5034, 1071, 943, 3342, 6275, 31, 203, 565, 2254, 5034, 1071, 7720, 5157, 861, 6275, 31, 203, 565, 2254, 5034, 1071, 943, 16936, 31, 203, 377, 203, 565, 1426, 1071, 12423, 38, 321, 1526, 273, 638, 31, 203, 565, 2254, 5034, 1071, 12423, 38, 321, 13865, 273, 12396, 3974, 31, 203, 565, 2254, 5034, 1071, 1142, 48, 84, 38, 321, 950, 31, 203, 377, 203, 565, 2254, 5034, 1071, 11297, 38, 321, 13865, 273, 5196, 6824, 31, 203, 565, 2254, 5034, 1071, 1142, 25139, 48, 84, 38, 321, 950, 31, 203, 203, 565, 1426, 1071, 8181, 382, 12477, 273, 638, 31, 203, 565, 1426, 1071, 1284, 7459, 3896, 273, 629, 31, 203, 565, 1426, 1071, 7720, 1526, 273, 629, 31, 203, 377, 203, 565, 1426, 1071, 7412, 6763, 1526, 273, 638, 31, 203, 203, 565, 2254, 5034, 1071, 30143, 5269, 2954, 281, 31, 203, 565, 2254, 5034, 1071, 30143, 3882, 21747, 14667, 31, 203, 2 ]
// SPDX-License-Identifier: UNLICENSED pragma solidity ^0.7.0; import "./ERC677Upgradeable.sol"; import "../dependencies/openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol"; import "../dependencies/openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol"; import "../dependencies/openzeppelin/contracts/math/SafeMath.sol"; /// @dev RampDefi Stablecoin. contract RUSD is ERC677Upgradeable, AccessControlUpgradeable { using SafeMath for uint256; bytes32 public constant MINTBURN_ROLE = keccak256("MINTBURN_ROLE"); function initialize() public initializer { __ERC677_init("rUSD", "rUSD"); _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _setupRole(MINTBURN_ROLE, msg.sender); } function mint(address _account, uint256 _amount) external hasMintBurnRole { _mint(_account, _amount); } function burn(address _account, uint256 _amount) external hasMintBurnRole { _burn(_account, _amount); } /********************** INTERNAL ********************************/ modifier hasMintBurnRole() { require(hasRole(MINTBURN_ROLE, msg.sender), "Caller does not have MINTBURN_ROLE"); _; } } // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.7.0; import "./ERC677Receiver.sol"; import "./IERC677Upgradable.sol"; import "../dependencies/openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol"; contract ERC677Upgradeable is ERC20Upgradeable, IERC677Upgradeable { function __ERC677_init(string memory name_, string memory symbol_) internal initializer { __ERC20_init(name_, symbol_); } /** * @dev transfer token to a contract address with additional data if the recipient is a contact. * @param _to The address to transfer to. * @param _value The amount to be transferred. * @param _data The extra data to be passed to the receiving contract. */ function transferAndCall( address _to, uint256 _value, bytes memory _data ) public virtual override returns (bool success) { super.transfer(_to, _value); emit Transfer(msg.sender, _to, _value, _data); if (isContract(_to)) { contractFallback(_to, _value, _data); } return true; } // PRIVATE function contractFallback( address _to, uint256 _value, bytes memory _data ) private { ERC677Receiver receiver = ERC677Receiver(_to); receiver.onTokenTransfer(msg.sender, _value, _data); } function isContract(address _addr) private view returns (bool hasCode) { uint256 length; assembly { length := extcodesize(_addr) } return length > 0; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/ContextUpgradeable.sol"; import "./IERC20Upgradeable.sol"; import "../../math/SafeMathUpgradeable.sol"; import "../../proxy/Initializable.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable { using SafeMathUpgradeable for uint256; mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ 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 virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve( sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance") ); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero") ); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal virtual { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} uint256[44] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/EnumerableSetUpgradeable.sol"; import "../utils/AddressUpgradeable.sol"; import "../utils/ContextUpgradeable.sol"; import "../proxy/Initializable.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable { function __AccessControl_init() internal initializer { __Context_init_unchained(); __AccessControl_init_unchained(); } function __AccessControl_init_unchained() internal initializer {} using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet; using AddressUpgradeable for address; struct RoleData { EnumerableSetUpgradeable.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()); } } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, 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; } } // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.7.0; // Based on https://github.com/smartcontractkit/LinkToken/blob/master/contracts/v0.6/token/ERC677Receiver.sol abstract contract ERC677Receiver { function onTokenTransfer( address _sender, uint256 _value, bytes memory _data ) public virtual; } // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.7.0; // Based on https://github.com/smartcontractkit/LinkToken/blob/master/contracts/v0.6/token/ERC677.sol import "../dependencies/openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; interface IERC677Upgradeable is IERC20Upgradeable { function transferAndCall( address to, uint256 value, bytes memory data ) external returns (bool success); event Transfer(address indexed from, address indexed to, uint256 value, bytes data); } // SPDX-License-Identifier: MIT 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); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../proxy/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. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer {} function _msgSender() internal view virtual returns (address 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; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMathUpgradeable { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version pragma solidity >=0.4.24 <0.8.0; import "../utils/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 a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } // SPDX-License-Identifier: MIT 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); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library 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(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } }
* @dev Collection of functions related to the address type/
library AddressUpgradeable { function isContract(address account) internal view returns (bool) { uint256 size; assembly { size := extcodesize(account) } return size > 0; } 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"); 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 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"); return _verifyCallResult(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) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) private pure returns (bytes memory) { if (success) { return returndata; if (returndata.length > 0) { assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } revert(errorMessage); } } } function _verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) private pure returns (bytes memory) { if (success) { return returndata; if (returndata.length > 0) { assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } revert(errorMessage); } } } } else { function _verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) private pure returns (bytes memory) { if (success) { return returndata; if (returndata.length > 0) { assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } revert(errorMessage); } } } function _verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) private pure returns (bytes memory) { if (success) { return returndata; if (returndata.length > 0) { assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } revert(errorMessage); } } } } else { }
13,412,922
[ 1, 2532, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 12083, 5267, 10784, 429, 288, 203, 203, 565, 445, 353, 8924, 12, 2867, 2236, 13, 2713, 1476, 1135, 261, 6430, 13, 288, 203, 203, 3639, 2254, 5034, 963, 31, 203, 3639, 19931, 288, 203, 5411, 963, 519, 1110, 7000, 554, 12, 4631, 13, 203, 3639, 289, 203, 3639, 327, 963, 405, 374, 31, 203, 565, 289, 203, 203, 565, 445, 353, 8924, 12, 2867, 2236, 13, 2713, 1476, 1135, 261, 6430, 13, 288, 203, 203, 3639, 2254, 5034, 963, 31, 203, 3639, 19931, 288, 203, 5411, 963, 519, 1110, 7000, 554, 12, 4631, 13, 203, 3639, 289, 203, 3639, 327, 963, 405, 374, 31, 203, 565, 289, 203, 203, 565, 445, 1366, 620, 12, 2867, 8843, 429, 8027, 16, 2254, 5034, 3844, 13, 2713, 288, 203, 3639, 2583, 12, 2867, 12, 2211, 2934, 12296, 1545, 3844, 16, 315, 1887, 30, 2763, 11339, 11013, 8863, 203, 203, 3639, 2583, 12, 4768, 16, 315, 1887, 30, 13496, 358, 1366, 460, 16, 8027, 2026, 1240, 15226, 329, 8863, 203, 565, 289, 203, 203, 3639, 261, 6430, 2216, 16, 262, 273, 8027, 18, 1991, 95, 460, 30, 3844, 289, 2932, 8863, 203, 565, 445, 445, 1477, 12, 2867, 1018, 16, 1731, 3778, 501, 13, 2713, 1135, 261, 3890, 3778, 13, 288, 203, 3639, 327, 445, 1477, 12, 3299, 16, 501, 16, 315, 1887, 30, 4587, 17, 2815, 745, 2535, 8863, 203, 565, 289, 203, 203, 565, 445, 445, 1477, 12, 203, 3639, 1758, 1018, 16, 203, 3639, 1731, 3778, 501, 16, 203, 3639, 533, 3778, 9324, 203, 565, 2 ]
//SPDX-License-Identifier: MIT pragma solidity >=0.8.4; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "@chainlink/contracts/src/v0.8/VRFConsumerBase.sol"; import "./SeedPhrasePricing.sol"; import "../interfaces/IN.sol"; import "../interfaces/IRarible.sol"; import "../interfaces/IKarmaScore.sol"; import "../interfaces/INOwnerResolver.sol"; import "../libraries/NilProtocolUtils.sol"; import "../libraries/SeedPhraseUtils.sol"; //////////////////////////////////////////////////////////////////////////////////////// // // // // // ░██████╗███████╗███████╗██████╗░  ██████╗░██╗░░██╗██████╗░░█████╗░░██████╗███████╗ // // ██╔════╝██╔════╝██╔════╝██╔══██╗  ██╔══██╗██║░░██║██╔══██╗██╔══██╗██╔════╝██╔════╝ // // ╚█████╗░█████╗░░█████╗░░██║░░██║  ██████╔╝███████║██████╔╝███████║╚█████╗░█████╗░░ // // ░╚═══██╗██╔══╝░░██╔══╝░░██║░░██║  ██╔═══╝░██╔══██║██╔══██╗██╔══██║░╚═══██╗██╔══╝░░ // // ██████╔╝███████╗███████╗██████╔╝  ██║░░░░░██║░░██║██║░░██║██║░░██║██████╔╝███████╗ // // ╚═════╝░╚══════╝╚══════╝╚═════╝░  ╚═╝░░░░░╚═╝░░╚═╝╚═╝░░╚═╝╚═╝░░╚═╝╚═════╝░╚══════╝ // // // // // // Title: Seed Phrase // // Devs: Harry Faulkner & maximonee (twitter.com/maximonee_) // // Description: This contract provides minting for the // // Seed Phrase NFT by Sean Elliott // // (twitter.com/seanelliottoc) // // // //////////////////////////////////////////////////////////////////////////////////////// contract SeedPhrase is SeedPhrasePricing, VRFConsumerBase { using Strings for uint256; using Strings for uint16; using Strings for uint8; using Counters for Counters.Counter; using SeedPhraseUtils for SeedPhraseUtils.Random; Counters.Counter private _doublePanelTokens; Counters.Counter private _tokenIds; address private _owner; // Tracks whether an n has been used already to mint mapping(uint256 => bool) public override nUsed; mapping(PreSaleType => uint16) public presaleLimits; address[] private genesisSketchAddresses; uint16[] private bipWordIds = new uint16[](2048); IRarible public immutable rarible; INOwnerResolver public immutable nOwnerResolver; IKarmaScore public immutable karma; struct Maps { // Map double panel tokens to burned singles mapping(uint256 => uint256[2]) burnedTokensPairings; // Mapping of valid double panel pairings (BIP39 IDs) mapping(uint16 => uint16) doubleWordPairings; // Stores the guarenteed token rarity for a double panel mapping(uint256 => uint8) doubleTokenRarity; mapping(address => bool) ogAddresses; // Map token to their unique seed mapping(uint256 => bytes32) tokenSeed; } struct Config { bool preSaleActive; bool publicSaleActive; bool isSaleHalted; bool bipWordsShuffled; bool vrfNumberGenerated; bool isBurnActive; bool isOwnerSupplyMinted; bool isGsAirdropComplete; uint8 ownerSupply; uint16 maxPublicMint; uint16 karmaRequirement; uint32 preSaleLaunchTime; uint32 publicSaleLaunchTime; uint256 doubleBurnTokens; uint256 linkFee; uint256 raribleTokenId; uint256 vrfRandomValue; address vrfCoordinator; address linkToken; bytes32 vrfKeyHash; } struct ContractAddresses { address n; address masterMint; address dao; address nOwnersRegistry; address vrfCoordinator; address linkToken; address karmaAddress; address rarible; } Config private config; Maps private maps; event Burnt(address to, uint256 firstBurntToken, uint256 secondBurntToken, uint256 doublePaneledToken); DerivativeParameters params = DerivativeParameters(false, false, 0, 2048, 4); constructor( ContractAddresses memory contractAddresses, bytes32 _vrfKeyHash, uint256 _linkFee ) SeedPhrasePricing( "Seed Phrase", "SEED", IN(contractAddresses.n), params, 30000000000000000, 60000000000000000, contractAddresses.masterMint, contractAddresses.dao ) VRFConsumerBase(contractAddresses.vrfCoordinator, contractAddresses.linkToken) { // Start token IDs at 1 _tokenIds.increment(); presaleLimits[PreSaleType.N] = 400; presaleLimits[PreSaleType.Karma] = 800; presaleLimits[PreSaleType.GenesisSketch] = 40; presaleLimits[PreSaleType.OG] = 300; presaleLimits[PreSaleType.GM] = 300; nOwnerResolver = INOwnerResolver(contractAddresses.nOwnersRegistry); rarible = IRarible(contractAddresses.rarible); karma = IKarmaScore(contractAddresses.karmaAddress); // Initialize Config struct config.maxPublicMint = 8; config.ownerSupply = 20; config.preSaleLaunchTime = 1639591200; config.publicSaleLaunchTime = 1639598400; config.raribleTokenId = 706480; config.karmaRequirement = 1020; config.vrfCoordinator = contractAddresses.vrfCoordinator; config.linkToken = contractAddresses.linkToken; config.linkFee = _linkFee; config.vrfKeyHash = _vrfKeyHash; _owner = 0x7F05F27CC5D83C3e879C53882de13Cc1cbCe8a8c; } function owner() external view virtual returns (address) { return _owner; } function setOwner(address owner_) external onlyAdmin { _owner = owner_; } function contractURI() public pure returns (string memory) { return "https://www.seedphrase.codes/metadata/seedphrase-metadata.json"; } function getVrfSeed() external onlyAdmin returns (bytes32) { require(!config.vrfNumberGenerated, "SP:VRF_ALREADY_CALLED"); require(LINK.balanceOf(address(this)) >= config.linkFee, "SP:NOT_ENOUGH_LINK"); return requestRandomness(config.vrfKeyHash, config.linkFee); } function fulfillRandomness(bytes32, uint256 randomNumber) internal override { config.vrfRandomValue = randomNumber; config.vrfNumberGenerated = true; } function _getTokenSeed(uint256 tokenId) internal view returns (bytes32) { return maps.tokenSeed[tokenId]; } function _getBipWordIdFromTokenId(uint256 tokenId) internal view returns (uint16) { return bipWordIds[tokenId - 1]; } function tokenSVG(uint256 tokenId) public view virtual returns (string memory svg, bytes memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); SeedPhraseUtils.Random memory random = SeedPhraseUtils.Random({ seed: uint256(_getTokenSeed(tokenId)), offsetBit: 0 }); uint16 bipWordId; uint16 secondBipWordId = 0; uint8 rarityValue = 0; if (tokenId >= 3000) { uint256[2] memory tokens = maps.burnedTokensPairings[tokenId]; bipWordId = _getBipWordIdFromTokenId(tokens[0]); secondBipWordId = _getBipWordIdFromTokenId(tokens[1]); rarityValue = maps.doubleTokenRarity[tokenId]; } else { bipWordId = _getBipWordIdFromTokenId(tokenId); } (bytes memory traits, SeedPhraseUtils.Attrs memory attributes) = SeedPhraseUtils.getTraitsAndAttributes( bipWordId, secondBipWordId, rarityValue, random ); return (SeedPhraseUtils.render(random, attributes), traits); } function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); (string memory output, bytes memory traits) = tokenSVG(tokenId); return SeedPhraseUtils.getTokenURI(output, traits, tokenId); } /** Updates the presale state for n holders */ function setPreSaleState(bool _preSaleActiveState) external onlyAdmin { config.preSaleActive = _preSaleActiveState; } /** Updates the public sale state for non-n holders */ function setPublicSaleState(bool _publicSaleActiveState) external onlyAdmin { config.publicSaleActive = _publicSaleActiveState; } function setPreSaleTime(uint32 _time) external onlyAdmin { config.preSaleLaunchTime = _time; } function setPublicSaleTime(uint32 _time) external onlyAdmin { config.publicSaleLaunchTime = _time; } /** Give the ability to halt the sale if necessary due to automatic sale enablement based on time */ function setSaleHaltedState(bool _saleHaltedState) external onlyAdmin { config.isSaleHalted = _saleHaltedState; } function setBurnActiveState(bool _burnActiveState) external onlyAdmin { config.isBurnActive = _burnActiveState; } function setGenesisSketchAllowList(address[] calldata addresses) external onlyAdmin { genesisSketchAddresses = addresses; } function setOgAllowList(address[] calldata addresses) external onlyAdmin { for (uint256 i = 0; i < addresses.length; i++) { maps.ogAddresses[addresses[i]] = true; } } function _isPreSaleActive() internal view returns (bool) { return ((block.timestamp >= config.preSaleLaunchTime || config.preSaleActive) && !config.isSaleHalted); } function _isPublicSaleActive() internal view override returns (bool) { return ((block.timestamp >= config.publicSaleLaunchTime || config.publicSaleActive) && !config.isSaleHalted); } function _canMintPresale( address addr, uint256 amount, bytes memory data ) internal view override returns (bool, PreSaleType) { if (maps.ogAddresses[addr] && presaleLimits[PreSaleType.OG] - amount >= 0) { return (true, PreSaleType.OG); } bool isGsHolder; for (uint256 i = 0; i < genesisSketchAddresses.length; i++) { if (genesisSketchAddresses[i] == addr) { isGsHolder = true; } } if (isGsHolder && presaleLimits[PreSaleType.GenesisSketch] - amount >= 0) { return (true, PreSaleType.GenesisSketch); } if (rarible.balanceOf(addr, config.raribleTokenId) > 0 && presaleLimits[PreSaleType.GM] - amount > 0) { return (true, PreSaleType.GM); } uint256 karmaScore = SeedPhraseUtils.getKarma(karma, data, addr); if (nOwnerResolver.balanceOf(addr) > 0) { if (karmaScore >= config.karmaRequirement && presaleLimits[PreSaleType.Karma] - amount >= 0) { return (true, PreSaleType.Karma); } if (presaleLimits[PreSaleType.N] - amount >= 0) { return (true, PreSaleType.N); } } return (false, PreSaleType.None); } function canMint(address account, bytes calldata data) public view virtual override returns (bool) { if (config.isBurnActive) { return false; } uint256 balance = balanceOf(account); if (_isPublicSaleActive() && (totalMintsAvailable() > 0) && balance < config.maxPublicMint) { return true; } if (_isPreSaleActive()) { (bool preSaleEligible, ) = _canMintPresale(account, 1, data); return preSaleEligible; } return false; } /** * @notice Allow a n token holder to bulk mint tokens with id of their n tokens' id * @param recipient Recipient of the mint * @param tokenIds Ids to be minted * @param paid Amount paid for the mint */ function mintWithN( address recipient, uint256[] calldata tokenIds, uint256 paid, bytes calldata data ) public virtual override nonReentrant { uint256 maxTokensToMint = tokenIds.length; (bool preSaleEligible, PreSaleType presaleType) = _canMintPresale(recipient, maxTokensToMint, data); require(config.bipWordsShuffled && config.vrfNumberGenerated, "SP:ENV_NOT_INIT"); require(_isPublicSaleActive() || (_isPreSaleActive() && preSaleEligible), "SP:SALE_NOT_ACTIVE"); require( balanceOf(recipient) + maxTokensToMint <= _getMaxMintPerWallet(), "NilPass:MINT_ABOVE_MAX_MINT_ALLOWANCE" ); require(!config.isBurnActive, "SP:SALE_OVER"); require(totalSupply() + maxTokensToMint <= params.maxTotalSupply, "NilPass:MAX_ALLOCATION_REACHED"); uint256 price = getNextPriceForNHoldersInWei(maxTokensToMint, recipient, data); require(paid == price, "NilPass:INVALID_PRICE"); for (uint256 i = 0; i < maxTokensToMint; i++) { require(!nUsed[tokenIds[i]], "SP:N_ALREADY_USED"); uint256 tokenId = _tokenIds.current(); require(tokenId <= params.maxTotalSupply, "SP:TOKEN_TOO_HIGH"); maps.tokenSeed[tokenId] = SeedPhraseUtils.generateSeed(tokenId, config.vrfRandomValue); _safeMint(recipient, tokenId); _tokenIds.increment(); nUsed[tokenIds[i]] = true; } if (preSaleEligible) { presaleLimits[presaleType] -= uint16(maxTokensToMint); } } /** * @notice Allow anyone to mint a token with the supply id if this pass is unrestricted. * n token holders can use this function without using the n token holders allowance, * this is useful when the allowance is fully utilized. * @param recipient Recipient of the mint * @param amount Amount of tokens to mint * @param paid Amount paid for the mint */ function mint( address recipient, uint8 amount, uint256 paid, bytes calldata data ) public virtual override nonReentrant { (bool preSaleEligible, PreSaleType presaleType) = _canMintPresale(recipient, amount, data); require(config.bipWordsShuffled && config.vrfNumberGenerated, "SP:ENV_NOT_INIT"); require( _isPublicSaleActive() || (_isPreSaleActive() && preSaleEligible && (presaleType != PreSaleType.N && presaleType != PreSaleType.Karma)), "SP:SALE_NOT_ACTIVE" ); require(!config.isBurnActive, "SP:SALE_OVER"); require(balanceOf(recipient) + amount <= _getMaxMintPerWallet(), "NilPass:MINT_ABOVE_MAX_MINT_ALLOWANCE"); require(totalSupply() + amount <= params.maxTotalSupply, "NilPass:MAX_ALLOCATION_REACHED"); uint256 price = getNextPriceForOpenMintInWei(amount, recipient, data); require(paid == price, "NilPass:INVALID_PRICE"); for (uint256 i = 0; i < amount; i++) { uint256 tokenId = _tokenIds.current(); require(tokenId <= params.maxTotalSupply, "SP:TOKEN_TOO_HIGH"); maps.tokenSeed[tokenId] = SeedPhraseUtils.generateSeed(tokenId, config.vrfRandomValue); _safeMint(recipient, tokenId); _tokenIds.increment(); } if (preSaleEligible) { presaleLimits[presaleType] -= amount; } } function mintOwnerSupply(address account) public nonReentrant onlyAdmin { require(!config.isOwnerSupplyMinted, "SP:ALREADY_MINTED"); require(config.bipWordsShuffled && config.vrfNumberGenerated, "SP:ENV_NOT_INIT"); require( totalSupply() + config.ownerSupply <= params.maxTotalSupply, "NilPass:MAX_ALLOCATION_REACHED" ); for (uint256 i = 0; i < config.ownerSupply; i++) { uint256 tokenId = _tokenIds.current(); maps.tokenSeed[tokenId] = SeedPhraseUtils.generateSeed(tokenId, config.vrfRandomValue); _mint(account, tokenId); _tokenIds.increment(); } config.isOwnerSupplyMinted = true; } /** * @notice Allow anyone to burn two single panels they own in order to mint * a double paneled token. * @param firstTokenId Token ID of the first token * @param secondTokenId Token ID of the second token */ function burnForDoublePanel(uint256 firstTokenId, uint256 secondTokenId) public nonReentrant { require(config.isBurnActive, "SP:BURN_INACTIVE"); require(ownerOf(firstTokenId) == msg.sender && ownerOf(secondTokenId) == msg.sender, "SP:INCORRECT_OWNER"); require(firstTokenId != secondTokenId, "SP:EQUAL_TOKENS"); // Ensure two owned tokens are in Burnable token pairings require( isValidPairing(_getBipWordIdFromTokenId(firstTokenId), _getBipWordIdFromTokenId(secondTokenId)), "SP:INVALID_TOKEN_PAIRING" ); _burn(firstTokenId); _burn(secondTokenId); // Any Token ID of 3000 or greater indicates it is a double panel e.g. 3000, 3001, 3002... uint256 doublePanelTokenId = 3000 + _doublePanelTokens.current(); maps.tokenSeed[doublePanelTokenId] = SeedPhraseUtils.generateSeed(doublePanelTokenId, config.vrfRandomValue); // Get the rarity rating from the burned tokens, store this against the new token // Burners are guaranteed their previous strongest trait (at least, could be rarer) uint8 rarity1 = SeedPhraseUtils.getRarityRating(_getTokenSeed(firstTokenId)); uint8 rarity2 = SeedPhraseUtils.getRarityRating(_getTokenSeed(secondTokenId)); maps.doubleTokenRarity[doublePanelTokenId] = (rarity1 > rarity2 ? rarity1 : rarity2); _mint(msg.sender, doublePanelTokenId); // Add burned tokens to maps.burnedTokensPairings mapping so we can use them to render the double panels later maps.burnedTokensPairings[doublePanelTokenId] = [firstTokenId, secondTokenId]; _doublePanelTokens.increment(); emit Burnt(msg.sender, firstTokenId, secondTokenId, doublePanelTokenId); } function airdropGenesisSketch() public nonReentrant onlyAdmin { require(!config.isGsAirdropComplete, "SP:ALREADY_AIRDROPPED"); require(config.bipWordsShuffled && config.vrfNumberGenerated, "SP:ENV_NOT_INIT"); uint256 airdropAmount = genesisSketchAddresses.length; require(totalSupply() + airdropAmount <= params.maxTotalSupply, "NilPass:MAX_ALLOCATION_REACHED"); for (uint256 i = 0; i < airdropAmount; i++) { uint256 tokenId = _tokenIds.current(); maps.tokenSeed[tokenId] = SeedPhraseUtils.generateSeed(tokenId, config.vrfRandomValue); _mint(genesisSketchAddresses[i], tokenId); _tokenIds.increment(); } config.isGsAirdropComplete = true; } function mintOrphanedPieces(uint256 amount, address addr) public nonReentrant onlyAdmin { require(totalMintsAvailable() == 0, "SP:MINT_NOT_OVER"); // _tokenIds - 1 to get the current number of minted tokens (token IDs start at 1) uint256 currentSupply = _tokenIds.current() - 1; config.doubleBurnTokens = derivativeParams.maxTotalSupply - currentSupply; require(config.doubleBurnTokens >= amount, "SP:NOT_ENOUGH_ORPHANS"); require(currentSupply + amount <= params.maxTotalSupply, "NilPass:MAX_ALLOCATION_REACHED"); for (uint256 i = 0; i < amount; i++) { uint256 tokenId = _tokenIds.current(); require(tokenId <= params.maxTotalSupply, "SP:TOKEN_TOO_HIGH"); maps.tokenSeed[tokenId] = SeedPhraseUtils.generateSeed(tokenId, config.vrfRandomValue); _mint(addr, tokenId); _tokenIds.increment(); } config.doubleBurnTokens -= amount; } /** * @notice Calculate the total available number of mints * @return total mint available */ function totalMintsAvailable() public view override returns (uint256) { uint256 totalAvailable = derivativeParams.maxTotalSupply - totalSupply(); if (block.timestamp > config.publicSaleLaunchTime + 18 hours) { // Double candle burning starts and decreases max. mintable supply with 1 token per minute. uint256 doubleBurn = (block.timestamp - (config.publicSaleLaunchTime + 18 hours)) / 1 minutes; totalAvailable = totalAvailable > doubleBurn ? totalAvailable - doubleBurn : 0; } return totalAvailable; } function getDoubleBurnedTokens() external view returns (uint256) { return config.doubleBurnTokens; } function _getMaxMintPerWallet() internal view returns (uint128) { return _isPublicSaleActive() ? config.maxPublicMint : params.maxMintAllowance; } function isValidPairing(uint16 first, uint16 second) public view returns (bool) { return maps.doubleWordPairings[first] == second; } function amendPairings(uint16[][] calldata pairings) external onlyAdmin { for (uint16 i = 0; i < pairings.length; i++) { if (pairings[i].length != 2) { continue; } maps.doubleWordPairings[pairings[i][0]] = pairings[i][1]; } } function shuffleBipWords() external onlyAdmin { require(config.vrfNumberGenerated, "SP:VRF_NOT_CALLED"); require(!config.bipWordsShuffled, "SP:ALREADY_SHUFFLED"); bipWordIds = SeedPhraseUtils.shuffleBipWords(config.vrfRandomValue); config.bipWordsShuffled = true; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library Counters { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./interfaces/LinkTokenInterface.sol"; import "./VRFRequestIDBase.sol"; /** **************************************************************************** * @notice Interface for contracts using VRF randomness * ***************************************************************************** * @dev PURPOSE * * @dev Reggie the Random Oracle (not his real job) wants to provide randomness * @dev to Vera the verifier in such a way that Vera can be sure he's not * @dev making his output up to suit himself. Reggie provides Vera a public key * @dev to which he knows the secret key. Each time Vera provides a seed to * @dev Reggie, he gives back a value which is computed completely * @dev deterministically from the seed and the secret key. * * @dev Reggie provides a proof by which Vera can verify that the output was * @dev correctly computed once Reggie tells it to her, but without that proof, * @dev the output is indistinguishable to her from a uniform random sample * @dev from the output space. * * @dev The purpose of this contract is to make it easy for unrelated contracts * @dev to talk to Vera the verifier about the work Reggie is doing, to provide * @dev simple access to a verifiable source of randomness. * ***************************************************************************** * @dev USAGE * * @dev Calling contracts must inherit from VRFConsumerBase, and can * @dev initialize VRFConsumerBase's attributes in their constructor as * @dev shown: * * @dev contract VRFConsumer { * @dev constuctor(<other arguments>, address _vrfCoordinator, address _link) * @dev VRFConsumerBase(_vrfCoordinator, _link) public { * @dev <initialization with other arguments goes here> * @dev } * @dev } * * @dev The oracle will have given you an ID for the VRF keypair they have * @dev committed to (let's call it keyHash), and have told you the minimum LINK * @dev price for VRF service. Make sure your contract has sufficient LINK, and * @dev call requestRandomness(keyHash, fee, seed), where seed is the input you * @dev want to generate randomness from. * * @dev Once the VRFCoordinator has received and validated the oracle's response * @dev to your request, it will call your contract's fulfillRandomness method. * * @dev The randomness argument to fulfillRandomness is the actual random value * @dev generated from your seed. * * @dev The requestId argument is generated from the keyHash and the seed by * @dev makeRequestId(keyHash, seed). If your contract could have concurrent * @dev requests open, you can use the requestId to track which seed is * @dev associated with which randomness. See VRFRequestIDBase.sol for more * @dev details. (See "SECURITY CONSIDERATIONS" for principles to keep in mind, * @dev if your contract could have multiple requests in flight simultaneously.) * * @dev Colliding `requestId`s are cryptographically impossible as long as seeds * @dev differ. (Which is critical to making unpredictable randomness! See the * @dev next section.) * * ***************************************************************************** * @dev SECURITY CONSIDERATIONS * * @dev A method with the ability to call your fulfillRandomness method directly * @dev could spoof a VRF response with any random value, so it's critical that * @dev it cannot be directly called by anything other than this base contract * @dev (specifically, by the VRFConsumerBase.rawFulfillRandomness method). * * @dev For your users to trust that your contract's random behavior is free * @dev from malicious interference, it's best if you can write it so that all * @dev behaviors implied by a VRF response are executed *during* your * @dev fulfillRandomness method. If your contract must store the response (or * @dev anything derived from it) and use it later, you must ensure that any * @dev user-significant behavior which depends on that stored value cannot be * @dev manipulated by a subsequent VRF request. * * @dev Similarly, both miners and the VRF oracle itself have some influence * @dev over the order in which VRF responses appear on the blockchain, so if * @dev your contract could have multiple VRF requests in flight simultaneously, * @dev you must ensure that the order in which the VRF responses arrive cannot * @dev be used to manipulate your contract's user-significant behavior. * * @dev Since the ultimate input to the VRF is mixed with the block hash of the * @dev block in which the request is made, user-provided seeds have no impact * @dev on its economic security properties. They are only included for API * @dev compatability with previous versions of this contract. * * @dev Since the block hash of the block which contains the requestRandomness * @dev call is mixed into the input to the VRF *last*, a sufficiently powerful * @dev miner could, in principle, fork the blockchain to evict the block * @dev containing the request, forcing the request to be included in a * @dev different block with a different hash, and therefore a different input * @dev to the VRF. However, such an attack would incur a substantial economic * @dev cost. This cost scales with the number of blocks the VRF oracle waits * @dev until it calls responds to a request. */ abstract contract VRFConsumerBase is VRFRequestIDBase { /** * @notice fulfillRandomness handles the VRF response. Your contract must * @notice implement it. See "SECURITY CONSIDERATIONS" above for important * @notice principles to keep in mind when implementing your fulfillRandomness * @notice method. * * @dev VRFConsumerBase expects its subcontracts to have a method with this * @dev signature, and will call it once it has verified the proof * @dev associated with the randomness. (It is triggered via a call to * @dev rawFulfillRandomness, below.) * * @param requestId The Id initially returned by requestRandomness * @param randomness the VRF output */ function fulfillRandomness( bytes32 requestId, uint256 randomness ) internal virtual; /** * @dev In order to keep backwards compatibility we have kept the user * seed field around. We remove the use of it because given that the blockhash * enters later, it overrides whatever randomness the used seed provides. * Given that it adds no security, and can easily lead to misunderstandings, * we have removed it from usage and can now provide a simpler API. */ uint256 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] + 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.4; import "../core/NilPassCore.sol"; abstract contract SeedPhrasePricing is NilPassCore { uint256 preSalePrice; uint256 publicSalePrice; constructor( string memory name, string memory symbol, IN n, DerivativeParameters memory derivativeParams, uint256 preSalePrice_, uint256 publicSalePrice_, address masterMint, address dao ) NilPassCore(name, symbol, n, derivativeParams, masterMint, dao) { preSalePrice = preSalePrice_; publicSalePrice = publicSalePrice_; } enum PreSaleType { GenesisSketch, OG, GM, Karma, N, None } function _canMintPresale( address addr, uint256 amount, bytes memory data ) internal view virtual returns (bool, PreSaleType); function _isPublicSaleActive() internal view virtual returns (bool); /** * @notice Returns the next price for an N mint */ function getNextPriceForNHoldersInWei( uint256 numberOfMints, address account, bytes memory data ) public view override returns (uint256) { (bool preSaleEligible, ) = _canMintPresale(account, numberOfMints, data); uint256 price = preSaleEligible && !_isPublicSaleActive() ? preSalePrice : publicSalePrice; return numberOfMints * price; } /** * @notice Returns the next price for an open mint */ function getNextPriceForOpenMintInWei( uint256 numberOfMints, address account, bytes memory data ) public view override returns (uint256) { (bool preSaleEligible, ) = _canMintPresale(account, numberOfMints, data); uint256 price = preSaleEligible && !_isPublicSaleActive() ? preSalePrice : publicSalePrice; return numberOfMints * price; } } // SPDX-License-Identifier: MIT pragma solidity 0.8.6; import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol"; interface IN is IERC721Enumerable, IERC721Metadata { function getFirst(uint256 tokenId) external view returns (uint256); function getSecond(uint256 tokenId) external view returns (uint256); function getThird(uint256 tokenId) external view returns (uint256); function getFourth(uint256 tokenId) external view returns (uint256); function getFifth(uint256 tokenId) external view returns (uint256); function getSixth(uint256 tokenId) external view returns (uint256); function getSeventh(uint256 tokenId) external view returns (uint256); function getEight(uint256 tokenId) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.8.6; import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol"; interface IRarible is IERC721Enumerable, IERC721Metadata { function balanceOf(address _owner, uint256 _id) external view returns (uint256); } //SPDX-License-Identifier: MIT /** @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@( (@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@( @@@@@@@@@@@@@@@@@@@@( @@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@ @@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@( @@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@( @@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@ @@@@@@@ @@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@( @@( @@( @@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@ @@ @@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@ @@@@@@@ @@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@ @@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@( @@@@@@@ @@@@@@@ @@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @ @ @@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@( @@@ @@@ @@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@ @@@@@@@ @@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@( @@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@( @@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@ @@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@( @@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@( @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ */ pragma solidity >=0.8.4; interface IKarmaScore { function verify( address account, uint256 score, bytes calldata data ) external view returns (bool); function merkleRoot() external view returns (bytes32); function setMerkleRoot(bytes32 _merkleRoot) external; } // SPDX-License-Identifier: MIT pragma solidity 0.8.6; interface INOwnerResolver { function ownerOf(uint256 nid) external view returns (address); function balanceOf(address account) external view returns (uint256); function nOwned(address owner) external view returns (uint256[] memory); } // SPDX-License-Identifier: MIT pragma solidity 0.8.6; library NilProtocolUtils { bytes internal constant TABLE = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; /// [MIT License] /// @title Base64 /// @notice Provides a function for encoding some bytes in base64 /// @author Brecht Devos <[email protected]> /// @notice Encodes some bytes to the base64 representation function base64encode(bytes memory data) external pure returns (string memory) { uint256 len = data.length; if (len == 0) return ""; // multiply by 4/3 rounded up uint256 encodedLen = 4 * ((len + 2) / 3); // Add some extra buffer at the end bytes memory result = new bytes(encodedLen + 32); bytes memory table = TABLE; assembly { let tablePtr := add(table, 1) let resultPtr := add(result, 32) for { let i := 0 } lt(i, len) { } { i := add(i, 3) let input := and(mload(add(data, i)), 0xffffff) let out := mload(add(tablePtr, and(shr(18, input), 0x3F))) out := shl(8, out) out := add(out, and(mload(add(tablePtr, and(shr(12, input), 0x3F))), 0xFF)) out := shl(8, out) out := add(out, and(mload(add(tablePtr, and(shr(6, input), 0x3F))), 0xFF)) out := shl(8, out) out := add(out, and(mload(add(tablePtr, and(input, 0x3F))), 0xFF)) out := shl(224, out) mstore(resultPtr, out) resultPtr := add(resultPtr, 4) } switch mod(len, 3) case 1 { mstore(sub(resultPtr, 2), shl(240, 0x3d3d)) } case 2 { mstore(sub(resultPtr, 1), shl(248, 0x3d)) } mstore(result, encodedLen) } return string(result); } // @notice converts number to string function stringify(uint256 value) external pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT license // 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); } } // SPDX-License-Identifier: MIT pragma solidity >=0.8.4; import "@openzeppelin/contracts/utils/Strings.sol"; import "../interfaces/IKarmaScore.sol"; import "./NilProtocolUtils.sol"; import "../libraries/NilProtocolUtils.sol"; library SeedPhraseUtils { using Strings for uint256; using Strings for uint16; using Strings for uint8; struct Random { uint256 seed; uint256 offsetBit; } struct Colors { string background; string panel; string panel2; string panelStroke; string selectedCircleStroke; string selectedCircleFill; string selectedCircleFill2; string negativeCircleStroke; string negativeCircleFill; string blackOrWhite; string dynamicOpacity; string backgroundCircle; } struct Attrs { bool showStroke; bool border; bool showPanel; bool backgroundSquare; bool bigBackgroundCircle; bool showGrid; bool backgroundCircles; bool greyscale; bool doublePanel; uint16 bipWordId; uint16 secondBipWordId; } uint8 internal constant strokeWeight = 7; uint16 internal constant segmentSize = 100; uint16 internal constant radius = 50; uint16 internal constant padding = 10; uint16 internal constant viewBox = 1600; uint16 internal constant panelWidth = segmentSize * 4; uint16 internal constant panelHeight = segmentSize * 10; uint16 internal constant singlePanelX = (segmentSize * 6); uint16 internal constant doublePanel1X = (segmentSize * 3); uint16 internal constant doublePanel2X = doublePanel1X + (segmentSize * 6); uint16 internal constant panelY = (segmentSize * 3); function generateSeed(uint256 tokenId, uint256 vrfRandomValue) external view returns (bytes32) { return keccak256(abi.encode(tokenId, block.timestamp, block.difficulty, vrfRandomValue)); } function _shouldAddTrait( bool isTrue, bytes memory trueName, bytes memory falseName, uint8 prevRank, uint8 newRank, bytes memory traits ) internal pure returns (bytes memory, uint8) { if (isTrue) { traits = abi.encodePacked(traits, ',{"value": "', trueName, '"}'); } // Only add the falsy trait if it's named (e.g. there's no negative version of "greyscale") else if (falseName.length != 0) { traits = abi.encodePacked(traits, ',{"value": "', falseName, '"}'); } // Return new (higher rank if trait is true) return (traits, (isTrue ? newRank : prevRank)); } function tokenTraits(Attrs memory attributes) internal pure returns (bytes memory traits, uint8 rarityRating) { rarityRating = 0; traits = abi.encodePacked("["); // Add both words to trait if a double panel if (attributes.doublePanel) { traits = abi.encodePacked( traits, '{"trait_type": "Double Panel BIP39 IDs", "value": "', attributes.bipWordId.toString(), " - ", attributes.secondBipWordId.toString(), '"},', '{"value": "Double Panel"}' ); } else { traits = abi.encodePacked( traits, '{"trait_type": "BIP39 ID", "display_type": "number", "max_value": 2048, "value": ', attributes.bipWordId.toString(), "}" ); } // Stroke trait - rank 1 (traits, rarityRating) = _shouldAddTrait( !attributes.showStroke, "No Stroke", "OG Stroke", rarityRating, 1, traits ); // Border - rank 2 (traits, rarityRating) = _shouldAddTrait(attributes.border, "Border", "", rarityRating, 2, traits); // No Panel - rank 3 (traits, rarityRating) = _shouldAddTrait( !attributes.showPanel, "No Panel", "OG Panel", rarityRating, 3, traits ); // Symmetry Group Square - rank 4 (traits, rarityRating) = _shouldAddTrait( attributes.backgroundSquare, "Group Square", "", rarityRating, 4, traits ); // Symmetry Group Circle - rank 5 (traits, rarityRating) = _shouldAddTrait( attributes.bigBackgroundCircle, "Group Circle", "", rarityRating, 5, traits ); // Caged - rank 6 (traits, rarityRating) = _shouldAddTrait(attributes.showGrid, "Caged", "", rarityRating, 6, traits); // Bubblewrap - rank 7 (traits, rarityRating) = _shouldAddTrait( attributes.backgroundCircles, "Bubblewrap", "", rarityRating, 7, traits ); // Monochrome - rank 8 (traits, rarityRating) = _shouldAddTrait(attributes.greyscale, "Monochrome", "", rarityRating, 8, traits); traits = abi.encodePacked(traits, "]"); } /** * @notice Generates the art defining attributes * @param bipWordId bip39 word id * @param secondBipWordId ^ only for a double panel * @param random RNG * @param predefinedRarity double panels trait to carry over * @return attributes struct */ function tokenAttributes( uint16 bipWordId, uint16 secondBipWordId, Random memory random, uint8 predefinedRarity ) internal pure returns (Attrs memory attributes) { attributes = Attrs({ showStroke: (predefinedRarity == 1) ? false : _boolPercentage(random, 70), // rank 1 border: (predefinedRarity == 2) ? true : _boolPercentage(random, 30), // rank 2 showPanel: (predefinedRarity == 3) ? false : _boolPercentage(random, 80), // rank 3 backgroundSquare: (predefinedRarity == 4) ? true : _boolPercentage(random, 18), // rank 4 bigBackgroundCircle: (predefinedRarity == 5) ? true : _boolPercentage(random, 12), // rank = 5 showGrid: (predefinedRarity == 6) ? true : _boolPercentage(random, 6), // rank 6 backgroundCircles: (predefinedRarity == 7) ? true : _boolPercentage(random, 4), // rank 7 greyscale: (predefinedRarity == 8) ? true : _boolPercentage(random, 2), // rank 8 bipWordId: bipWordId, doublePanel: (secondBipWordId > 0), secondBipWordId: secondBipWordId }); // Rare attributes should always superseed less-rare // If greyscale OR grid is true then turn on stroke (as it is required) if (attributes.showGrid || attributes.greyscale) { attributes.showStroke = true; } // backgroundCircles superseeds grid (they cannot co-exist) if (attributes.backgroundCircles) { attributes.showGrid = false; } // Border cannot be on if background shapes are turned on if (attributes.bigBackgroundCircle || attributes.backgroundSquare) { attributes.border = false; // Big Background Shapes cannot co-exist if (attributes.bigBackgroundCircle) { attributes.backgroundSquare = false; } } } /** * @notice Converts a tokenId (uint256) into the formats needed to generate the art * @param tokenId tokenId (also the BIP39 word) * @return tokenArray with prepended 0's (if tokenId is less that 4 digits) also returns in string format */ function _transformTokenId(uint256 tokenId) internal pure returns (uint8[4] memory tokenArray, string memory) { bytes memory tokenString; uint8 digit; for (int8 i = 3; i >= 0; i--) { digit = uint8(tokenId % 10); // This returns the final digit in the token if (tokenId > 0) { tokenId = tokenId / 10; // this removes the last digit from the token as we've grabbed the digit already tokenArray[uint8(i)] = digit; } tokenString = abi.encodePacked(digit.toString(), tokenString); } return (tokenArray, string(tokenString)); } function _renderText(string memory text, string memory color) internal pure returns (bytes memory svg) { svg = abi.encodePacked( "<text x='1500' y='1500' text-anchor='end' style='font:700 36px &quot;Courier New&quot;;fill:", color, ";opacity:.4'>#", text, "</text>" ); return svg; } function _backgroundShapeSizing(Random memory random, Attrs memory attributes) internal pure returns (uint16, uint16) { uint256 idx; // If we DON'T have a 'doublePanel' or 'no panel' we can return the default sizing if (!attributes.doublePanel && attributes.showPanel) { uint16[2][6] memory defaultSizing = [ [1275, 200], [1150, 375], [900, 300], [925, 225], [850, 150], [775, 125] ]; idx = SeedPhraseUtils._next(random, 0, defaultSizing.length); return (defaultSizing[idx][0], defaultSizing[idx][1]); } // Otherwise we need to return some slightly different data if (attributes.bigBackgroundCircle) { uint16[2][4] memory restrictedCircleDimensions = [[1150, 150], [1275, 200], [1300, 100], [1350, 200]]; idx = SeedPhraseUtils._next(random, 0, restrictedCircleDimensions.length); return (restrictedCircleDimensions[idx][0], restrictedCircleDimensions[idx][1]); } // Else we can assume that it is backgroundSquares uint16[2][4] memory restrictedSquareDimensions = [[1150, 50], [1100, 125], [1275, 200], [1300, 150]]; idx = SeedPhraseUtils._next(random, 0, restrictedSquareDimensions.length); return (restrictedSquareDimensions[idx][0], restrictedSquareDimensions[idx][1]); } function _getStrokeStyle( bool showStroke, string memory color, string memory opacity, uint8 customStrokeWeight ) internal pure returns (bytes memory strokeStyle) { if (showStroke) { strokeStyle = abi.encodePacked( " style='stroke-opacity:", opacity, ";stroke:", color, ";stroke-width:", customStrokeWeight.toString(), "' " ); return strokeStyle; } } function _getPalette(Random memory random, Attrs memory attributes) internal pure returns (Colors memory) { string[6] memory selectedPallet; uint8[6] memory lumosity; if (attributes.greyscale) { selectedPallet = ["#f8f9fa", "#c3c4c4", "#909091", "#606061", "#343435", "#0a0a0b"]; lumosity = [249, 196, 144, 96, 52, 10]; } else { uint256 randPalette = SeedPhraseUtils._next(random, 0, 25); if (randPalette == 0) { selectedPallet = ["#ffe74c", "#ff5964", "#ffffff", "#6bf178", "#35a7ff", "#5b3758"]; lumosity = [225, 125, 255, 204, 149, 65]; } else if (randPalette == 1) { selectedPallet = ["#ff0000", "#ff8700", "#e4ff33", "#a9ff1f", "#0aefff", "#0a33ff"]; lumosity = [54, 151, 235, 221, 191, 57]; } else if (randPalette == 2) { selectedPallet = ["#f433ab", "#cb04a5", "#934683", "#65334d", "#2d1115", "#e0e2db"]; lumosity = [101, 58, 91, 64, 23, 225]; } else if (randPalette == 3) { selectedPallet = ["#f08700", "#f6aa28", "#f9d939", "#00a6a6", "#bbdef0", "#23556c"]; lumosity = [148, 177, 212, 131, 216, 76]; } else if (randPalette == 4) { selectedPallet = ["#f7e6de", "#e5b59e", "#cb7d52", "#bb8f77", "#96624a", "#462b20"]; lumosity = [233, 190, 138, 151, 107, 48]; } else if (randPalette == 5) { selectedPallet = ["#f61379", "#d91cbc", "#da81ee", "#5011e4", "#4393ef", "#8edef6"]; lumosity = [75, 80, 156, 46, 137, 207]; } else if (randPalette == 6) { selectedPallet = ["#010228", "#006aa3", "#005566", "#2ac1df", "#82dded", "#dbf5fa"]; lumosity = [5, 88, 68, 163, 203, 240]; } else if (randPalette == 7) { selectedPallet = ["#f46036", "#5b85aa", "#414770", "#372248", "#171123", "#f7f5fb"]; lumosity = [124, 127, 73, 41, 20, 246]; } else if (randPalette == 8) { selectedPallet = ["#393d3f", "#fdfdff", "#c6c5b9", "#62929e", "#546a7b", "#c52233"]; lumosity = [60, 253, 196, 137, 103, 70]; } else if (randPalette == 9) { selectedPallet = ["#002626", "#0e4749", "#95c623", "#e55812", "#efe7da", "#8ddbe0"]; lumosity = [30, 59, 176, 113, 232, 203]; } else if (randPalette == 10) { selectedPallet = ["#03071e", "#62040d", "#d00000", "#e85d04", "#faa307", "#ffcb47"]; lumosity = [8, 25, 44, 116, 170, 205]; } else if (randPalette == 11) { selectedPallet = ["#f56a00", "#ff931f", "#ffd085", "#20003d", "#7b2cbf", "#c698eb"]; lumosity = [128, 162, 213, 11, 71, 168]; } else if (randPalette == 12) { selectedPallet = ["#800016", "#ffffff", "#ff002b", "#407ba7", "#004e89", "#00043a"]; lumosity = [29, 255, 57, 114, 66, 7]; } else if (randPalette == 13) { selectedPallet = ["#d6d6d6", "#f9f7dc", "#ffee32", "#ffd100", "#202020", "#6c757d"]; lumosity = [214, 245, 228, 204, 32, 116]; } else if (randPalette == 14) { selectedPallet = ["#fff5d6", "#ccc5b9", "#403d39", "#252422", "#eb5e28", "#bb4111"]; lumosity = [245, 198, 61, 36, 120, 87]; } else if (randPalette == 15) { selectedPallet = ["#0c0f0a", "#ff206e", "#fbff12", "#41ead4", "#6c20fd", "#ffffff"]; lumosity = [14, 85, 237, 196, 224, 255]; } else if (randPalette == 16) { selectedPallet = ["#fdd8d8", "#f67979", "#e51010", "#921314", "#531315", "#151315"]; lumosity = [224, 148, 61, 46, 33, 20]; } else if (randPalette == 17) { selectedPallet = ["#000814", "#002752", "#0066cc", "#f5bc00", "#ffd60a", "#ffee99"]; lumosity = [7, 34, 88, 187, 208, 235]; } else if (randPalette == 18) { selectedPallet = ["#010b14", "#022d4f", "#fdfffc", "#2ec4b6", "#e71d36", "#ff990a"]; lumosity = [10, 38, 254, 163, 74, 164]; } else if (randPalette == 19) { selectedPallet = ["#fd650d", "#d90368", "#820263", "#291720", "#06efa9", "#0d5943"]; lumosity = [127, 56, 36, 27, 184, 71]; } else if (randPalette == 20) { selectedPallet = ["#002914", "#005200", "#34a300", "#70e000", "#aef33f", "#e0ff85"]; lumosity = [31, 59, 128, 184, 215, 240]; } else if (randPalette == 21) { selectedPallet = ["#001413", "#fafffe", "#6f0301", "#a92d04", "#f6b51d", "#168eb6"]; lumosity = [16, 254, 26, 68, 184, 119]; } else if (randPalette == 22) { selectedPallet = ["#6a1f10", "#d53e20", "#f7d1ca", "#c4f3fd", "#045362", "#fffbfa"]; lumosity = [46, 92, 217, 234, 67, 252]; } else if (randPalette == 23) { selectedPallet = ["#6b42ff", "#a270ff", "#dda1f7", "#ffd6eb", "#ff8fb2", "#f56674"]; lumosity = [88, 133, 180, 224, 169, 133]; } else if (randPalette == 24) { selectedPallet = ["#627132", "#273715", "#99a271", "#fefae1", "#e0a35c", "#bf6b21"]; lumosity = [105, 49, 157, 249, 171, 120]; } } // Randomize pallet order here... return _shufflePallet(random, selectedPallet, lumosity, attributes); } function _shufflePallet( Random memory random, string[6] memory hexColors, uint8[6] memory lumaValues, Attrs memory attributes ) internal pure returns (Colors memory) { // Shuffle colors and luma values with the same index for (uint8 i = 0; i < hexColors.length; i++) { // n = Pick random i > (array length - i) uint256 n = i + SeedPhraseUtils._next(random, 0, (hexColors.length - i)); // temp = Temporarily store value from array[n] string memory tempHex = hexColors[n]; uint8 tempLuma = lumaValues[n]; // Swap n value with i value hexColors[n] = hexColors[i]; hexColors[i] = tempHex; lumaValues[n] = lumaValues[i]; lumaValues[i] = tempLuma; } Colors memory pallet = Colors({ background: hexColors[0], panel: hexColors[1], panel2: "", // panel2 should match selected circles panelStroke: hexColors[2], selectedCircleStroke: hexColors[2], // Match panel stroke negativeCircleStroke: hexColors[3], negativeCircleFill: hexColors[4], selectedCircleFill: hexColors[5], selectedCircleFill2: "", // should match panel1 backgroundCircle: "", blackOrWhite: lumaValues[0] < 150 ? "#fff" : "#000", dynamicOpacity: lumaValues[0] < 150 ? "0.08" : "0.04" }); if (attributes.doublePanel) { pallet.panel2 = pallet.selectedCircleFill; pallet.selectedCircleFill2 = pallet.panel; } if (attributes.bigBackgroundCircle) { // Set background circle colors here pallet.backgroundCircle = pallet.background; pallet.background = pallet.panel; // Luma based on 'new background', previous background is used for bgCircleColor) pallet.blackOrWhite = lumaValues[1] < 150 ? "#fff" : "#000"; pallet.dynamicOpacity = lumaValues[1] < 150 ? "0.08" : "0.04"; } return pallet; } /// @notice get an random number between (min and max) using seed and offseting bits /// this function assumes that max is never bigger than 0xffffff (hex color with opacity included) /// @dev this function is simply used to get random number using a seed. /// if does bitshifting operations to try to reuse the same seed as much as possible. /// should be enough for anyth /// @param random the randomizer /// @param min the minimum /// @param max the maximum /// @return result the resulting pseudo random number function _next( Random memory random, uint256 min, uint256 max ) internal pure returns (uint256 result) { uint256 newSeed = random.seed; uint256 newOffset = random.offsetBit + 3; uint256 maxOffset = 4; uint256 mask = 0xf; if (max > 0xfffff) { mask = 0xffffff; maxOffset = 24; } else if (max > 0xffff) { mask = 0xfffff; maxOffset = 20; } else if (max > 0xfff) { mask = 0xffff; maxOffset = 16; } else if (max > 0xff) { mask = 0xfff; maxOffset = 12; } else if (max > 0xf) { mask = 0xff; maxOffset = 8; } // if offsetBit is too high to get the max number // just get new seed and restart offset to 0 if (newOffset > (256 - maxOffset)) { newOffset = 0; newSeed = uint256(keccak256(abi.encode(newSeed))); } uint256 offseted = (newSeed >> newOffset); uint256 part = offseted & mask; result = min + (part % (max - min)); random.seed = newSeed; random.offsetBit = newOffset; } function _boolPercentage(Random memory random, uint256 percentage) internal pure returns (bool) { // E.G. If percentage = 30, and random = 0-29 we return true // Percentage = 1, random = 0 (TRUE) return (SeedPhraseUtils._next(random, 0, 100) < percentage); } /// @param random source of randomness (based on tokenSeed) /// @param attributes art attributes /// @return the json function render(SeedPhraseUtils.Random memory random, SeedPhraseUtils.Attrs memory attributes) external pure returns (string memory) { // Get color pallet SeedPhraseUtils.Colors memory pallet = SeedPhraseUtils._getPalette(random, attributes); // Start SVG (viewbox & static patterns) bytes memory svg = abi.encodePacked( "<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 1600 1600'><path fill='", pallet.background, "' ", SeedPhraseUtils._getStrokeStyle(attributes.border, pallet.blackOrWhite, "0.3", 50), " d='M0 0h1600v1600H0z'/>", " <pattern id='panelCircles' x='0' y='0' width='.25' height='.1' patternUnits='objectBoundingBox'>", "<circle cx='50' cy='50' r='40' fill='", pallet.negativeCircleFill, "' ", SeedPhraseUtils._getStrokeStyle(attributes.showStroke, pallet.negativeCircleStroke, "1", strokeWeight), " /></pattern>" ); // Render optional patterns (grid OR background circles) if (attributes.backgroundCircles) { svg = abi.encodePacked( svg, "<pattern id='backgroundCircles' x='0' y='0' width='100' height='100'", " patternUnits='userSpaceOnUse'><circle cx='50' cy='50' r='40' fill='", pallet.blackOrWhite, "' style='fill-opacity: ", pallet.dynamicOpacity, ";'></circle></pattern><path fill='url(#backgroundCircles)' d='M0 0h1600v1600H0z'/>" ); } else if (attributes.showGrid) { svg = abi.encodePacked( svg, "<pattern id='grid' x='0' y='0' width='100' height='100'", " patternUnits='userSpaceOnUse'><rect x='0' y='0' width='100' height='100' fill='none' ", SeedPhraseUtils._getStrokeStyle(true, pallet.blackOrWhite, pallet.dynamicOpacity, strokeWeight), " /></pattern><path fill='url(#grid)' d='M0 0h1600v1600H0z'/>" ); } if (attributes.bigBackgroundCircle) { (uint16 shapeSize, uint16 stroke) = SeedPhraseUtils._backgroundShapeSizing(random, attributes); // uint16 centerCircle = (viewBox / 2); // Viewbox = 1600, Center = 800 svg = abi.encodePacked( svg, "<circle cx='800' cy='800' r='", (shapeSize / 2).toString(), "' fill='", pallet.backgroundCircle, "' stroke='", pallet.negativeCircleStroke, "' style='stroke-width:", stroke.toString(), ";stroke-opacity:0.3'/>" ); } else if (attributes.backgroundSquare) { (uint16 shapeSize, uint16 stroke) = SeedPhraseUtils._backgroundShapeSizing(random, attributes); uint16 centerSquare = ((viewBox - shapeSize) / 2); svg = abi.encodePacked( svg, "<rect x='", centerSquare.toString(), "' y='", centerSquare.toString(), "' width='", shapeSize.toString(), "' height='", shapeSize.toString(), "' fill='", pallet.backgroundCircle, "' stroke='", pallet.negativeCircleStroke, "' style='stroke-width:", stroke.toString(), ";stroke-opacity:0.3'/>" ); } // Double panel (only if holder has burned two tokens from the defined pairings) if (attributes.doublePanel) { (uint8[4] memory firstBipIndexArray, string memory firstBipIndexStr) = SeedPhraseUtils._transformTokenId( attributes.bipWordId ); (uint8[4] memory secondBipIndexArray, string memory secondBipIndexStr) = SeedPhraseUtils._transformTokenId( attributes.secondBipWordId ); svg = abi.encodePacked( svg, _renderSinglePanel(firstBipIndexArray, attributes, pallet, doublePanel1X, false), _renderSinglePanel(secondBipIndexArray, attributes, pallet, doublePanel2X, true) ); // Create text bytes memory combinedText = abi.encodePacked(firstBipIndexStr, " - #", secondBipIndexStr); svg = abi.encodePacked( svg, SeedPhraseUtils._renderText(string(combinedText), pallet.blackOrWhite), "</svg>" ); } // Single Panel else { (uint8[4] memory bipIndexArray, string memory bipIndexStr) = SeedPhraseUtils._transformTokenId( attributes.bipWordId ); svg = abi.encodePacked(svg, _renderSinglePanel(bipIndexArray, attributes, pallet, singlePanelX, false)); // Add closing text and svg element svg = abi.encodePacked(svg, SeedPhraseUtils._renderText(bipIndexStr, pallet.blackOrWhite), "</svg>"); } return string(svg); } function _renderSinglePanel( uint8[4] memory bipIndexArray, SeedPhraseUtils.Attrs memory attributes, SeedPhraseUtils.Colors memory pallet, uint16 panelX, bool secondPanel ) internal pure returns (bytes memory panelSvg) { // Draw panels bool squareEdges = (attributes.doublePanel && attributes.backgroundSquare); if (attributes.showPanel) { panelSvg = abi.encodePacked( "<rect x='", (panelX - padding).toString(), "' y='", (panelY - padding).toString(), "' width='", (panelWidth + (padding * 2)).toString(), "' height='", (panelHeight + (padding * 2)).toString(), "' rx='", (squareEdges ? 0 : radius).toString(), "' fill='", (secondPanel ? pallet.panel2 : pallet.panel), "' ", SeedPhraseUtils._getStrokeStyle(attributes.showStroke, pallet.panelStroke, "1", strokeWeight), "/>" ); } // Fill panel with negative circles, should resemble M600 300h400v1000H600z panelSvg = abi.encodePacked( panelSvg, "<path fill='url(#panelCircles)' d='M", panelX.toString(), " ", panelY.toString(), "h", panelWidth.toString(), "v", panelHeight.toString(), "H", panelX.toString(), "z'/>" ); // Draw selected circles panelSvg = abi.encodePacked( panelSvg, _renderSelectedCircles(bipIndexArray, pallet, attributes.showStroke, panelX, secondPanel) ); } function _renderSelectedCircles( uint8[4] memory bipIndexArray, SeedPhraseUtils.Colors memory pallet, bool showStroke, uint16 panelX, bool secondPanel ) internal pure returns (bytes memory svg) { for (uint8 i = 0; i < bipIndexArray.length; i++) { svg = abi.encodePacked( svg, "<circle cx='", (panelX + (segmentSize * i) + radius).toString(), "' cy='", (panelY + (segmentSize * bipIndexArray[i]) + radius).toString(), "' r='41' fill='", // Increase the size a tiny bit here (+1) to hide negative circle outline (secondPanel ? pallet.selectedCircleFill2 : pallet.selectedCircleFill), "' ", SeedPhraseUtils._getStrokeStyle(showStroke, pallet.selectedCircleStroke, "1", strokeWeight), " />" ); } } function getRarityRating(bytes32 tokenSeed) external pure returns (uint8) { SeedPhraseUtils.Random memory random = SeedPhraseUtils.Random({ seed: uint256(tokenSeed), offsetBit: 0 }); (, uint8 rarityRating) = SeedPhraseUtils.tokenTraits(SeedPhraseUtils.tokenAttributes(0, 0, random, 0)); return rarityRating; } function getTraitsAndAttributes( uint16 bipWordId, uint16 secondBipWordId, uint8 rarityValue, SeedPhraseUtils.Random memory random ) external pure returns (bytes memory, SeedPhraseUtils.Attrs memory) { SeedPhraseUtils.Attrs memory attributes = SeedPhraseUtils.tokenAttributes( bipWordId, secondBipWordId, random, rarityValue ); (bytes memory traits, ) = SeedPhraseUtils.tokenTraits(attributes); return (traits, attributes); } function getKarma(IKarmaScore karma, bytes memory data, address account) external view returns (uint256) { if (data.length > 0) { (, uint256 karmaScore, ) = abi.decode(data, (address, uint256, bytes32[])); if (karma.verify(account, karmaScore, data)) { return account == address(0) ? 1000 : karmaScore; } } return 1000; } function shuffleBipWords(uint256 randomValue) external pure returns (uint16[] memory) { uint16 size = 2048; uint16[] memory result = new uint16[](size); // Initialize array. for (uint16 i = 0; i < size; i++) { result[i] = i + 1; } // Set the initial randomness based on the provided entropy from VRF. bytes32 random = keccak256(abi.encodePacked(randomValue)); // Set the last item of the array which will be swapped. uint16 lastItem = size - 1; // We need to do `size - 1` iterations to completely shuffle the array. for (uint16 i = 1; i < size - 1; i++) { // Select a number based on the randomness. uint16 selectedItem = uint16(uint256(random) % lastItem); // Swap items `selected_item <> last_item`. (result[lastItem], result[selectedItem]) = (result[selectedItem], result[lastItem]); // Decrease the size of the possible shuffle // to preserve the already shuffled items. // The already shuffled items are at the end of the array. lastItem--; // Generate new randomness. random = keccak256(abi.encodePacked(random)); } return result; } function getDescriptionPt1() internal pure returns (string memory) { return "\"Seed Phrase is a 'Crypto Native' *fully* on-chain collection.\\n\\nA '*SEED*' is unique, it represents a single word from the BIP-0039 word list (the most commonly used word list to generate a seed/recovery phrase, think of it as a dictionary that only holds 2048 words).\\n\\n***Your 'SEED*' = *Your 'WORD*' in the list.** \\nClick [here](https://www.seedphrase.codes/token?id="; } function getDescriptionPt2() internal pure returns (string memory) { return ") to decipher *your 'SEED*' and find out which word it translates to!\\n\\nFor Licensing, T&Cs or any other info, please visit: [www.seedphrase.codes](https://www.seedphrase.codes/).\""; } function getTokenURI(string memory output, bytes memory traits, uint256 tokenId) external pure returns (string memory) { return string( abi.encodePacked( "data:application/json;base64,", NilProtocolUtils.base64encode( bytes( string( abi.encodePacked( '{"name": "Seed Phrase #', NilProtocolUtils.stringify(tokenId), '", "image": "data:image/svg+xml;base64,', NilProtocolUtils.base64encode(bytes(output)), '", "attributes": ', traits, ', "description": ', getDescriptionPt1(), tokenId.toString(), getDescriptionPt2(), "}" ) ) ) ) ) ); } } // 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; 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; interface LinkTokenInterface { function allowance( address owner, address spender ) external view returns ( uint256 remaining ); function approve( address spender, uint256 value ) external returns ( bool success ); function balanceOf( address owner ) external view returns ( uint256 balance ); function decimals() external view returns ( uint8 decimalPlaces ); function decreaseApproval( address spender, uint256 addedValue ) external returns ( bool success ); function increaseApproval( address spender, uint256 subtractedValue ) external; function name() external view returns ( string memory tokenName ); function symbol() external view returns ( string memory tokenSymbol ); function totalSupply() external view returns ( uint256 totalTokensIssued ); function transfer( address to, uint256 value ) external returns ( bool success ); function transferAndCall( address to, uint256 value, bytes calldata data ) external returns ( bool success ); function transferFrom( address from, address to, uint256 value ) external returns ( bool success ); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; contract VRFRequestIDBase { /** * @notice returns the seed which is actually input to the VRF coordinator * * @dev To prevent repetition of VRF output due to repetition of the * @dev user-supplied seed, that seed is combined in a hash with the * @dev user-specific nonce, and the address of the consuming contract. The * @dev risk of repetition is mostly mitigated by inclusion of a blockhash in * @dev the final seed, but the nonce does protect against repetition in * @dev requests which are included in a single block. * * @param _userSeed VRF seed input provided by user * @param _requester Address of the requesting contract * @param _nonce User-specific nonce at the time of the request */ function makeVRFInputSeed( bytes32 _keyHash, uint256 _userSeed, address _requester, uint256 _nonce ) internal pure returns ( uint256 ) { return uint256(keccak256(abi.encode(_keyHash, _userSeed, _requester, _nonce))); } /** * @notice Returns the id for this request * @param _keyHash The serviceAgreement ID to be used for this request * @param _vRFInputSeed The seed to be passed directly to the VRF * @return The id for this request * * @dev Note that _vRFInputSeed is not the seed passed by the consuming * @dev contract, but the one generated by makeVRFInputSeed */ function makeRequestId( bytes32 _keyHash, uint256 _vRFInputSeed ) internal pure returns ( bytes32 ) { return keccak256(abi.encodePacked(_keyHash, _vRFInputSeed)); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.6; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts/utils/math/Math.sol"; import "../interfaces/IN.sol"; import "../interfaces/INilPass.sol"; import "../interfaces/IPricingStrategy.sol"; /** * @title NilPassCore contract * @author Tony Snark * @notice This contract provides basic functionalities to allow minting using the NilPass * @dev This contract should be used only for testing or testnet deployments */ abstract contract NilPassCore is ERC721Enumerable, ReentrancyGuard, AccessControl, INilPass, IPricingStrategy { uint128 public constant MAX_MULTI_MINT_AMOUNT = 32; uint128 public constant MAX_N_TOKEN_ID = 8888; bytes32 public constant ADMIN_ROLE = keccak256("ADMIN"); bytes32 public constant DAO_ROLE = keccak256("DAO"); IN public immutable n; uint16 public reserveMinted; uint256 public mintedOutsideNRange; address public masterMint; DerivativeParameters public derivativeParams; uint128 maxTokenId; struct DerivativeParameters { bool onlyNHolders; bool supportsTokenId; uint16 reservedAllowance; uint128 maxTotalSupply; uint128 maxMintAllowance; } event Minted(address to, uint256 tokenId); /** * @notice Construct an NilPassCore instance * @param name Name of the token * @param symbol Symbol of the token * @param n_ Address of your n instance (only for testing) * @param derivativeParams_ Parameters describing the derivative settings * @param masterMint_ Address of the master mint contract * @param dao_ Address of the NIL DAO */ constructor( string memory name, string memory symbol, IN n_, DerivativeParameters memory derivativeParams_, address masterMint_, address dao_ ) ERC721(name, symbol) { derivativeParams = derivativeParams_; require(derivativeParams.maxTotalSupply > 0, "NilPass:INVALID_SUPPLY"); require( !derivativeParams.onlyNHolders || (derivativeParams.onlyNHolders && derivativeParams.maxTotalSupply <= MAX_N_TOKEN_ID), "NilPass:INVALID_SUPPLY" ); require(derivativeParams.maxTotalSupply >= derivativeParams.reservedAllowance, "NilPass:INVALID_ALLOWANCE"); require(masterMint_ != address(0), "NilPass:INVALID_MASTERMINT"); require(dao_ != address(0), "NilPass:INVALID_DAO"); n = n_; masterMint = masterMint_; derivativeParams.maxMintAllowance = derivativeParams.maxMintAllowance < MAX_MULTI_MINT_AMOUNT ? derivativeParams.maxMintAllowance : MAX_MULTI_MINT_AMOUNT; maxTokenId = derivativeParams.maxTotalSupply > MAX_N_TOKEN_ID ? derivativeParams.maxTotalSupply : MAX_N_TOKEN_ID; _setupRole(ADMIN_ROLE, msg.sender); _setupRole(DAO_ROLE, dao_); _setRoleAdmin(ADMIN_ROLE, ADMIN_ROLE); _setRoleAdmin(DAO_ROLE, DAO_ROLE); } modifier onlyAdmin() { require(hasRole(ADMIN_ROLE, msg.sender), "Nil:ACCESS_DENIED"); _; } modifier onlyDAO() { require(hasRole(DAO_ROLE, msg.sender), "Nil:ACCESS_DENIED"); _; } /** * @notice Allow anyone to mint a token with the supply id if this pass is unrestricted. * n token holders can use this function without using the n token holders allowance, * this is useful when the allowance is fully utilized. */ function mint( address, uint8, uint256, bytes calldata ) public virtual override nonReentrant { require(false, "MINTING DISABLED"); } /** * @notice Allow anyone to mint multiple tokens with the provided IDs if this pass is unrestricted. * n token holders can use this function without using the n token holders allowance, * this is useful when the allowance is fully utilized. */ function mintTokenId( address, uint256[] calldata, uint256, bytes calldata ) public virtual override nonReentrant { require(false, "MINTING DISABLED"); } /** * @notice Allow a n token holder to bulk mint tokens with id of their n tokens' id */ function mintWithN( address, uint256[] calldata, uint256, bytes calldata ) public virtual override nonReentrant { require(false, "MINTING DISABLED"); } /** * @dev Safely mints `tokenId` and transfers it to `to` */ function _safeMint(address to, uint256 tokenId) internal virtual override { require(msg.sender == masterMint, "NilPass:INVALID_MINTER"); super._safeMint(to, tokenId); emit Minted(to, tokenId); } /** * @notice Set the exclusivity flag to only allow N holders to mint * @param status Boolean to enable or disable N holder exclusivity */ function setOnlyNHolders(bool status) public onlyAdmin { derivativeParams.onlyNHolders = status; } /** * @notice Calculate the currently available number of reserved tokens for n token holders * @return Reserved mint available */ function nHoldersMintsAvailable() public view returns (uint256) { return derivativeParams.reservedAllowance - reserveMinted; } /** * @notice Calculate the currently available number of open mints * @return Open mint available */ function openMintsAvailable() public view returns (uint256) { uint256 maxOpenMints = derivativeParams.maxTotalSupply - derivativeParams.reservedAllowance; uint256 currentOpenMints = totalSupply() - reserveMinted; return maxOpenMints - currentOpenMints; } /** * @notice Calculate the total available number of mints * @return total mint available */ function totalMintsAvailable() public view virtual override returns (uint256) { return nHoldersMintsAvailable() + openMintsAvailable(); } function mintParameters() external view override returns (INilPass.MintParams memory) { return INilPass.MintParams({ reservedAllowance: derivativeParams.reservedAllowance, maxTotalSupply: derivativeParams.maxTotalSupply, openMintsAvailable: openMintsAvailable(), totalMintsAvailable: totalMintsAvailable(), nHoldersMintsAvailable: nHoldersMintsAvailable(), nHolderPriceInWei: getNextPriceForNHoldersInWei(1, address(0x1), ""), openPriceInWei: getNextPriceForOpenMintInWei(1, address(0x1), ""), totalSupply: totalSupply(), onlyNHolders: derivativeParams.onlyNHolders, maxMintAllowance: derivativeParams.maxMintAllowance, supportsTokenId: derivativeParams.supportsTokenId }); } /** * @notice Check if a token with an Id exists * @param tokenId The token Id to check for */ function tokenExists(uint256 tokenId) external view override returns (bool) { return _exists(tokenId); } function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721Enumerable, IERC165, AccessControl) returns (bool) { return super.supportsInterface(interfaceId); } function maxTotalSupply() external view override returns (uint256) { return derivativeParams.maxTotalSupply; } function reservedAllowance() public view returns (uint16) { return derivativeParams.reservedAllowance; } function getNextPriceForNHoldersInWei( uint256 numberOfMints, address account, bytes memory data ) public view virtual override returns (uint256); function getNextPriceForOpenMintInWei( uint256 numberOfMints, address account, bytes memory data ) public view virtual override returns (uint256); function canMint(address account, bytes calldata data) external view virtual override returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC721.sol"; import "./IERC721Enumerable.sol"; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IAccessControl.sol"; import "../utils/Context.sol"; import "../utils/Strings.sol"; import "../utils/introspection/ERC165.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context, IAccessControl, ERC165 { struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ */ function _checkRole(bytes32 role, address account) internal view { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", Strings.toHexString(uint160(account), 20), " is missing role ", Strings.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } function _grantRole(bytes32 role, address account) private { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow. return (a & b) + (a ^ b) / 2; } /** * @dev Returns the ceiling of the division of two numbers. * * This differs from standard division with `/` in that it rounds up instead * of rounding down. */ function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b - 1) / b can overflow on addition, so we distribute. return a / b + (a % b == 0 ? 0 : 1); } } // SPDX-License-Identifier: MIT pragma solidity >=0.8.4; import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol"; interface INilPass is IERC721Enumerable { struct MintParams { uint256 reservedAllowance; uint256 maxTotalSupply; uint256 nHoldersMintsAvailable; uint256 openMintsAvailable; uint256 totalMintsAvailable; uint256 nHolderPriceInWei; uint256 openPriceInWei; uint256 totalSupply; uint256 maxMintAllowance; bool onlyNHolders; bool supportsTokenId; } function mint( address recipient, uint8 amount, uint256 paid, bytes calldata data ) external; function mintTokenId( address recipient, uint256[] calldata tokenIds, uint256 paid, bytes calldata data ) external; function mintWithN( address recipient, uint256[] calldata tokenIds, uint256 paid, bytes calldata data ) external; function totalMintsAvailable() external view returns (uint256); function maxTotalSupply() external view returns (uint256); function mintParameters() external view returns (MintParams memory); function tokenExists(uint256 tokenId) external view returns (bool); function canMint(address account, bytes calldata data) external view returns (bool); function nUsed(uint256 nid) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity 0.8.6; interface IPricingStrategy { /** * @notice Returns the next price for an N mint */ function getNextPriceForNHoldersInWei( uint256 numberOfMints, address account, bytes memory data ) external view returns (uint256); /** * @notice Returns the next price for an open mint */ function getNextPriceForOpenMintInWei( uint256 numberOfMints, address account, bytes memory data ) external view returns (uint256); } // 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; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControl { /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {AccessControl-_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) external view returns (bool); /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {AccessControl-_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) external view returns (bytes32); /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) external; /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) external; /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) external; }
Tracks whether an n has been used already to mint
contract SeedPhrase is SeedPhrasePricing, VRFConsumerBase { using Strings for uint256; using Strings for uint16; using Strings for uint8; using Counters for Counters.Counter; using SeedPhraseUtils for SeedPhraseUtils.Random; Counters.Counter private _doublePanelTokens; Counters.Counter private _tokenIds; address private _owner; mapping(uint256 => bool) public override nUsed; mapping(PreSaleType => uint16) public presaleLimits; address[] private genesisSketchAddresses; uint16[] private bipWordIds = new uint16[](2048); IRarible public immutable rarible; INOwnerResolver public immutable nOwnerResolver; IKarmaScore public immutable karma; pragma solidity >=0.8.4; struct Maps { mapping(uint256 => uint256[2]) burnedTokensPairings; mapping(uint16 => uint16) doubleWordPairings; mapping(uint256 => uint8) doubleTokenRarity; mapping(address => bool) ogAddresses; mapping(uint256 => bytes32) tokenSeed; } struct Config { bool preSaleActive; bool publicSaleActive; bool isSaleHalted; bool bipWordsShuffled; bool vrfNumberGenerated; bool isBurnActive; bool isOwnerSupplyMinted; bool isGsAirdropComplete; uint8 ownerSupply; uint16 maxPublicMint; uint16 karmaRequirement; uint32 preSaleLaunchTime; uint32 publicSaleLaunchTime; uint256 doubleBurnTokens; uint256 linkFee; uint256 raribleTokenId; uint256 vrfRandomValue; address vrfCoordinator; address linkToken; bytes32 vrfKeyHash; } struct ContractAddresses { address n; address masterMint; address dao; address nOwnersRegistry; address vrfCoordinator; address linkToken; address karmaAddress; address rarible; } Config private config; Maps private maps; event Burnt(address to, uint256 firstBurntToken, uint256 secondBurntToken, uint256 doublePaneledToken); DerivativeParameters params = DerivativeParameters(false, false, 0, 2048, 4); constructor( ContractAddresses memory contractAddresses, bytes32 _vrfKeyHash, uint256 _linkFee ) SeedPhrasePricing( "Seed Phrase", "SEED", IN(contractAddresses.n), params, 30000000000000000, 60000000000000000, contractAddresses.masterMint, contractAddresses.dao ) VRFConsumerBase(contractAddresses.vrfCoordinator, contractAddresses.linkToken) { _tokenIds.increment(); presaleLimits[PreSaleType.N] = 400; presaleLimits[PreSaleType.Karma] = 800; presaleLimits[PreSaleType.GenesisSketch] = 40; presaleLimits[PreSaleType.OG] = 300; presaleLimits[PreSaleType.GM] = 300; nOwnerResolver = INOwnerResolver(contractAddresses.nOwnersRegistry); rarible = IRarible(contractAddresses.rarible); karma = IKarmaScore(contractAddresses.karmaAddress); config.maxPublicMint = 8; config.ownerSupply = 20; config.preSaleLaunchTime = 1639591200; config.publicSaleLaunchTime = 1639598400; config.raribleTokenId = 706480; config.karmaRequirement = 1020; config.vrfCoordinator = contractAddresses.vrfCoordinator; config.linkToken = contractAddresses.linkToken; config.linkFee = _linkFee; config.vrfKeyHash = _vrfKeyHash; _owner = 0x7F05F27CC5D83C3e879C53882de13Cc1cbCe8a8c; } function owner() external view virtual returns (address) { return _owner; } function setOwner(address owner_) external onlyAdmin { _owner = owner_; } function contractURI() public pure returns (string memory) { } function getVrfSeed() external onlyAdmin returns (bytes32) { require(!config.vrfNumberGenerated, "SP:VRF_ALREADY_CALLED"); require(LINK.balanceOf(address(this)) >= config.linkFee, "SP:NOT_ENOUGH_LINK"); return requestRandomness(config.vrfKeyHash, config.linkFee); } function fulfillRandomness(bytes32, uint256 randomNumber) internal override { config.vrfRandomValue = randomNumber; config.vrfNumberGenerated = true; } function _getTokenSeed(uint256 tokenId) internal view returns (bytes32) { return maps.tokenSeed[tokenId]; } function _getBipWordIdFromTokenId(uint256 tokenId) internal view returns (uint16) { return bipWordIds[tokenId - 1]; } function tokenSVG(uint256 tokenId) public view virtual returns (string memory svg, bytes memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); SeedPhraseUtils.Random memory random = SeedPhraseUtils.Random({ seed: uint256(_getTokenSeed(tokenId)), offsetBit: 0 }); uint16 bipWordId; uint16 secondBipWordId = 0; uint8 rarityValue = 0; if (tokenId >= 3000) { uint256[2] memory tokens = maps.burnedTokensPairings[tokenId]; bipWordId = _getBipWordIdFromTokenId(tokens[0]); secondBipWordId = _getBipWordIdFromTokenId(tokens[1]); rarityValue = maps.doubleTokenRarity[tokenId]; bipWordId = _getBipWordIdFromTokenId(tokenId); } (bytes memory traits, SeedPhraseUtils.Attrs memory attributes) = SeedPhraseUtils.getTraitsAndAttributes( bipWordId, secondBipWordId, rarityValue, random ); return (SeedPhraseUtils.render(random, attributes), traits); } function tokenSVG(uint256 tokenId) public view virtual returns (string memory svg, bytes memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); SeedPhraseUtils.Random memory random = SeedPhraseUtils.Random({ seed: uint256(_getTokenSeed(tokenId)), offsetBit: 0 }); uint16 bipWordId; uint16 secondBipWordId = 0; uint8 rarityValue = 0; if (tokenId >= 3000) { uint256[2] memory tokens = maps.burnedTokensPairings[tokenId]; bipWordId = _getBipWordIdFromTokenId(tokens[0]); secondBipWordId = _getBipWordIdFromTokenId(tokens[1]); rarityValue = maps.doubleTokenRarity[tokenId]; bipWordId = _getBipWordIdFromTokenId(tokenId); } (bytes memory traits, SeedPhraseUtils.Attrs memory attributes) = SeedPhraseUtils.getTraitsAndAttributes( bipWordId, secondBipWordId, rarityValue, random ); return (SeedPhraseUtils.render(random, attributes), traits); } function tokenSVG(uint256 tokenId) public view virtual returns (string memory svg, bytes memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); SeedPhraseUtils.Random memory random = SeedPhraseUtils.Random({ seed: uint256(_getTokenSeed(tokenId)), offsetBit: 0 }); uint16 bipWordId; uint16 secondBipWordId = 0; uint8 rarityValue = 0; if (tokenId >= 3000) { uint256[2] memory tokens = maps.burnedTokensPairings[tokenId]; bipWordId = _getBipWordIdFromTokenId(tokens[0]); secondBipWordId = _getBipWordIdFromTokenId(tokens[1]); rarityValue = maps.doubleTokenRarity[tokenId]; bipWordId = _getBipWordIdFromTokenId(tokenId); } (bytes memory traits, SeedPhraseUtils.Attrs memory attributes) = SeedPhraseUtils.getTraitsAndAttributes( bipWordId, secondBipWordId, rarityValue, random ); return (SeedPhraseUtils.render(random, attributes), traits); } } else { function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); (string memory output, bytes memory traits) = tokenSVG(tokenId); return SeedPhraseUtils.getTokenURI(output, traits, tokenId); } Updates the presale state for n holders function setPreSaleState(bool _preSaleActiveState) external onlyAdmin { config.preSaleActive = _preSaleActiveState; } Updates the public sale state for non-n holders function setPublicSaleState(bool _publicSaleActiveState) external onlyAdmin { config.publicSaleActive = _publicSaleActiveState; } function setPreSaleTime(uint32 _time) external onlyAdmin { config.preSaleLaunchTime = _time; } function setPublicSaleTime(uint32 _time) external onlyAdmin { config.publicSaleLaunchTime = _time; } Give the ability to halt the sale if necessary due to automatic sale enablement based on time function setSaleHaltedState(bool _saleHaltedState) external onlyAdmin { config.isSaleHalted = _saleHaltedState; } function setBurnActiveState(bool _burnActiveState) external onlyAdmin { config.isBurnActive = _burnActiveState; } function setGenesisSketchAllowList(address[] calldata addresses) external onlyAdmin { genesisSketchAddresses = addresses; } function setOgAllowList(address[] calldata addresses) external onlyAdmin { for (uint256 i = 0; i < addresses.length; i++) { maps.ogAddresses[addresses[i]] = true; } } function setOgAllowList(address[] calldata addresses) external onlyAdmin { for (uint256 i = 0; i < addresses.length; i++) { maps.ogAddresses[addresses[i]] = true; } } function _isPreSaleActive() internal view returns (bool) { return ((block.timestamp >= config.preSaleLaunchTime || config.preSaleActive) && !config.isSaleHalted); } function _isPublicSaleActive() internal view override returns (bool) { return ((block.timestamp >= config.publicSaleLaunchTime || config.publicSaleActive) && !config.isSaleHalted); } function _canMintPresale( address addr, uint256 amount, bytes memory data ) internal view override returns (bool, PreSaleType) { if (maps.ogAddresses[addr] && presaleLimits[PreSaleType.OG] - amount >= 0) { return (true, PreSaleType.OG); } bool isGsHolder; for (uint256 i = 0; i < genesisSketchAddresses.length; i++) { if (genesisSketchAddresses[i] == addr) { isGsHolder = true; } } if (isGsHolder && presaleLimits[PreSaleType.GenesisSketch] - amount >= 0) { return (true, PreSaleType.GenesisSketch); } if (rarible.balanceOf(addr, config.raribleTokenId) > 0 && presaleLimits[PreSaleType.GM] - amount > 0) { return (true, PreSaleType.GM); } uint256 karmaScore = SeedPhraseUtils.getKarma(karma, data, addr); if (nOwnerResolver.balanceOf(addr) > 0) { if (karmaScore >= config.karmaRequirement && presaleLimits[PreSaleType.Karma] - amount >= 0) { return (true, PreSaleType.Karma); } if (presaleLimits[PreSaleType.N] - amount >= 0) { return (true, PreSaleType.N); } } return (false, PreSaleType.None); } function _canMintPresale( address addr, uint256 amount, bytes memory data ) internal view override returns (bool, PreSaleType) { if (maps.ogAddresses[addr] && presaleLimits[PreSaleType.OG] - amount >= 0) { return (true, PreSaleType.OG); } bool isGsHolder; for (uint256 i = 0; i < genesisSketchAddresses.length; i++) { if (genesisSketchAddresses[i] == addr) { isGsHolder = true; } } if (isGsHolder && presaleLimits[PreSaleType.GenesisSketch] - amount >= 0) { return (true, PreSaleType.GenesisSketch); } if (rarible.balanceOf(addr, config.raribleTokenId) > 0 && presaleLimits[PreSaleType.GM] - amount > 0) { return (true, PreSaleType.GM); } uint256 karmaScore = SeedPhraseUtils.getKarma(karma, data, addr); if (nOwnerResolver.balanceOf(addr) > 0) { if (karmaScore >= config.karmaRequirement && presaleLimits[PreSaleType.Karma] - amount >= 0) { return (true, PreSaleType.Karma); } if (presaleLimits[PreSaleType.N] - amount >= 0) { return (true, PreSaleType.N); } } return (false, PreSaleType.None); } function _canMintPresale( address addr, uint256 amount, bytes memory data ) internal view override returns (bool, PreSaleType) { if (maps.ogAddresses[addr] && presaleLimits[PreSaleType.OG] - amount >= 0) { return (true, PreSaleType.OG); } bool isGsHolder; for (uint256 i = 0; i < genesisSketchAddresses.length; i++) { if (genesisSketchAddresses[i] == addr) { isGsHolder = true; } } if (isGsHolder && presaleLimits[PreSaleType.GenesisSketch] - amount >= 0) { return (true, PreSaleType.GenesisSketch); } if (rarible.balanceOf(addr, config.raribleTokenId) > 0 && presaleLimits[PreSaleType.GM] - amount > 0) { return (true, PreSaleType.GM); } uint256 karmaScore = SeedPhraseUtils.getKarma(karma, data, addr); if (nOwnerResolver.balanceOf(addr) > 0) { if (karmaScore >= config.karmaRequirement && presaleLimits[PreSaleType.Karma] - amount >= 0) { return (true, PreSaleType.Karma); } if (presaleLimits[PreSaleType.N] - amount >= 0) { return (true, PreSaleType.N); } } return (false, PreSaleType.None); } function _canMintPresale( address addr, uint256 amount, bytes memory data ) internal view override returns (bool, PreSaleType) { if (maps.ogAddresses[addr] && presaleLimits[PreSaleType.OG] - amount >= 0) { return (true, PreSaleType.OG); } bool isGsHolder; for (uint256 i = 0; i < genesisSketchAddresses.length; i++) { if (genesisSketchAddresses[i] == addr) { isGsHolder = true; } } if (isGsHolder && presaleLimits[PreSaleType.GenesisSketch] - amount >= 0) { return (true, PreSaleType.GenesisSketch); } if (rarible.balanceOf(addr, config.raribleTokenId) > 0 && presaleLimits[PreSaleType.GM] - amount > 0) { return (true, PreSaleType.GM); } uint256 karmaScore = SeedPhraseUtils.getKarma(karma, data, addr); if (nOwnerResolver.balanceOf(addr) > 0) { if (karmaScore >= config.karmaRequirement && presaleLimits[PreSaleType.Karma] - amount >= 0) { return (true, PreSaleType.Karma); } if (presaleLimits[PreSaleType.N] - amount >= 0) { return (true, PreSaleType.N); } } return (false, PreSaleType.None); } function _canMintPresale( address addr, uint256 amount, bytes memory data ) internal view override returns (bool, PreSaleType) { if (maps.ogAddresses[addr] && presaleLimits[PreSaleType.OG] - amount >= 0) { return (true, PreSaleType.OG); } bool isGsHolder; for (uint256 i = 0; i < genesisSketchAddresses.length; i++) { if (genesisSketchAddresses[i] == addr) { isGsHolder = true; } } if (isGsHolder && presaleLimits[PreSaleType.GenesisSketch] - amount >= 0) { return (true, PreSaleType.GenesisSketch); } if (rarible.balanceOf(addr, config.raribleTokenId) > 0 && presaleLimits[PreSaleType.GM] - amount > 0) { return (true, PreSaleType.GM); } uint256 karmaScore = SeedPhraseUtils.getKarma(karma, data, addr); if (nOwnerResolver.balanceOf(addr) > 0) { if (karmaScore >= config.karmaRequirement && presaleLimits[PreSaleType.Karma] - amount >= 0) { return (true, PreSaleType.Karma); } if (presaleLimits[PreSaleType.N] - amount >= 0) { return (true, PreSaleType.N); } } return (false, PreSaleType.None); } function _canMintPresale( address addr, uint256 amount, bytes memory data ) internal view override returns (bool, PreSaleType) { if (maps.ogAddresses[addr] && presaleLimits[PreSaleType.OG] - amount >= 0) { return (true, PreSaleType.OG); } bool isGsHolder; for (uint256 i = 0; i < genesisSketchAddresses.length; i++) { if (genesisSketchAddresses[i] == addr) { isGsHolder = true; } } if (isGsHolder && presaleLimits[PreSaleType.GenesisSketch] - amount >= 0) { return (true, PreSaleType.GenesisSketch); } if (rarible.balanceOf(addr, config.raribleTokenId) > 0 && presaleLimits[PreSaleType.GM] - amount > 0) { return (true, PreSaleType.GM); } uint256 karmaScore = SeedPhraseUtils.getKarma(karma, data, addr); if (nOwnerResolver.balanceOf(addr) > 0) { if (karmaScore >= config.karmaRequirement && presaleLimits[PreSaleType.Karma] - amount >= 0) { return (true, PreSaleType.Karma); } if (presaleLimits[PreSaleType.N] - amount >= 0) { return (true, PreSaleType.N); } } return (false, PreSaleType.None); } function _canMintPresale( address addr, uint256 amount, bytes memory data ) internal view override returns (bool, PreSaleType) { if (maps.ogAddresses[addr] && presaleLimits[PreSaleType.OG] - amount >= 0) { return (true, PreSaleType.OG); } bool isGsHolder; for (uint256 i = 0; i < genesisSketchAddresses.length; i++) { if (genesisSketchAddresses[i] == addr) { isGsHolder = true; } } if (isGsHolder && presaleLimits[PreSaleType.GenesisSketch] - amount >= 0) { return (true, PreSaleType.GenesisSketch); } if (rarible.balanceOf(addr, config.raribleTokenId) > 0 && presaleLimits[PreSaleType.GM] - amount > 0) { return (true, PreSaleType.GM); } uint256 karmaScore = SeedPhraseUtils.getKarma(karma, data, addr); if (nOwnerResolver.balanceOf(addr) > 0) { if (karmaScore >= config.karmaRequirement && presaleLimits[PreSaleType.Karma] - amount >= 0) { return (true, PreSaleType.Karma); } if (presaleLimits[PreSaleType.N] - amount >= 0) { return (true, PreSaleType.N); } } return (false, PreSaleType.None); } function _canMintPresale( address addr, uint256 amount, bytes memory data ) internal view override returns (bool, PreSaleType) { if (maps.ogAddresses[addr] && presaleLimits[PreSaleType.OG] - amount >= 0) { return (true, PreSaleType.OG); } bool isGsHolder; for (uint256 i = 0; i < genesisSketchAddresses.length; i++) { if (genesisSketchAddresses[i] == addr) { isGsHolder = true; } } if (isGsHolder && presaleLimits[PreSaleType.GenesisSketch] - amount >= 0) { return (true, PreSaleType.GenesisSketch); } if (rarible.balanceOf(addr, config.raribleTokenId) > 0 && presaleLimits[PreSaleType.GM] - amount > 0) { return (true, PreSaleType.GM); } uint256 karmaScore = SeedPhraseUtils.getKarma(karma, data, addr); if (nOwnerResolver.balanceOf(addr) > 0) { if (karmaScore >= config.karmaRequirement && presaleLimits[PreSaleType.Karma] - amount >= 0) { return (true, PreSaleType.Karma); } if (presaleLimits[PreSaleType.N] - amount >= 0) { return (true, PreSaleType.N); } } return (false, PreSaleType.None); } function _canMintPresale( address addr, uint256 amount, bytes memory data ) internal view override returns (bool, PreSaleType) { if (maps.ogAddresses[addr] && presaleLimits[PreSaleType.OG] - amount >= 0) { return (true, PreSaleType.OG); } bool isGsHolder; for (uint256 i = 0; i < genesisSketchAddresses.length; i++) { if (genesisSketchAddresses[i] == addr) { isGsHolder = true; } } if (isGsHolder && presaleLimits[PreSaleType.GenesisSketch] - amount >= 0) { return (true, PreSaleType.GenesisSketch); } if (rarible.balanceOf(addr, config.raribleTokenId) > 0 && presaleLimits[PreSaleType.GM] - amount > 0) { return (true, PreSaleType.GM); } uint256 karmaScore = SeedPhraseUtils.getKarma(karma, data, addr); if (nOwnerResolver.balanceOf(addr) > 0) { if (karmaScore >= config.karmaRequirement && presaleLimits[PreSaleType.Karma] - amount >= 0) { return (true, PreSaleType.Karma); } if (presaleLimits[PreSaleType.N] - amount >= 0) { return (true, PreSaleType.N); } } return (false, PreSaleType.None); } function canMint(address account, bytes calldata data) public view virtual override returns (bool) { if (config.isBurnActive) { return false; } uint256 balance = balanceOf(account); if (_isPublicSaleActive() && (totalMintsAvailable() > 0) && balance < config.maxPublicMint) { return true; } if (_isPreSaleActive()) { (bool preSaleEligible, ) = _canMintPresale(account, 1, data); return preSaleEligible; } return false; } function canMint(address account, bytes calldata data) public view virtual override returns (bool) { if (config.isBurnActive) { return false; } uint256 balance = balanceOf(account); if (_isPublicSaleActive() && (totalMintsAvailable() > 0) && balance < config.maxPublicMint) { return true; } if (_isPreSaleActive()) { (bool preSaleEligible, ) = _canMintPresale(account, 1, data); return preSaleEligible; } return false; } function canMint(address account, bytes calldata data) public view virtual override returns (bool) { if (config.isBurnActive) { return false; } uint256 balance = balanceOf(account); if (_isPublicSaleActive() && (totalMintsAvailable() > 0) && balance < config.maxPublicMint) { return true; } if (_isPreSaleActive()) { (bool preSaleEligible, ) = _canMintPresale(account, 1, data); return preSaleEligible; } return false; } function canMint(address account, bytes calldata data) public view virtual override returns (bool) { if (config.isBurnActive) { return false; } uint256 balance = balanceOf(account); if (_isPublicSaleActive() && (totalMintsAvailable() > 0) && balance < config.maxPublicMint) { return true; } if (_isPreSaleActive()) { (bool preSaleEligible, ) = _canMintPresale(account, 1, data); return preSaleEligible; } return false; } function mintWithN( address recipient, uint256[] calldata tokenIds, uint256 paid, bytes calldata data ) public virtual override nonReentrant { uint256 maxTokensToMint = tokenIds.length; (bool preSaleEligible, PreSaleType presaleType) = _canMintPresale(recipient, maxTokensToMint, data); require(config.bipWordsShuffled && config.vrfNumberGenerated, "SP:ENV_NOT_INIT"); require(_isPublicSaleActive() || (_isPreSaleActive() && preSaleEligible), "SP:SALE_NOT_ACTIVE"); require( balanceOf(recipient) + maxTokensToMint <= _getMaxMintPerWallet(), "NilPass:MINT_ABOVE_MAX_MINT_ALLOWANCE" ); require(!config.isBurnActive, "SP:SALE_OVER"); require(totalSupply() + maxTokensToMint <= params.maxTotalSupply, "NilPass:MAX_ALLOCATION_REACHED"); uint256 price = getNextPriceForNHoldersInWei(maxTokensToMint, recipient, data); require(paid == price, "NilPass:INVALID_PRICE"); for (uint256 i = 0; i < maxTokensToMint; i++) { require(!nUsed[tokenIds[i]], "SP:N_ALREADY_USED"); uint256 tokenId = _tokenIds.current(); require(tokenId <= params.maxTotalSupply, "SP:TOKEN_TOO_HIGH"); maps.tokenSeed[tokenId] = SeedPhraseUtils.generateSeed(tokenId, config.vrfRandomValue); _safeMint(recipient, tokenId); _tokenIds.increment(); nUsed[tokenIds[i]] = true; } if (preSaleEligible) { presaleLimits[presaleType] -= uint16(maxTokensToMint); } } function mintWithN( address recipient, uint256[] calldata tokenIds, uint256 paid, bytes calldata data ) public virtual override nonReentrant { uint256 maxTokensToMint = tokenIds.length; (bool preSaleEligible, PreSaleType presaleType) = _canMintPresale(recipient, maxTokensToMint, data); require(config.bipWordsShuffled && config.vrfNumberGenerated, "SP:ENV_NOT_INIT"); require(_isPublicSaleActive() || (_isPreSaleActive() && preSaleEligible), "SP:SALE_NOT_ACTIVE"); require( balanceOf(recipient) + maxTokensToMint <= _getMaxMintPerWallet(), "NilPass:MINT_ABOVE_MAX_MINT_ALLOWANCE" ); require(!config.isBurnActive, "SP:SALE_OVER"); require(totalSupply() + maxTokensToMint <= params.maxTotalSupply, "NilPass:MAX_ALLOCATION_REACHED"); uint256 price = getNextPriceForNHoldersInWei(maxTokensToMint, recipient, data); require(paid == price, "NilPass:INVALID_PRICE"); for (uint256 i = 0; i < maxTokensToMint; i++) { require(!nUsed[tokenIds[i]], "SP:N_ALREADY_USED"); uint256 tokenId = _tokenIds.current(); require(tokenId <= params.maxTotalSupply, "SP:TOKEN_TOO_HIGH"); maps.tokenSeed[tokenId] = SeedPhraseUtils.generateSeed(tokenId, config.vrfRandomValue); _safeMint(recipient, tokenId); _tokenIds.increment(); nUsed[tokenIds[i]] = true; } if (preSaleEligible) { presaleLimits[presaleType] -= uint16(maxTokensToMint); } } function mintWithN( address recipient, uint256[] calldata tokenIds, uint256 paid, bytes calldata data ) public virtual override nonReentrant { uint256 maxTokensToMint = tokenIds.length; (bool preSaleEligible, PreSaleType presaleType) = _canMintPresale(recipient, maxTokensToMint, data); require(config.bipWordsShuffled && config.vrfNumberGenerated, "SP:ENV_NOT_INIT"); require(_isPublicSaleActive() || (_isPreSaleActive() && preSaleEligible), "SP:SALE_NOT_ACTIVE"); require( balanceOf(recipient) + maxTokensToMint <= _getMaxMintPerWallet(), "NilPass:MINT_ABOVE_MAX_MINT_ALLOWANCE" ); require(!config.isBurnActive, "SP:SALE_OVER"); require(totalSupply() + maxTokensToMint <= params.maxTotalSupply, "NilPass:MAX_ALLOCATION_REACHED"); uint256 price = getNextPriceForNHoldersInWei(maxTokensToMint, recipient, data); require(paid == price, "NilPass:INVALID_PRICE"); for (uint256 i = 0; i < maxTokensToMint; i++) { require(!nUsed[tokenIds[i]], "SP:N_ALREADY_USED"); uint256 tokenId = _tokenIds.current(); require(tokenId <= params.maxTotalSupply, "SP:TOKEN_TOO_HIGH"); maps.tokenSeed[tokenId] = SeedPhraseUtils.generateSeed(tokenId, config.vrfRandomValue); _safeMint(recipient, tokenId); _tokenIds.increment(); nUsed[tokenIds[i]] = true; } if (preSaleEligible) { presaleLimits[presaleType] -= uint16(maxTokensToMint); } } function mint( address recipient, uint8 amount, uint256 paid, bytes calldata data ) public virtual override nonReentrant { (bool preSaleEligible, PreSaleType presaleType) = _canMintPresale(recipient, amount, data); require(config.bipWordsShuffled && config.vrfNumberGenerated, "SP:ENV_NOT_INIT"); require( _isPublicSaleActive() || (_isPreSaleActive() && preSaleEligible && (presaleType != PreSaleType.N && presaleType != PreSaleType.Karma)), "SP:SALE_NOT_ACTIVE" ); require(!config.isBurnActive, "SP:SALE_OVER"); require(balanceOf(recipient) + amount <= _getMaxMintPerWallet(), "NilPass:MINT_ABOVE_MAX_MINT_ALLOWANCE"); require(totalSupply() + amount <= params.maxTotalSupply, "NilPass:MAX_ALLOCATION_REACHED"); uint256 price = getNextPriceForOpenMintInWei(amount, recipient, data); require(paid == price, "NilPass:INVALID_PRICE"); for (uint256 i = 0; i < amount; i++) { uint256 tokenId = _tokenIds.current(); require(tokenId <= params.maxTotalSupply, "SP:TOKEN_TOO_HIGH"); maps.tokenSeed[tokenId] = SeedPhraseUtils.generateSeed(tokenId, config.vrfRandomValue); _safeMint(recipient, tokenId); _tokenIds.increment(); } if (preSaleEligible) { presaleLimits[presaleType] -= amount; } } function mint( address recipient, uint8 amount, uint256 paid, bytes calldata data ) public virtual override nonReentrant { (bool preSaleEligible, PreSaleType presaleType) = _canMintPresale(recipient, amount, data); require(config.bipWordsShuffled && config.vrfNumberGenerated, "SP:ENV_NOT_INIT"); require( _isPublicSaleActive() || (_isPreSaleActive() && preSaleEligible && (presaleType != PreSaleType.N && presaleType != PreSaleType.Karma)), "SP:SALE_NOT_ACTIVE" ); require(!config.isBurnActive, "SP:SALE_OVER"); require(balanceOf(recipient) + amount <= _getMaxMintPerWallet(), "NilPass:MINT_ABOVE_MAX_MINT_ALLOWANCE"); require(totalSupply() + amount <= params.maxTotalSupply, "NilPass:MAX_ALLOCATION_REACHED"); uint256 price = getNextPriceForOpenMintInWei(amount, recipient, data); require(paid == price, "NilPass:INVALID_PRICE"); for (uint256 i = 0; i < amount; i++) { uint256 tokenId = _tokenIds.current(); require(tokenId <= params.maxTotalSupply, "SP:TOKEN_TOO_HIGH"); maps.tokenSeed[tokenId] = SeedPhraseUtils.generateSeed(tokenId, config.vrfRandomValue); _safeMint(recipient, tokenId); _tokenIds.increment(); } if (preSaleEligible) { presaleLimits[presaleType] -= amount; } } function mint( address recipient, uint8 amount, uint256 paid, bytes calldata data ) public virtual override nonReentrant { (bool preSaleEligible, PreSaleType presaleType) = _canMintPresale(recipient, amount, data); require(config.bipWordsShuffled && config.vrfNumberGenerated, "SP:ENV_NOT_INIT"); require( _isPublicSaleActive() || (_isPreSaleActive() && preSaleEligible && (presaleType != PreSaleType.N && presaleType != PreSaleType.Karma)), "SP:SALE_NOT_ACTIVE" ); require(!config.isBurnActive, "SP:SALE_OVER"); require(balanceOf(recipient) + amount <= _getMaxMintPerWallet(), "NilPass:MINT_ABOVE_MAX_MINT_ALLOWANCE"); require(totalSupply() + amount <= params.maxTotalSupply, "NilPass:MAX_ALLOCATION_REACHED"); uint256 price = getNextPriceForOpenMintInWei(amount, recipient, data); require(paid == price, "NilPass:INVALID_PRICE"); for (uint256 i = 0; i < amount; i++) { uint256 tokenId = _tokenIds.current(); require(tokenId <= params.maxTotalSupply, "SP:TOKEN_TOO_HIGH"); maps.tokenSeed[tokenId] = SeedPhraseUtils.generateSeed(tokenId, config.vrfRandomValue); _safeMint(recipient, tokenId); _tokenIds.increment(); } if (preSaleEligible) { presaleLimits[presaleType] -= amount; } } function mintOwnerSupply(address account) public nonReentrant onlyAdmin { require(!config.isOwnerSupplyMinted, "SP:ALREADY_MINTED"); require(config.bipWordsShuffled && config.vrfNumberGenerated, "SP:ENV_NOT_INIT"); require( totalSupply() + config.ownerSupply <= params.maxTotalSupply, "NilPass:MAX_ALLOCATION_REACHED" ); for (uint256 i = 0; i < config.ownerSupply; i++) { uint256 tokenId = _tokenIds.current(); maps.tokenSeed[tokenId] = SeedPhraseUtils.generateSeed(tokenId, config.vrfRandomValue); _mint(account, tokenId); _tokenIds.increment(); } config.isOwnerSupplyMinted = true; } function mintOwnerSupply(address account) public nonReentrant onlyAdmin { require(!config.isOwnerSupplyMinted, "SP:ALREADY_MINTED"); require(config.bipWordsShuffled && config.vrfNumberGenerated, "SP:ENV_NOT_INIT"); require( totalSupply() + config.ownerSupply <= params.maxTotalSupply, "NilPass:MAX_ALLOCATION_REACHED" ); for (uint256 i = 0; i < config.ownerSupply; i++) { uint256 tokenId = _tokenIds.current(); maps.tokenSeed[tokenId] = SeedPhraseUtils.generateSeed(tokenId, config.vrfRandomValue); _mint(account, tokenId); _tokenIds.increment(); } config.isOwnerSupplyMinted = true; } function burnForDoublePanel(uint256 firstTokenId, uint256 secondTokenId) public nonReentrant { require(config.isBurnActive, "SP:BURN_INACTIVE"); require(ownerOf(firstTokenId) == msg.sender && ownerOf(secondTokenId) == msg.sender, "SP:INCORRECT_OWNER"); require(firstTokenId != secondTokenId, "SP:EQUAL_TOKENS"); require( isValidPairing(_getBipWordIdFromTokenId(firstTokenId), _getBipWordIdFromTokenId(secondTokenId)), "SP:INVALID_TOKEN_PAIRING" ); _burn(firstTokenId); _burn(secondTokenId); uint256 doublePanelTokenId = 3000 + _doublePanelTokens.current(); maps.tokenSeed[doublePanelTokenId] = SeedPhraseUtils.generateSeed(doublePanelTokenId, config.vrfRandomValue); uint8 rarity1 = SeedPhraseUtils.getRarityRating(_getTokenSeed(firstTokenId)); uint8 rarity2 = SeedPhraseUtils.getRarityRating(_getTokenSeed(secondTokenId)); maps.doubleTokenRarity[doublePanelTokenId] = (rarity1 > rarity2 ? rarity1 : rarity2); _mint(msg.sender, doublePanelTokenId); maps.burnedTokensPairings[doublePanelTokenId] = [firstTokenId, secondTokenId]; _doublePanelTokens.increment(); emit Burnt(msg.sender, firstTokenId, secondTokenId, doublePanelTokenId); } function airdropGenesisSketch() public nonReentrant onlyAdmin { require(!config.isGsAirdropComplete, "SP:ALREADY_AIRDROPPED"); require(config.bipWordsShuffled && config.vrfNumberGenerated, "SP:ENV_NOT_INIT"); uint256 airdropAmount = genesisSketchAddresses.length; require(totalSupply() + airdropAmount <= params.maxTotalSupply, "NilPass:MAX_ALLOCATION_REACHED"); for (uint256 i = 0; i < airdropAmount; i++) { uint256 tokenId = _tokenIds.current(); maps.tokenSeed[tokenId] = SeedPhraseUtils.generateSeed(tokenId, config.vrfRandomValue); _mint(genesisSketchAddresses[i], tokenId); _tokenIds.increment(); } config.isGsAirdropComplete = true; } function airdropGenesisSketch() public nonReentrant onlyAdmin { require(!config.isGsAirdropComplete, "SP:ALREADY_AIRDROPPED"); require(config.bipWordsShuffled && config.vrfNumberGenerated, "SP:ENV_NOT_INIT"); uint256 airdropAmount = genesisSketchAddresses.length; require(totalSupply() + airdropAmount <= params.maxTotalSupply, "NilPass:MAX_ALLOCATION_REACHED"); for (uint256 i = 0; i < airdropAmount; i++) { uint256 tokenId = _tokenIds.current(); maps.tokenSeed[tokenId] = SeedPhraseUtils.generateSeed(tokenId, config.vrfRandomValue); _mint(genesisSketchAddresses[i], tokenId); _tokenIds.increment(); } config.isGsAirdropComplete = true; } function mintOrphanedPieces(uint256 amount, address addr) public nonReentrant onlyAdmin { require(totalMintsAvailable() == 0, "SP:MINT_NOT_OVER"); uint256 currentSupply = _tokenIds.current() - 1; config.doubleBurnTokens = derivativeParams.maxTotalSupply - currentSupply; require(config.doubleBurnTokens >= amount, "SP:NOT_ENOUGH_ORPHANS"); require(currentSupply + amount <= params.maxTotalSupply, "NilPass:MAX_ALLOCATION_REACHED"); for (uint256 i = 0; i < amount; i++) { uint256 tokenId = _tokenIds.current(); require(tokenId <= params.maxTotalSupply, "SP:TOKEN_TOO_HIGH"); maps.tokenSeed[tokenId] = SeedPhraseUtils.generateSeed(tokenId, config.vrfRandomValue); _mint(addr, tokenId); _tokenIds.increment(); } config.doubleBurnTokens -= amount; } function mintOrphanedPieces(uint256 amount, address addr) public nonReentrant onlyAdmin { require(totalMintsAvailable() == 0, "SP:MINT_NOT_OVER"); uint256 currentSupply = _tokenIds.current() - 1; config.doubleBurnTokens = derivativeParams.maxTotalSupply - currentSupply; require(config.doubleBurnTokens >= amount, "SP:NOT_ENOUGH_ORPHANS"); require(currentSupply + amount <= params.maxTotalSupply, "NilPass:MAX_ALLOCATION_REACHED"); for (uint256 i = 0; i < amount; i++) { uint256 tokenId = _tokenIds.current(); require(tokenId <= params.maxTotalSupply, "SP:TOKEN_TOO_HIGH"); maps.tokenSeed[tokenId] = SeedPhraseUtils.generateSeed(tokenId, config.vrfRandomValue); _mint(addr, tokenId); _tokenIds.increment(); } config.doubleBurnTokens -= amount; } function totalMintsAvailable() public view override returns (uint256) { uint256 totalAvailable = derivativeParams.maxTotalSupply - totalSupply(); if (block.timestamp > config.publicSaleLaunchTime + 18 hours) { uint256 doubleBurn = (block.timestamp - (config.publicSaleLaunchTime + 18 hours)) / 1 minutes; totalAvailable = totalAvailable > doubleBurn ? totalAvailable - doubleBurn : 0; } return totalAvailable; } function totalMintsAvailable() public view override returns (uint256) { uint256 totalAvailable = derivativeParams.maxTotalSupply - totalSupply(); if (block.timestamp > config.publicSaleLaunchTime + 18 hours) { uint256 doubleBurn = (block.timestamp - (config.publicSaleLaunchTime + 18 hours)) / 1 minutes; totalAvailable = totalAvailable > doubleBurn ? totalAvailable - doubleBurn : 0; } return totalAvailable; } function getDoubleBurnedTokens() external view returns (uint256) { return config.doubleBurnTokens; } function _getMaxMintPerWallet() internal view returns (uint128) { return _isPublicSaleActive() ? config.maxPublicMint : params.maxMintAllowance; } function isValidPairing(uint16 first, uint16 second) public view returns (bool) { return maps.doubleWordPairings[first] == second; } function amendPairings(uint16[][] calldata pairings) external onlyAdmin { for (uint16 i = 0; i < pairings.length; i++) { if (pairings[i].length != 2) { continue; } maps.doubleWordPairings[pairings[i][0]] = pairings[i][1]; } } function amendPairings(uint16[][] calldata pairings) external onlyAdmin { for (uint16 i = 0; i < pairings.length; i++) { if (pairings[i].length != 2) { continue; } maps.doubleWordPairings[pairings[i][0]] = pairings[i][1]; } } function amendPairings(uint16[][] calldata pairings) external onlyAdmin { for (uint16 i = 0; i < pairings.length; i++) { if (pairings[i].length != 2) { continue; } maps.doubleWordPairings[pairings[i][0]] = pairings[i][1]; } } function shuffleBipWords() external onlyAdmin { require(config.vrfNumberGenerated, "SP:VRF_NOT_CALLED"); require(!config.bipWordsShuffled, "SP:ALREADY_SHUFFLED"); bipWordIds = SeedPhraseUtils.shuffleBipWords(config.vrfRandomValue); config.bipWordsShuffled = true; } }
6,394,478
[ 1, 22138, 2856, 392, 290, 711, 2118, 1399, 1818, 358, 312, 474, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 16351, 28065, 12812, 353, 28065, 12812, 52, 1512, 310, 16, 776, 12918, 5869, 2171, 288, 203, 565, 1450, 8139, 364, 2254, 5034, 31, 203, 565, 1450, 8139, 364, 2254, 2313, 31, 203, 565, 1450, 8139, 364, 2254, 28, 31, 203, 565, 1450, 9354, 87, 364, 9354, 87, 18, 4789, 31, 203, 565, 1450, 28065, 12812, 1989, 364, 28065, 12812, 1989, 18, 8529, 31, 203, 203, 565, 9354, 87, 18, 4789, 3238, 389, 9056, 5537, 5157, 31, 203, 565, 9354, 87, 18, 4789, 3238, 389, 2316, 2673, 31, 203, 203, 565, 1758, 3238, 389, 8443, 31, 203, 203, 565, 2874, 12, 11890, 5034, 516, 1426, 13, 1071, 3849, 290, 6668, 31, 203, 203, 565, 2874, 12, 1386, 30746, 559, 516, 2254, 2313, 13, 1071, 4075, 5349, 12768, 31, 203, 203, 565, 1758, 8526, 3238, 21906, 22900, 7148, 31, 203, 565, 2254, 2313, 8526, 3238, 324, 625, 3944, 2673, 273, 394, 2254, 2313, 8526, 12, 21573, 28, 1769, 203, 203, 565, 15908, 297, 1523, 1071, 11732, 436, 297, 1523, 31, 203, 565, 2120, 5541, 4301, 1071, 11732, 290, 5541, 4301, 31, 203, 565, 467, 47, 297, 2540, 7295, 1071, 11732, 417, 297, 2540, 31, 203, 203, 683, 9454, 18035, 560, 1545, 20, 18, 28, 18, 24, 31, 203, 203, 565, 1958, 19837, 288, 203, 3639, 2874, 12, 11890, 5034, 516, 2254, 5034, 63, 22, 5717, 18305, 329, 5157, 4154, 899, 31, 203, 3639, 2874, 12, 11890, 2313, 516, 2254, 2313, 13, 1645, 3944, 4154, 899, 31, 203, 3639, 2874, 12, 11890, 5034, 516, 2254, 28, 13, 2 ]